public async void GetServices(object userState)
        {
            if (string.IsNullOrEmpty(Uri))
                throw new InvalidOperationException(Resources.Strings.ExceptionUriMustNotBeNull);

            UriBuilder builder = new UriBuilder(Uri);
            builder.Query = Utils.GetQueryParameters(Uri);
            finalUrl = builder.Uri;

            finalUrl = ESRI.ArcGIS.Mapping.Core.Utility.CreateUriWithProxy(ProxyUrl, finalUrl);

            if (webClient == null)
                webClient = new ArcGISWebClient();

            try
            {
                ArcGISWebClient.DownloadStringCompletedEventArgs result =
                    await webClient.DownloadStringTaskAsync(finalUrl, userState);
                processResult(result);
            }
            catch (Exception ex)
            {
                OnGetServicesInFolderFailed(new ExceptionEventArgs(ex, userState));
            }
        }
Example #2
0
        public async void GetServiceDetails(object userState)
        {
            if (string.IsNullOrEmpty(Uri))
            {
                throw new InvalidOperationException(Resources.Strings.ExceptionUriMustNotBeNull);
            }

            UriBuilder builder = new UriBuilder(Uri);

            builder.Query = Utils.GetQueryParameters(Uri);
            finalUrl      = builder.Uri;

            if (webClient == null)
            {
                webClient = new ArcGISWebClient();
            }
            webClient.ProxyUrl = ProxyUrl;

            try
            {
                ArcGISWebClient.DownloadStringCompletedEventArgs result = await webClient.DownloadStringTaskAsync(finalUrl, userState);

                processResult(result);
            }
            catch (Exception ex)
            {
                OnServiceDetailsDownloadFailed(new ExceptionEventArgs(ex, userState));
            }
        }
        public void LoadMetadata(bool designTime, string proxyUrl = null)
        {
            ServiceInfo = null;
            Error = null;
            if (designTime)
            {
                //Designtime datasource
                ServiceInfo = new GPMetaData()
                {
                    DisplayName = "{TITLE}",
                    Parameters = new GPParameter[] {
								new GPParameter() { 
									DisplayName = "{DisplayName1}", DefaultValue = "{Default value}", Name="Param1",
									DataType = "GPString", Direction="esriGPParameterDirectionInput", ParameterType="esriGPParameterTypeRequired"
								},
								new GPParameter() { 
									DisplayName = "{DisplayName2}", DefaultValue = "{Default value}", Name="Param2",
									DataType = "GPString", Direction="esriGPParameterDirectionInput", ParameterType="esriGPParameterTypeRequired"
								}
						}
                };
                if (LoadSucceeded != null)
                    LoadSucceeded(this, null);
                return;
            }
            ArcGISWebClient wc = new ArcGISWebClient() { ProxyUrl = proxyUrl };
            wc.DownloadStringCompleted += wc_OpenReadCompleted;
            
            // Get service endpoint JSON URL
            string url = ServiceEndpoint.AbsoluteUri + "?f=json";

            Uri uri = new Uri(url, UriKind.Absolute);
            wc.DownloadStringAsync(uri, null, ArcGISWebClient.HttpMethods.Auto, proxyUrl);
        }
        private void GPServerInfoDownloaded(object sender, ArcGISWebClient.DownloadStringCompletedEventArgs e)
        {
            #region Error checking
            if (e.Error != null)
            {
                Error = e.Error;
                if (LoadFailed != null)
                    LoadFailed(this, null);
                return;
            }

            string json = e.Result;
            if (string.IsNullOrEmpty(json) || json.StartsWith("{\"error\":", StringComparison.Ordinal))
            {
                if (LoadFailed != null)
                    LoadFailed(this, null);
                return;
            }
            #endregion

            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(GeoprocessingServiceInfo));
            MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
            GeoprocessingServiceInfo gpServerInfo = (GeoprocessingServiceInfo)serializer.ReadObject(ms);

            ServiceInfo.ResultMapServerName = gpServerInfo.ResultMapServerName;
            ServiceInfo.CurrentVersion = gpServerInfo.CurrentVersion;
                
            if (LoadSucceeded != null)
                LoadSucceeded(this, null);
        }
Example #5
0
        public async void GetCatalog(object userState)
        {
            if (string.IsNullOrEmpty(Uri))
                throw new InvalidOperationException(Resources.Strings.ExceptionUriMustNotBeNull);

            // ensure that catalog requests always end with /services
            if (!Uri.EndsWith("/services", StringComparison.OrdinalIgnoreCase)
                && !Uri.EndsWith("/services/", StringComparison.OrdinalIgnoreCase))
            {
                if (!Uri.EndsWith("/", StringComparison.Ordinal))
                    Uri += "/";
                Uri += "services";
            }

            UriBuilder builder = new UriBuilder(Uri);
            builder.Query = Utils.GetQueryParameters(Uri);
            finalUrl = builder.Uri;

            if (webClient == null)
                webClient = new ArcGISWebClient();
            webClient.ProxyUrl = ProxyUrl;

            try
            {
                ArcGISWebClient.DownloadStringCompletedEventArgs result =
                    await webClient.DownloadStringTaskAsync(finalUrl, userState);
                processResult(result);
            }
            catch (Exception ex)
            {
                OnGetCatalogFailed(new ExceptionEventArgs(ex, userState));
            }
        }
        protected async override void OnServiceDetailsDownloadCompleted(ServiceDetailsDownloadCompletedEventArgs args)
        {
            // Workaround for the fact that DataContractJsonSerializer doesn't call the default contructor
            // http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx
            if (ServiceInfo != null && ServiceInfo.SpatialReference != null)
            {
                if (ServiceInfo.SpatialReference.WKID == default(int))
                {
                    ServiceInfo.SpatialReference.WKID = -1;
                }
            }

            Uri finalUrl = new Uri(string.Format("{0}/layers?f=json", Uri));

            if (webClient == null)
            {
                webClient = new ArcGISWebClient();
            }
            webClient.ProxyUrl = ProxyUrl;

            try
            {
                ArcGISWebClient.DownloadStringCompletedEventArgs result =
                    await webClient.DownloadStringTaskAsync(finalUrl, args);

                processResult(result);
            }
            catch
            {
                base.OnServiceDetailsDownloadCompleted(args);
            }
        }
Example #7
0
        /// <summary>
        /// Opens a readable stream to the specified resource
        /// </summary>
        public static Task <ArcGISWebClient.OpenReadCompletedEventArgs> OpenReadTaskAsync(
            this ArcGISWebClient client, Uri uri, IDictionary <string, string> parameters = null,
            ArcGISWebClient.HttpMethods httpMethod = ArcGISWebClient.HttpMethods.Auto, object userState = null)
        {
            TaskCompletionSource <ArcGISWebClient.OpenReadCompletedEventArgs> tcs =
                new TaskCompletionSource <ArcGISWebClient.OpenReadCompletedEventArgs>();

            EventHandler <ArcGISWebClient.OpenReadCompletedEventArgs> openReadHandler = null;

            openReadHandler = (o, e) =>
            {
                client.OpenReadCompleted -= openReadHandler;
                if (e != null)
                {
                    tcs.TrySetResult(e);
                }
                else
                {
                    tcs.TrySetException(new Exception(Strings.ExceptionNoResult));
                }
            };
            client.OpenReadCompleted += openReadHandler;
            client.OpenReadAsync(uri, parameters, httpMethod, userState);

            return(tcs.Task);
        }
        public ArcGISWebClientSimple()
        {
            InitializeComponent();

            _webclient = new ArcGISWebClient();
            _webclient.OpenReadCompleted       += webclient_OpenReadCompleted;
            _webclient.DownloadStringCompleted += webclient_DownloadStringCompleted;
        }
        /// <summary>
        /// Helper method to download a string from a web service asynchronously.
        /// </summary>
        public static void DownloadStringAsync(Uri uri, object userState, EventHandler <ArcGISWebClient.DownloadStringCompletedEventArgs> callback)
        {
            System.Diagnostics.Debug.WriteLine(uri.ToString());
            var wc = new ArcGISWebClient();

            wc.DownloadStringCompleted += callback;
            wc.DownloadStringAsync(uri, null, ArcGISWebClient.HttpMethods.Auto, userState);
        }
        public ArcGISWebClientSimple()
        {
            InitializeComponent();

            _webclient = new ArcGISWebClient();
            _webclient.OpenReadCompleted += webclient_OpenReadCompleted;
            _webclient.DownloadStringCompleted += webclient_DownloadStringCompleted;
        }
Example #11
0
        /// <summary>
        /// Issues a GET request to the specified URI and returns the result
        /// </summary>
        public static Task <ArcGISWebClient.DownloadStringCompletedEventArgs> DownloadStringTaskAsync(
            this ArcGISWebClient client, Uri uri, IDictionary <string, string> parameters,
            ArcGISWebClient.HttpMethods httpMethod, object userState = null)
        {
            TaskCompletionSource <ArcGISWebClient.DownloadStringCompletedEventArgs> tcs =
                new TaskCompletionSource <ArcGISWebClient.DownloadStringCompletedEventArgs>();

            EventHandler <ApplicationUnhandledExceptionEventArgs>           unhandledExceptionHandler = null;
            EventHandler <ArcGISWebClient.DownloadStringCompletedEventArgs> downloadHandler           = null;

            // Handle application unhandled exception due to issue with API where uncatchable deserialization
            // exception is sometimes thrown for requests that return an error
            unhandledExceptionHandler = (o, e) =>
            {
                DownloadStringTaskInProgress = false;

                Application.Current.UnhandledException -= unhandledExceptionHandler;
                client.DownloadStringCompleted         -= downloadHandler;

                e.Handled = true;

                tcs.TrySetException(new Exception(Strings.ExceptionNoResult));
            };

            downloadHandler = (o, e) =>
            {
                DownloadStringTaskInProgress = false;

                if (Application.Current != null)
                {
                    Application.Current.UnhandledException -= unhandledExceptionHandler;
                }

                client.DownloadStringCompleted -= downloadHandler;
                if (e != null)
                {
                    tcs.TrySetResult(e);
                }
                else
                {
                    tcs.TrySetException(new Exception(Strings.ExceptionNoResult));
                }
            };
            client.DownloadStringCompleted += downloadHandler;

            if (Application.Current != null)
            {
                Application.Current.UnhandledException += unhandledExceptionHandler;
            }

            DownloadStringTaskInProgress = true;
            client.DownloadStringAsync(uri, parameters, httpMethod, userState);

            return(tcs.Task);
        }
        private async void getLayerInfosForPre10Servers(object userState)
        {
            string url = Url + "?f=json";
            if (webClient == null)
                webClient = new ArcGISWebClient();

            if (webClient.IsBusy)
                webClient.CancelAsync();

            webClient.ProxyUrl = ProxyUrl;
            ArcGISWebClient.DownloadStringCompletedEventArgs result =  
                await webClient.DownloadStringTaskAsync(new Uri(url), userState);
            processPre10LayerInfoResult(result);
        }
        private async void getLayerInfosForPre10Servers(object userState)
        {
            string url = Url + "?f=json";
            if (webClient == null)
                webClient = new ArcGISWebClient();

            if (webClient.IsBusy)
                webClient.CancelAsync();

            Uri uri = ESRI.ArcGIS.Mapping.Core.Utility.CreateUriWithProxy(ProxyUrl, url);            
            ArcGISWebClient.DownloadStringCompletedEventArgs result =  
                await webClient.DownloadStringTaskAsync(uri, userState);
            processPre10LayerInfoResult(result);
        }
        private static void doOpenRead(Uri uri, object userState, EventHandler <OpenReadEventArgs> callback, string proxyUrl = null)
        {
            var wc = new ArcGISWebClient()
            {
                ProxyUrl = proxyUrl
            };

            wc.OpenReadCompleted += (sender, e) =>
            {
                // if the request failed because of a security exception - missing clientaccesspolicy file -
                // then try to go thru the proxy server
                //
                if (e.Error is System.Security.SecurityException)
                {
                    if (string.IsNullOrEmpty(ArcGISOnlineEnvironment.ConfigurationUrls.ProxyServer))
                    {
                        handleQueuedRequests();
                        callback(sender, new OpenReadEventArgs(e));
                        return;
                    }

                    wc = new ArcGISWebClient()
                    {
                        ProxyUrl = ArcGISOnlineEnvironment.ConfigurationUrls.ProxyServer
                    };
                    wc.OpenReadCompleted += (sender2, e2) =>
                    {
                        handleQueuedRequests();
                        callback(sender, new OpenReadEventArgs(e2)
                        {
                            UsedProxy = true
                        });
                    };

                    System.Diagnostics.Debug.WriteLine(uri.ToString());
                    wc.OpenReadAsync(uri, null, ArcGISWebClient.HttpMethods.Auto, userState);
                }
                else
                {
                    handleQueuedRequests();
                    callback(sender, new OpenReadEventArgs(e));
                }
            };
            wc.OpenReadAsync(uri, null, ArcGISWebClient.HttpMethods.Auto, userState);
        }
        public void LoadMetadata(bool designTime, string proxyUrl = null)
        {
            ServiceInfo = null;
            Error       = null;
            if (designTime)
            {
                //Designtime datasource
                ServiceInfo = new GPMetaData()
                {
                    DisplayName = "{TITLE}",
                    Parameters  = new GPParameter[] {
                        new GPParameter()
                        {
                            DisplayName = "{DisplayName1}", DefaultValue = "{Default value}", Name = "Param1",
                            DataType    = "GPString", Direction = "esriGPParameterDirectionInput", ParameterType = "esriGPParameterTypeRequired"
                        },
                        new GPParameter()
                        {
                            DisplayName = "{DisplayName2}", DefaultValue = "{Default value}", Name = "Param2",
                            DataType    = "GPString", Direction = "esriGPParameterDirectionInput", ParameterType = "esriGPParameterTypeRequired"
                        }
                    }
                };
                if (LoadSucceeded != null)
                {
                    LoadSucceeded(this, null);
                }
                return;
            }
            ArcGISWebClient wc = new ArcGISWebClient()
            {
                ProxyUrl = proxyUrl
            };

            wc.DownloadStringCompleted += wc_OpenReadCompleted;

            // Get service endpoint JSON URL
            string url = ServiceEndpoint.AbsoluteUri + "?f=json";

            Uri uri = new Uri(url, UriKind.Absolute);

            wc.DownloadStringAsync(uri, null, ArcGISWebClient.HttpMethods.Auto, proxyUrl);
        }
        private async void getLayerInfo(int layerID, object userState)
        {
            if (cancelSingleRequests)
            {
                return;
            }
            string          layerUrl  = string.Format("{0}/{1}?f=pjson", Url, layerID);
            ArcGISWebClient webClient = new ArcGISWebClient()
            {
                ProxyUrl = ProxyUrl
            };

            singleRequestWebClients.Add(webClient);

            ArcGISWebClient.DownloadStringCompletedEventArgs result =
                await webClient.DownloadStringTaskAsync(new Uri(layerUrl), userState);

            processLayerInfoResult(result);
        }
        /// <summary>
        /// Helper method to read from a web service asynchronously.
        /// </summary>
        public static void OpenReadAsync(Uri uri, object userState, EventHandler <OpenReadEventArgs> callback, string proxyUrl = null)
        {
            ArcGISWebClient wc = new ArcGISWebClient()
            {
                ProxyUrl = proxyUrl
            };

            wc.OpenReadCompleted += (sender, e) =>
            {
                // TODO: Revisit handling of request failure due to missing clientaccesspolicy

                // if the request failed because of a security exception - missing clientaccesspolicy file -
                // then try to go thru the proxy server
                //
                //if (e.Error is System.Security.SecurityException)
                //{
                //    string proxyUrl = MapApplication.Current.Urls.GetProxyUrl();
                //    if (string.IsNullOrEmpty(proxyUrl))
                //    {
                //        callback(sender, new OpenReadEventArgs(e));
                //        return;
                //    }

                //    wc = new WebClient();
                //    wc.OpenReadCompleted += (sender2, e2) =>
                //    {
                //        callback(sender, new OpenReadEventArgs(e2) { UsedProxy = true });
                //    };

                //    uri = new Uri(proxyUrl + "?" + uri.ToString());
                //    wc.OpenReadAsync(uri, userState);
                //}
                //else

                callback(sender, new OpenReadEventArgs(e)
                {
                    UsedProxy = !string.IsNullOrEmpty(proxyUrl)
                });
            };

            wc.OpenReadAsync(uri, null, ArcGISWebClient.HttpMethods.Auto, userState);
        }
        private async void getLayerInfosForPre10Servers(object userState)
        {
            string url = Url + "?f=json";

            if (webClient == null)
            {
                webClient = new ArcGISWebClient();
            }

            if (webClient.IsBusy)
            {
                webClient.CancelAsync();
            }

            webClient.ProxyUrl = ProxyUrl;
            ArcGISWebClient.DownloadStringCompletedEventArgs result =
                await webClient.DownloadStringTaskAsync(new Uri(url), userState);

            processPre10LayerInfoResult(result);
        }
Example #19
0
        public async void GetCatalog(object userState)
        {
            if (string.IsNullOrEmpty(Uri))
            {
                throw new InvalidOperationException(Resources.Strings.ExceptionUriMustNotBeNull);
            }

            // ensure that catalog requests always end with /services
            if (!Uri.EndsWith("/services", StringComparison.OrdinalIgnoreCase) &&
                !Uri.EndsWith("/services/", StringComparison.OrdinalIgnoreCase))
            {
                if (!Uri.EndsWith("/", StringComparison.Ordinal))
                {
                    Uri += "/";
                }
                Uri += "services";
            }

            UriBuilder builder = new UriBuilder(Uri);

            builder.Query = Utils.GetQueryParameters(Uri);
            finalUrl      = builder.Uri;

            if (webClient == null)
            {
                webClient = new ArcGISWebClient();
            }
            webClient.ProxyUrl = ProxyUrl;

            try
            {
                ArcGISWebClient.DownloadStringCompletedEventArgs result =
                    await webClient.DownloadStringTaskAsync(finalUrl, userState);

                processResult(result);
            }
            catch (Exception ex)
            {
                OnGetCatalogFailed(new ExceptionEventArgs(ex, userState));
            }
        }
 /// <summary>
 /// Retrieves the demographics and other relevant 
 /// characteristics associated with the surrounding area.
 /// </summary>
 /// <param name="parameters">input parameters to Geoenrichment Service.</param>
 /// <param name="userToken">user token.</param>
 public void ExecuteAsync(GeoenrichmentParameter parameters, object userToken = null)
 {
     // Web requests made through ArcGISWebClient takes advantage of the IdentityManager.
     var client = new ArcGISWebClient();
     client.DownloadStringCompleted += (s, e) =>
     {
         if (e.Cancelled)
             OnExecuteCompleted(new GeoenrichmentEventArgs(new OperationCanceledException(), e.UserState));
         else if (e.Error != null)
             OnExecuteCompleted(new GeoenrichmentEventArgs(e.Error, e.UserState));
         else
         {
             var json = e.Result;
             var serviceException = ServiceException.FromJson(json);
             if(serviceException != null)
                 OnExecuteCompleted(new GeoenrichmentEventArgs(serviceException, e.UserState));
             OnExecuteCompleted(new GeoenrichmentEventArgs(GeoenrichmentResult.FromJson(json), e.UserState));
         }
     };
     client.DownloadStringAsync(new Uri(string.Format("{0}/enrich", ServiceUrl)),
         parameters.GetParameters(),
         ArcGISWebClient.HttpMethods.Auto, userToken);
 }
        // When map service item selected in Listbox, choose appropriate type and add to the map
        void webclient_DownloadStringCompleted(object sender, ArcGISWebClient.DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                    throw new Exception(e.Error.Message);

                // Get the service url from the user object
                string svcUrl = e.UserState as string;

                // Abstract JsonValue holds json response
                JsonValue serviceInfo = JsonObject.Parse(e.Result);
                // Use "singleFusedMapCache" to determine if a tiled or dynamic layer should be added to the map
                bool isTiledMapService = Boolean.Parse(serviceInfo["singleFusedMapCache"].ToString());

                Layer lyr = null;

                if (isTiledMapService)
                    lyr = new ArcGISTiledMapServiceLayer() { Url = svcUrl };
                else
                    lyr = new ArcGISDynamicMapServiceLayer() { Url = svcUrl };

                if (lyr != null)
                {
                    lyr.InitializationFailed += (a, b) =>
                    {
                        throw new Exception(lyr.InitializationFailure.Message);
                    };
                    MyMap.Layers.Add(lyr);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public async void GetGroupLayerDetails(object userState)
        {
            if (string.IsNullOrEmpty(Uri))
                throw new InvalidOperationException(Resources.Strings.ExceptionUriMustNotBeNull);

            UriBuilder builder = new UriBuilder(Uri);
            builder.Query = Utils.GetQueryParameters(Uri);
            finalUrl = builder.Uri;

            if (webClient == null)
                webClient = new ArcGISWebClient();
            webClient.ProxyUrl = ProxyUrl;

            try
            {
                ArcGISWebClient.DownloadStringCompletedEventArgs result =
                    await webClient.DownloadStringTaskAsync(finalUrl, userState);
                processResult(result);
            }
            catch (Exception ex)
            {
                OnGetGroupLayerDetailsFailed(new ExceptionEventArgs(ex, userState));
            }
        }
        /// <summary>
        /// Opens a readable stream to the specified resource
        /// </summary>
        public static Task<ArcGISWebClient.OpenReadCompletedEventArgs> OpenReadTaskAsync(
            this ArcGISWebClient client, Uri uri, IDictionary<string, string> parameters = null, 
            ArcGISWebClient.HttpMethods httpMethod = ArcGISWebClient.HttpMethods.Auto, object userState = null)
        {
            TaskCompletionSource<ArcGISWebClient.OpenReadCompletedEventArgs> tcs =
                new TaskCompletionSource<ArcGISWebClient.OpenReadCompletedEventArgs>();

            EventHandler<ArcGISWebClient.OpenReadCompletedEventArgs> openReadHandler = null;
            openReadHandler = (o, e) =>
            {
                client.OpenReadCompleted -= openReadHandler;
                if (e != null)
                    tcs.TrySetResult(e);
                else
                    tcs.TrySetException(new Exception(Strings.ExceptionNoResult));
            };
            client.OpenReadCompleted += openReadHandler;
            client.OpenReadAsync(uri, parameters, httpMethod, userState);

            return tcs.Task;
        }
        /// <summary>
        /// Issues a GET request to the specified URI and returns the result
        /// </summary>
        public static Task<ArcGISWebClient.DownloadStringCompletedEventArgs> DownloadStringTaskAsync(
            this ArcGISWebClient client, Uri uri, IDictionary<string, string> parameters, 
            ArcGISWebClient.HttpMethods httpMethod, object userState = null)
        {
            TaskCompletionSource<ArcGISWebClient.DownloadStringCompletedEventArgs> tcs =
                new TaskCompletionSource<ArcGISWebClient.DownloadStringCompletedEventArgs>();

            EventHandler<ApplicationUnhandledExceptionEventArgs> unhandledExceptionHandler = null;
            EventHandler<ArcGISWebClient.DownloadStringCompletedEventArgs> downloadHandler = null;

            // Handle application unhandled exception due to issue with API where uncatchable deserialization 
            // exception is sometimes thrown for requests that return an error
            unhandledExceptionHandler = (o, e) =>
                {
                    DownloadStringTaskInProgress = false;

                    Application.Current.UnhandledException -= unhandledExceptionHandler;
                    client.DownloadStringCompleted -= downloadHandler;

                    e.Handled = true;

                    tcs.TrySetException(new Exception(Strings.ExceptionNoResult));
                };

            downloadHandler = (o, e) =>
                {
                    DownloadStringTaskInProgress = false;

                    if (Application.Current != null)
                        Application.Current.UnhandledException -= unhandledExceptionHandler;

                    client.DownloadStringCompleted -= downloadHandler;
                    if (e != null)
                        tcs.TrySetResult(e);
                    else
                        tcs.TrySetException(new Exception(Strings.ExceptionNoResult));
                };
            client.DownloadStringCompleted += downloadHandler;

            if (Application.Current != null)
                Application.Current.UnhandledException += unhandledExceptionHandler;

            DownloadStringTaskInProgress = true;
            client.DownloadStringAsync(uri, parameters, httpMethod, userState);

            return tcs.Task;
        }
        private void BrowseButton_Click(object sender, RoutedEventArgs e)
        {
            // Call the ShowDialog method to show the dialog box.
            bool?userClickedOK = openFileDialog.ShowDialog();

            if (userClickedOK == true)
            {
                // Open the selected file to read.
                System.IO.FileInfo file = openFileDialog.File;

                // Uri to the ArcGIS Portal API generate operation.
                // Reference documentation available here: http://www.arcgis.com/apidocs/rest/generate.html
                Uri address = new Uri("http://www.arcgis.com/sharing/rest/content/features/generate");

                // Get the file contents for the local file
                FileStream fs = file.OpenRead();

                // Create ArcGISWebClient.StreamContent instance
                ArcGISWebClient.StreamContent streamContent = new ArcGISWebClient.StreamContent()
                {
                    Name        = "file",
                    Filename    = file.Name,
                    Stream      = fs,
                    ContentType = "application/zip"
                };

                // Create a list of stream content to POST
                IList <ArcGISWebClient.StreamContent> filestream = new List <ArcGISWebClient.StreamContent>();
                filestream.Add(streamContent);

                // Create dictionary to store parameter to POST
                Dictionary <string, string> postParameters = new Dictionary <string, string>();

                // A class created to store publish parameters for the generate operation
                GenerateFeaturesParams param = new GenerateFeaturesParams()
                {
                    name            = file.Name.Substring(0, file.Name.LastIndexOf(".")),
                    maxRecordCount  = 1000,
                    generalize      = false,
                    reducePrecision = true,
                    targetSR        = MyMap.SpatialReference
                };

                // Must specify the output type (json) the file type (shapefile) and the publish parameters
                postParameters.Add("f", "json");
                postParameters.Add("filetype", "shapefile");
                postParameters.Add("publishParameters", SerializeToJsonString(param));

                // Url to the generate operation, part of the ArcGIS Portal REST API (http://www.arcgis.com/apidocs/rest/generate.html)
                string postURL = "http://www.arcgis.com/sharing/rest/content/features/generate";

                // Use ArcGISWebClient POST shapefile to the ArcGIS Portal generate operation.  The generate operation requires a file to be passed
                // in a multi-part post request.
                ArcGISWebClient agsWebClient = new ArcGISWebClient();
                agsWebClient.PostMultipartCompleted += (a, b) =>
                {
                    if (b.Error == null)
                    {
                        try
                        {
                            // Use the the generic JsonValue to handle dynamic json content.
                            // In this case, generate always returns a "featureCollection" object which contains
                            // a "layers" array with one feature layer.
                            JsonValue featureCollection = JsonValue.Load(b.Result);
                            string    layer             = featureCollection["featureCollection"]["layers"][0].ToString();

                            FeatureLayer featureLayer = FeatureLayer.FromJson(layer);

                            if (featureLayer != null)
                            {
                                // Add the feature layer to the map and zoom to it
                                MyMap.Layers.Add(featureLayer);
                                MyMap.ZoomTo(featureLayer.FullExtent.Expand(1.25));
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "FeatureLayer creation failed", MessageBoxButton.OK);
                        }
                    }
                };
                agsWebClient.PostMultipartAsync(new Uri(postURL), postParameters, filestream, null);
            }
        }
        private void processResult(ArcGISWebClient.OpenReadCompletedEventArgs e)
        {
            if (e == null || e.Cancelled)
                return;

            if (e.Error != null)
            {
                OnGetLayerDetailsFailed(new ExceptionEventArgs(e.Error, e.UserState));
                return;
            }

            if (e.Result == null)
            {
                OnGetLayerDetailsFailed(new ExceptionEventArgs(new Exception(Resources.Strings.ExceptionEmptyResponse), e.UserState));
                return;
            }

            string json = (new StreamReader(e.Result)).ReadToEnd();
            if (string.IsNullOrEmpty(json))
            {
                OnGetLayerDetailsFailed(new ExceptionEventArgs(new Exception(Resources.Strings.ExceptionEmptyResponse), e.UserState));
                return;
            }

            LayerDetails layerDetails;
            try
            {
                Exception exception = Utils.CheckJsonForException(json);
                if (exception != null)
                {
                    OnGetLayerDetailsFailed(new ExceptionEventArgs(exception, e.UserState));
                    return;
                }
                byte[] bytes = Encoding.Unicode.GetBytes(json);
                using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(bytes))
                {
                    DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(LayerDetails));
                    layerDetails = dataContractJsonSerializer.ReadObject(memoryStream) as LayerDetails;
                    memoryStream.Close();
                }

                if (layerDetails == null)
                {
                    OnGetLayerDetailsFailed(new ExceptionEventArgs(new Exception(Resources.Strings.ExceptionUnableToDeserializeResponse), e.UserState));
                    return;
                }
            }
            catch (Exception ex)
            {
                OnGetLayerDetailsFailed(new ExceptionEventArgs(ex, e.UserState));
                return;
            }

            List<Resource> childResources = new List<Resource>();
            if (layerDetails.Fields != null)
            {
                foreach (ESRI.ArcGIS.Mapping.Core.Field field in layerDetails.Fields)
                {
                    childResources.Add(new Resource()
                    {
                        ResourceType = ResourceType.Field,
                        DisplayName = field.Alias,
                        ProxyUrl = ProxyUrl,
                        Url = field.Type,
                    });
                }
            }

            OnGetLayerDetailsCompleted(new GetLayerDetailsCompletedEventArgs() { ChildResources = childResources, LayerDetails = layerDetails, UserState = e.UserState });
        }
 private void processLayerInfoResult(ArcGISWebClient.DownloadStringCompletedEventArgs e)
 {
     #region Parse layer info from json
     if (e.Cancelled)
         return;
     if (e.Error != null)
     {
         singleLayerRequestCompleted(null, e);
         return;
     }
     string json = null;
     try
     {
         json = e.Result;
     }
     catch (Exception exception)
     {
         if (exception != null)
         {
             singleLayerRequestCompleted(null, e);
             return;
         }
     }
     Exception ex = ESRI.ArcGIS.Mapping.DataSources.Utils.CheckJsonForException(json);
     if (ex != null)
     {
         singleLayerRequestCompleted(null, e);
         return;
     }
     json = "{\"layerDefinition\":" + json + "}";
     FeatureLayer featureLayer = FeatureLayer.FromJson(json);
     FeatureLayerInfo featurelayerinfo = featureLayer.LayerInfo;
     if (featurelayerinfo == null)
     {
         singleLayerRequestCompleted(null, e);
         return;
     }
     LayerInformation info = new LayerInformation()
     {
         ID = featurelayerinfo.Id,
         DisplayField = featurelayerinfo.DisplayField,
         Name = featurelayerinfo.Name,
         PopUpsEnabled = false,
         LayerJson = json,
         FeatureLayer = featureLayer
     };
     Collection<ESRI.ArcGIS.Mapping.Core.FieldInfo> fieldInfos = new Collection<ESRI.ArcGIS.Mapping.Core.FieldInfo>();
     if (featurelayerinfo.Fields != null)
     {
         foreach (ESRI.ArcGIS.Client.Field field in featurelayerinfo.Fields)
         {
             if (FieldHelper.IsFieldFilteredOut(field.Type))
                 continue;
             ESRI.ArcGIS.Mapping.Core.FieldInfo fieldInfo = ESRI.ArcGIS.Mapping.Core.FieldInfo.FieldInfoFromField(featureLayer, field);
             fieldInfos.Add(fieldInfo);
         }
     }
     info.Fields = fieldInfos;
     if (fieldInfos.Count > 0)
         singleLayerRequestCompleted(info, e);
     else
         singleLayerRequestCompleted(null, e);
     #endregion
 }
        // Show a list of map services in the Listbox
        void webclient_OpenReadCompleted(object sender, ArcGISWebClient.OpenReadCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                    throw new Exception(e.Error.Message);

                // Deserialize response using classes defined by a data contract, included in this class definition below
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(MySvcs));
                MySvcs mysvcs = serializer.ReadObject(e.Result) as MySvcs;

                if (mysvcs.Services.Count == 0)
                    throw new Exception("No services returned");

                // Use LINQ to return all map services
                var mapSvcs = from s in mysvcs.Services
                              where s.Type == "MapServer"
                              select s;

                // If map services are returned, show the Listbox with items as map services
                if (mapSvcs.Count() > 0)
                {
                    MySvcTreeView.ItemsSource = mapSvcs;
                    MySvcTreeView.Visibility = System.Windows.Visibility.Visible;
                    NoMapServicesTextBlock.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    MySvcTreeView.Visibility = System.Windows.Visibility.Collapsed;
                    NoMapServicesTextBlock.Visibility = System.Windows.Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (e.Result != null)
                    e.Result.Close();
            }
        }
        private void wc_OpenReadCompleted(object sender, ArcGISWebClient.DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                Error = e.Error;
                if (LoadFailed != null)
                {
                    LoadFailed(this, null);
                }
                return;
            }

            // Make sure response is not empty
            string json = e.Result;

            if (string.IsNullOrEmpty(json))
            {
                Error = new Exception(Strings.EmptyResponse);
                if (LoadFailed != null)
                {
                    LoadFailed(this, null);
                }
                return;
            }

            // Check whether response contains error message
            if (json.StartsWith("{\"error\":", StringComparison.Ordinal))
            {
                try
                {
                    // Parse error message
                    ESRI.ArcGIS.Client.Utils.JavaScriptSerializer jss = new Client.Utils.JavaScriptSerializer();
                    Dictionary <string, object> dictionary            = jss.DeserializeObject(json) as
                                                                        Dictionary <string, object>;

                    bool errorRetrieved = false;
                    if (dictionary != null && dictionary.ContainsKey("error"))
                    {
                        Dictionary <string, object> errorInfo = dictionary["error"]
                                                                as Dictionary <string, object>;
                        if (errorInfo != null && errorInfo.ContainsKey("message") &&
                            errorInfo["message"] is string)
                        {
                            Error          = new Exception((string)errorInfo["message"]);
                            errorRetrieved = true;
                        }
                    }

                    if (!errorRetrieved)
                    {
                        Error = new Exception(Strings.UnexpectedServiceAccessError);
                    }
                }
                catch
                {
                    Error = new Exception(Strings.UnexpectedServiceAccessError);
                }

                if (LoadFailed != null)
                {
                    LoadFailed(this, null);
                }

                return;
            }

            //Inject __type information to help DataContractJsonSerializer determine which abstract class to
            //use when deserialing defaultValue property.
            int idx = json.IndexOf("\"dataType\"", 0, StringComparison.Ordinal);

            json = json.Replace("\"defaultValue\":{}", "\"defaultValue\":null");
            while (idx > -1)
            {
                string type = json.Substring(idx + 12,
                                             json.Substring(idx + 13).IndexOf("\"", StringComparison.Ordinal) + 1);
                int start  = json.IndexOf("\"defaultValue\":{", idx, StringComparison.Ordinal);
                int start2 = json.IndexOf("\"defaultValue\":[", idx, StringComparison.Ordinal);
                if (start2 > 0 && start2 < start)
                {
                    start = start2;
                }

                if (start > -1)
                {
                    string __type = null;
                    if (type == "GPFeatureRecordSetLayer")
                    {
                        __type = "\"__type\":\"GPFeatureRecordSetLayer:#ESRI.ArcGIS.Mapping.GP.MetaData\",";
                    }
                    else if (type == "GPLinearUnit")
                    {
                        __type = "\"__type\":\"GPLinearUnit:#ESRI.ArcGIS.Mapping.GP.MetaData\",";
                    }
                    else if (type == "GPDataFile")
                    {
                        __type = "\"__type\":\"GPDataFile:#ESRI.ArcGIS.Mapping.GP.MetaData\",";
                    }
                    if (__type != null)
                    {
                        json = json.Substring(0, start + 16) + __type + json.Substring(start + 16);
                    }
                }
                idx = json.IndexOf("\"dataType\"", idx + 10, StringComparison.Ordinal);
            }
            json = json.Replace("}\"Fields\"", "},\"Fields\""); //fix for bug in service
            Type[] types =
            {
                typeof(GPFeatureRecordSetLayer),
                typeof(GPLinearUnit),
                typeof(GPDataFile)
            };
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(GPMetaData), types);
            MemoryStream ms    = new MemoryStream(Encoding.Unicode.GetBytes(json));
            object       graph = serializer.ReadObject(ms);

            ServiceInfo = (GPMetaData)graph;

            ArcGISWebClient wc = new ArcGISWebClient()
            {
                ProxyUrl = e.UserState as string
            };

            wc.DownloadStringCompleted += GPServerInfoDownloaded;
            string gp = "/GPServer/";

            string url = ServiceEndpoint.AbsoluteUri.Substring(0,
                                                               ServiceEndpoint.AbsoluteUri.LastIndexOf(gp) + gp.Length - 1) + "?f=json";

            Uri uri = new Uri(url, UriKind.Absolute);

            wc.DownloadStringAsync(uri);
        }
        // When map service item selected in Listbox, choose appropriate type and add to the map
        void webclient_DownloadStringCompleted(object sender, ArcGISWebClient.DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                    throw new Exception(e.Error.Message);

                // Get the service url from the user object
                string svcUrl = e.UserState as string;

                //only available in Silverlight or .Net 4.5
                // Abstract JsonValue holds json response
                // JsonValue serviceInfo = JsonObject.Parse(e.Result);

                string[] jsonPairs = e.Result.Split(',');
                string mapCachePair = jsonPairs.Where(json => json.Contains("singleFusedMapCache")).FirstOrDefault();
                string[] mapCacheKeyAndValue = mapCachePair.Split(':');
                bool isTiledMapService = Boolean.Parse(mapCacheKeyAndValue[1]);

                // Use "singleFusedMapCache" to determine if a tiled or dynamic layer should be added to the map
                //bool isTiledMapService = Boolean.Parse(serviceInfo["singleFusedMapCache"].ToString());

                Layer lyr = null;

                if (isTiledMapService)
                    lyr = new ArcGISTiledMapServiceLayer() { Url = svcUrl };
                else
                    lyr = new ArcGISDynamicMapServiceLayer() { Url = svcUrl };

                if (lyr != null)
                {
                    lyr.InitializationFailed += (a, b) =>
                    {
                        throw new Exception(lyr.InitializationFailure.Message);
                    };
                    MyMap.Layers.Add(lyr);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private async void getLayerInfo(int layerID, object userState)
        {
            if (cancelSingleRequests)
                return;
            string layerUrl = string.Format("{0}/{1}?f=pjson", Url, layerID);
            ArcGISWebClient webClient = new ArcGISWebClient() { ProxyUrl = ProxyUrl };
            singleRequestWebClients.Add(webClient);

            ArcGISWebClient.DownloadStringCompletedEventArgs result =
                await webClient.DownloadStringTaskAsync(new Uri(layerUrl), userState);
            processLayerInfoResult(result);
        }
        /// <summary>
        /// Attempt to use application environment credentials to authenticate against the specified URL
        /// </summary>
        public static async Task<IdentityManager.Credential> TryExistingCredentials(string requestUrl, string proxyUrl = null)
        {
            if (string.IsNullOrEmpty(requestUrl) || UserManagement.Current.Credentials.Count == 0)
                return null;

            bool isPortalUrl = await requestUrl.IsFederatedWithPortal();
            string credentialUrl = requestUrl;

            // Get the token auth endpoint if the requested URL is not an ArcGIS Online/Portal URL
            if (!isPortalUrl)
                credentialUrl = await ArcGISServerDataSource.GetServicesDirectoryURL(requestUrl, proxyUrl);

            // Check whether there's already a credential for the url
            foreach (IdentityManager.Credential cred in UserManagement.Current.Credentials)
            {
                IdentityManager.Credential newCred = null;
                if (isPortalUrl && !string.IsNullOrEmpty(cred.Url) && await cred.Url.IsFederatedWithPortal())
                {
                    try
                    {
                        // If a portal credential already exists, try simply getting a new credential for the same portal
                        newCred = await IdentityManager.Current.GetCredentialTaskAsync(requestUrl, false); 
                    }
                    catch { }
                }
                else if (!string.IsNullOrEmpty(cred.Url) 
                && cred.Url.Equals(credentialUrl, StringComparison.OrdinalIgnoreCase))
                {
                    newCred = cred; // If a credential that matches the requested URL exists, try it                
                }
                else if (!string.IsNullOrEmpty(cred.UserName) && !string.IsNullOrEmpty(cred.Password))
                {
                    try
                    {
                        var options = new IdentityManager.GenerateTokenOptions() { ProxyUrl = proxyUrl };
                        // Try authenticating with the user name and password
                        newCred = await IdentityManager.Current.GenerateCredentialTaskAsync(credentialUrl, cred.UserName, cred.Password, options);
                    }
                    catch { } // Intentionally trying credentials that may not work, so swallow exceptions
                }

                if (newCred != null)
                {
                    // Try the original request URL with the new credential's token
                    string testUrl = requestUrl;

                    // Construct the URL with the token
                    if (testUrl.Contains("?"))
                        testUrl += string.Format("&token={0}&f=json", newCred.Token);
                    else
                        testUrl += string.Format("?token={0}&f=json", newCred.Token);
                    var wc = new ArcGISWebClient() { ProxyUrl = proxyUrl };
                    string result = null;
                    try
                    {
                        // Issue the request
                        result = await wc.DownloadStringTaskAsync(new Uri(testUrl));
                    }
                    catch
                    {
                        continue;
                    }

                    if (result != null)
                    {
                        try
                        {
                            // Check whether the response contains a JSON error
                            JsonObject o = (JsonObject)JsonObject.Parse(result);
                            if (o.ContainsKey("error"))
                            {
                                o = (JsonObject)o["error"];

                                // Check the error code
                                if (o.ContainsKey("code"))
                                {
                                    int statusCode = o["code"];
                                    // Server should return 401 Unauthorized, 403 Forbidden, 498 Invalid Token, or 499
                                    // Token Required if the token was insufficient authorization.  Other errors should 
                                    // mean that the resource was accessible with the token, but was just not used 
                                    // properly.
                                    if (statusCode == 401 || statusCode == 403 || statusCode == 498 || statusCode == 499) 
                                        continue;                               
                                }
                            }
                        }
                        catch
                        {
                            // could not parse response, so it's probably HTML or an image.  Assume the 
                            // credential is valid since these types of responses are generally not returned 
                            // by Portal/Server if there is an error.
                            return newCred;
                        }
                        return newCred;
                    }
                }
            }
            return null;
        }
Example #33
0
        /// <summary>
        /// Retrieve instance-level meatadata for the server
        /// </summary>
        public async Task<ServerInfo> GetServerInfo()
        {
            if (string.IsNullOrEmpty(Uri))
                throw new InvalidOperationException(Resources.Strings.ExceptionUriMustNotBeNull);

            string serverInfoUrl = Uri;

            // Try to construct the server info URL

            // First, find "/services" in the URL and extract the part leading up to it
            if (serverInfoUrl.EndsWith("/services", StringComparison.OrdinalIgnoreCase)
            || serverInfoUrl.EndsWith("/services/", StringComparison.OrdinalIgnoreCase))
                serverInfoUrl = serverInfoUrl.Substring(0, serverInfoUrl.Length - 9);
            else if (serverInfoUrl.IndexOf("/services/", StringComparison.OrdinalIgnoreCase) > -1)
                serverInfoUrl = serverInfoUrl.Substring(0, serverInfoUrl.IndexOf("/services/", StringComparison.OrdinalIgnoreCase));

            // Second, append "/info" to the URL
            if (!serverInfoUrl.EndsWith("/info", StringComparison.OrdinalIgnoreCase)
                && !serverInfoUrl.EndsWith("/info/", StringComparison.OrdinalIgnoreCase))
            {
                if (!serverInfoUrl.EndsWith("/", StringComparison.Ordinal))
                    serverInfoUrl += "/";
                serverInfoUrl += "info";
            }

            // Add the query parameters to the URL and convert it to a URI
            UriBuilder builder = new UriBuilder(serverInfoUrl);
            builder.Query = Utils.GetQueryParameters(serverInfoUrl);
            finalUrl = builder.Uri;

            if (webClient == null)
                webClient = new ArcGISWebClient();
            webClient.ProxyUrl = ProxyUrl;

            string json = null;
            try
            {
                // Download the server metadata
                json = await webClient.DownloadStringTaskAsync(finalUrl);
            }
            catch (Exception exception)
            {
                throw exception;
            }

            // Check the result for cancellation or error

            if (string.IsNullOrEmpty(json))
                throw new Exception(Strings.ExceptionEmptyResponse);

            Exception ex = Utils.CheckJsonForException(json);

            if (ex != null)
                throw ex;

            // Deserialize the result
            ServerInfo info = null;
            try
            {
                byte[] bytes = Encoding.Unicode.GetBytes(json);
                using (MemoryStream memoryStream = new MemoryStream(bytes))
                {
                    DataContractJsonSerializer dataContractJsonSerializer = 
                        new DataContractJsonSerializer(typeof(ServerInfo));
                    info = dataContractJsonSerializer.ReadObject(memoryStream) as ServerInfo;
                    memoryStream.Close();
                }
            }
            catch (Exception exception)
            {
                throw new Exception(Strings.ExceptionCouldNotReadServerInfo, exception);
            }

            // Apply the URL used to retrieve the metadata to the ServerInfo instance
            if (info != null)
            {
                info.Url = finalUrl.ToString();
                info.BaseUrl = serverInfoUrl;
                if (!string.IsNullOrEmpty(ProxyUrl))
                    info.ProxyUrl = ProxyUrl;
            }

            // Return the ServerInfo
            return info;
        }        
 private void GetResultLayer(JobResult jobResult, string taskUrl, string outputName, object userToken = null)
 {
     var client = new ArcGISWebClient();
     client.DownloadStringCompleted += (a, b) =>
     {
         var json = b.Result;
         var jObject = JObject.Parse(json);
         var fsJson = jObject["value"]["featureCollection"].ToString();
         OnAnalysisCompleted(new AnalysisEventArgs(FeatureSet.FromJson(fsJson), userToken));
     };
     var parameters = new Dictionary<string, string>();
     parameters["f"] = "json";
     parameters["token"] = Token;
     parameters["returnType"] = "data";
     client.DownloadStringAsync(new Uri(string.Format("{0}/jobs/{1}/results/{2}", taskUrl, jobResult.ID, outputName)), parameters);
 }
Example #35
0
        private void processResult(ArcGISWebClient.DownloadStringCompletedEventArgs e) 
        {
            if (e.Cancelled)
                return;

            if (e.Error != null)
            {
                OnGetCatalogFailed(new ExceptionEventArgs(e.Error, e.UserState));
                return;
            }
            if (string.IsNullOrEmpty(e.Result))
            {
                OnGetCatalogFailed(new ExceptionEventArgs(new Exception(Resources.Strings.ExceptionEmptyResponse), e.UserState));                                        
                return;
            }

            string json = e.Result;
            Exception exception = Utils.CheckJsonForException(json);
            if (exception != null)
            {
                OnGetCatalogFailed(new ExceptionEventArgs(exception, e.UserState));
                return;
            }
            Catalog catalog = null;
            try
            {
                byte[] bytes = Encoding.Unicode.GetBytes(json);
                using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(bytes))
                {
                    DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(Catalog));
                    catalog = dataContractJsonSerializer.ReadObject(memoryStream) as Catalog;
                    memoryStream.Close();
                }
            }
            catch(Exception ex)
            {
                OnGetCatalogFailed(new ExceptionEventArgs(ex, e.UserState));   
                return; 
            }

            if (catalog == null) 
            { 
                OnGetCatalogFailed(new ExceptionEventArgs(new Exception(Resources.Strings.ExceptionUnableToDeserializeCatalog), e.UserState));   
                return; 
            }

            if (catalog.Folders == null && catalog.Services == null)
            {
                OnGetCatalogFailed(new ExceptionEventArgs(new Exception(Resources.Strings.ExceptionNoServicesFoundOnServer), e.UserState));
                return; 
            }

            List<Resource> childResources = new List<Resource>();
            List<Resource> resources = Utility.GetResources(catalog, Filter, Uri, ProxyUrl, lockObj);
            int childCount = 0;
            int totalChildCount = resources != null ? resources.Count : 0;

            // If the catalog has any folders, add them to the returned list first
            if (catalog.Folders != null)
            {
                totalChildCount += catalog.Folders.Count;
                foreach (string folderName in catalog.Folders)
                {
                    Folder folder = new Folder(string.Format("{0}/{1}", Uri, folderName), ProxyUrl)
                    {
                        Filter = Filter,
                    };
                    folder.GetServicesInFolderFailed += (o, args) =>
                    {
                        // Remove the folder
                        lock (lockObj)
                        {
                            childResources.Remove(args.UserState as Resource);
                        }

                        childCount++;
                        if (childCount >= totalChildCount)
                            OnGetCatalogCompleted(new GetCatalogCompletedEventArgs() { ChildResources = childResources, UserState = e.UserState });
                    };
                    folder.GetServicesInFolderCompleted += (o, args) =>
                    {
                        int nestedChildTotalCount = args.ChildResources.Count();
                        if (nestedChildTotalCount == 0)
                        {
                            // Remove the folder
                            lock (lockObj)
                            {
                                childResources.Remove(args.UserState as Resource);
                            }
                        }

                        childCount++;
                        if (childCount >= totalChildCount)
                            OnGetCatalogCompleted(new GetCatalogCompletedEventArgs() { ChildResources = childResources, UserState = e.UserState });
                    };

                    // Add the folder before validation so that the catalog order is preserved.  Folder will be
                    // removed if found to be invalid.
                    Resource folderResource = new Resource()
                    {
                        DisplayName = folderName,
                        Url = string.Format("{0}/{1}", Uri, folderName),
                        ProxyUrl = ProxyUrl,
                        ResourceType = ResourceType.Folder,
                    };
                    lock (lockObj)
                    {
                        childResources.Add(folderResource);
                    }
                    folder.GetServices(folderResource);
                }
            }

            // Remove any undesired services due to filtering
            foreach (Resource childRes in resources)
            {
                IService childService = ServiceFactory.CreateService(childRes.ResourceType, childRes.Url, childRes.ProxyUrl);
                if (childService != null)
                {
                    // Determine if filtering requires detailed information about the server and only make async call to
                    // obtain detailed info if true.
                    if (childService.IsServiceInfoNeededToApplyThisFilter(Filter))
                    {
                        childService.ServiceDetailsDownloadFailed += (o, args) =>
                        {
                            // Remove resource
                            lock (lockObj)
                            {
                                childResources.Remove(args.UserState as Resource);
                            }

                            childCount++;
                            if (childCount >= totalChildCount)
                                OnGetCatalogCompleted(new GetCatalogCompletedEventArgs() { ChildResources = childResources, UserState = e.UserState });
                        };
                        childService.ServiceDetailsDownloadCompleted += (o, args) =>
                        {
                            IService service = o as IService;
                            if (service == null || !service.IsFilteredIn(Filter)) // check if service is filtered
                            {
                                // Remove resource
                                lock (lockObj)
                                {
                                    childResources.Remove(args.UserState as Resource);
                                }
                            }
                            childCount++;
                            if (childCount >= totalChildCount)
                                OnGetCatalogCompleted(new GetCatalogCompletedEventArgs() { ChildResources = childResources, UserState = e.UserState });
                        };

                        // Add the service before validation so that the catalog order is preserved.  Service will be
                        // removed if found to be invalid.
                        Resource childResource = new Resource()
                        {
                            DisplayName = childRes.DisplayName,
                            Url = childService.Uri,
                            ProxyUrl = ProxyUrl,
                            ResourceType = childService.Type
                        };
                        lock (lockObj)
                        {
                            childResources.Add(childResource);
                        }
                        childService.GetServiceDetails(childResource);
                    }
                    else
                    {
                        // Apply filtering using basic information, not detailed information
                        if (childService != null && childService.IsFilteredIn(Filter))
                        {
                            lock (lockObj)
                            {
                                childResources.Add(new Resource()
                                {
                                    DisplayName = childRes.DisplayName,
                                    Url = childService.Uri,
                                    ProxyUrl = ProxyUrl,
                                    ResourceType = childService.Type
                                });
                            }
                        }
                        ++childCount;
                    }
                }
            }

            if (childCount >= totalChildCount)
                OnGetCatalogCompleted(new GetCatalogCompletedEventArgs() { ChildResources = childResources, UserState = e.UserState });
        }
        private async void getLayerInfo(int layerID, object userState)
        {
            if (cancelSingleRequests)
                return;
            string layerUrl = string.Format("{0}/{1}?f=pjson", Url, layerID);
            ArcGISWebClient webClient = new ArcGISWebClient();
            singleRequestWebClients.Add(webClient);

            Uri uri = ESRI.ArcGIS.Mapping.Core.Utility.CreateUriWithProxy(ProxyUrl, layerUrl);
            ArcGISWebClient.DownloadStringCompletedEventArgs result =
                await webClient.DownloadStringTaskAsync(uri, userState);
            processLayerInfoResult(result);
        }
        private void processPre10LayerInfoResult(ArcGISWebClient.DownloadStringCompletedEventArgs e)
        {
            #region Parse layer ids from json
            if (e.Cancelled)
                return;
            if (e.Error != null)
            {
                onLayerInfosCompleted(new LayerInfosEventArgs() { LayerInfos = null, UserState = e });
                return;
            }
            string json = null;
            try
            {
                json = e.Result;
            }
            catch (Exception exception)
            {
                if (exception != null)
                {
                    onLayerInfosCompleted(new LayerInfosEventArgs() { LayerInfos = null, UserState = e });
                    return;
                }
            }
            Exception ex = ESRI.ArcGIS.Mapping.DataSources.Utils.CheckJsonForException(json);
            if (ex != null)
            {
                onLayerInfosCompleted(new LayerInfosEventArgs() { LayerInfos = null, UserState = e });
                return;
            }

            MapServiceInfo mapServiceInfo = JsonSerializer.Deserialize<MapServiceInfo>(json);
            if (mapServiceInfo == null || mapServiceInfo.Layers == null)
            {
                onLayerInfosCompleted(new LayerInfosEventArgs() { LayerInfos = null, UserState = e });
                return;
            }
            singleRequestLayerIds = new List<int>();
            foreach (MapServiceLayerInfo layer in mapServiceInfo.Layers)
            {
                LayerInformation info = new LayerInformation()
                {
                    ID = layer.ID,
                    Name = layer.Name,
                    PopUpsEnabled = false
                };
                if (layer.SubLayerIds == null || layer.SubLayerIds.Length < 1)
                {
                    singleRequestLayerIds.Add(layer.ID);
                }
            }
            if (singleRequestLayerIds.Count < 1)
            {
                onLayerInfosCompleted(new LayerInfosEventArgs() { LayerInfos = null, UserState = e });
            }
            else
            {
                singleRequestLayerInfos = new List<LayerInformation>();
                singleRequestWebClients = new List<ArcGISWebClient>();
                cancelSingleRequests = false;
                pendingRequests = singleRequestLayerIds.Count;
                foreach (int id in singleRequestLayerIds)
                {
                    getLayerInfo(id, e.UserState);
                }
            }
            #endregion
        }
        private void wc_OpenReadCompleted(object sender, ArcGISWebClient.DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                Error = e.Error;
                if (LoadFailed != null)
                    LoadFailed(this, null);
                return;
            }

            // Make sure response is not empty
            string json = e.Result;
            if (string.IsNullOrEmpty(json))
            {
                Error = new Exception(Strings.EmptyResponse);
                if (LoadFailed != null)
                    LoadFailed(this, null);
                return;
            }

            // Check whether response contains error message
            if (json.StartsWith("{\"error\":", StringComparison.Ordinal))
            {
                try
                {
                    // Parse error message
                    ESRI.ArcGIS.Client.Utils.JavaScriptSerializer jss = new Client.Utils.JavaScriptSerializer();
                    Dictionary<string, object> dictionary = jss.DeserializeObject(json) as 
                        Dictionary<string, object>;

                    bool errorRetrieved = false;
                    if (dictionary != null && dictionary.ContainsKey("error"))
                    {
                        Dictionary<string, object> errorInfo = dictionary["error"] 
                            as Dictionary<string, object>;
                        if (errorInfo != null && errorInfo.ContainsKey("message")
                        && errorInfo["message"] is string)
                        {
                            Error = new Exception((string)errorInfo["message"]);
                            errorRetrieved = true;
                        }
                    }

                    if (!errorRetrieved)
                        Error = new Exception(Strings.UnexpectedServiceAccessError);
                }
                catch
                {
                    Error = new Exception(Strings.UnexpectedServiceAccessError);
                }

                if (LoadFailed != null)
                    LoadFailed(this, null);

                return;
            }

            //Inject __type information to help DataContractJsonSerializer determine which abstract class to
            //use when deserialing defaultValue property.
            int idx = json.IndexOf("\"dataType\"", 0, StringComparison.Ordinal);
            json = json.Replace("\"defaultValue\":{}", "\"defaultValue\":null");
            while (idx > -1)
            {
                string type = json.Substring(idx + 12,
                    json.Substring(idx + 13).IndexOf("\"", StringComparison.Ordinal) + 1);
                int start = json.IndexOf("\"defaultValue\":{", idx, StringComparison.Ordinal);
                int start2 = json.IndexOf("\"defaultValue\":[", idx, StringComparison.Ordinal);
                if (start2 > 0 && start2 < start)
                    start = start2;

                if (start > -1)
                {
                    string __type = null;
                    if (type == "GPFeatureRecordSetLayer")
                    {
                        __type = "\"__type\":\"GPFeatureRecordSetLayer:#ESRI.ArcGIS.Mapping.GP.MetaData\",";
                    }
                    else if (type == "GPLinearUnit")
                    {
                        __type = "\"__type\":\"GPLinearUnit:#ESRI.ArcGIS.Mapping.GP.MetaData\",";
                    }
                    else if (type == "GPDataFile")
                    {
                        __type = "\"__type\":\"GPDataFile:#ESRI.ArcGIS.Mapping.GP.MetaData\",";
                    }
                    if (__type != null)
                        json = json.Substring(0, start + 16) + __type + json.Substring(start + 16);
                }
                idx = json.IndexOf("\"dataType\"", idx + 10, StringComparison.Ordinal);
            }
            json = json.Replace("}\"Fields\"", "},\"Fields\""); //fix for bug in service
            Type[] types = {
						typeof(GPFeatureRecordSetLayer), 
						typeof(GPLinearUnit),
						typeof(GPDataFile)
					};
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(GPMetaData), types);
            MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
            object graph = serializer.ReadObject(ms);
            ServiceInfo = (GPMetaData)graph;

            ArcGISWebClient wc = new ArcGISWebClient() { ProxyUrl = e.UserState as string };
            wc.DownloadStringCompleted += GPServerInfoDownloaded;
            string gp = "/GPServer/";

            string url = ServiceEndpoint.AbsoluteUri.Substring(0, 
                ServiceEndpoint.AbsoluteUri.LastIndexOf(gp) + gp.Length - 1) + "?f=json";

            Uri uri = new Uri(url, UriKind.Absolute);
            wc.DownloadStringAsync(uri);
        }
 /// <summary>
 /// Figures out which points fall within each polygon's area, 
 /// calculates statistics about all points in the polygon and assigns to the area.
 /// </summary>
 /// <param name="parameter">input parameter to AggregatePoints</param>
 /// <param name="userToken">user token</param>
 public void AggregatePoints(AggregatePointsParameter parameter, object userToken = null)
 {
     var aggregateTaskUrl = string.Format("{0}/AggregatePoints", ServiceUrl);
     var client = new ArcGISWebClient();
     client.DownloadStringCompleted += (s, e) =>
     {
         if (e.Cancelled)
             OnAnalysisCompleted(new AnalysisEventArgs(new OperationCanceledException(), e.UserState));
         else if (e.Error != null)
             OnAnalysisCompleted(new AnalysisEventArgs(e.Error, e.UserState));
         else if (e.Result != null)
         {
             var json = e.Result;
             var serviceException = ServiceException.FromJson(json);
             if (serviceException != null)
                 OnAnalysisCompleted(new AnalysisEventArgs(serviceException, e.UserState));
             else
             {
                 var jobResult = JobResult.FromJson(json);
                 if (jobResult.Status == esriJobStatus.esriJobSubmitted)
                     CheckJobStatus(jobResult, aggregateTaskUrl, "AggregatedLayer", e.UserState);
             }
         }
     };
     client.DownloadStringAsync(new Uri(string.Format("{0}/submitJob", aggregateTaskUrl)), parameter.GetParameters(Token), ArcGISWebClient.HttpMethods.Auto, userToken);
 }
        private void processResult(ArcGISWebClient.DownloadStringCompletedEventArgs e) 
        {
            if (e.Cancelled)
                return;

            if (e.Error != null)
            {
                OnGetGroupLayerDetailsFailed(new ExceptionEventArgs(e.Error, e.UserState));
                return;
            }

            if (string.IsNullOrEmpty(e.Result))
            {
                OnGetGroupLayerDetailsFailed(new ExceptionEventArgs(new Exception(Resources.Strings.ExceptionEmptyResponse), e.UserState));
                return;
            }

            LayerDetails layerDetails;
            try
            {
                string json = e.Result;
                Exception exception = Utils.CheckJsonForException(json);
                if (exception != null)
                {
                    OnGetGroupLayerDetailsFailed(new ExceptionEventArgs(exception, e.UserState));
                    return;
                }
                byte[] bytes = Encoding.Unicode.GetBytes(json);
                using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(bytes))
                {
                    DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(LayerDetails));
                    layerDetails = dataContractJsonSerializer.ReadObject(memoryStream) as LayerDetails;
                    memoryStream.Close();
                }

                if (layerDetails == null)
                {
                    OnGetGroupLayerDetailsFailed(new ExceptionEventArgs(new Exception(Resources.Strings.ExceptionUnableToDeserializeResponse), e.UserState));
                    return;
                }
            }
            catch (Exception ex)
            {
                OnGetGroupLayerDetailsFailed(new ExceptionEventArgs(ex, e.UserState));
                return;
            }

            List<Resource> childResources = new List<Resource>();
            if (layerDetails.SubLayers != null)
            {
                int totalSubLayerCount = layerDetails.SubLayers.Count;
                int subLayerCount = 0;                
                string parentMapServerUrl = Uri.Substring(0, Uri.IndexOf("MapServer", StringComparison.OrdinalIgnoreCase)+9);
                foreach (SubLayer subLayer in layerDetails.SubLayers)
                {       
                    // In order to determine whether a sub layer is a group layer or not, we need to make more requests
                    string subLayerUrl = string.Format("{0}/{1}", parentMapServerUrl, subLayer.ID);
                    Layer lyr = new Layer(subLayerUrl, ProxyUrl);
                    lyr.GetLayerDetailsFailed += (o, args) =>{

                        // Remove layer
                        childResources.Remove(args.UserState as Resource);

                        subLayerCount++;
                        if(subLayerCount >= totalSubLayerCount)
                            OnGetGroupLayerDetailsCompleted(new GetLayerDetailsCompletedEventArgs() { ChildResources = childResources, LayerDetails = layerDetails, UserState = e.UserState });
                    };
                    lyr.GetLayerDetailsCompleted += (o,args) =>{
                        subLayerCount++;
                        if (args.LayerDetails == null)
                        {
                            childResources.Remove(args.UserState as Resource);
                            return;
                        }

                        Resource childResource = args.UserState as Resource;
                        childResource.ResourceType = args.LayerDetails.Type == "Group Layer" ? ResourceType.GroupLayer : ResourceType.Layer;
                        childResource.DisplayName = args.LayerDetails.Name;
                        childResource.Url = string.Format("{0}/{1}", parentMapServerUrl, args.LayerDetails.ID);
                        childResource.ProxyUrl = ProxyUrl;
                        childResource.Tag = args.LayerDetails.ID;

                        if(subLayerCount >= totalSubLayerCount)
                            OnGetGroupLayerDetailsCompleted(new GetLayerDetailsCompletedEventArgs() { ChildResources = childResources, LayerDetails = layerDetails, UserState = e.UserState });
                    };

                    // Add layer before validating to preserve catalog order.  Layer will be removed if validation
                    // fails.
                    Resource child = new Resource();
                    childResources.Add(child);

                    lyr.GetLayerDetails(child);
                }
            }
            else
            {
                OnGetGroupLayerDetailsCompleted(new GetLayerDetailsCompletedEventArgs() { ChildResources = childResources, LayerDetails = layerDetails, UserState = e.UserState });
            }
        }
Example #41
0
        /// <summary>
        /// Retrieve instance-level meatadata for the server
        /// </summary>
        public async Task <ServerInfo> GetServerInfo()
        {
            if (string.IsNullOrEmpty(Uri))
            {
                throw new InvalidOperationException(Resources.Strings.ExceptionUriMustNotBeNull);
            }

            string serverInfoUrl = Uri;

            // Try to construct the server info URL

            // First, find "/services" in the URL and extract the part leading up to it
            if (serverInfoUrl.EndsWith("/services", StringComparison.OrdinalIgnoreCase) ||
                serverInfoUrl.EndsWith("/services/", StringComparison.OrdinalIgnoreCase))
            {
                serverInfoUrl = serverInfoUrl.Substring(0, serverInfoUrl.Length - 9);
            }
            else if (serverInfoUrl.IndexOf("/services/", StringComparison.OrdinalIgnoreCase) > -1)
            {
                serverInfoUrl = serverInfoUrl.Substring(0, serverInfoUrl.IndexOf("/services/", StringComparison.OrdinalIgnoreCase));
            }

            // Second, append "/info" to the URL
            if (!serverInfoUrl.EndsWith("/info", StringComparison.OrdinalIgnoreCase) &&
                !serverInfoUrl.EndsWith("/info/", StringComparison.OrdinalIgnoreCase))
            {
                if (!serverInfoUrl.EndsWith("/", StringComparison.Ordinal))
                {
                    serverInfoUrl += "/";
                }
                serverInfoUrl += "info";
            }

            // Add the query parameters to the URL and convert it to a URI
            UriBuilder builder = new UriBuilder(serverInfoUrl);

            builder.Query = Utils.GetQueryParameters(serverInfoUrl);
            finalUrl      = builder.Uri;

            if (webClient == null)
            {
                webClient = new ArcGISWebClient();
            }
            webClient.ProxyUrl = ProxyUrl;

            string json = null;

            try
            {
                // Download the server metadata
                json = await webClient.DownloadStringTaskAsync(finalUrl);
            }
            catch (Exception exception)
            {
                throw exception;
            }

            // Check the result for cancellation or error

            if (string.IsNullOrEmpty(json))
            {
                throw new Exception(Strings.ExceptionEmptyResponse);
            }

            Exception ex = Utils.CheckJsonForException(json);

            if (ex != null)
            {
                throw ex;
            }

            // Deserialize the result
            ServerInfo info = null;

            try
            {
                byte[] bytes = Encoding.Unicode.GetBytes(json);
                using (MemoryStream memoryStream = new MemoryStream(bytes))
                {
                    DataContractJsonSerializer dataContractJsonSerializer =
                        new DataContractJsonSerializer(typeof(ServerInfo));
                    info = dataContractJsonSerializer.ReadObject(memoryStream) as ServerInfo;
                    memoryStream.Close();
                }
            }
            catch (Exception exception)
            {
                throw new Exception(Strings.ExceptionCouldNotReadServerInfo, exception);
            }

            // Apply the URL used to retrieve the metadata to the ServerInfo instance
            if (info != null)
            {
                info.Url     = finalUrl.ToString();
                info.BaseUrl = serverInfoUrl;
                if (!string.IsNullOrEmpty(ProxyUrl))
                {
                    info.ProxyUrl = ProxyUrl;
                }
            }

            // Return the ServerInfo
            return(info);
        }
Example #42
0
 /// <summary>
 /// Opens a readable stream to the specified resource
 /// </summary>
 public static async Task <ArcGISWebClient.OpenReadCompletedEventArgs> OpenReadTaskAsync(
     this ArcGISWebClient client, Uri uri, object userState = null)
 {
     return(await client.OpenReadTaskAsync(uri, null, ArcGISWebClient.HttpMethods.Auto, userState));
 }
Example #43
0
        private void processResult(ArcGISWebClient.DownloadStringCompletedEventArgs e) 
        {
            if (e.Cancelled)
                return;

            if (e.Error != null)
            {
                OnGetServicesInFolderFailed(new ExceptionEventArgs(e.Error, e.UserState));
                return;
            }
            if (string.IsNullOrEmpty(e.Result))
            {
                OnGetServicesInFolderFailed(new ExceptionEventArgs(new Exception(Resources.Strings.ExceptionEmptyResponse), e.UserState));
                return;
            }

            Catalog catalog = null;
            try
            {                
                string json = e.Result;
                byte[] bytes = Encoding.Unicode.GetBytes(json);
                using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(bytes))
                {
                    DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(Catalog));
                    catalog = dataContractJsonSerializer.ReadObject(memoryStream) as Catalog;
                    memoryStream.Close();
                }

                if (catalog == null)
                {
                    OnGetServicesInFolderFailed(new ExceptionEventArgs(new Exception(Resources.Strings.ExceptionUnableToDeserializeResponse), e.UserState));
                    return;
                }

                bool retrieveChildServices = (Filter & Filter.CachedResources) == Filter.CachedResources;
                List<Resource> resources = Utility.GetResources(catalog, Filter, Uri, ProxyUrl);
                if (retrieveChildServices && resources.Count > 0)
                {
                    int childCount = 0;
                    List<Resource> childResources = new List<Resource>();
                    foreach (Resource childResource in resources)
                    {
                        IService service = ServiceFactory.CreateService(childResource.ResourceType, childResource.Url, childResource.ProxyUrl);
                        if (service != null)
                        {
                            service.ServiceDetailsDownloadFailed += (o, args) =>
                            {
                                // Remove service
                                childResources.Remove(args.UserState as Resource);

                                childCount++;
                                if (childCount >= resources.Count)
                                    OnGetServicesInFolderCompleted(new GetServicesInFolderCompletedEventArgs() { ChildResources = childResources, UserState = e.UserState });
                            };
                            service.ServiceDetailsDownloadCompleted += (o, args) =>
                            {
                                childCount++;
                                IService ser = o as IService;
                                if (ser == null || !ser.IsFilteredIn(Filter))
                                {
                                    // Remove service
                                    childResources.Remove(args.UserState as Resource);
                                }
                                if (childCount >= resources.Count)
                                    OnGetServicesInFolderCompleted(new GetServicesInFolderCompletedEventArgs() { ChildResources = childResources, UserState = e.UserState });
                            };

                            // Add the service before validation so that the catalog order is preserved.  Service will be
                            // removed if found to be invalid.
                            Resource child = new Resource()
                            {
                                DisplayName = childResource.DisplayName,
                                Url = service.Uri,
                                ProxyUrl = ProxyUrl,
                                ResourceType = service.Type,
                            };
                            childResources.Add(child);

                            service.GetServiceDetails(child);
                        }
                    }
                }
                else
                {
                    OnGetServicesInFolderCompleted(new GetServicesInFolderCompletedEventArgs() { ChildResources = resources, UserState = e.UserState });
                }
            }
            catch(Exception ex)
            {
                OnGetServicesInFolderFailed(new ExceptionEventArgs(ex, e.UserState));
            }
        }
        /// <summary>
        /// Attempt to use application environment credentials to authenticate against the specified URL
        /// </summary>
        public static async Task <IdentityManager.Credential> TryExistingCredentials(string requestUrl, string proxyUrl = null)
        {
            if (string.IsNullOrEmpty(requestUrl) || UserManagement.Current.Credentials.Count == 0)
            {
                return(null);
            }

            bool isPortalUrl = await requestUrl.IsFederatedWithPortal();

            string credentialUrl = requestUrl;

            // Get the token auth endpoint if the requested URL is not an ArcGIS Online/Portal URL
            if (!isPortalUrl)
            {
                credentialUrl = await ArcGISServerDataSource.GetServicesDirectoryURL(requestUrl, proxyUrl);
            }

            // Check whether there's already a credential for the url
            foreach (IdentityManager.Credential cred in UserManagement.Current.Credentials)
            {
                IdentityManager.Credential newCred = null;
                if (isPortalUrl && !string.IsNullOrEmpty(cred.Url) && await cred.Url.IsFederatedWithPortal())
                {
                    try
                    {
                        // If a portal credential already exists, try simply getting a new credential for the same portal
                        newCred = await IdentityManager.Current.GetCredentialTaskAsync(requestUrl, false);
                    }
                    catch { }
                }
                else if (!string.IsNullOrEmpty(cred.Url) &&
                         cred.Url.Equals(credentialUrl, StringComparison.OrdinalIgnoreCase))
                {
                    newCred = cred; // If a credential that matches the requested URL exists, try it
                }
                else if (!string.IsNullOrEmpty(cred.UserName) && !string.IsNullOrEmpty(cred.Password))
                {
                    try
                    {
                        var options = new IdentityManager.GenerateTokenOptions()
                        {
                            ProxyUrl = proxyUrl
                        };
                        // Try authenticating with the user name and password
                        newCred = await IdentityManager.Current.GenerateCredentialTaskAsync(credentialUrl, cred.UserName, cred.Password, options);
                    }
                    catch { } // Intentionally trying credentials that may not work, so swallow exceptions
                }

                if (newCred != null)
                {
                    // Try the original request URL with the new credential's token
                    string testUrl = requestUrl;

                    // Construct the URL with the token
                    if (testUrl.Contains("?"))
                    {
                        testUrl += string.Format("&token={0}&f=json", newCred.Token);
                    }
                    else
                    {
                        testUrl += string.Format("?token={0}&f=json", newCred.Token);
                    }
                    var wc = new ArcGISWebClient()
                    {
                        ProxyUrl = proxyUrl
                    };
                    string result = null;
                    try
                    {
                        // Issue the request
                        result = await wc.DownloadStringTaskAsync(new Uri(testUrl));
                    }
                    catch
                    {
                        continue;
                    }

                    if (result != null)
                    {
                        try
                        {
                            // Check whether the response contains a JSON error
                            JsonObject o = (JsonObject)JsonObject.Parse(result);
                            if (o.ContainsKey("error"))
                            {
                                o = (JsonObject)o["error"];

                                // Check the error code
                                if (o.ContainsKey("code"))
                                {
                                    int statusCode = o["code"];
                                    // Server should return 401 Unauthorized, 403 Forbidden, 498 Invalid Token, or 499
                                    // Token Required if the token was insufficient authorization.  Other errors should
                                    // mean that the resource was accessible with the token, but was just not used
                                    // properly.
                                    if (statusCode == 401 || statusCode == 403 || statusCode == 498 || statusCode == 499)
                                    {
                                        continue;
                                    }
                                }
                            }
                        }
                        catch
                        {
                            // could not parse response, so it's probably HTML or an image.  Assume the
                            // credential is valid since these types of responses are generally not returned
                            // by Portal/Server if there is an error.
                            return(newCred);
                        }
                        return(newCred);
                    }
                }
            }
            return(null);
        }
        private void BrowseButton_Click(object sender, RoutedEventArgs e)
        {
            // Call the ShowDialog method to show the dialog box.
            bool? userClickedOK = openFileDialog.ShowDialog();

            if (userClickedOK == true)
            {
                // Open the selected file to read.
                System.IO.FileInfo file = openFileDialog.File;

                // Uri to the ArcGIS Portal API generate operation.
                // Reference documentation available here: http://www.arcgis.com/apidocs/rest/generate.html
                Uri address = new Uri("http://www.arcgis.com/sharing/rest/content/features/generate");

                // Get the file contents for the local file
                FileStream fs = file.OpenRead();

                // Create ArcGISWebClient.StreamContent instance
                ArcGISWebClient.StreamContent streamContent = new ArcGISWebClient.StreamContent()
                {
                    Name = "file",
                    Filename = file.Name,
                    Stream = fs,
                    ContentType = "application/zip"
                };

                // Create a list of stream content to POST
                IList<ArcGISWebClient.StreamContent> filestream = new List<ArcGISWebClient.StreamContent>();
                filestream.Add(streamContent);

                // Create dictionary to store parameter to POST
                Dictionary<string, string> postParameters = new Dictionary<string, string>();

                // A class created to store publish parameters for the generate operation
                GenerateFeaturesParams param = new GenerateFeaturesParams()
                {
                    name = file.Name.Substring(0, file.Name.LastIndexOf(".")),
                    maxRecordCount = 1000,
                    generalize = false,
                    reducePrecision = true,
                    targetSR = MyMap.SpatialReference
                };

                // Must specify the output type (json) the file type (shapefile) and the publish parameters
                postParameters.Add("f", "json");
                postParameters.Add("filetype", "shapefile");
                postParameters.Add("publishParameters", SerializeToJsonString(param));

                // Url to the generate operation, part of the ArcGIS Portal REST API (http://www.arcgis.com/apidocs/rest/generate.html)
                string postURL = "http://www.arcgis.com/sharing/rest/content/features/generate";

                // Use ArcGISWebClient POST shapefile to the ArcGIS Portal generate operation.  The generate operation requires a file to be passed
                // in a multi-part post request.
                ArcGISWebClient agsWebClient = new ArcGISWebClient();
                agsWebClient.PostMultipartCompleted += (a, b) =>
                {
                    if (b.Error == null)
                    {
                        try
                        {
                            // Use the the generic JsonValue to handle dynamic json content.
                            // In this case, generate always returns a "featureCollection" object which contains
                            // a "layers" array with one feature layer.
                            JsonValue featureCollection = JsonValue.Load(b.Result);
                            string layer = featureCollection["featureCollection"]["layers"][0].ToString();

                            FeatureLayer featureLayer = FeatureLayer.FromJson(layer);

                            if (featureLayer != null)
                            {
                                // Add the feature layer to the map and zoom to it
                                MyMap.Layers.Add(featureLayer);
                                MyMap.ZoomTo(featureLayer.FullExtent.Expand(1.25));
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "FeatureLayer creation failed", MessageBoxButton.OK);
                        }
                    }
                };
                agsWebClient.PostMultipartAsync(new Uri(postURL), postParameters, filestream, null);
            }
        }