Пример #1
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));
            }
        }
        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);
            }
        }
        // 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);
            }
        }
        // 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);
            }
        }
        private void processResult(ArcGISWebClient.DownloadStringCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                return;
            }
            ServiceDetailsDownloadCompletedEventArgs eventArgs = e.UserState as ServiceDetailsDownloadCompletedEventArgs;

            if (e.Error != null)
            {
                base.OnServiceDetailsDownloadCompleted(eventArgs);
                return;
            }

            string    json = e.Result;
            Exception ex   = Utils.CheckJsonForException(json);

            if (ex != null) // if the service is pre-10.x then it doesn't support /layers operation
            {
                base.OnServiceDetailsDownloadCompleted(eventArgs);
                return;
            }

            try
            {
                AllLayersResponse response = JsonSerializer.Deserialize <AllLayersResponse>(e.Result);
                _layersInService = response.Layers;
                if (_layersInService != null)
                {
                    _notSupportedLayerIds = new List <int>();
                    foreach (MapServiceLayerInfo mapServiceLayerInfo in _layersInService)
                    {
                        if (Utility.RasterLayer.Equals(mapServiceLayerInfo.Type) || Utility.ImageServerLayer.Equals(mapServiceLayerInfo.Type))
                        {
                            _notSupportedLayerIds.Add(mapServiceLayerInfo.ID);
                        }
                    }
                }
            }
            catch (Exception)
            {
                // Ok to swallow
            }
            base.OnServiceDetailsDownloadCompleted(eventArgs);
        }
        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);
        }
        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);
        }
Пример #8
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));
            }
        }
        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);
            }
        }
Пример #10
0
        private void processResult(ArcGISWebClient.DownloadStringCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                return;
            }

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

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

            try
            {
                string json = e.Result;

                // Check if there is a JSON error
                JsonObject o = (JsonObject)JsonObject.Parse(json);
                if (o.ContainsKey("error"))
                {
                    string errorMessage = "";
                    int    statusCode   = -1;

                    o = (JsonObject)o["error"];

                    // Extract the error message
                    if (o.ContainsKey("message"))
                    {
                        errorMessage = o["message"];
                    }

                    // Extract the HTTP status code
                    if (o.ContainsKey("code"))
                    {
                        statusCode = o["code"];
                    }

                    // Fire the failed event
                    OnServiceDetailsDownloadFailed(new ExceptionEventArgs(new Exception(errorMessage), e.UserState, statusCode));
                    return;
                }
                byte[] bytes = Encoding.Unicode.GetBytes(json);
                using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(bytes))
                {
                    DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T));
                    ServiceInfo = dataContractJsonSerializer.ReadObject(memoryStream) as T;
                    memoryStream.Close();
                }

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

            OnServiceDetailsDownloadCompleted(new ServiceDetailsDownloadCompletedEventArgs()
            {
                UserState = e.UserState
            });
        }
        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 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
 }
Пример #13
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
                });
            }
        }
Пример #14
0
        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
                });
            }
        }
Пример #15
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));
            }
        }
        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);
        }