private void getFieldsInDatabaseTable(Resource parentResource, object userState)
 {
     featureServer = new FeatureService(parentResource.Url);
     featureServer.GetFeatureServiceDetailsFailed += (o, e) =>
     {
         OnGetChildResourcesFailed(e);
     };
     featureServer.GetFeatureServiceDetailsCompleted += (o, e) =>
     {
         OnGetChildResourcesCompleted(new GetChildResourcesCompletedEventArgs()
         {
             ChildResources = e.ChildResources, UserState = e.UserState
         });
     };
     featureServer.GetFeatureServiceDetails(userState);
 }
        public override void CreateLayerAsync(Resource layerResource, SpatialReference mapSpatialReference, object userState)
        {
            if (layerResource.ResourceType == ResourceType.DatabaseTable)
            {
                featureService = new FeatureService(layerResource.Url);
                featureService.GetFeatureServiceDetailsFailed += (o, e) =>
                {
                    OnCreateLayerFailed(e);
                };
                featureService.GetFeatureServiceDetailsCompleted += (o, e) =>
                {
                    if (e.FeatureServiceInfo == null)
                    {
                        OnCreateLayerFailed(new ESRI.ArcGIS.Mapping.Core.ExceptionEventArgs(new Exception(Resources.Strings.ExceptionUnableToRetrieveLayerDetails), e.UserState));
                        return;
                    }
                    GeometryType GeometryType = GeometryType.Unknown;
                    switch (e.FeatureServiceInfo.GeometryType)
                    {
                    case "esriGeometryPoint":
                        GeometryType = GeometryType.Point;
                        break;

                    case "esriGeometryMultipoint":
                        GeometryType = GeometryType.MultiPoint;
                        break;

                    case "esriGeometryPolyline":
                        GeometryType = GeometryType.Polyline;
                        break;

                    case "esriGeometryPolygon":
                        GeometryType = GeometryType.Polygon;
                        break;
                    }
                    FeatureLayer newFeatureLayer = new FeatureLayer()
                    {
                        Url      = featureService.Uri,
                        ID       = Guid.NewGuid().ToString("N"),
                        Mode     = FeatureLayer.QueryMode.OnDemand,
                        Renderer = new ESRI.ArcGIS.Mapping.Core.Symbols.HiddenRenderer()
                    };
                    newFeatureLayer.SetValue(MapApplication.LayerNameProperty, layerResource.DisplayName);
                    newFeatureLayer.SetValue(Core.LayerExtensions.GeometryTypeProperty, GeometryType);
                    newFeatureLayer.SetValue(Core.LayerExtensions.DisplayUrlProperty, layerResource.Url);

                    if (e.FeatureServiceInfo.Fields != null)
                    {
                        Collection <FieldInfo> fields = new Collection <FieldInfo>();
                        foreach (Field field in e.FeatureServiceInfo.Fields)
                        {
                            if (field.DataType == "Microsoft.SqlServer.Types.SqlGeometry" || field.DataType == "esriFieldTypeGeometry")
                            {
                                continue;
                            }
                            fields.Add(new FieldInfo()
                            {
                                DisplayName = field.Name,
                                FieldType   = mapFieldType(field.DataType),
                                Name        = field.Name,
                                VisibleInAttributeDisplay = true,
                                VisibleOnMapTip           = true,
                            });
                        }
                        newFeatureLayer.SetValue(Core.LayerExtensions.FieldsProperty, fields);
                    }
                    newFeatureLayer.OutFields.Add("*"); // Get all fields at configuration time
                    OnCreateLayerCompleted(new CreateLayerCompletedEventArgs()
                    {
                        Layer = newFeatureLayer, UserState = e.UserState, GeometryType = GeometryType
                    });
                };
                featureService.GetFeatureServiceDetails(userState);
            }
            else
            {
                OnCreateLayerFailed(new ESRI.ArcGIS.Mapping.Core.ExceptionEventArgs(new Exception(string.Format(Resources.Strings.ExceptionCannotCreateLayerForResourceType, layerResource.ResourceType.ToString())), userState));
            }
        }
        public override void CreateLayerAsync(Resource layerResource, SpatialReference mapSpatialReference, object userState)
        {
            if (layerResource.ResourceType == ResourceType.DatabaseTable)
            {
                featureService = new FeatureService(layerResource.Url);
                featureService.GetFeatureServiceDetailsFailed += (o, e) =>
                {
                    OnCreateLayerFailed(e);
                };
                featureService.GetFeatureServiceDetailsCompleted += (o, e) =>
                {
                    if (e.FeatureServiceInfo == null)
                    {
                        OnCreateLayerFailed(new ESRI.ArcGIS.Mapping.Core.ExceptionEventArgs(new Exception(Resources.Strings.ExceptionUnableToRetrieveLayerDetails), e.UserState));
                        return;
                    }
                    GeometryType GeometryType = GeometryType.Unknown;
                    switch (e.FeatureServiceInfo.GeometryType)
                    {
                        case "esriGeometryPoint":
                            GeometryType = GeometryType.Point;
                            break;
                        case "esriGeometryMultipoint":
                            GeometryType = GeometryType.MultiPoint;
                            break;
                        case "esriGeometryPolyline":
                            GeometryType = GeometryType.Polyline;
                            break;
                        case "esriGeometryPolygon":
                            GeometryType = GeometryType.Polygon;
                            break;
                    }
                    FeatureLayer newFeatureLayer = new FeatureLayer()
                    {
                        Url = featureService.Uri,
                        ID = Guid.NewGuid().ToString("N"),
                        Mode = FeatureLayer.QueryMode.OnDemand,
                        Renderer = new ESRI.ArcGIS.Mapping.Core.Symbols.HiddenRenderer()
                    };        
                    newFeatureLayer.SetValue(MapApplication.LayerNameProperty, layerResource.DisplayName);
                    newFeatureLayer.SetValue(Core.LayerExtensions.GeometryTypeProperty, GeometryType);
                    newFeatureLayer.SetValue(Core.LayerExtensions.DisplayUrlProperty, layerResource.Url);

                    if (e.FeatureServiceInfo.Fields != null)
                    {
                        Collection<FieldInfo> fields = new Collection<FieldInfo>();
                        foreach (Field field in e.FeatureServiceInfo.Fields)
                        {
                            if (field.DataType == "Microsoft.SqlServer.Types.SqlGeometry" || field.DataType == "esriFieldTypeGeometry")
                                continue;
                            fields.Add(new FieldInfo()
                            {
                                DisplayName = field.Name,
                                FieldType = mapFieldType(field.DataType),
                                Name = field.Name,
                                VisibleInAttributeDisplay = true,
                                VisibleOnMapTip = true,
                            });
                        }
                        newFeatureLayer.SetValue(Core.LayerExtensions.FieldsProperty, fields);
                    }
                    newFeatureLayer.OutFields.Add("*"); // Get all fields at configuration time
                    OnCreateLayerCompleted(new CreateLayerCompletedEventArgs() { Layer = newFeatureLayer, UserState = e.UserState, GeometryType = GeometryType });
                };
                featureService.GetFeatureServiceDetails(userState);
            }
            else
            {
                OnCreateLayerFailed(new ESRI.ArcGIS.Mapping.Core.ExceptionEventArgs(new Exception(string.Format(Resources.Strings.ExceptionCannotCreateLayerForResourceType, layerResource.ResourceType.ToString())), userState));
            }
        }
 private void getFieldsInDatabaseTable(Resource parentResource, object userState)
 {
     featureServer = new FeatureService(parentResource.Url);
     featureServer.GetFeatureServiceDetailsFailed += (o, e) =>
     {
         OnGetChildResourcesFailed(e);
     };
     featureServer.GetFeatureServiceDetailsCompleted += (o, e) =>
     {
         OnGetChildResourcesCompleted(new GetChildResourcesCompletedEventArgs() { ChildResources = e.ChildResources, UserState = e.UserState });
     };
     featureServer.GetFeatureServiceDetails(userState);
 }
        private void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                return;
            }

            if (e.Error != null)
            {
                bool redownloadAttempted = WebClientFactory.RedownloadAttempted.Contains(webClient);
                if (Utils.IsMessageLimitExceededException(e.Error) && !redownloadAttempted)
                {
                    // Re-issue the request which should serve it out of cache
                    // and helps us avoid the error which is caused by setting AllowReadStreamBuffering=false
                    // which was used to workaround the problem of SL4 and gzipped content
                    WebClientFactory.RedownloadStringAsync(webClient, finalUrl, e.UserState);
                }
                else
                {
                    if (redownloadAttempted)
                    {
                        WebClientFactory.RedownloadAttempted.Remove(webClient);
                    }
                    OnGetTablesInDatabaseFailed(new ExceptionEventArgs(e.Error, e.UserState));
                }
                return;
            }
            if (string.IsNullOrEmpty(e.Result))
            {
                OnGetTablesInDatabaseFailed(new ExceptionEventArgs(new Exception("Empty response"), e.UserState));
                return;
            }

            DatabaseTables databaseTables = null;

            try
            {
                string json = e.Result;
                if (Utils.IsSDSCatalogResponse(json))
                {
                    // We were expecting a response consisting of tables, instead we got a response of the catalog
                    // this must be because we formed/guessed our URL wrong
                    OnGetTablesInDatabaseFailed(new ExceptionEventArgs(new Exception("Invalid response recieved. Catalog response recieved when expecting database tables"), e.UserState));
                    return;
                }
                Exception exception = Utils.CheckJsonForException(json);
                if (exception != null)
                {
                    OnGetTablesInDatabaseFailed(new ExceptionEventArgs(exception, e.UserState));
                    return;
                }
                byte[] bytes = Encoding.Unicode.GetBytes(json);
                using (MemoryStream memoryStream = new MemoryStream(bytes))
                {
                    DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(DatabaseTables));
                    databaseTables = dataContractJsonSerializer.ReadObject(memoryStream) as DatabaseTables;
                    memoryStream.Close();
                }

                if (databaseTables == null)
                {
                    OnGetTablesInDatabaseFailed(new ExceptionEventArgs(new Exception("Unable to deserialize response"), e.UserState));
                    return;
                }

                List <Resource> childResources  = new List <Resource>();
                int             totalTableCount = databaseTables.Tables != null ? databaseTables.Tables.Count : 0;
                if (databaseTables.Tables != null)
                {
                    int tableCount = 0;
                    foreach (string table in databaseTables.Tables)
                    {
                        Resource databaseTable = new Resource()
                        {
                            ResourceType = ResourceType.DatabaseTable,
                            DisplayName  = table,
                            Url          = string.Format("{0}/{1}", Uri, table),
                        };
                        if (FilterForSpatialContent)
                        {
                            FeatureService featureService = new FeatureService(databaseTable.Url);
                            featureService.GetFeatureServiceDetailsFailed += (o, args) => {
                                // Remove the table
                                childResources.Remove(args.UserState as Resource);

                                tableCount++;
                                if (tableCount >= totalTableCount)
                                {
                                    // all done raise the event
                                    OnGetTablesInDatabaseFailed(args);
                                }
                            };
                            featureService.GetFeatureServiceDetailsCompleted += (o, args) =>
                            {
                                tableCount++;
                                if (args.FeatureServiceInfo == null ||
                                    !args.FeatureServiceInfo.DoesTableHasGeometryColumn())
                                {
                                    // Remove the table
                                    childResources.Remove(args.UserState as Resource);
                                }

                                if (tableCount >= totalTableCount)
                                {
                                    // all done raise the event
                                    OnGetTablesInDatabaseCompleted(new GetTablesInDatabaseCompletedEventArgs()
                                    {
                                        ChildResources = childResources, UserState = e.UserState
                                    });
                                }
                            };

                            // Add table before validation to preserve catalog order.  Table will be removed if
                            // validation fails.
                            Resource child = new Resource()
                            {
                                ResourceType = ResourceType.DatabaseTable,
                                DisplayName  = databaseTable.DisplayName,
                                Url          = databaseTable.Url,
                            };
                            childResources.Add(child);

                            featureService.GetFeatureServiceDetails(child);
                        }
                        else
                        {
                            childResources.Add(databaseTable);
                        }
                    }
                }

                if (!FilterForSpatialContent || totalTableCount == 0)
                {
                    OnGetTablesInDatabaseCompleted(new GetTablesInDatabaseCompletedEventArgs()
                    {
                        ChildResources = childResources, UserState = e.UserState
                    });
                }
            }
            catch (Exception ex)
            {
                OnGetTablesInDatabaseFailed(new ExceptionEventArgs(ex, e.UserState));
            }
        }
        private void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Cancelled)
                return;

            if (e.Error != null)
            {
                bool redownloadAttempted = WebClientFactory.RedownloadAttempted.Contains(webClient);
                if (Utils.IsMessageLimitExceededException(e.Error) && !redownloadAttempted)
                {
                    // Re-issue the request which should serve it out of cache      
                    // and helps us avoid the error which is caused by setting AllowReadStreamBuffering=false
                    // which was used to workaround the problem of SL4 and gzipped content
                    WebClientFactory.RedownloadStringAsync(webClient, finalUrl, e.UserState);
                }
                else
                {
                    if (redownloadAttempted) WebClientFactory.RedownloadAttempted.Remove(webClient);
                    OnGetTablesInDatabaseFailed(new ExceptionEventArgs(e.Error, e.UserState));
                }
                return;
            }
            if (string.IsNullOrEmpty(e.Result))
            {
                OnGetTablesInDatabaseFailed(new ExceptionEventArgs(new Exception("Empty response"), e.UserState));
                return;
            }

            DatabaseTables databaseTables = null;
            try
            {
                string json = e.Result;
                if (Utils.IsSDSCatalogResponse(json))
                {
                    // We were expecting a response consisting of tables, instead we got a response of the catalog
                    // this must be because we formed/guessed our URL wrong
                    OnGetTablesInDatabaseFailed(new ExceptionEventArgs(new Exception("Invalid response recieved. Catalog response recieved when expecting database tables"), e.UserState));
                    return;
                }
                Exception exception = Utils.CheckJsonForException(json);
                if (exception != null)
                {
                    OnGetTablesInDatabaseFailed(new ExceptionEventArgs(exception, e.UserState));
                    return;
                }
                byte[] bytes = Encoding.Unicode.GetBytes(json);
                using (MemoryStream memoryStream = new MemoryStream(bytes))
                {
                    DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(DatabaseTables));
                    databaseTables = dataContractJsonSerializer.ReadObject(memoryStream) as DatabaseTables;
                    memoryStream.Close();
                }

                if (databaseTables == null)
                {
                    OnGetTablesInDatabaseFailed(new ExceptionEventArgs(new Exception("Unable to deserialize response"), e.UserState));
                    return;
                }

                List<Resource> childResources = new List<Resource>();
                int totalTableCount = databaseTables.Tables != null ? databaseTables.Tables.Count : 0;                
                if (databaseTables.Tables != null)
                {
                    int tableCount = 0;
                    foreach (string table in databaseTables.Tables)
                    {                        
                        Resource databaseTable = new Resource()
                        {
                            ResourceType = ResourceType.DatabaseTable,
                            DisplayName = table,
                            Url = string.Format("{0}/{1}", Uri, table),
                        };
                        if (FilterForSpatialContent)
                        {
                            FeatureService featureService = new FeatureService(databaseTable.Url);
                            featureService.GetFeatureServiceDetailsFailed += (o, args) => {
                                // Remove the table
                                childResources.Remove(args.UserState as Resource);

                                tableCount++;
                                if (tableCount >= totalTableCount)
                                {
                                    // all done raise the event
                                    OnGetTablesInDatabaseFailed(args);
                                }
                            };
                            featureService.GetFeatureServiceDetailsCompleted += (o, args) =>
                            {
                                tableCount++;
                                if (args.FeatureServiceInfo == null
                                    || !args.FeatureServiceInfo.DoesTableHasGeometryColumn())
                                {       
                                    // Remove the table
                                    childResources.Remove(args.UserState as Resource);
                                }

                                if (tableCount >= totalTableCount)
                                {
                                    // all done raise the event
                                    OnGetTablesInDatabaseCompleted(new GetTablesInDatabaseCompletedEventArgs() { ChildResources = childResources, UserState = e.UserState });
                                }
                            };

                            // Add table before validation to preserve catalog order.  Table will be removed if
                            // validation fails.
                            Resource child = new Resource()
                            {
                                ResourceType = ResourceType.DatabaseTable,
                                DisplayName = databaseTable.DisplayName,
                                Url = databaseTable.Url,
                            };
                            childResources.Add(child);

                            featureService.GetFeatureServiceDetails(child);
                        }
                        else
                        {
                            childResources.Add(databaseTable);
                        }
                    }
                }

                if (!FilterForSpatialContent || totalTableCount == 0)
                {
                    OnGetTablesInDatabaseCompleted(new GetTablesInDatabaseCompletedEventArgs() { ChildResources = childResources, UserState = e.UserState });
                }
            }
            catch (Exception ex)
            {
                OnGetTablesInDatabaseFailed(new ExceptionEventArgs(ex, e.UserState));
            }
        }