private async Task <string> UploadImpl()
        {
            // Create EsriHttpClient object
            var httpClient = new EsriHttpClient();

            // Upload vtpk file to the currently active portal
            var itemToUpload = ItemFactory.Create(FilePath);
            var tags         = new string[] { "ArcGIS Pro", "SDK", "UploadVtpkToAgol Demo" };
            var portalUrl    = ArcGISPortalManager.Current.GetActivePortal().PortalUri.ToString();

            var result = httpClient.Upload(
                portalUrl, itemToUpload, string.Empty, tags);

            if (result.Item1 == false)
            {
                return($@"Unable to upload this item: {FilePath} to ArcGIS Online");
            }

            string userName = ArcGISPortalManager.Current.GetActivePortal().GetSignOnUsername();
            string query    = $@"q=owner:{userName} tags:""UploadVtpkToAgol Demo"" ";

            // Once uploaded make another REST call to search for the uploaded data
            var searchUrl = new UriBuilder(portalUrl)
            {
                Path  = "sharing/rest/search",
                Query = $@"{query}&f=json"
            };

            var searchResults = httpClient.Get(searchUrl.Uri.ToString());

            dynamic resultItems = JObject.Parse(await searchResults.Content.ReadAsStringAsync());

            long numberOfTotalItems = resultItems.total.Value;

            if (numberOfTotalItems == 0)
            {
                return($@"Unable to find uploaded item with query: {query}");
            }

            var resultItemList = new List <dynamic>();

            resultItemList.AddRange(resultItems.results);
            //get the first result
            dynamic item = resultItemList[0];

            // Create an item from the search results

            string itemId      = item.id;
            var    currentItem = ItemFactory.Create(itemId, ItemFactory.ItemType.PortalItem);

            // Finally add the feature service to the map
            // if we have an item that can be turned into a layer
            // add it to the map
            if (LayerFactory.CanCreateLayerFrom(currentItem))
            {
                LayerFactory.CreateLayer(currentItem, MapView.Active.Map);
            }
            return($@"Uploaded this item: {FilePath} to ArcGIS Online and added the item to the Map");
        }
 /// <summary>
 /// Adds a layer to the current map using the given path or url
 /// </summary>
 /// <remarks>Gets run in the worker thread</remarks>
 /// <param name="uri"></param>
 /// <returns></returns>
 public Task <Layer> AddLayer(string uri)
 {
     return(QueuedTask.Run(() =>
     {
         Map map = MapView.Active.Map;
         return LayerFactory.CreateLayer(new Uri(uri), map);
     }));
 }
示例#3
0
        protected async override void OnClick()
        {
            //TODO - Get the URL of the Active Portal
            //HINT: Use PortalManager
            string portalUrl = PortalManager.GetActivePortal().ToString();

            UriBuilder searchURL = new UriBuilder(portalUrl);

            searchURL.Path = "sharing/rest/search";
            string layers = "(type:\"Map Service\" OR type:\"Image Service\" OR type:\"Feature Service\" OR type:\"WMS\" OR type:\"KML\")";

            //any public layer content
            searchURL.Query = string.Format("q={0}&f=json", layers);

            EsriHttpClient httpClient = new EsriHttpClient();

            var     searchResponse = httpClient.Get(searchURL.Uri.ToString());
            dynamic resultItems    = JObject.Parse(await searchResponse.Content.ReadAsStringAsync());

            //Use EsriHttpClient to call Online - Use the GET method

            //TODO get the JSON result from the searchResponse
            //HINT - examine methoods of searchResponse.Content

            //TODO Parse the returned JSON - here you will use the Newtonsoft library's JObject
            //examine JObject.Parse. Use a dynamic type to get the results of the Parse
            long numberOfTotalItems = resultItems.total.Value;

            if (numberOfTotalItems == 0)
            {
                return;
            }

            List <dynamic> resultItemList = new List <dynamic>();

            resultItemList.AddRange(resultItems.results);
            //TODO add the ".results" of the returned JSON.
            //eg: resultItemList.AddRange(resultItems.results);

            //get the first result from resultItemList (or an index of your choice)
            //dynamic item = ....
            dynamic item = resultItemList[0];


            //TODO create an Item via the ItemFactory. Use the ItemFactory.ItemType.PortalItem item type.
            string itemID      = item.id;
            Item   currentItem = ItemFactory.Create(itemID, ItemFactory.ItemType.PortalItem);

            await QueuedTask.Run(() => {
                // if we have an item that can be turned into a layer
                // add it to the map
                //TODO use the LayerFactory.CreateLayer and the MapView.Active.Map
                if (LayerFactory.CanCreateLayerFrom(currentItem))
                {
                    LayerFactory.CreateLayer(currentItem, MapView.Active.Map);
                }
            });
        }
示例#4
0
        /// <summary>
        /// Create a raster layer and add it to a map.
        /// </summary>
        /// <returns>Task that contains a layer.</returns>
        private async Task AddRasterLayerToMap()
        {
            try
            {
                // Get the first map called "Map" from the current project.
                Map myMap = null;
                myMap = await GetMapFromProject(Project.Current, "Map");

                if (myMap == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Failed to get map.");
                    return;
                }


                // Create a url pointing to the source. In this case it is a url to an image service
                // which will result in an image service layer being created.
                string dataSoureUrl = @"http://imagery.arcgisonline.com/arcgis/services/LandsatGLS/GLS2010_Enhanced/ImageServer";
                // Note: A url can also point to
                // 1.) An image on disk or an in a file geodatabase. e.g. string dataSoureUrl = @"C:\temp\a.tif"; This results in a raster layer.
                // 2.) A mosaic dataset in a file gdb e.g. string dataSoureUrl = @"c:\temp\mygdb.gdb\MyMosaicDataset"; This results in a mosaic layer.
                // 3.) A raster or mosaic dataset in an enterprise geodatabase.

                // Create an ImageServiceLayer object to hold the new layer.
                ImageServiceLayer rasterLayer = null;

                // The layer has to be created on the Main CIM Thread (MCT).
                await QueuedTask.Run(() =>
                {
                    // Create a layer based on the url. In this case the layer we are creating is an image service layer.
                    rasterLayer = (ImageServiceLayer)LayerFactory.CreateLayer(new Uri(dataSoureUrl), myMap);

                    // Check if it is created.
                    if (rasterLayer == null)
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Failed to create layer for url:" + dataSoureUrl);
                        return;
                    }

                    // Validate the colorizer to see if the layer is colorized correctly.
                    if (!(rasterLayer.GetColorizer() is CIMRasterRGBColorizer))
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Colorizer does not match for layer created from url: " + dataSoureUrl);
                    }
                });
            }
            catch (Exception exc)
            {
                // Catch any exception found and display a message box.
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught: " + exc.Message);
                return;
            }
        }
示例#5
0
文件: DbGate.cs 项目: Adipa-G/ndbgate
        public DbGate(int dbType)
        {
            _config     = new DbGateConfig();
            _statistics = new DbGateStatistics();
            InitializeDefaults();

            IDbLayer dbLayer = LayerFactory.CreateLayer(dbType, _config);

            CacheManager.Init(_config);
            _persistRetrievalLayer = new PersistRetrievalLayer(dbLayer, _statistics, _config);
            _dataMigrationLayer    = new DataMigrationLayer(dbLayer, _statistics, _config);
            dbLayer.DataManipulate();
        }
示例#6
0
        /// <summary>
        /// Create a Layer from the selected item and add it to the active map.
        /// </summary>
        /// <param name="listItem">Selected item(ArcGIS.Desktop.Core.Item)</param>
        private void AddLayerToMap(object listItem)
        {
            QueuedTask.Run(() =>
            {
                var selectedItem = listItem as Item;

                if (selectedItem != null && MapView.Active != null)
                {
                    Layer newLayer = LayerFactory.CreateLayer(selectedItem, MapView.Active.Map);

                    MapView.Active.ZoomTo(newLayer.QueryExtent(), new TimeSpan(0, 0, 0, 0, 500));
                }
            });
        }
        public NeuralNetwork(double learningRate, IFunction function, params int[] countLayerNeurons)
        {
            _layers       = new List <Layer>();
            Errors        = new List <double>();
            _learningRate = learningRate;
            _momentum     = 0;
            var factory = new LayerFactory();

            for (var i = 0; i < countLayerNeurons.Length; i++)
            {
                var type        = i == 0 ? NeuronType.Input : i == countLayerNeurons.Length - 1 ? NeuronType.Output : NeuronType.Normal;
                var countInputs = i == 0 ? 1 : countLayerNeurons[i - 1];
                var layer       = factory.CreateLayer(countInputs, countLayerNeurons[i], type, function);
                _layers.Add(layer);
            }
        }
        /// <summary>
        /// Create an image service layer and add it to the first 2D map.
        /// </summary>
        /// <returns>Task that contains a layer.</returns>
        public static async Task AddRasterLayerToMapAsync()
        {
            try
            {
                // Get the first 2D map from the project that is called Map.
                Map _map = await GetMapFromProject(Project.Current, "Map");

                if (_map == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("AddRasterLayerToMap: Failed to get map.");
                    return;
                }

                // Create a url pointing to the source. In this case it is a url to an image service
                // which will result in an image service layer being created.
                string dataSoureUrl = @"https://landsat2.arcgis.com/arcgis/services/Landsat/MS/ImageServer";
                // Note: A url can also point to
                // 1.) An image on disk or an in a file geodatabase. e.g. string dataSoureUrl = @"C:\temp\a.tif"; This results in a raster layer.
                // 2.) A mosaic dataset in a file gdb e.g. string dataSoureUrl = @"c:\temp\mygdb.gdb\MyMosaicDataset"; This results in a mosaic layer.
                // 3.) A raster or mosaic dataset in an enterprise geodatabase.

                // Create an ImageServiceLayer object to hold the new layer.
                ImageServiceLayer imageServiceLayer = null;

                // The layer has to be created on the Main CIM Thread (MCT).
                await QueuedTask.Run(() =>
                {
                    // Create a layer based on the url. In this case the layer we are creating is an image service layer.
                    imageServiceLayer = (ImageServiceLayer)LayerFactory.CreateLayer(new Uri(dataSoureUrl), _map);
                    if (imageServiceLayer == null)
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Failed to create layer for url:" + dataSoureUrl);
                        return;
                    }
                });
            }
            catch (Exception exc)
            {
                // Catch any exception found and display a message box.
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught while trying to add layer: " + exc.Message);
                return;
            }
        }
        internal void AddLayerToMap(string url)
        {
            //clear previous flag, if any
            _addFailed = false;
            OnPropertyChanged("AddStatus");

            string id = url;
            //get the query result
            var result = _results.FirstOrDefault(ri => ri.Id == id);

            if (result == null)
            {
                throw new ApplicationException(string.Format("Debug: bad id {0}", id));
            }
            if (result.Item == null)
            {
                result.Item = ItemFactory.Create(id, ItemFactory.ItemType.PortalItem);
            }
            // Syntax can get complicated here
            // Question - do you need to await the QueuedTask.Run? If so, you need a Func<Task>
            // and not an Action.
            //http://stackoverflow.com/questions/20395826/explicitly-use-a-functask-for-asynchronous-lambda-function-when-action-overloa
            //
            //As it currently stands, this QueuedTask.Run will return to the caller on the first await
            QueuedTask.Run(action: async() => {
                if (LayerFactory.CanCreateLayerFrom(result.Item))
                {
                    LayerFactory.CreateLayer(result.Item, MapView.Active.Map);
                }
                else if (MapFactory.CanCreateMapFrom(result.Item))
                {
                    Map newMap          = await MapFactory.CreateMapAsync(result.Item);
                    IMapPane newMapPane = await ProApp.Panes.CreateMapPaneAsync(newMap);
                }
                else
                {
                    _addFailed = true;//cannot be added
                    FrameworkApplication.Current.Dispatcher.Invoke(() => OnPropertyChanged("AddStatus"));
                }
            });
        }
示例#10
0
        public void CreateDistanceLayerTest()
        {
            LayerFactory        factory             = new LayerFactory();
            IActivationFunction ActivationThresHold = new ThresholdFunction();

            DistanceLayer layer = (DistanceLayer)factory.CreateLayer(NETWORK_TYPE_DISTANCE, INPUT_COUNT, ActivationThresHold);

            Assert.Equal(3, layer.GetNeuronCount());
            DistanceNeuron actNeuron = (DistanceNeuron)layer.GetNeuron(1);

            Assert.NotNull(actNeuron);

            List <ISynapse> inputs = actNeuron.FetchInputs();

            Assert.NotNull(inputs);
            Assert.Equal(INPUT_COUNT, inputs.Count);

            ISynapse input = inputs[1];

            Assert.True(input.Weight != 0);
        }
        protected override async void OnClick()
        {
            UriBuilder searchURL = new UriBuilder(PortalManager.GetActivePortal());

            searchURL.Path = "sharing/rest/search";
            string layers = "(type:\"Map Service\" OR type:\"Image Service\" OR type:\"Feature Service\" OR type:\"WMS\" OR type:\"KML\")";

            //any public layer content
            searchURL.Query = string.Format("q={0}&f=json", layers);

            EsriHttpClient httpClient = new EsriHttpClient();

            var     searchResponse = httpClient.Get(searchURL.Uri.ToString());
            dynamic resultItems    = JObject.Parse(await searchResponse.Content.ReadAsStringAsync());

            long numberOfTotalItems = resultItems.total.Value;

            if (numberOfTotalItems == 0)
            {
                return;
            }

            List <dynamic> resultItemList = new List <dynamic>();

            resultItemList.AddRange(resultItems.results);
            //get the first result
            dynamic item = resultItemList[0];

            string itemID      = item.id;
            Item   currentItem = ItemFactory.Create(itemID, ItemFactory.ItemType.PortalItem);

            await QueuedTask.Run(() => {
                // if we have an item that can be turned into a layer
                // add it to the map
                if (LayerFactory.CanCreateLayerFrom(currentItem))
                {
                    LayerFactory.CreateLayer(currentItem, MapView.Active.Map);
                }
            });
        }
        private Task AddToMap()
        {
            return(QueuedTask.Run(() =>
            {
                try
                {
                    // first we create an 'Item' using itemfactory
                    Item currentItem = ItemFactory.Create(FilePath);

                    // Finally add the feature service to the map
                    // if we have an item that can be turned into a layer
                    // add it to the map
                    if (LayerFactory.CanCreateLayerFrom(currentItem))
                    {
                        LayerFactory.CreateLayer(currentItem, MapView.Active.Map);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error while adding vector tile to map");
                }
            }));
        }
        protected override void OnClick()
        {
            OpenItemDialog openDlg = new OpenItemDialog();

            openDlg.Title           = "Add Layers";
            openDlg.InitialLocation = Project.Current.HomeFolderPath;
            openDlg.Filter          = ItemFilters.default_addToMap;
            openDlg.MultiSelect     = true;

            if (openDlg.ShowDialog() ?? false)
            {
                QueuedTask.Run(() =>
                {
                    IEnumerable <ArcGIS.Desktop.Core.Item> selectedItems = openDlg.Items;
                    foreach (var item in selectedItems)
                    {
                        if (LayerFactory.CanCreateLayerFrom(item))
                        {
                            LayerFactory.CreateLayer(item, MapView.Active.Map);
                        }
                    }
                });
            }
        }
        private async Task <string> QueryImpl()
        {
            // Create EsriHttpClient object
            var httpClient = new EsriHttpClient();

            // Make a self call to extract the signed on username for now.
            // Coming soon - An API which will give you the the signed on username for a portal
            var selfUrl = new UriBuilder(PortalManager.GetActivePortal())
            {
                Path  = "sharing/rest/portals/self",
                Query = "f=json"
            };

            EsriHttpResponseMessage response = httpClient.Get(selfUrl.Uri.ToString());

            dynamic portalSelf = JObject.Parse(await response.Content.ReadAsStringAsync());

            // if the response doesn't contain the user information then it is essentially
            // an anonymous request against the portal
            if (portalSelf.user == null)
            {
                return("Unable to get current user from portal");
            }

            string userName = portalSelf.user.username;
            string query    = $@"q=owner:{userName} tags:""UploadVtpkToAgol Demo"" type:""Vector Tile Service"" ";

            // Once uploaded make another REST call to search for the uploaded data
            var searchUrl = new UriBuilder(PortalManager.GetActivePortal())
            {
                Path  = "sharing/rest/search",
                Query = $@"{query}&f=json"
            };

            var searchResults = httpClient.Get(searchUrl.Uri.ToString());

            dynamic resultItems = JObject.Parse(await searchResults.Content.ReadAsStringAsync());

            long numberOfTotalItems = resultItems.total.Value;

            if (numberOfTotalItems == 0)
            {
                return($@"Unable to find uploaded item with query: {query}");
            }

            var resultItemList = new List <dynamic>();

            resultItemList.AddRange(resultItems.results);
            //get the first result
            dynamic item = resultItemList[0];

            // Create an item from the search results

            string itemId      = item.id;
            var    currentItem = ItemFactory.Create(itemId, ItemFactory.ItemType.PortalItem);

            // Finally add the feature service to the map
            // if we have an item that can be turned into a layer
            // add it to the map
            if (LayerFactory.CanCreateLayerFrom(currentItem))
            {
                LayerFactory.CreateLayer(currentItem, MapView.Active.Map);
            }
            return($@"Downloaded this item: {item.name} [Type: {item.type}] to ArcGIS Online and added the item to the Map");
        }
        protected internal async virtual void ExecuteItemAction(string url)
        {
            _result = _results.FirstOrDefault(ri => ri.Id == url);
            if (_result == null)
            {
                return;
            }

            //Either we open a project and then create the item or
            //we download the item and then create a project from it.
            //MapPackage is a special case. We download it, create
            //a project and then add the map package to it.
            switch (_result.OnlineItemType)
            {
            case OnlineItemType.WebMap:
            {
                await Project.CreateAsync(new CreateProjectSettings()
                    {
                        Name = System.IO.Path.GetFileNameWithoutExtension(_result.Name)
                    });

                var currentItem = ItemFactory.Create(_result.Id, ItemFactory.ItemType.PortalItem);
                if (MapFactory.CanCreateMapFrom(currentItem))
                {
                    var newMap = await MapFactory.CreateMapAsync(currentItem);

                    await FrameworkApplication.Panes.CreateMapPaneAsync(newMap);
                }
            }
            break;

            case OnlineItemType.Layer:
            {
                var ps = new CreateProjectSettings()
                {
                    Name         = System.IO.Path.GetFileNameWithoutExtension(_result.Name),
                    LocationPath = ConfigWithStartWizardModule.DefaultFolder(),
                    TemplatePath = ConfigWithStartWizardModule.GetDefaultTemplates()[0]         //Scene
                };
                _eventToken = ArcGIS.Desktop.Mapping.Events.MapViewInitializedEvent.Subscribe((args) =>
                    {
                        Item currentItem = ItemFactory.Create(_result.Id, ItemFactory.ItemType.PortalItem);
                        if (LayerFactory.CanCreateLayerFrom(currentItem))
                        {
                            QueuedTask.Run(() => LayerFactory.CreateLayer(currentItem, args.MapView.Map));
                        }
                        ArcGIS.Desktop.Mapping.Events.MapViewInitializedEvent.Unsubscribe(_eventToken);
                        _eventToken = null;
                    });
                try
                {
                    await Project.CreateAsync(ps);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.ToString());
                }
            }
            break;

            default:
                var query = new OnlineQuery(_activePortalUri);
                query.ConfigureData("", _result.Id, _result.Name);

                await new SubmitQuery().DownloadFileAsync(query);

                //Project package
                if (_result.OnlineItemType == OnlineItemType.ProjectPackage)
                {
                    Project.OpenAsync(query.DownloadFileName);
                }
                //Project Template
                else if (_result.OnlineItemType == OnlineItemType.Template)
                {
                    var ps = new CreateProjectSettings()
                    {
                        Name         = System.IO.Path.GetFileNameWithoutExtension(_result.Name),
                        LocationPath = ConfigWithStartWizardModule.DefaultFolder(),
                        TemplatePath = query.DownloadFileName
                    };
                    try
                    {
                        await Project.CreateAsync(ps);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.ToString());
                    }
                }
                //Map Package
                else if (_result.OnlineItemType == OnlineItemType.MapPackage)
                {
                    await Project.CreateAsync(new CreateProjectSettings()
                    {
                        Name = System.IO.Path.GetFileNameWithoutExtension(_result.Name)
                    });

                    try
                    {
                        var mapPackage = ItemFactory.Create(query.DownloadFileName);
                        await Project.Current.AddAsync(mapPackage);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.ToString());
                    }
                }
                break;
            }
        }