/// <summary>
        /// Adds a new related record to highlighted feature.
        /// </summary>
        private async void AddButton_Click(object sender, RoutedEventArgs e)
        {
            SetAttributeEditor();
            var    featureID = (Int64)AddButton.Tag;
            var    requestID = (string)RelatedRecords.Tag;
            string message   = null;

            try
            {
                if (table == null)
                {
                    table = await GetRelatedTableAsync();
                }
                var feature = new GeodatabaseFeature(table.Schema);
                feature.Attributes[relationship.KeyField] = requestID;
                feature.Attributes["rank"]     = 5;
                feature.Attributes["comments"] = "Describe service requirement here.";
                feature.Attributes["submitdt"] = DateTime.UtcNow;
                var relatedFeatureID = await table.AddAsync(feature);
                await SaveEditsAsync();
                await QueryRelatedRecordsAsync();
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            if (!string.IsNullOrWhiteSpace(message))
            {
                await new MessageDialog(message).ShowAsync();
            }
        }
        /// <summary>
        /// Removes selected feature and updates the layer.
        /// </summary>
        /// <param name="feature">Feature to remove.</param>
        private async void RemoveFeature(GeodatabaseFeature feature)
        {
            if (feature == null)
            {
                return;
            }

            Exception exceptionToHandle = null;

            try
            {
                await _selectedLayer.FeatureTable.DeleteAsync(feature);

                // Save edits to the service if using ServiceTable
                if (_selectedLayer.FeatureTable is GeodatabaseFeatureServiceTable)
                {
                    var featureTable = (GeodatabaseFeatureServiceTable)_selectedLayer.FeatureTable;
                    await featureTable.ApplyEditsAsync();
                }
            }
            catch (Exception exception)
            {
                exceptionToHandle = exception;
            }

            if (exceptionToHandle != null)
            {
                await MessageService.Instance.ShowMessage(string.Format(
                                                              "Could not delete selected feature. Error = {0}", exceptionToHandle.ToString()),
                                                          "An error occured");
            }
        }
        /// <summary>
        /// Adds new feature on tap.
        /// </summary>
        private async void AddButton_Click(object sender, RoutedEventArgs e)
        {
            var    layer   = MyMapView.Map.Layers["Notes"] as FeatureLayer;
            var    table   = layer.FeatureTable;
            string message = null;

            try
            {
                var mapPoint = await MyMapView.Editor.RequestPointAsync();

                var feature = new GeodatabaseFeature(table.Schema)
                {
                    Geometry = mapPoint
                };
                await table.AddAsync(feature);
            }
            catch (TaskCanceledException te)
            {
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            if (!string.IsNullOrWhiteSpace(message))
            {
                MessageBox.Show(message);
            }
        }
Ejemplo n.º 4
0
		public static GeodatabaseFeature Clone(this GeodatabaseFeature feature)
        {
            if (feature == null) return null;

			var clone = new GeodatabaseFeature(feature.Schema);
            clone.CopyFrom(feature.Attributes);
            return clone;
        }
Ejemplo n.º 5
0
        public static FieldInfo GetFieldInfo(this GeodatabaseFeature feature, string fieldName)
        {
            if (feature == null || string.IsNullOrEmpty(fieldName))
            {
                return(null);
            }

            return(feature.Schema.Fields.FirstOrDefault(x => x.Name == fieldName));
        }
        /// <summary>
        /// Edits the feature. On points it request new location and on polylines and
        /// polygons editing existing geometry is requested by using Editor.
        /// </summary>
        /// <param name="feature">Feature to edit.</param>
        /// <remarks>Edits are saved immediately.</remarks>
        private async void EditFeature(GeodatabaseFeature feature)
        {
            if (feature == null)
            {
                return;
            }

            Exception exceptionToHandle = null;

            try
            {
                switch (feature.Geometry.GeometryType)
                {
                case GeometryType.Point:
                    var newLocation = await Editor.RequestPointAsync();

                    feature.Geometry = newLocation;
                    break;

                case GeometryType.Polyline:     // Could be combined with polygon to reduce lines, but could do more stuff here if needed
                    var polyine = await Editor.EditGeometryAsync(feature.Geometry, null, _editingProgress);

                    feature.Geometry = polyine;
                    break;

                case GeometryType.Polygon:
                    var polygon = await Editor.EditGeometryAsync(feature.Geometry, null, _editingProgress);

                    feature.Geometry = polygon;
                    break;
                }

                await _selectedLayer.FeatureTable.UpdateAsync(feature);

                // Save edits to the service if using ServiceTable
                if (_selectedLayer.FeatureTable is GeodatabaseFeatureServiceTable)
                {
                    var featureTable = (GeodatabaseFeatureServiceTable)_selectedLayer.FeatureTable;
                    await featureTable.ApplyEditsAsync();
                }
            }
            catch (TaskCanceledException editCancelledException)
            {
                // This is raised when editing is cancelled so eat it.
            }
            catch (Exception exception)
            {
                exceptionToHandle = exception;
            }

            if (exceptionToHandle != null)
            {
                await MessageService.Instance.ShowMessage(string.Format(
                                                              "Could not edit or update selected feature. Error = {0}", exceptionToHandle.ToString()),
                                                          "An error occured");
            }
        }
        /// <summary>
        /// Selects feature.
        /// </summary>
        private async void SelectFeature(MapViewInputEventArgs parameters)
        {
            // If editor is active skip selecting features
            if (Editor.IsActive)
            {
                return;
            }

            // Unselect all features
            var featureLayers = Map.Layers.OfType <FeatureLayer>();

            foreach (var layer in featureLayers)
            {
                layer.ClearSelection();
            }

            GeodatabaseFeature feature           = null;
            Exception          exceptionToHandle = null;

            try
            {
                foreach (var layer in featureLayers.Where(l => l.Status == LayerStatus.Initialized).Reverse())
                {
                    // Using MapViewService to handle hit testing.
                    var hit = await MapViewService.HitTestAsync(parameters.Position, layer) as GeodatabaseFeature;

                    if (hit != null)
                    {
                        // Set feature selected
                        layer.SelectFeatures(new[] { (long)hit.Attributes[layer.FeatureTable.ServiceInfo.ObjectIdField] });

                        // Take feature and its layer for later use
                        feature        = hit;
                        _selectedLayer = layer;
                        break;
                    }
                }
            }
            catch (Exception exception)
            {
                exceptionToHandle = exception;
            }

            if (exceptionToHandle != null)
            {
                // Initialization failed, show message and return
                await MessageService.Instance.ShowMessage(string.Format(
                                                              "Could not create basemap. Error = {0}", exceptionToHandle.ToString()),
                                                          "An error occured");
            }

            // Select or clear selection
            SelectedFeature = feature;
        }
Ejemplo n.º 8
0
        public static GeodatabaseFeature Clone(this GeodatabaseFeature feature)
        {
            if (feature == null)
            {
                return(null);
            }

            var clone = new GeodatabaseFeature(feature.Schema);

            clone.CopyFrom(feature.Attributes);
            return(clone);
        }
        /// <summary>
        /// Creates a UI control for editing each field.
        /// </summary>
        /// <param name="feature">The feature.</param>
        /// <param name="fieldInfo">FieldInfo for edit control</param>
        /// <param name="isReadOnly">Value indicating if control should be readonly</param>
        /// <returns></returns>
        private FrameworkElement CreateControl(GeodatabaseFeature feature, FieldInfo fieldInfo, bool isReadOnly)
        {
            var control = new FeatureDataField
            {
                GeodatabaseFeature = feature,
                FieldName          = fieldInfo.Name,
                IsReadOnly         = isReadOnly,
            };

            control.PropertyChanged += ControlOnPropertyChanged;
            return(control);
        }
        private async void MyMapView_MapViewTapped(object sender, Esri.ArcGISRuntime.Controls.MapViewInputEventArgs e)
        {
            try
            {
                if (MyDataForm.ResetCommand.CanExecute(null))
                {
                    MyDataForm.ResetCommand.Execute(null);
                }

                MyDataForm.GeodatabaseFeature = null;

                if (_editedLayer != null)
                {
                    _editedLayer.ClearSelection();
                }

                foreach (var layer in MyMapView.Map.Layers.OfType <FeatureLayer>().Reverse())
                {
                    // Get possible features and if none found, move to next layer
                    var foundFeatures = await layer.HitTestAsync(MyMapView, new Rect(e.Position, new Size(10, 10)), 1);

                    if (foundFeatures.Count() == 0)
                    {
                        continue;
                    }

                    // Get feature from table
                    var feature = await layer.FeatureTable.QueryAsync(foundFeatures[0]);

                    // Change UI
                    DescriptionTextArea.Visibility = Visibility.Collapsed;
                    DataFormArea.Visibility        = Visibility.Visible;

                    _editedFeature = feature as GeodatabaseFeature;
                    _editedLayer   = layer;
                    _editedLayer.SelectFeatures(new long[] { foundFeatures[0] });

                    // Set feature that is being edited to data form
                    MyDataForm.GeodatabaseFeature = _editedFeature;
                    return;
                }

                // No features found
                DescriptionTextArea.Visibility = Visibility.Visible;
                DataFormArea.Visibility        = Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Error occured : {0}", ex.ToString()), "Sample error");
            }
        }
        /// <summary>
        /// This will override all edit feature changes back
        /// to the original feature values.
        /// </summary>
        private void Reset()
        {
            if (_editFeature == null || GeodatabaseFeature == null)
            {
                return;
            }

            // copy original feature back to edit feature
            _editFeature = GeodatabaseFeature.Clone();
            HasEdits     = false;
            HasError     = false;
            ((ActionCommand)ApplyCommand).RaiseCanExecute();
            ((ActionCommand)ResetCommand).RaiseCanExecute();
            Refresh();
        }
		private async void MyMapView_MapViewTapped(object sender, Esri.ArcGISRuntime.Controls.MapViewInputEventArgs e)
		{
			try
			{
				if (MyDataForm.ResetCommand.CanExecute(null))
					MyDataForm.ResetCommand.Execute(null);

				MyDataForm.GeodatabaseFeature = null;

				if (_editedLayer != null)
					_editedLayer.ClearSelection();

				foreach (var layer in MyMapView.Map.Layers.OfType<FeatureLayer>().Reverse())
				{
					// Get possible features and if none found, move to next layer
					var foundFeatures = await layer.HitTestAsync(MyMapView, new Rect(e.Position, new Size(10, 10)), 1);
					if (foundFeatures.Count() == 0)
						continue;

					// Get feature from table
					var feature = await layer.FeatureTable.QueryAsync(foundFeatures[0]);

					// Change UI
					DescriptionTextArea.Visibility = Visibility.Collapsed;
					DataFormArea.Visibility = Visibility.Visible;

					_editedFeature = feature as GeodatabaseFeature;
					_editedLayer = layer;
					_editedLayer.SelectFeatures(new long[] { foundFeatures[0] });

					// Set feature that is being edited to data form
					MyDataForm.GeodatabaseFeature = _editedFeature;
					return;
				}

				// No features found
				DescriptionTextArea.Visibility = Visibility.Visible;
				DataFormArea.Visibility = Visibility.Collapsed;
			}
			catch (Exception ex)
			{
				var _x = new MessageDialog(string.Format("Error occured : {0}", ex.ToString()), "Sample error").ShowAsync();
			}
		}
Ejemplo n.º 13
0
        // Adds a new bird row to the local geodatabase
        private async void RegisterBirdSightingButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var birdsTable = LocalBirdsLayer.FeatureTable as ArcGISFeatureTable;
                if (birdsTable == null)
                {
                    throw new ApplicationException("Birds table was not found in the local geodatabase.");
                }

                var bird = new GeodatabaseFeature(birdsTable.Schema);
                bird.Geometry = TapLocation;

                if (bird.Schema.Fields.Any(fld => fld.Name == "type"))
                {
                    bird.Attributes["type"] = comboBirdType.SelectedValue;
                }
                if (bird.Schema.Fields.Any(fld => fld.Name == "comments"))
                {
                    bird.Attributes["comments"] = txtComment.Text;
                }
                if (bird.Schema.Fields.Any(fld => fld.Name == "creator"))
                {
                    bird.Attributes["creator"] = "DOTNET_SAMPLE";
                }
                if (bird.Schema.Fields.Any(fld => fld.Name == "created_date"))
                {
                    bird.Attributes["created_date"] = DateTime.Now;
                }

                var id = await birdsTable.AddAsync(bird);

                await RefreshDataView();

                _graphicsOverlay.Graphics.Clear();
                IsEditing = false;
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
        /// <summary>
        /// This will save edit featue changes back to original feature.
        /// </summary>
        private void ApplyChanges()
        {
            if (_editFeature == null || GeodatabaseFeature == null)
            {
                return;
            }

            // copy edit feature back to original feature
            GeodatabaseFeature.CopyFrom(_editFeature.Attributes);
            HasEdits = false;
            HasError = false;
            ((ActionCommand)ApplyCommand).RaiseCanExecute();
            ((ActionCommand)ResetCommand).RaiseCanExecute();

            // Notify user that Apply has been completed.
            var handler = ApplyCompleted;

            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }
 /// <summary>
 /// Adds new feature on tap.
 /// </summary>
 private async void AddButton_Click(object sender, RoutedEventArgs e)
 {
     var layer = MyMapView.Map.Layers["Notes"] as FeatureLayer;
     var table = layer.FeatureTable;
     string message = null;
     try
     {
         var mapPoint = await MyMapView.Editor.RequestPointAsync();
         var feature = new GeodatabaseFeature(table.Schema)
         {
             Geometry = mapPoint
         };
         await table.AddAsync(feature);
     }
     catch (TaskCanceledException te)
     {
     }
     catch (Exception ex)
     {
         message = ex.Message;
     }
     if (!string.IsNullOrWhiteSpace(message))
         await new MessageDialog(message).ShowAsync();
 }
        /// <summary>
        /// Selects feature.
        /// </summary>
        private async void SelectFeature(MapViewInputEventArgs parameters)
        {
            // If editor is active skip selecting features
            if (Editor.IsActive)
                return;

            // Unselect all features
            var featureLayers = Map.Layers.OfType<FeatureLayer>();
            foreach (var layer in featureLayers)
                layer.ClearSelection();

            GeodatabaseFeature feature = null;
			Exception exceptionToHandle = null;
			try
			{
				foreach (var layer in featureLayers.Where(l => l.Status == LayerStatus.Initialized).Reverse())
				{
					// Using MapViewService to handle hit testing. 
					var hit = await MapViewService.HitTestAsync(parameters.Position, layer) as GeodatabaseFeature;
					if (hit != null)
					{
						// Set feature selected
						layer.SelectFeatures(new[] { (long)hit.Attributes[layer.FeatureTable.ServiceInfo.ObjectIdField] });

						// Take feature and its layer for later use
						feature = hit;
						_selectedLayer = layer;
						break;
					}
				}
			}
			catch (Exception exception)
			{
				exceptionToHandle = exception;
			}

			if (exceptionToHandle != null)
			{
				// Initialization failed, show message and return
				await MessageService.Instance.ShowMessage(string.Format(
					"Could not create basemap. Error = {0}", exceptionToHandle.ToString()),
					"An error occured");
			}
		
            // Select or clear selection
            SelectedFeature = feature;
        }
        // Adds a new bird row to the local geodatabase
        private async void RegisterBirdSightingButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var birdsTable = LocalBirdsLayer.FeatureTable as ArcGISFeatureTable;
                if (birdsTable == null)
                    throw new ApplicationException("Birds table was not found in the local geodatabase.");

                var bird = new GeodatabaseFeature(birdsTable.Schema);
                bird.Geometry = TapLocation;

                if (bird.Schema.Fields.Any(fld => fld.Name == "type"))
                    bird.Attributes["type"] = comboBirdType.SelectedValue;
                if (bird.Schema.Fields.Any(fld => fld.Name == "comments"))
                    bird.Attributes["comments"] = txtComment.Text;
                if (bird.Schema.Fields.Any(fld => fld.Name == "creator"))
                    bird.Attributes["creator"] = "DOTNET_SAMPLE";
                if (bird.Schema.Fields.Any(fld => fld.Name == "created_date"))
                    bird.Attributes["created_date"] = DateTime.Now;

                var id = await birdsTable.AddAsync(bird);

                await RefreshDataView();

                _graphicsOverlay.Graphics.Clear();
                IsEditing = false;
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
		/// <summary>
		/// Adds a new turtle feature owned by current user.
		/// </summary>
		private async void AddButton_Click(object sender, RoutedEventArgs e)
		{
			var layer = MyMapView.Map.Layers["Marine"] as FeatureLayer;
			var table = (ArcGISFeatureTable)layer.FeatureTable;
			var typeID = (Int32)((Button)sender).Tag;
			string message = null;
			try
			{
				var mapPoint = await MyMapView.Editor.RequestPointAsync();
				var feature = new GeodatabaseFeature(table.Schema) { Geometry = mapPoint };
				if (table.ServiceInfo.Types == null)
					return;
				var featureType = table.ServiceInfo.Types.FirstOrDefault(t => Int32.Equals(Convert.ToInt32(t.ID, CultureInfo.InvariantCulture), typeID));
				if (featureType == null)
					return;
				var template = featureType.Templates.FirstOrDefault();
				if (template == null || template.Prototype == null || template.Prototype.Attributes == null)
					return;
				foreach (var item in template.Prototype.Attributes)
					feature.Attributes[item.Key] = item.Value;
				if (table.CanAddFeature(feature))
					table.AddAsync(feature);
				if (table.HasEdits)
				{
					if (table is ServiceFeatureTable)
					{
						var serviceTable = (ServiceFeatureTable)table;
						// Pushes new feature back to the server.
						var result = await serviceTable.ApplyEditsAsync();
						if (result.AddResults == null || result.AddResults.Count < 1)
							return;
						var addResult = result.AddResults[0];
						if (addResult.Error != null)
							message = addResult.Error.Message;
					}
				}
			}
			catch (Exception ex)
			{
				message = ex.Message;
			}
			if (!string.IsNullOrWhiteSpace(message))
				MessageBox.Show(message);
		}
 /// <summary>
 /// Adds a new related record to highlighted feature.
 /// </summary>
 private async void AddButton_Click(object sender, RoutedEventArgs e)
 {
     SetAttributeEditor();
     var featureID = (Int64)AddButton.Tag;
     var requestID = (string)RelatedRecords.Tag;
     string message = null;
     try
     {
         if (table == null)
             table = await GetRelatedTableAsync();
         var feature = new GeodatabaseFeature(table.Schema);
         feature.Attributes[relationship.KeyField] = requestID;
         feature.Attributes["rank"] = 5;
         feature.Attributes["comments"] = "Describe service requirement here.";
         feature.Attributes["submitdt"] = DateTime.UtcNow;
         var relatedFeatureID = await table.AddAsync(feature);
         await SaveEditsAsync();
         await QueryRelatedRecordsAsync();
     }
     catch (Exception ex)
     {
         message = ex.Message;
     }
     if (!string.IsNullOrWhiteSpace(message))
         await new MessageDialog(message).ShowAsync();
 }
        /// <summary>
        /// Adds new feature. Uses Editor to request geometry for the new graphic.
        /// </summary>
        private async void AddFeature(TemplatePicker.TemplatePickedEventArgs parameters)
        {
            var       targetLayer       = parameters.Layer;
            var       featureTemplate   = parameters.FeatureTemplate;
            Exception exceptionToHandle = null;

            // Clear selection since we are now addding new features
            SelectedFeature = null;
            _selectedLayer  = null;
            foreach (var layer in Map.Layers.OfType <FeatureLayer>())
            {
                layer.ClearSelection();
            }

            try
            {
                // Get symbol for the editor that is used when sketching
                Symbol symbol   = null;
                var    renderer = targetLayer.Renderer ?? targetLayer.FeatureTable.ServiceInfo.DrawingInfo.Renderer;
                if (renderer != null)
                {
                    symbol = renderer.GetSymbol(new Graphic(featureTemplate.Prototype.Attributes));
                }

                DrawShape requestedShape = DrawShape.Point;

                // TODO commented out since always return freehand, in this demo we want to use specific geometry editing
                //switch (featureTemplate.DrawingTool)
                //{
                //    case FeatureEditTool.Polygon:
                //        requestedShape = DrawShape.Polygon; break;
                //    case FeatureEditTool.Freehand:
                //        requestedShape = DrawShape.Freehand; break;
                //    case FeatureEditTool.Point:
                //        requestedShape = DrawShape.Point; break;
                //    case FeatureEditTool.Line:
                //        requestedShape = DrawShape.Polyline; break;
                //    default:
                //        throw new NotImplementedException();
                //}

                if (targetLayer.ID.ToLowerInvariant().Contains("lines"))
                {
                    requestedShape = DrawShape.Polyline;
                }
                else if (targetLayer.ID.ToLowerInvariant().Contains("polygons"))
                {
                    requestedShape = DrawShape.Polygon;
                }

                // Enable geometry editing and wait until it is done, returned geometry is the edited version.
                var requestedGeometry = await Editor.RequestShapeAsync(requestedShape, symbol, _editingProgress);

                // Create new feature based on the feature schema and give created geometry to new feature
                var geodatabaseFeature = new GeodatabaseFeature(targetLayer.FeatureTable.Schema);
                geodatabaseFeature.Geometry = requestedGeometry;

                // Copy initial vaulues for attributes from prototype
                // This is needed since features might have non-nullable fields and in this case
                // Points uses "EventType" to definde symbol and lines and polygons "symbolId"
                foreach (var attribute in featureTemplate.Prototype.Attributes)
                {
                    geodatabaseFeature.Attributes.Add(attribute.Key, attribute.Value);
                }

                // Add feature to the layer
                var newID = await targetLayer.FeatureTable.AddAsync(geodatabaseFeature);

                // When working with GeodatabaseFeatureServiceTable, edits are not automatically sent to the server
                // So you can have fine grained control when to do apply edits, here it automatically sends
                // update when it is done on the client.
                if (targetLayer.FeatureTable is GeodatabaseFeatureServiceTable)
                {
                    var featureTable = (GeodatabaseFeatureServiceTable)targetLayer.FeatureTable;
                    await featureTable.ApplyEditsAsync();
                }
            }
            catch (TaskCanceledException editCancelledException)
            {
                // This is raised when editing is cancelled so eat it.
            }
            catch (Exception exception)
            {
                exceptionToHandle = exception;
            }

            if (exceptionToHandle != null)
            {
                // Initialization failed, show message and return
                await MessageService.Instance.ShowMessage(string.Format(
                                                              "Could not create basemap. Error = {0}", exceptionToHandle.ToString()),
                                                          "An error occured");
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// This method is used to create the UI for the FeatureDataField.
        /// </summary>
        private void Refresh()
        {
            // if the content control template part is missing then draw nothing.
            if (_contentControl == null)
            {
                return;
            }

            // attempt retrive the field info for our control
            _fieldInfo = GeodatabaseFeature.GetFieldInfo(FieldName);

            // if field information was not obtain then draw nothing.
            if (_fieldInfo == null)
            {
                return;
            }

            // Get the value from the GeodatabaseFeature if the attribute exists.
            BindingValue = GeodatabaseFeature.Attributes.ContainsKey(FieldName) ? GeodatabaseFeature.Attributes[FieldName] : null;

            // If the FeatureDataField.IsReadOnly property has been set to true or the FieldInfo
            if (IsReadOnly || !_fieldInfo.IsEditable)
            {
                switch (_fieldInfo.Type)
                {
                case FieldType.String:
                case FieldType.Double:
                case FieldType.Single:
                case FieldType.SmallInteger:
                case FieldType.Integer:
                case FieldType.Date:
                case FieldType.GlobalID:
                case FieldType.Guid:
                case FieldType.Oid:
                    GenerateReadonlyField();
                    break;

                case FieldType.Raster:
                case FieldType.Geometry:
                case FieldType.Unknown:
                case FieldType.Xml:
                case FieldType.Blob:
                    Visibility = Visibility.Collapsed;
                    break;
                }
            }
            else if (_fieldInfo.Domain is CodedValueDomain)
            {
                // Create selector UI
                GenerateSelectorField();
            }
            else
            {
                switch (_fieldInfo.Type)
                {
                case FieldType.String:
                    GenerateInputField();
                    break;

                case FieldType.Double:
                case FieldType.Single:
                case FieldType.SmallInteger:
                case FieldType.Integer:
                    GenerateInputField();
                    break;

                case FieldType.Date:
                    GenerateInputField();
                    break;

                case FieldType.GlobalID:
                case FieldType.Guid:
                case FieldType.Oid:
                    GenerateReadonlyField();
                    break;

                case FieldType.Raster:
                case FieldType.Geometry:
                case FieldType.Unknown:
                case FieldType.Xml:
                case FieldType.Blob:
                    Visibility = Visibility.Collapsed;
                    break;
                }
            }
        }
        /// <summary>
        /// This will override all edit feature changes back
        /// to the original feature values.
        /// </summary>
        private void Reset()
        {
			if (_editFeature == null || GeodatabaseFeature == null) return;
            
            // copy original feature back to edit feature
			_editFeature = GeodatabaseFeature.Clone();
            HasEdits = false;
            HasError = false;                 
            ((ActionCommand)ApplyCommand).RaiseCanExecute();
            ((ActionCommand)ResetCommand).RaiseCanExecute();
            Refresh(); 
        }
        /// <summary>
        /// Creates a UI control for editing each field.
        /// </summary>
        /// <param name="feature">The feature.</param>
        /// <param name="fieldInfo">FieldInfo for edit control</param>
        /// <param name="isReadOnly">Value indicating if control should be readonly</param>
        /// <returns></returns>
		private FrameworkElement CreateControl(GeodatabaseFeature feature, FieldInfo fieldInfo, bool isReadOnly)
        {
            var control = new FeatureDataField
            {
				GeodatabaseFeature = feature,
                FieldName = fieldInfo.Name,
                IsReadOnly = isReadOnly,                
            };                        
            control.PropertyChanged += ControlOnPropertyChanged;
            return control;
        }        
        /// <summary>
        /// Edits the feature. On points it request new location and on polylines and
        /// polygons editing existing geometry is requested by using Editor.
        /// </summary>
        /// <param name="feature">Feature to edit.</param>
        /// <remarks>Edits are saved immediately.</remarks>
        private async void EditFeature(GeodatabaseFeature feature)
        {
            if (feature == null)
                return;

            Exception exceptionToHandle = null;
            try
            {
                switch (feature.Geometry.GeometryType)
                {
                    case GeometryType.Point:
                        var newLocation = await Editor.RequestPointAsync();
                        feature.Geometry = newLocation;
                        break;
                    case GeometryType.Polyline: // Could be combined with polygon to reduce lines, but could do more stuff here if needed
                        var polyine = await Editor.EditGeometryAsync(feature.Geometry, null, _editingProgress);
                        feature.Geometry = polyine;
                        break;
                    case GeometryType.Polygon:
                        var polygon = await Editor.EditGeometryAsync(feature.Geometry, null, _editingProgress);
                        feature.Geometry = polygon;
                        break;
                }

                await _selectedLayer.FeatureTable.UpdateAsync(feature);
                
                // Save edits to the service if using ServiceTable
                if (_selectedLayer.FeatureTable is GeodatabaseFeatureServiceTable)
                {
                    var featureTable = (GeodatabaseFeatureServiceTable)_selectedLayer.FeatureTable;
                    await featureTable.ApplyEditsAsync();
                }
            }
            catch (TaskCanceledException editCancelledException)
            {
                // This is raised when editing is cancelled so eat it.
            }
            catch (Exception exception)
            {
                exceptionToHandle = exception;
            }

            if (exceptionToHandle != null)
            {
                await MessageService.Instance.ShowMessage(string.Format(
                    "Could not edit or update selected feature. Error = {0}", exceptionToHandle.ToString()),
                    "An error occured");
			}
        }
Ejemplo n.º 25
0
        private async void NewPointFlyoutButton_Click(object sender, RoutedEventArgs e)
        {
            NewPointFlyout.Visibility = Visibility.Collapsed;
            string message = null;

            try
            {
                var mapPoint = _stopsOverlay.Graphics.Last().Geometry;

                if (_table.ServiceInfo.Types == null)
                {
                    return;
                }


                var feature = new GeodatabaseFeature(_table.Schema)
                {
                    Geometry = mapPoint
                };
                if (_table.ServiceInfo.Types == null)
                {
                    return;
                }

                var template = _table.ServiceInfo.Templates.FirstOrDefault();
                if (template == null || template.Prototype == null || template.Prototype.Attributes == null)
                {
                    return;
                }
                foreach (var item in template.Prototype.Attributes)
                {
                    string value = "";
                    if (_campos.TryGetValue(item.Key.ToString(), out value))
                    {
                        try
                        {
                            feature.Attributes[item.Key] = value;
                        }
                        catch (Exception)
                        {
                            switch (_table.Schema.Fields.Where(u => u.Name == item.Key.ToString()).FirstOrDefault().Type)
                            {
                            case Esri.ArcGISRuntime.Data.FieldType.Integer:
                                feature.Attributes[item.Key] = Convert.ToInt32(value);
                                break;

                            case Esri.ArcGISRuntime.Data.FieldType.Double:
                                feature.Attributes[item.Key] = Convert.ToDouble(value);
                                break;

                            case Esri.ArcGISRuntime.Data.FieldType.Date:
                                feature.Attributes[item.Key] = Convert.ToDateTime(value);
                                break;

                            default:
                                throw;
                            }
                        }
                    }
                }

                if (_table.CanAddFeature(feature))
                {
                    await _table.AddAsync(feature);

                    if (Foto != null && _table.CanAddAttachment(feature))
                    {
                        var featureID = ((ArcGISFeatureTable)_table).GetAddedFeatureIDs().FirstOrDefault();
                        await _table.AddAttachmentAsync(featureID, Foto);
                    }
                    ((ServiceFeatureTable)_table).OutFields = new Esri.ArcGISRuntime.Tasks.Query.OutFields(feature.Attributes.Keys);
                    await((ServiceFeatureTable)_table).ApplyEditsAsync();

                    if (Foto != null)
                    {
                        await((ServiceFeatureTable)_table).ApplyAttachmentEditsAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            if (_stopsOverlay.Graphics.Count() > 0)
            {
                _stopsOverlay.Graphics.Clear();
                _routesOverlay.Graphics.Clear();
                MyMapView.Overlays.Items.Clear();
                _directionsOverlay.GraphicsSource = null;
            }
            if (!string.IsNullOrWhiteSpace(message))
            {
                await new MessageDialog(message).ShowAsync();
            }
        }
        /// <summary>
        /// Adds a new turtle feature owned by current user.
        /// </summary>
        private async void AddButton_Click(object sender, RoutedEventArgs e)
        {
            var    layer   = MyMapView.Map.Layers["Marine"] as FeatureLayer;
            var    table   = (ArcGISFeatureTable)layer.FeatureTable;
            var    typeID  = (Int32)((Button)sender).Tag;
            string message = null;

            try
            {
                var mapPoint = await MyMapView.Editor.RequestPointAsync();

                var feature = new GeodatabaseFeature(table.Schema)
                {
                    Geometry = mapPoint
                };
                if (table.ServiceInfo.Types == null)
                {
                    return;
                }
                var featureType = table.ServiceInfo.Types.FirstOrDefault(t => Int32.Equals(Convert.ToInt32(t.ID, CultureInfo.InvariantCulture), typeID));
                if (featureType == null)
                {
                    return;
                }
                var template = featureType.Templates.FirstOrDefault();
                if (template == null || template.Prototype == null || template.Prototype.Attributes == null)
                {
                    return;
                }
                foreach (var item in template.Prototype.Attributes)
                {
                    feature.Attributes[item.Key] = item.Value;
                }
                if (table.CanAddFeature(feature))
                {
                    table.AddAsync(feature);
                }
                if (table.HasEdits)
                {
                    if (table is ServiceFeatureTable)
                    {
                        var serviceTable = (ServiceFeatureTable)table;
                        // Pushes new feature back to the server.
                        var result = await serviceTable.ApplyEditsAsync();

                        if (result.AddResults == null || result.AddResults.Count < 1)
                        {
                            return;
                        }
                        var addResult = result.AddResults[0];
                        if (addResult.Error != null)
                        {
                            message = addResult.Error.Message;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            if (!string.IsNullOrWhiteSpace(message))
            {
                await new MessageDialog(message).ShowAsync();
            }
        }
        /// <summary>
        /// Adds new feature. Uses Editor to request geometry for the new graphic.
        /// </summary>
        private async void AddFeature(TemplatePicker.TemplatePickedEventArgs parameters)
        {
            var targetLayer = parameters.Layer;
            var featureTemplate = parameters.FeatureTemplate;
            Exception exceptionToHandle = null;
				
            // Clear selection since we are now addding new features
            SelectedFeature = null;
            _selectedLayer = null;
            foreach (var layer in Map.Layers.OfType<FeatureLayer>())
                layer.ClearSelection();

            try
            {
                // Get symbol for the editor that is used when sketching
                Symbol symbol = null;
                var renderer = targetLayer.Renderer ?? targetLayer.FeatureTable.ServiceInfo.DrawingInfo.Renderer;
                if (renderer != null)
                {
                    symbol = renderer.GetSymbol(new Graphic(featureTemplate.Prototype.Attributes));
                }

                DrawShape requestedShape = DrawShape.Point;

                // TODO commented out since always return freehand, in this demo we want to use specific geometry editing
                //switch (featureTemplate.DrawingTool)
                //{
                //    case FeatureEditTool.Polygon:
                //        requestedShape = DrawShape.Polygon; break;
                //    case FeatureEditTool.Freehand:
                //        requestedShape = DrawShape.Freehand; break;
                //    case FeatureEditTool.Point:
                //        requestedShape = DrawShape.Point; break;
                //    case FeatureEditTool.Line:
                //        requestedShape = DrawShape.Polyline; break;
                //    default:
                //        throw new NotImplementedException();
                //}

                if (targetLayer.ID.ToLowerInvariant().Contains("lines"))
                {
                    requestedShape = DrawShape.Polyline;
                }
                else if (targetLayer.ID.ToLowerInvariant().Contains("polygons"))
                {
                    requestedShape = DrawShape.Polygon;
                }
                
                // Enable geometry editing and wait until it is done, returned geometry is the edited version.
                var requestedGeometry = await Editor.RequestShapeAsync(requestedShape, symbol, _editingProgress);

                // Create new feature based on the feature schema and give created geometry to new feature
                var geodatabaseFeature = new GeodatabaseFeature(targetLayer.FeatureTable.Schema);
                geodatabaseFeature.Geometry = requestedGeometry;

                // Copy initial vaulues for attributes from prototype
                // This is needed since features might have non-nullable fields and in this case
                // Points uses "EventType" to definde symbol and lines and polygons "symbolId"
                foreach (var attribute in featureTemplate.Prototype.Attributes)
                {
                    geodatabaseFeature.Attributes.Add(attribute.Key, attribute.Value);
                }

                // Add feature to the layer
                var newID = await targetLayer.FeatureTable.AddAsync(geodatabaseFeature);

                // When working with GeodatabaseFeatureServiceTable, edits are not automatically sent to the server
                // So you can have fine grained control when to do apply edits, here it automatically sends 
                // update when it is done on the client.
                if (targetLayer.FeatureTable is GeodatabaseFeatureServiceTable)
                {
                    var featureTable = (GeodatabaseFeatureServiceTable)targetLayer.FeatureTable;
                    await featureTable.ApplyEditsAsync();
                }
            }
            catch (TaskCanceledException editCancelledException)
            {
                // This is raised when editing is cancelled so eat it.
            }
            catch (Exception exception)
            {
                exceptionToHandle = exception;
            }

            if (exceptionToHandle != null)
            {
                // Initialization failed, show message and return
                await MessageService.Instance.ShowMessage(string.Format(
                    "Could not create basemap. Error = {0}", exceptionToHandle.ToString()),
                    "An error occured");
            }
        }
        /// <summary>
        /// Removes selected feature and updates the layer.
        /// </summary>
        /// <param name="feature">Feature to remove.</param>
        private async void RemoveFeature(GeodatabaseFeature feature)
        {
            if (feature == null)
                return;

            Exception exceptionToHandle = null;
            try
            {
                await _selectedLayer.FeatureTable.DeleteAsync(feature);

                // Save edits to the service if using ServiceTable
                if (_selectedLayer.FeatureTable is GeodatabaseFeatureServiceTable)
                {
                    var featureTable = (GeodatabaseFeatureServiceTable)_selectedLayer.FeatureTable;
                    await featureTable.ApplyEditsAsync();
                }
            }
            catch (Exception exception)
            {
                exceptionToHandle = exception;
            }

            if (exceptionToHandle != null)
            {
                await MessageService.Instance.ShowMessage(string.Format(
                    "Could not delete selected feature. Error = {0}", exceptionToHandle.ToString()),
                    "An error occured");
            }
        }
		private async Task CreateNewFeature(FeatureLayerInfo featureLayerInfo, LegendInfo legendInfo)
		{
			if (CurrentEsriMapView.Editor.IsActive)
			{
				CurrentEsriMapView.Editor.Cancel.Execute(null);
			}
			Graphic graphic = null;

			switch (featureLayerInfo.FeatureLayer.FeatureTable.GeometryType)
			{
				case GeometryType.Unknown:
					break;
				case GeometryType.Point:
					graphic = await CreateGraphicAsync(legendInfo.EsriSymbol, DrawShape.Point);
					break;
				case GeometryType.Polyline:
					graphic = await CreateGraphicAsync(legendInfo.EsriSymbol, DrawShape.Polyline);
					break;
				case GeometryType.Polygon:
					graphic = await CreateGraphicAsync(legendInfo.EsriSymbol, DrawShape.Polygon);
					break;
				case GeometryType.Envelope:
					break;
			}


			if (featureLayerInfo.FeatureLayer.FeatureTable is GeodatabaseFeatureTable)
			{
				var table = featureLayerInfo.FeatureLayer.FeatureTable as GeodatabaseFeatureTable;
				//_model.SetMessageInfo("Table was not found in the local geodatabase.");
				var feature = new GeodatabaseFeature(table.Schema) {Geometry = graphic.Geometry,};

				if (feature.Schema.Fields.Any(fld => fld.Name == table.ServiceInfo.DisplayField))
					feature.Attributes[table.ServiceInfo.DisplayField] = legendInfo.Label;

				await table.AddAsync(feature);
			}

			if (featureLayerInfo.FeatureLayer.FeatureTable is ServiceFeatureTable)
			{
				var table = featureLayerInfo.FeatureLayer.FeatureTable as ServiceFeatureTable;

				var feature = new GeodatabaseFeature(table.Schema) {Geometry = graphic.Geometry,};

				if (feature.Schema.Fields.Any(fld => fld.Name == table.ServiceInfo.DisplayField))
					feature.Attributes[table.ServiceInfo.DisplayField] = legendInfo.Label;

				await table.AddAsync(feature);
			}
		}