// Resolves a user-friendly value for a given input value, field, and layer
        private void resolveValue()
        {
            if (!string.IsNullOrEmpty(FieldName) && Value != null && Layer != null && MapApplication.Current != null)
            {
                // Create a dummy graphic with the value to resolve and the field the value belongs to
                Graphic g = new Graphic();
                g.Attributes.Add(FieldName, Value);

                // Get the popup info for the graphic and the layer to which the input value belongs.  This will initialize
                // and give access to field metadata for the layer
                OnClickPopupInfo info = MapApplication.Current.GetPopup(g, Layer);

                // Resolve the value into its user-friendly equivalent
                if (info != null)
                {
                    ResolvedValue = ConverterUtil.GetValue(info.PopupItem, FieldName);
                }
                else
                {
                    ResolvedValue = null;
                }
            }
            else
            {
                ResolvedValue = null;
            }
        }
Exemplo n.º 2
0
        }         // public void doExecute(object parameter)

        /// <summary>
        /// Checks whether the Query Related Records tool can be used.
        /// </summary>
        /// <param name="parameter">The OnClickPopupInfo from the layer.</param>
        public bool CanExecute(object parameter)
        {
            try {
                popupInfo = parameter as OnClickPopupInfo;
                if (popupInfo == null || popupInfo.PopupItem == null || popupInfo.PopupItem.Graphic == null)
                {
                    //log(string.Format("CanExecute false, popupinfo or popupitem is null"));
                    return(false);
                }

                if (MapApplication.Current == null || MapApplication.Current.Map == null ||
                    MapApplication.Current.Map.Layers == null)
                {
                    //log(string.Format("CanExecute false, map or layers is null"));
                    return(false);
                }

                var lyr = new mwb02.AddIns.VLayer(popupInfo.PopupItem.Layer);
                if (lyr.lyrType.Contains("DynamicMapServiceLayer"))
                {
                    lyr = lyr.getSubLayer(popupInfo.PopupItem.LayerId);
                }
                if (!lyr.lyrType.Contains("Feature"))
                {
                    log(string.Format("CanExecute false, layer is not FeatureLayer, {0}", lyr.lyrType));
                    return(false);
                }

                // http://www.dotnetperls.com/dictionary
                var vfl = new mwb02.AddIns.VLayer();
                if (!flList.TryGetValue(lyr.lyrUrl, out vfl))
                {
                    log(string.Format("CanExecute false, layer not in list {0}", lyr.lyrUrl));
                    addFL2Collection(lyr);
                    return(false);
                }

                var fl = vfl.lyr as FeatureLayer;
                if (fl.LayerInfo != null && fl.LayerInfo.Relationships != null && fl.LayerInfo.Relationships.Count() > 0)
                {
                    var relrecs = countRelatedRecords(vfl, popupInfo.PopupItem.Graphic);
                    if (relrecs != 0)
                    {
                        return(true);
                    }
                    log(string.Format("CanExecute false, relatedrecords.count = 0. {0}", lyr.lyrUrl));
                    return(false);
                }

                log(string.Format("CanExecute false, layerinfo or relations is null {0}", lyr.lyrUrl));
                return(false);
            }
            catch (Exception ex) {
                log(string.Format("CanExecute error {0}\n{1}", ex.Message, ex.StackTrace));
                return(false);
            }
        }                                            // public bool CanExecute(object parameter)
        private static void ShowPopup(OnClickPopupInfo popupInfo, Geometry geometry)
        {
            if (popupInfo.Container is InfoWindow)
            {
                MapPoint anchorPoint = GetLastPoint(geometry);

                if (anchorPoint != null)
                {
                    ShowPopup(popupInfo, anchorPoint);
                }
            }
        }
 public static EditValuesCommand ShowPopup(OnClickPopupInfo popupInfo, MapPoint anchorPoint)
 {
     if (popupInfo.Container is InfoWindow)
     {
         ((InfoWindow)popupInfo.Container).Show(anchorPoint);
         SyncPreviousDisplayMode(popupInfo);
         if (OnClickPopupControl != null)
         {
             return(OnClickPopupControl.GetEditValuesToolCommand());
         }
     }
     return(null);
 }
        /// <summary>
        /// Executes edit values command if that is the mode we are in
        /// </summary>
        /// <param name="popupInfo"></param>
        public static void SyncPreviousDisplayMode(OnClickPopupInfo popupInfo)
        {
            if (popupInfo == null || popupInfo.PopupItem == null)
            {
                return;
            }

            InfoWindow win = popupInfo.Container as InfoWindow;

            if (win == null || OnClickPopupControl == null)
            {
                return;
            }

            // find the edit values command associated with the active tool
            EditValuesCommand editValues = OnClickPopupControl.GetEditValuesToolCommand();

            bool isEditable = LayerProperties.GetIsEditable(popupInfo.PopupItem.Layer);

            if (isEditable)
            {
                if (editValues == null)
                {
                    //if we were showing edit values panel, show that again
                    if (_wasEditingValues && popupInfo != null && popupInfo.Container is InfoWindow)
                    {
                        win.Dispatcher.BeginInvoke(() =>
                        {
                            EditValuesCommand cmd =
                                new EditValuesCommand();
                            cmd.Execute(popupInfo);
                        });
                    }
                }
                else
                {
                    if (_wasEditingValues)
                    {
                        win.Dispatcher.BeginInvoke(() => { editValues.Execute(popupInfo); });
                    }
                    else
                    {
                        editValues.BackToOriginalContent(popupInfo);
                    }
                }
            }
            else if (editValues != null)
            {
                editValues.BackToOriginalContent(popupInfo);
            }
        }
        } // public void doExecute(object parameter)

        /// <summary>
        /// Checks whether the Query Related Records tool can be used.
        /// </summary>
        /// <param name="parameter">The OnClickPopupInfo from the layer.</param>
        public bool CanExecute(object parameter)
        {
            popupInfo = parameter as OnClickPopupInfo;

            return(popupInfo != null && popupInfo.PopupItem != null
                   //&& popupInfo.PopupItem.Layer is FeatureLayer
                   //&& ((FeatureLayer)popupInfo.PopupItem.Layer).LayerInfo != null
                   //&& ((FeatureLayer)popupInfo.PopupItem.Layer).LayerInfo.Relationships != null
                   //&& ((FeatureLayer)popupInfo.PopupItem.Layer).LayerInfo.Relationships.Count() > 0
                   && MapApplication.Current != null && MapApplication.Current.Map != null &&
                   MapApplication.Current.Map.Layers != null &&
                   MapApplication.Current.Map.Layers.Contains(popupInfo.PopupItem.Layer) &&
                   popupInfo.PopupItem.Graphic != null);
        } // public bool CanExecute(object parameter)
Exemplo n.º 7
0
        public static void EditShape(OnClickPopupInfo popupInfo, ESRI.ArcGIS.Client.Editor editor = null, bool dismissPopup = false)
        {
            if (popupInfo == null)
            {
                return;
            }

            if (editor == null)
            {
                editor = FindEditorInVisualTree();
            }

            PopupItem popup = popupInfo.PopupItem;

            if (popup == null && popupInfo.PopupItems != null && popupInfo.PopupItems.Count >= 1)
            {
                popup = popupInfo.PopupItems[0];
            }

            if (!CanEditShape(popup, editor))
            {
                return;
            }

            Graphic graphic      = popup.Graphic;
            var     featureLayer = popup.Layer as FeatureLayer;

            if (featureLayer != null && featureLayer.LayerInfo != null)
            {
                // Dismiss popup so it does not get in the way of shape edits
                InfoWindow container = popupInfo.Container as InfoWindow;
                if (container != null && dismissPopup)
                {
                    container.IsOpen = false;
                }

                if (featureLayer.LayerInfo.GeometryType == GeometryType.Polygon ||
                    featureLayer.LayerInfo.GeometryType == GeometryType.Polyline ||
                    featureLayer.LayerInfo.GeometryType == GeometryType.MultiPoint)
                {
                    EditGeometry(graphic, featureLayer);
                }
                else if (featureLayer.LayerInfo.GeometryType == Client.Tasks.GeometryType.Point)
                {
                    // edit point using Editor
                    EditPoint(editor, graphic);
                }
            }
        }
Exemplo n.º 8
0
 internal void BackToOriginalContent(OnClickPopupInfo popupInfo)
 {
     if (_OriginalPopupContent != null)
     {
         InfoWindow win = popupInfo.Container as InfoWindow;
         if (win != null)
         {
             Dispatcher.BeginInvoke(() =>
             {
                 win.Content = _OriginalPopupContent;
                 PopupHelper.SetDisplayMode(PopupHelper.DisplayMode.ReadOnly);
             });
         }
     }
 }
        internal static OnClickPopupInfo GetPopup(IEnumerable <Graphic> graphics, Layer layer, int?layerId = null)
        {
            OnClickPopupInfo popupInfo = new OnClickPopupInfo();

            OnClickPopupControl.PopupInfo = popupInfo;

            if (graphics != null && layer != null)
            {
                foreach (PopupItem popupItem in GetPopupItems(graphics, layer, layerId))
                {
                    popupInfo.PopupItems.Add(popupItem);
                }

                if (popupInfo.SelectedIndex < 0 && popupInfo.PopupItems.Count > 0)
                {
                    popupInfo.SelectedIndex = 0;
                }
            }

            return(popupInfo);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Checks whether the QueryRelatedRecords tool can be used. Layer must have a relationship associated
        /// with it for the tool to be enabled.
        /// </summary>
        /// <param name="parameter">OnClickPopupInfo from clicked layer</param>
        public bool CanExecute(object parameter)
        {
            popupInfo = parameter as OnClickPopupInfo;

            if (popupWindow != null && popupInfo.PopupItem != null)
            {
                // If the pop-up item (and therefore pop-up) changes, then verify whether the
                // KeepOnMap View should still be included in the pop-up.
                popupWindow = popupInfo.Container as InfoWindow;
                popupInfo.PropertyChanged += PopupItem_PropertyChanged;
            }

            return(popupInfo != null && popupInfo.PopupItem != null &&
                   popupInfo.PopupItem.Layer is FeatureLayer &&
                   ((FeatureLayer)popupInfo.PopupItem.Layer).LayerInfo != null &&
                   ((FeatureLayer)popupInfo.PopupItem.Layer).LayerInfo.Relationships != null &&
                   ((FeatureLayer)popupInfo.PopupItem.Layer).LayerInfo.Relationships.Count() > 0 &&
                   MapApplication.Current != null && MapApplication.Current.Map != null &&
                   MapApplication.Current.Map.Layers != null &&
                   MapApplication.Current.Map.Layers.Contains(popupInfo.PopupItem.Layer) &&
                   popupInfo.PopupItem.Graphic != null);
        }
        internal static void ShowPopup(Graphic graphic, Layer layer, int?layerId = null)
        {
            OnClickPopupInfo popupInfo = GetPopup(new[] { graphic }, layer, layerId);

            if (graphic.Geometry is MapPoint)
            {
                ShowPopup(popupInfo, (MapPoint)graphic.Geometry);
            }
            else if (graphic.Geometry is Polygon)
            {
                if (!string.IsNullOrEmpty(MapApplication.Current.Urls.GeometryServiceUrl))
                {
                    GeometryService geometryService = new GeometryService(MapApplication.Current.Urls.GeometryServiceUrl);
                    geometryService.LabelPointsCompleted += (s, args) =>
                    {
                        if (args.Results != null && args.Results.Count > 0)
                        {
                            ShowPopup(popupInfo, (MapPoint)args.Results[0].Geometry);
                        }
                        else
                        {
                            ShowPopup(popupInfo, graphic.Geometry);
                        }
                    };
                    geometryService.Failed += (s, args) =>
                    {
                        ShowPopup(popupInfo, graphic.Geometry);
                    };
                    geometryService.LabelPointsAsync(new[] { graphic });
                }
                else
                {
                    ShowPopup(popupInfo, graphic.Geometry);
                }
            }
            SyncPreviousDisplayMode(popupInfo);
        }
Exemplo n.º 12
0
        }         // public void Execute(object parameter)

        /// <summary>
        /// Executes the relationship query against the layer.
        /// </summary>
        /// <param name="parameter">The OnClickPopupInfo from the layer.</param>
        public void doExecute(object parameter)
        {
            // The plan is:
            // Get the featurelayer and clicked feature from the pop-up.
            // The PopupItem property of OnClickPopupInfo provides information about the item currently shown in the pop-up.
            // Then get feature ID value and put it into ExecuteRelationshipQueryAsync task.
            // Then get related records ID's and create FeatureLayer from related table/feature class, filtered by that ID's.
            // Then show grid for that layer.
            popupInfo    = parameter as OnClickPopupInfo;
            inputFeature = popupInfo.PopupItem.Graphic;
            var lyr = new mwb02.AddIns.VLayer(popupInfo.PopupItem.Layer);

            // print layer info to console
            log(string.Format("Execute, layer type '{0}', popupInd '{1}', popupDescr '{2}', lyrID '{3}', lyrName '{4}', title '{5}'",
                              popupInfo.PopupItem.Layer.GetType(),   // 'ESRI.ArcGIS.Client.ArcGISDynamicMapServiceLayer'
                              popupInfo.SelectedIndex, popupInfo.SelectionDescription,
                              popupInfo.PopupItem.LayerId, popupInfo.PopupItem.LayerName, popupInfo.PopupItem.Title));
            // SelectedIndex - index 0-n for found features.
            // SelectionDescription - note about current record for user, '2 from 2' for example.
            // lyrID '0' - sublayer id for ArcGISDynamicMapServiceLayer
            // lyrName 'Аэродромы и вертодромы' - sublayer name for ArcGISDynamicMapServiceLayer
            log(string.Format("Execute, lyrType '{0}', lyrUrl '{1}'", lyr.lyrType, lyr.lyrUrl));
            // layer type 'ESRI.ArcGIS.Client.ArcGISDynamicMapServiceLayer', popupInd '0', popupDescr '1 из 2', lyrID '0', lyrName 'Wells', title 'UNKNOWN'
            // lyrType 'ArcGISDynamicMapServiceLayer', lyrUrl 'http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Petroleum/KSPetro/MapServer'
            log(string.Format("Execute, inputFeature.Attributes.Count '{0}'", inputFeature.Attributes.Count));

            // we need FeatureLayer
            if (lyr.lyrType == "FeatureLayer")
            {
                relatesLayer = lyr;                 // The layer to get related records for. This is used to get the RelationshipID and Query url.
            }
            else if (lyr.lyrType == "ArcGISDynamicMapServiceLayer")
            {
                var rLyr = getSubLayer(lyr, popupInfo.PopupItem.LayerId) as FeatureLayer;
                if (relatesLayer != null && relatesLayer.lyrUrl == rLyr.Url)
                {
                    ;                  // we here after relatesLayer.Initialized
                }
                else                   // init new FeatureLayer
                {
                    relatesLayer = new mwb02.AddIns.VLayer(rLyr);
                    relatesLayer.lyr.Initialized += (a, b) => {
                        if (relatesLayer.lyr.InitializationFailure == null)
                        {
                            var info = (relatesLayer.lyr as FeatureLayer).LayerInfo;
                            log(string.Format("Execute, relatesLayer.InitializationFailure == null, info '{0}'", info));
                            Execute(parameter);
                        }
                    };                     // callback
                    relatesLayer.lyr.Initialize();
                    log(string.Format("Execute, relatesLayer.Initialize called, wait..."));
                    return;
                }         // init new FeatureLayer
            }             // if(lyr.lyrType == "ArcGISDynamicMapServiceLayer")
            else
            {
                throw new Exception("Тип слоя должен быть или FeatureLayer или ArcGISDynamicMapServiceLayer");
            }

            // we have inited FeatureLayer now
            if (relatesLayer.getFL().LayerInfo == null)
            {
                throw new Exception(string.Format("Execute, relatesLayer.LayerInfo == null"));
            }
            var clickedLayer = relatesLayer;
            var storedFL     = this.flList[clickedLayer.lyrUrl];

            // check FeatureLayer info
            log(string.Format("Execute, relatesLayer lyrType '{0}', lyrUrl '{1}'", clickedLayer.lyrType, clickedLayer.lyrUrl));

            // get relationship id
            var rels = relatesLayer.getFL().LayerInfo.Relationships;

            log(string.Format("Execute, getrelid.1, rels.count '{0}'", rels.Count()));
            if (rels.Count() <= 0)
            {
                log(string.Format("Execute, relationships.count <= 0"));
                throw new Exception(string.Format("У выбранного слоя нет связей с другими таблицами"));
            }
            else if (rels.Count() > 1)
            {
                log(string.Format("Execute, relationships.count > 1"));
                if (relationsListForm.relationsList.Count > 0)
                {
                    // continue after user input
                    relationInfo = relationsListForm.listBox1.SelectedItem as mwb02.AddIns.VRelationInfo;
                    relationsListForm.relationsList.Clear();
                }                 // user select relID already
                else
                {
                    // new query
                    relationInfo = null;
                    foreach (var r in rels)
                    {
                        var ri = storedFL.getRelation(r);
                        if (ri == null)
                        {
                            ri = new mwb02.AddIns.VRelationInfo(r);
                        }
                        ri.oid = clickedLayer.getOID(inputFeature);
                        if (ri.oid == -1)
                        {
                            log(string.Format("featurelayer.getOID returns invalid OID; {0}", clickedLayer.lyrUrl));
                            continue;
                        }
                        relationsListForm.relationsList.Add(ri);
                    }
                    relationsListForm.listBox1.SelectedItem = relationsListForm.relationsList.First();
                    MapApplication.Current.ShowWindow("Relations",
                                                      relationsListForm,
                                                      false,                                                                      // ismodal
                                                      (sender, canceleventargs) => { log("relationsListForm onhidINGhandler"); }, // onhidinghandler
                                                      (sender, eventargs) => {
                        log("relationsListForm onhidEhandler");
                        //if(relationsListForm.listBox1.SelectedItem != null)
                        Execute(parameter);
                    },                             // onhidehandler
                                                      WindowType.Floating
                                                      );
                    return; // wait for user input
                }           // new query
            }               // rels.count > 1
            else            // rels.count == 1
            {
                log(string.Format("Execute, relationships.count = 1"));
                relationInfo = new mwb02.AddIns.VRelationInfo(rels.First());
            }

            // ok, we get relation info now
            if (relationInfo == null)
            {
                throw new Exception("Не указана связанная таблица");
            }
            log(string.Format("Execute, getrelid.2, relationshipID '{0}', rels.count '{1}'", relationInfo.id, rels.Count()));

            // Get the name of the ObjectID field.
            objectID = clickedLayer.getOIDFieldnameOrAlias();

            // get key value
            int objIdValue = clickedLayer.getOID(inputFeature);

            if (objIdValue == -1)
            {
                // Attributes key = 'Object ID' but ObjectIdField = 'OBJECTID'
                var ks = string.Join(", ", inputFeature.Attributes.Keys);                 // inputFeature.AttributesKeys='Object ID, Shape, Field KID,
                var vs = string.Join(", ", inputFeature.Attributes.Values);
                log(string.Format("Execute, inputFeature.AttributesKeys='{0}', values='{1}'", ks, vs));
                throw new Exception(string.Format("Поле OBJECTID не содержит целого числа"));
            }
            log(string.Format("Execute, objIdValue.int='{0}'", objIdValue));

            // Input parameters for QueryTask
            RelationshipParameter relationshipParameters = new RelationshipParameter()
            {
                ObjectIds           = new int[] { objIdValue },
                OutFields           = new string[] { "*" }, // Return all fields
                ReturnGeometry      = true,                 // Return the geometry so that features can be displayed on the map if applicable
                RelationshipId      = relationInfo.id,      // Obtain the desired RelationshipID from the Service Details page. Here it takes the first relationship it finds if there is more than one.
                OutSpatialReference = MapApplication.Current.Map.SpatialReference
            };

            log(string.Format("Execute, relationshipParameters set"));

            // Specify the Feature Service url for the QueryTask.
            if (queryTask.IsBusy)
            {
                throw new Exception("Выполняется предыдущий запрос, попробуйте позже");
            }
            queryTask.Url = relatesLayer.lyrUrl;

            //  Execute the Query Task with specified parameters
            queryTask.ExecuteRelationshipQueryAsync(relationshipParameters);

            // Find the attribute grid in the Pop-up and insert the BusyIndicator
            attributeGrid = Utils.FindChildOfType <Grid>(popupInfo.AttributeContainer, 3);
            indicator     = new BusyIndicator();
            if (attributeGrid != null)
            {
                // Add the Busy Indicator
                attributeGrid.Children.Add(indicator);
                indicator.IsBusy = true;
            }

            log(string.Format("Execute, completed, wait for QueryTask_ExecuteRelationshipQueryCompleted"));
        }         // public void doExecute(object parameter)
Exemplo n.º 13
0
 static void layer_EndSaveEdits(object sender, Client.Tasks.EndEditEventArgs e)
 {
     EditShape(_viewModel);
     // let go of the viewmodel
     _viewModel = null;
 }
Exemplo n.º 14
0
        /// <summary>
        /// Retrieves the pop-up info and determines whether there is more than one relationship for the layer. If there is more
        /// than one, the relationships are displayed in a list for the user to choose from before proceeding.
        /// </summary>
        /// <param name="parameter">OnClickPopupInfo from clicked layer</param>
        public void Execute(object parameter)
        {
            relationshipList.Clear();

            OnClickPopupInfo popupInfo = parameter as OnClickPopupInfo;

            popupWindow = popupInfo.Container as InfoWindow;

            // Instantiate the View Model
            if (vm == null)
            {
                vm = new QueryRelatedViewModel(relationshipList, MapApplication.Current.Map);
            }

            // Instantiate the Relationship View
            if (relationshipView == null)
            {
                relationshipView = new RelationshipSelectionView();
            }

            // Instantiate the Keep on Map View
            if (keepOnMapView == null)
            {
                keepOnMapView = new KeepOnMap();
            }

            // Instantiate the No results found View
            if (noRecordsView == null)
            {
                noRecordsView = new NoRecordsFoundView();
            }

            // Set the variables on the ViewModel
            vm.PopupInfo          = popupInfo;
            vm.KeepOnMapView      = keepOnMapView;
            vm.RelationshipView   = relationshipView;
            vm.NoRecordsFoundView = noRecordsView;

            // Set the data context of the RelationshipView and the KeepOnMapView to the QueryRelatedViewModel
            relationshipView.DataContext = vm;
            keepOnMapView.DataContext    = vm;
            noRecordsView.DataContext    = vm;

            // Get the layer info from the pop-up to access the Relationships. Verify the layer is a FeatureLayer to proceed.
            FeatureLayer relatesLayer;
            Layer        lyr = popupInfo.PopupItem.Layer;

            if (lyr is FeatureLayer)
            {
                relatesLayer = lyr as FeatureLayer;

                // Check the number of relationships for the layer
                int relCount = relatesLayer.LayerInfo.Relationships.Count();
                if (relCount > 1) // Layer has more than one relationship
                {
                    foreach (Relationship rel in relatesLayer.LayerInfo.Relationships)
                    {
                        relationshipList.Add(rel);
                    }

                    numberOfRelates = string.Format(Strings.RelationshipsFound,
                                                    relatesLayer.LayerInfo.Relationships.Count().ToString());
                    vm.NumberOfRelationships = numberOfRelates;

                    // Add the available relationships view to the popupWindow.
                    Grid infoWindowGrid = Utils.FindChildOfType <Grid>(popupWindow, 3);
                    infoWindowGrid.Children.Add(relationshipView);


                    // Can now navigate back to attributes and close the popup from the relationship view,
                    // so notify about change in executable state
                    ((DelegateCommand)vm.GoBack).RaiseCanExecuteChanged();
                    ((DelegateCommand)vm.CloseRelationshipView).RaiseCanExecuteChanged();
                }
                else // Layer only has one relationship, so can use Relationship.First to retrieve the ID.
                {
                    // Set the SelectedRelationship property on the ViewModel
                    vm.SelectedRelationship = relatesLayer.LayerInfo.Relationships.First();
                    // Call Execute method on the ViewModel
                    vm.QueryRelated.Execute(vm.SelectedRelationship);
                }
            }
            else
            {
                return;
            }
        }
Exemplo n.º 15
0
        } // public void Execute(object parameter)

        /// <summary>
        /// Executes the relationship query against the layer.
        /// </summary>
        /// <param name="parameter">The OnClickPopupInfo from the layer.</param>
        public void doExecute(object parameter)
        {
            // The plan is:
            // Get the featurelayer and clicked feature from the pop-up.
            // The PopupItem property of OnClickPopupInfo provides information
            // about the item currently shown in the pop-up.
            // Then get feature ID value and put it into ExecuteRelationshipQueryAsync task.
            // Then get related records ID's and create FeatureLayer from
            // related table/feature class, filtered by that ID's.
            // Then show grid for that layer.
            popupInfo    = parameter as OnClickPopupInfo;
            inputFeature = popupInfo.PopupItem.Graphic;
            var lyr = new VUtils.ArcGIS.SLViewer.VLayer(popupInfo.PopupItem.Layer);

            // print layer info to console
            log(string.Format(
                    "Execute, layer type '{0}', popupInd '{1}', popupDescr '{2}', lyrID '{3}', lyrName '{4}', title '{5}'",
                    popupInfo.PopupItem.Layer.GetType(),
                    popupInfo.SelectedIndex, popupInfo.SelectionDescription,
                    popupInfo.PopupItem.LayerId, popupInfo.PopupItem.LayerName, popupInfo.PopupItem.Title));
            log(string.Format("Execute, lyrType '{0}', lyrUrl '{1}'", lyr.lyrType, lyr.lyrUrl));
            log(string.Format("Execute, inputFeature.Attributes.Count '{0}'", inputFeature.Attributes.Count));

            // we need FeatureLayer
            if (lyr.lyrType == "FeatureLayer")
            {
                // The layer to get related records for.
                // This is used to get the RelationshipID and Query url.
                relatesLayer = lyr.lyr as FeatureLayer;
            }
            else if (lyr.lyrType == "ArcGISDynamicMapServiceLayer")
            {
                var rLyr = getSubLayer(lyr, popupInfo.PopupItem.LayerId) as FeatureLayer;
                if (relatesLayer != null && relatesLayer.Url == rLyr.Url)
                {
                    // we're here after relatesLayer.Initialized
                    ;
                }
                else
                {
                    // init new FeatureLayer
                    relatesLayer              = rLyr;
                    relatesLayer.Initialized += (a, b) => {
                        if (relatesLayer.InitializationFailure == null)
                        {
                            var info = relatesLayer.LayerInfo;
                            log(string.Format(
                                    "Execute, relatesLayer.InitializationFailure == null, info '{0}'",
                                    info));
                            Execute(parameter);
                        }
                    }; // callback
                    relatesLayer.Initialize();
                    log(string.Format("Execute, relatesLayer.Initialize called, wait..."));
                    return;
                } // init new FeatureLayer
            }     // if(lyr.lyrType == "ArcGISDynamicMapServiceLayer")
            else
            {
                throw new Exception("Layer type must be FeatureLayer or ArcGISDynamicMapServiceLayer");
            }

            // we have inited FeatureLayer now
            if (relatesLayer.LayerInfo == null)
            {
                throw new Exception(string.Format("Execute, relatesLayer.LayerInfo == null"));
            }
            var clickedLayer = new VUtils.ArcGIS.SLViewer.VLayer(relatesLayer);

            // check FeatureLayer info
            log(string.Format(
                    "Execute, relatesLayer lyrType '{0}', lyrUrl '{1}'",
                    clickedLayer.lyrType, clickedLayer.lyrUrl));

            // get relationship id
            var rels = relatesLayer.LayerInfo.Relationships;

            if (rels.Count() <= 0)
            {
                log(string.Format("Execute, relationships.count <= 0"));
                throw new Exception(string.Format("Layer have not relations"));
            }
            else if (rels.Count() > 1)
            {
                log(string.Format("Execute, relationships.count > 1"));
                if (relationsListForm.listBox1.Items.Count > 0)
                {
                    // continue after user input
                    // user selected relID already
                    relationInfo = new VUtils.ArcGIS.SLViewer.VRelationInfo(
                        relationsListForm.listBox1.SelectedItem as string);
                    relationsListForm.listBox1.Items.Clear();
                }
                else
                {
                    // new query
                    foreach (var r in rels)
                    {
                        var ri = new VUtils.ArcGIS.SLViewer.VRelationInfo(r);
                        relationsListForm.listBox1.Items.Add(ri.descr);
                    }
                    relationsListForm.listBox1.SelectedItem = relationsListForm.listBox1.Items.First();
                    MapApplication.Current.ShowWindow("Relations",
                                                      relationsListForm,
                                                      false, // ismodal
                                                      (sender, canceleventargs) => {
                        log("relationsListForm onhidINGhandler");
                    },     // onhidinghandler
                                                      (sender, eventargs) => {
                        log("relationsListForm onhidEhandler");
                        if (relationsListForm.listBox1.SelectedItem != null)
                        {
                            Execute(parameter);
                        }
                    },     // onhidehandler
                                                      WindowType.Floating
                                                      );
                    return; // wait for user input
                } // new query
            } // rels.count > 1
            else   // rels.count == 1
            {
                log(string.Format("Execute, relationships.count = 1"));
                relationInfo = new VUtils.ArcGIS.SLViewer.VRelationInfo(rels.First());
            }

            // ok, we get relation info now
            log(string.Format(
                    "Execute, getrelid, relationshipID '{0}', rels.count '{1}'",
                    relationInfo.id, rels.Count()));

            // Get the name of the ObjectID field.
            objectID = relatesLayer.LayerInfo.ObjectIdField;
            string objectIDAlias = clickedLayer.getFieldAlias(objectID);

            log(string.Format("Execute, objectID '{0}', alias '{1}'", objectID, objectIDAlias));
            if (objectIDAlias != "")
            {
                objectID = objectIDAlias;                     // because of bug? in Graphic.Attributes[fieldname]
            }
            // get key value
            Object v = null;

            v = inputFeature.Attributes[objectID];
            log(string.Format("Execute, objIdValue.str='{0}'", v));
            int objIdValue = -1;

            try {
                objIdValue = Int32.Parse(string.Format("{0}", v));
            }
            catch (Exception ex) {
                // fieldname = 'OBJECTID' but alias = 'Object ID'
                var ks = string.Join(", ", inputFeature.Attributes.Keys);
                var vs = string.Join(", ", inputFeature.Attributes.Values);
                log(string.Format("Execute, inputFeature.AttributesKeys='{0}', values='{1}'", ks, vs));
                throw new Exception(string.Format("OBJECTID is not an integer"));
            }
            log(string.Format("Execute, objIdValue.int='{0}'", objIdValue));

            // Input parameters for QueryTask
            RelationshipParameter relationshipParameters = new RelationshipParameter()
            {
                ObjectIds      = new int[] { objIdValue },
                OutFields      = new string[] { "*" }, // Return all fields
                ReturnGeometry = true,                 // Return the geometry
                // so that features can be displayed on the map if applicable

                RelationshipId = relationInfo.id, // Obtain the desired RelationshipID
                // from the Service Details page. Here it takes the first relationship
                // it finds if there is more than one.

                OutSpatialReference = MapApplication.Current.Map.SpatialReference
            };

            // Specify the Feature Service url for the QueryTask.
            queryTask.Url = relatesLayer.Url;

            //  Execute the Query Task with specified parameters
            queryTask.ExecuteRelationshipQueryAsync(relationshipParameters);

            // Find the attribute grid in the Pop-up and insert the BusyIndicator
            attributeGrid = Utils.FindChildOfType <Grid>(popupInfo.AttributeContainer, 3);
            indicator     = new BusyIndicator();
            if (attributeGrid != null)
            {
                // Add the Busy Indicator
                attributeGrid.Children.Add(indicator);
                indicator.IsBusy = true;
            }

            log(string.Format("Execute, completed, wait for QueryTask_ExecuteRelationshipQueryCompleted"));
        } // public void doExecute(object parameter)
        private void DoIdentify()
        {
            if (Map == null)
            {
                return;
            }

            if (PendingIdentifies > 0 && identifyTasks != null)
            {
                foreach (IdentifyTask task in identifyTasks)
                {
                    task.CancelAsync();
                }
            }
            identifyTasks = new List <IdentifyTask>();
            List <IdentifyParameters> parameters = new List <IdentifyParameters>();
            List <Layer> layers = new List <Layer>();
            List <GraphicsLayerResult> graphicsLayerResults = new List <GraphicsLayerResult>();

            identifyTaskResults = new List <object>();
            IdentifyTask identifyTask;

            _popupInfo = MapApplication.Current.GetPopup(null, null);

            // Watch for property changes on the view model. The one in particular that this event handler is interested
            // in is when the popupitem changes. When this happens we will want to then establish a new event handler for
            // when properties change of the popupitem. In particular, when the Graphic property changes so that we can
            // reconstruct the header value for the popup if the value that changed was the field used to display in the
            // header.
            _popupInfo.PropertyChanged += _popupInfo_PropertyChanged;

            for (int i = Map.Layers.Count - 1; i >= 0; i--)
            {
                Layer layer = Map.Layers[i];
                if (!ESRI.ArcGIS.Client.Extensibility.LayerProperties.GetIsPopupEnabled(layer))
                {
                    continue;
                }
                if (!layer.Visible)
                {
                    continue;
                }
                if (layer is ArcGISDynamicMapServiceLayer || layer is ArcGISTiledMapServiceLayer)
                {
                    Collection <int> layerIds = getIdentifyLayerIds(layer);

                    // If layer is a dynamic map service layer, get layer definitions
                    IEnumerable <LayerDefinition> layerDefinitions = null;
                    IEnumerable <TimeOption>      timeOptions      = null;
                    if (layer is ArcGISDynamicMapServiceLayer)
                    {
                        var dynamicLayer = (ArcGISDynamicMapServiceLayer)layer;
                        if (dynamicLayer.LayerDefinitions != null)
                        {
                            layerDefinitions = dynamicLayer.LayerDefinitions.Where(
                                l => layerIds.Contains(l.LayerID));
                        }

                        if (dynamicLayer.LayerTimeOptions != null)
                        {
                            timeOptions = dynamicLayer.LayerTimeOptions.Where(
                                to => layerIds.Contains(int.Parse(to.LayerId)));
                        }
                        else if (dynamicLayer.TimeExtent != null)
                        {
                            timeOptions = dynamicLayer.Layers.Select(l => new TimeOption()
                            {
                                LayerId = l.ID.ToString(),
                                UseTime = true
                            });
                        }
                    }

                    if ((layer.GetValue(ESRI.ArcGIS.Mapping.Core.LayerExtensions.LayerInfosProperty) as Collection <LayerInformation>)
                        == null) //require layer infos
                    {
                        continue;
                    }
                    if ((layerIds != null && layerIds.Count > 0))
                    {
                        identifyTask = new IdentifyTask(IdentifySupport.GetLayerUrl(layer));
                        identifyTask.ExecuteCompleted += IdentifyTask_ExecuteCompleted;
                        identifyTask.Failed           += IdentifyTask_Failed;

                        string proxy = IdentifySupport.GetLayerProxyUrl(layer);
                        if (!string.IsNullOrEmpty(proxy))
                        {
                            identifyTask.ProxyURL = proxy;
                        }

                        int width, height;
                        if (!int.TryParse(Map.ActualHeight.ToString(), out height))
                        {
                            height = 100;
                        }
                        if (!int.TryParse(Map.ActualWidth.ToString(), out width))
                        {
                            width = 100;
                        }
                        IdentifyParameters identifyParams = new IdentifyParameters()
                        {
                            Geometry         = clickPoint,
                            MapExtent        = Map.Extent,
                            SpatialReference = Map.SpatialReference,
                            LayerOption      = LayerOption.visible,
                            Width            = width,
                            Height           = height,
                            LayerDefinitions = layerDefinitions,
                            TimeExtent       = AssociatedObject.TimeExtent,
                            TimeOptions      = timeOptions
                        };
                        foreach (int item in layerIds)
                        {
                            identifyParams.LayerIds.Add(item);
                        }
                        identifyTasks.Add(identifyTask);
                        parameters.Add(identifyParams);
                        layers.Add(layer);
                    }
                }
                else if (layer is GraphicsLayer &&
                         ESRI.ArcGIS.Mapping.Core.LayerExtensions.GetPopUpsOnClick(layer as GraphicsLayer))
                {
                    GraphicsLayer         graphicsLayer = layer as GraphicsLayer;
                    GeneralTransform      t             = GetTransformToRoot(Map);
                    IEnumerable <Graphic> selected      = Core.Utility.FindGraphicsInHostCoordinates(graphicsLayer, t.Transform(Map.MapToScreen(clickPoint)));
                    if (selected != null)
                    {
                        List <Graphic> results = new List <Graphic>(selected);
                        if (results.Count > 0)
                        {
                            graphicsLayerResults.Add(new GraphicsLayerResult()
                            {
                                Layer        = graphicsLayer,
                                Results      = results,
                                ClickedPoint = clickPoint
                            });
                        }
                    }
                }
            }
            PendingIdentifies = identifyTasks.Count + graphicsLayerResults.Count;
            if (PendingIdentifies > 0)
            {
                for (int i = 0; i < identifyTasks.Count; i++)
                {
                    identifyTasks[i].ExecuteAsync(parameters[i], new UserState()
                    {
                        ClickedPoint = clickPoint, Layer = layers[i]
                    });
                }
                for (int i = 0; i < graphicsLayerResults.Count; i++)
                {
                    reportResults(graphicsLayerResults[i]);
                }
            }
        }
Exemplo n.º 17
0
        private static void OnEditorEditCompleted(object sender, ESRI.ArcGIS.Client.Editor.EditEventArgs e)
        {
            FindEditorInVisualTree();
            if (_editor == null || _widget == null)
            {
                return;
            }

            if (EditorConfiguration.Current.ShowAttributesOnAdd && e.Action == ESRI.ArcGIS.Client.Editor.EditAction.Add)
            {
                foreach (ESRI.ArcGIS.Client.Editor.Change change  in e.Edits)
                {
                    var layer = change.Layer as FeatureLayer;
                    if (layer != null && change.Graphic != null && View.Instance != null && View.Instance.Map != null)
                    {
                        OnClickPopupInfo vm = MapApplication.Current.GetPopup(change.Graphic, layer);
                        if (vm != null)
                        {
                            PopupItem localPopupItem = vm.PopupItem;
                            if (localPopupItem == null && vm.PopupItems != null && vm.PopupItems.Count >= 1)
                            {
                                localPopupItem = vm.PopupItems[0];
                            }

                            if (localPopupItem != null && localPopupItem.Graphic != null && localPopupItem.Graphic.Geometry != null)
                            {
                                MapPoint popupAnchor = null;
                                MapPoint pt          = localPopupItem.Graphic.Geometry as MapPoint;
                                if (pt != null)
                                {
                                    // This is a point feature.  Show the popup just above it and ignore edit handles
                                    Point screenPoint = View.Instance.Map.MapToScreen(pt);
                                    popupAnchor = View.Instance.Map.ScreenToMap(new Point(screenPoint.X, screenPoint.Y - 4));
                                }
                                else if (localPopupItem.Graphic.Geometry is Polygon)
                                {
                                    if (_editor.MoveEnabled || _editor.RotateEnabled || _editor.ScaleEnabled)
                                    {
                                        // editing is enabled
                                        Envelope env   = localPopupItem.Graphic.Geometry.Extent;
                                        MapPoint tmpPt = new MapPoint(env.XMax - ((env.XMax - env.XMin) / 2.0), env.YMax);
                                        // Show the popup at the top/center of the graphic extent minus 4pixels
                                        Point screenPoint = View.Instance.Map.MapToScreen(tmpPt);
                                        popupAnchor = View.Instance.Map.ScreenToMap(new Point(screenPoint.X, screenPoint.Y - 4));
                                    }
                                    else
                                    {
                                        // no edit handles - position to northern most vertex
                                        popupAnchor = GetNorthernMostPointPolygon(localPopupItem.Graphic.Geometry as Polygon);
                                    }
                                }
                                else if (localPopupItem.Graphic.Geometry is Polyline)
                                {
                                    if (_editor.MoveEnabled || _editor.RotateEnabled || _editor.ScaleEnabled)
                                    {
                                        // editing is enabled
                                        Envelope env   = localPopupItem.Graphic.Geometry.Extent;
                                        MapPoint tmpPt = new MapPoint(env.XMax - ((env.XMax - env.XMin) / 2.0), env.YMax);
                                        // Show the popup at the top/center of the graphic extent minus 4pixels
                                        Point screenPoint = View.Instance.Map.MapToScreen(tmpPt);
                                        popupAnchor = View.Instance.Map.ScreenToMap(new Point(screenPoint.X, screenPoint.Y - 4));
                                    }
                                    else
                                    {
                                        // no edit handles - position to northern most vertex
                                        popupAnchor = GetNorthernMostPointPolyline(localPopupItem.Graphic.Geometry as Polyline);
                                    }
                                }

                                // Show the identify popup
                                if (popupAnchor != null && vm.Container != null)
                                {
                                    EditValuesCommand cmd = PopupHelper.ShowPopup(vm, popupAnchor);

                                    vm.Container.Dispatcher.BeginInvoke(() =>
                                    {
                                        if (cmd == null)
                                        {
                                            cmd = new EditValuesCommand();
                                        }
                                        cmd.Execute(vm);
                                    });
                                    _viewModel = vm;
                                    // wait until layer edits are done before editing the shape
                                    if (layer.AutoSave)
                                    {
                                        layer.EndSaveEdits -= layer_EndSaveEdits;
                                        layer.EndSaveEdits += layer_EndSaveEdits;
                                    }
                                    else
                                    {
                                        // in case auto save is off, wait until the popup has loaded
                                        vm.Container.Loaded -= OnIdentifyPopupLoaded;
                                        vm.Container.Loaded += OnIdentifyPopupLoaded;
                                    }
                                }
                            }
                        }
                        break;
                    }
                }
            }
        }