Example #1
0
        private void _dataGridView_Sorted(object sender, EventArgs e)
        {
            _msg.VerboseDebug("DataGridViewFindController._dataGridView_Sorted");

            if (!string.IsNullOrEmpty(_findText))
            {
                _hasPendingFind = true;
            }
        }
Example #2
0
        protected override void OnToolActivatingCore()
        {
            _msg.VerboseDebug("OnToolActivatingCore");

            if (!RequiresSelection)
            {
                StartSketchPhase();
            }
        }
Example #3
0
        private static IGeometry TryGetIntersection([NotNull] IGeometry sourceGeometry,
                                                    [NotNull] IGeometry targetGeometry)
        {
            IGeometry targetToIntersect =
                targetGeometry.GeometryType == esriGeometryType.esriGeometryMultiPatch
                                        ? GeometryFactory.CreatePolygon(targetGeometry)
                                        : targetGeometry;

            esriGeometryDimension dimension =
                sourceGeometry is IPolygon
                                        ? esriGeometryDimension.esriGeometry2Dimension
                                        : esriGeometryDimension.esriGeometry1Dimension;

            IGeometry intersection = IntersectionUtils.Intersect(
                sourceGeometry, targetToIntersect, dimension);

            _msg.VerboseDebug("Simplifying...");

            GeometryUtils.Simplify(intersection);

            Marshal.ReleaseComObject(targetToIntersect);

            if (!intersection.IsEmpty)
            {
                return(intersection);
            }

            return(null);
        }
Example #4
0
        private bool GetIsReshapeMemberCandidate()
        {
            if (CanReshape)
            {
                return(false);
            }

            // exclude the ones that directly connect different parts - cannot be usedd
            if (TouchAtToPoint && TouchAtFromPoint &&
                (_touchingDifferentParts != null && (bool)_touchingDifferentParts))
            {
                return(false);
            }

            _msg.VerboseDebug("GetIsReshapeMemberCandidate: Trying to connect.");

            // traverse graph by first starting with FromNode to try to connect to the line to be reshaped
            if (TryCanConnect(FromNode, cutSubcurve => !cutSubcurve.IsFiltered))
            {
                return(true);
            }

            // try again starting with to-node in case the from-node check has used some
            // essential nodes from to-node check:
            return(TryCanConnect(ToNode, cutSubcurve => !cutSubcurve.IsFiltered));
        }
Example #5
0
        public object OpenDataset(IDdxDataset dataset, Type knownType)
        {
            Assert.ArgumentNotNull(dataset, nameof(dataset));

            if (knownType != null)
            {
                return(OpenKnownDatasetType(dataset, knownType));
            }

            try
            {
                if (dataset is ObjectDataset objectDataset)
                {
                    return(_datasetContext.OpenObjectClass(objectDataset) != null);
                }

                // TODO: Raster, Mosaic

                return(null);
            }
            catch (Exception e)
            {
                _msg.VerboseDebug($"Error opening dataset {dataset.Name}", e);
                return(false);
            }
        }
Example #6
0
        private void LogTransfer([CanBeNull] object sourceValue,
                                 FieldValueTransferLogLevel logLevel)
        {
            string formattedValue = GetFormattedValue(sourceValue);

            string message =
                string.Format("Transferring value from field '{0}' to field '{1}': {2}",
                              SourceFieldName, TargetFieldName, formattedValue);

            switch (logLevel)
            {
            case FieldValueTransferLogLevel.Debug:
                _msg.Debug(message);
                break;

            case FieldValueTransferLogLevel.VerboseDebug:
                _msg.VerboseDebug(message);
                break;

            case FieldValueTransferLogLevel.Info:
                _msg.Info(message);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(logLevel));
            }
        }
Example #7
0
        public static bool?AreCoplanar([NotNull] IList <Pnt3D> points,
                                       [NotNull] Plane3D plane,
                                       double tolerance,
                                       out double maxDeviationFromPlane,
                                       out string message)
        {
            message = null;

            if (!plane.IsDefined)
            {
                message =
                    $"The plane is not sufficiently defined by the input points {StringUtils.Concatenate(points, ", ")}.";
                maxDeviationFromPlane = double.NaN;
                return(null);
            }

            if (MathUtils.AreEqual(
                    0, GeomUtils.GetArea3D(points, new Pnt3D(plane.Normal))))
            {
                // Technically, the plane could be defined, but it is quite random
                message =
                    $"The ring is degenerate without 3D area {StringUtils.Concatenate(points, ", ")}.";
                maxDeviationFromPlane = double.NaN;
                return(null);
            }

            var coplanar = true;

            double maxDistance      = 0;
            Pnt3D  maxDistancePoint = null;

            foreach (Pnt3D pnt3D in points)
            {
                double d = plane.GetDistanceSigned(pnt3D);

                if (!MathUtils.AreEqual(d, 0, tolerance))
                {
                    if (Math.Abs(d) > Math.Abs(maxDistance))
                    {
                        maxDistance      = d;
                        maxDistancePoint = pnt3D;
                    }

                    coplanar = false;
                }
            }

            if (!coplanar)
            {
                _msg.VerboseDebug(
                    $"Coplanarity of point {maxDistancePoint} with plane {plane} is violated: {maxDistance}m");
                message =
                    $"Coplanarity of the plane is violated by {maxDistance} at point {maxDistancePoint}";
            }

            maxDeviationFromPlane = Math.Abs(maxDistance);

            return(coplanar);
        }
Example #8
0
        protected override Task OnToolActivateAsync(bool hasMapViewChanged)
        {
            _msg.VerboseDebug("OnToolActivateAsync");

            MapPropertyChangedEvent.Subscribe(OnPropertyChanged);
            MapSelectionChangedEvent.Subscribe(OnMapSelectionChanged);
            EditCompletedEvent.Subscribe(OnEditCompleted);

            PressedKeys.Clear();

            try
            {
                return(QueuedTask.Run(
                           () =>
                {
                    OnToolActivatingCore();

                    if (RequiresSelection)
                    {
                        ProcessSelection(ActiveMapView);
                    }

                    return OnToolActivatedCore(hasMapViewChanged);
                }));
            }
            catch (Exception e)
            {
                HandleError($"Error in tool activation ({Caption}): {e.Message}", e);
            }

            return(Task.CompletedTask);
        }
        private void FilterRowsCore(
            [NotNull] Func <DataGridViewRow, bool> isRowVisible)
        {
            _msg.VerboseDebug("FilterableDataGridView.FilterRowsCore");

            bool wasIgnored = _ignoreRowStateChange;

            _ignoreRowStateChange = true;

            var selectionChanged   = false;
            var visibleRowsChanged = false;

            try
            {
                foreach (DataGridViewRow row in Rows)
                {
                    if (row.IsNewRow)
                    {
                        continue;
                    }

                    bool newVisible = isRowVisible(row);
                    if (newVisible != row.Visible)
                    {
                        row.Visible        = newVisible;
                        visibleRowsChanged = true;
                    }

                    // make sure that invisible rows are not selected
                    if (!row.Visible && row.Selected)
                    {
                        row.Selected     = false;
                        selectionChanged = true;
                    }
                }
            }
            finally
            {
                _ignoreRowStateChange = wasIgnored;
                if (!wasIgnored)
                {
                    ForcePendingRowStateChanges();
                }

                if (selectionChanged)
                {
                    OnSelectionChanged(EventArgs.Empty);
                }

                if (visibleRowsChanged)
                {
                    OnFilteredRowsChanged();
                }
            }
        }
Example #10
0
        protected override void OnKeyDownCore(MapViewKeyEventArgs k)
        {
            if (KeyboardUtils.IsModifierPressed(Keys.Shift, true))
            {
                SetCursor(SelectionCursorShift);
            }
            else
            {
                SetCursor(SelectionCursor);
            }

            _msg.VerboseDebug($"Key {k.Key} was pressed.");
        }
Example #11
0
        private static void LogProgress(VerificationProgressMsg progressMsg)
        {
            if (progressMsg == null)
            {
                return;
            }

            _msg.VerboseDebug($"{DateTime.Now} - {progressMsg}");

            _msg.DebugFormat(
                "Received service progress of type {0}/{1}: {2} / {3}",
                (VerificationProgressType)progressMsg.ProgressType,
                (VerificationProgressStep)progressMsg.ProgressStep,
                progressMsg.OverallProgressCurrentStep,
                progressMsg.OverallProgressTotalSteps);
        }
        private static bool ExistsDataset([NotNull] IDdxDataset dataset,
                                          [NotNull] IOpenDataset datasetOpener)
        {
            // -> allow work context to load dataset from other database ('master')
            try
            {
                var aoDataset = datasetOpener.OpenDataset(dataset);

                return(aoDataset != null);
            }
            catch (Exception e)
            {
                _msg.VerboseDebug($"Error opening dataset {dataset.Name}", e);
                return(false);
            }
        }
Example #13
0
        public static bool TrySendResponse <T>([NotNull] IServerStreamWriter <T> responseStream,
                                               [NotNull] T response)
        {
            try
            {
                responseStream.WriteAsync(response);
            }
            catch (InvalidOperationException ex)
            {
                // For example: System.InvalidOperationException: Only one write can be pending at a time
                _msg.VerboseDebug("Error sending response to the client", ex);

                return(false);
            }

            return(true);
        }
Example #14
0
        private static void WriteProgressAndIssues(
            VerificationProgressEventArgs e,
            ConcurrentBag <IssueMsg> issues,
            VerificationProgressMsg currentProgress,
            Action <VerificationResponse> writeAction)
        {
            VerificationResponse response = new VerificationResponse
            {
                ServiceCallStatus = (int)ServiceCallStatus.Running
            };

            if (!UpdateProgress(currentProgress, e) && issues.Count == 0)
            {
                return;
            }

            response.Progress = currentProgress;

            //List<IssueMsg> sentIssues = new List<IssueMsg>(issues.Count);

            while (issues.TryTake(out IssueMsg issue))
            {
                response.Issues.Add(issue);
            }

            _msg.DebugFormat("Sending {0} errors back to client...", issues.Count);

            try
            {
                writeAction(response);
            }
            catch (InvalidOperationException ex)
            {
                // For example: System.InvalidOperationException: Only one write can be pending at a time
                _msg.VerboseDebug("Error sending progress to the client", ex);

                // The issues would be lost, so put them back into the collection
                foreach (IssueMsg issue in response.Issues)
                {
                    issues.Add(issue);
                }
            }
        }
Example #15
0
        /// <summary>
        /// Selects the requested features from the specified layer and immediately disposes
        /// the selection to avoid selection and immediate de-selection (for selection method XOR)
        /// because it is called in 2 threads.
        /// </summary>
        /// <param name="featureLayer"></param>
        /// <param name="combinationMethod"></param>
        /// <param name="objectIds"></param>
        public static void SelectFeatures([NotNull] BasicFeatureLayer featureLayer,
                                          SelectionCombinationMethod combinationMethod,
                                          [NotNull] IReadOnlyList <long> objectIds)
        {
            var queryFilter = new QueryFilter
            {
                ObjectIDs = objectIds
            };

            using (Selection selection = featureLayer.Select(queryFilter, combinationMethod))
            {
                if (_msg.IsVerboseDebugEnabled)
                {
                    _msg.VerboseDebug(
                        $"Selected OIDs {StringUtils.Concatenate(selection.GetObjectIDs(), ", ")} " +
                        $"from {featureLayer.Name}");
                }
            }
        }
        public bool TryWritePendingChanges()
        {
            try
            {
                if (!_hasPendingChanges)
                {
                    _msg.VerboseDebug("no pending changes");
                    return(false);
                }

                if (AutoSave)
                {
                    _canSave = true;
                }

                if (!CanHandlePendingChanges())
                {
                    _msg.VerboseDebugFormat(
                        "Cannot handle pending changes. Reason: saving {0}, aborting {1}, can save {2}",
                        _saving,
                        _aborting, _canSave);
                    return(false);
                }

                BeginWrite();

                WriteChanges();
                return(true);
            }

            catch (Exception e)
            {
                ErrorHandler.HandleError(e.Message, e, _msg, _owner);
                return(false);
            }
            finally
            {
                _canSave = false;
                EndWrite();
            }
        }
Example #17
0
        protected override async Task <bool> OnSketchModifiedAsync()
        {
            _msg.VerboseDebug("OnSketchModifiedAsync");

            if (_updateFeedbackTask != null)
            {
                // Still working on the previous update (large poylgons!)
                // -> Consider using latch (but ensure that the overlay must probably be scheduled properly)
                return(false);
            }

            bool nonDefaultSide =
                _nonDefaultSideMode || PressedKeys.Contains(_keyToggleNonDefaultSide);

            bool updated = false;

            try
            {
                if (!PressedKeys.Contains(Key.Space))
                {
                    // TODO: Exclude finish sketch by double clicking -> should not calculate preview
                    //       E.g. wait for SystemInformation.DoubleClickTime for the second click
                    //       and only start if it has not ocvurred
                    _updateFeedbackTask = UpdateFeedbackAsync(nonDefaultSide);
                    updated             = await _updateFeedbackTask;
                }
            }
            catch (Exception e)
            {
                _msg.Warn("Error generating preview", e);
                return(false);
            }
            finally
            {
                _updateFeedbackTask = null;
            }

            // Does it make any difference what the return value is?
            return(updated);
        }
Example #18
0
        public void Callback()
        {
            if (_pending)
            {
                _msg.VerboseDebug("Callback already pending - ignored");
                return;
            }

            _expectedThreadId = Thread.CurrentThread.ManagedThreadId;

            if (_synchronizationContext == null)
            {
                // get the winforms synchronization context
                // NOTE: relying on the current synchronization context of the current thread is not sufficient,
                //       as this gets changed depending on previous winforms actions:
                //       - after showing a modal dialog, the synchronization context DOES NOT displatch back to the gui thread
                //       - after opening/activating a modeless form, it DOES dispatch back to the gui thread
                // -> better to set the expected synchronization context explicitly
                // NOTE: this must be done on the gui thread, otherwise even this synchronization context will not dispatch back to it
                _synchronizationContext = new WindowsFormsSynchronizationContext();
            }

            _msg.VerboseDebugFormat("Scheduling delayed processing (thread: {0})",
                                    Thread.CurrentThread.ManagedThreadId);

            try
            {
                _pending = true;

                _synchronizationContext.Post(delegate { TryExecuteProcedure(); }, null);
            }
            catch (Exception ex)
            {
                _pending = false;
                _msg.Error($"Error executing procedure via synchronization context: {ex.Message}",
                           ex);
            }
        }
Example #19
0
        private static async Task <bool> ExecuteAsync([NotNull] string tool,
                                                      [NotNull] IReadOnlyList <string> parameters)
        {
            Assert.ArgumentNotNullOrEmpty(tool, nameof(tool));
            Assert.ArgumentNotNull(parameters, nameof(parameters));
            Assert.ArgumentCondition(parameters.Count > 0, "no parameter");

            _msg.VerboseDebug($"{tool}, Parameters: {StringUtils.Concatenate(parameters, ", ")}");

            IReadOnlyList <KeyValuePair <string, string> > environments =
                Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);

            IGPResult result = await Geoprocessing.ExecuteToolAsync(tool, parameters, environments);

            if (!result.IsFailed)
            {
                return(true);
            }

            _msg.Info(
                $"{tool} has failed: {StringUtils.Concatenate(Format(result.Messages), ", ")}, Parameters: {StringUtils.Concatenate(parameters, ", ")}");
            return(false);
        }
Example #20
0
        public static CalculateOverlapsResponse CalculateOverlaps(
            [NotNull] CalculateOverlapsRequest request,
            [CanBeNull] ITrackCancel trackCancel)
        {
            var watch = Stopwatch.StartNew();

            IList <IFeature> sourceFeatures =
                ProtobufConversionUtils.FromGdbObjectMsgList(
                    request.SourceFeatures, request.ClassDefinitions);

            IList <IFeature> targetFeatures =
                ProtobufConversionUtils.FromGdbObjectMsgList(
                    request.TargetFeatures, request.ClassDefinitions);

            _msg.DebugStopTiming(watch, "Unpacked feature lists from request params");

            Overlaps selectableOverlaps = RemoveOverlapsUtils.GetSelectableOverlaps(
                sourceFeatures, targetFeatures, trackCancel);

            watch = Stopwatch.StartNew();

            var result = new CalculateOverlapsResponse();

            foreach (var overlapByGdbRef
                     in selectableOverlaps.OverlapsBySourceRef)
            {
                var gdbObjRefMsg = ProtobufGdbUtils.ToGdbObjRefMsg(overlapByGdbRef.Key);

                var overlap = overlapByGdbRef.Value;

                var overlapsMsg = new OverlapMsg()
                {
                    OriginalFeatureRef = gdbObjRefMsg
                };

                foreach (IGeometry geometry in overlap)
                {
                    // TODO: At some point the SR-XY tol/res should be transferred separately (via class-lookup?)
                    var shapeFormat = ShapeMsg.FormatOneofCase.EsriShape;
                    var srFormat    = SpatialReferenceMsg.FormatOneofCase.SpatialReferenceEsriXml;

                    overlapsMsg.Overlaps.Add(
                        ProtobufGeometryUtils.ToShapeMsg(
                            geometry, shapeFormat, srFormat));

                    if (_msg.IsVerboseDebugEnabled)
                    {
                        _msg.VerboseDebug(
                            $"Calculated overlap: {GeometryUtils.ToString(geometry)}");
                    }
                }

                result.Overlaps.Add(overlapsMsg);
            }

            foreach (var notification in selectableOverlaps.Notifications)
            {
                result.Notifications.Add(notification.Message);
            }

            _msg.DebugStopTiming(watch, "Packed overlaps into response");

            return(result);
        }
Example #21
0
        private static void Log([NotNull] IMsg msg, [CanBeNull] string method)
        {
            Assert.ArgumentNotNull(msg, nameof(msg));

            msg.VerboseDebug($"{method}");
        }