Exemplo n.º 1
0
        /// <summary>
        /// Saves the form state.
        /// </summary>
        /// <remarks>
        /// All exceptions are ignored to make sure that this miscellaneous function
        /// does never break the application.
        /// </remarks>
        /// <returns>True if form state was successfully stored, false if an error
        /// occurred</returns>
        public bool SaveState()
        {
            if (Form.WindowState == FormWindowState.Minimized)
            {
                // don't save state if minimized
                return(false);
            }

            try
            {
                // get the current form state
                T formState = GetCurrentState();

                // write form state
                FormStatePersistence.WriteToXml(_fileName, formState, typeof(T));
            }
            catch (Exception ex)
            {
                _msg.Warn("Error saving form state", ex);

                // ignore errors
                return(false);
            }

            return(true);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Saves the window settings for the form.
        /// </summary>
        /// <remarks>
        /// All exceptions are ignored to make sure that this miscellaneous function
        /// does never break the application.
        /// </remarks>
        /// <returns>True if settings were successfully stored, false if an error
        /// occurred</returns>
        public bool SaveSettings()
        {
            if (_form.WindowState == FormWindowState.Minimized)
            {
                // don't save state if minimized
                return(false);
            }
            else
            {
                try
                {
                    // get the current settings for the form
                    WindowSettings settings = GetCurrentSettings();

                    // write settings
                    FormStatePersistence.WriteToXml(_fileName, settings, _settingsType);
                }
                catch (Exception ex)
                {
                    _msg.Warn("Error saving window settings", ex);

                    // ignore errors
                    return(false);
                }

                return(true);
            }
        }
Exemplo n.º 3
0
        protected override void CalculateDerivedGeometries(IList <Feature> selectedFeatures,
                                                           CancelableProgressor progressor)
        {
            selectedFeatures = GetApplicableSelectedFeatures(selectedFeatures).ToList();

            IList <Feature> overlappingFeatures =
                GetOverlappingFeatures(selectedFeatures, progressor);

            if (progressor != null && !progressor.CancellationToken.IsCancellationRequested)
            {
                _msg.Warn("Calculation of removable overlaps was cancelled.");
                return;
            }

            _overlaps = CalculateOverlaps(selectedFeatures, overlappingFeatures, progressor);

            if (progressor != null && progressor.CancellationToken.IsCancellationRequested)
            {
                _msg.Warn("Calculation of removable overlaps was cancelled.");
                return;
            }

            // TODO: Options
            bool insertVerticesInTarget = false;

            _overlappingFeatures = insertVerticesInTarget
                                                       ? overlappingFeatures
                                                       : null;

            _feedback.Update(_overlaps);
        }
        private static void LogBeginVerification(
            [NotNull] QualitySpecification qualitySpecification,
            double tileSize,
            [CanBeNull] AreaOfInterest areaOfInterest)
        {
            using (_msg.IncrementIndentation("Begin quality verification"))
            {
                _msg.InfoFormat("Quality specification: {0}", qualitySpecification.Name);
                _msg.InfoFormat("Verification tile size: {0}", tileSize);

                if (areaOfInterest != null)
                {
                    IGeometry testPerimeter = areaOfInterest.Geometry;

                    if (testPerimeter.IsEmpty)
                    {
                        _msg.Warn("Test perimeter is empty");
                    }
                    else
                    {
                        var envelope = testPerimeter as IEnvelope;

                        string message;
                        if (envelope == null)
                        {
                            Assert.ArgumentCondition(testPerimeter is IPolygon,
                                                     "Unexpected test perimeter type: {0}; must be polygon or envelope",
                                                     testPerimeter.GeometryType);

                            envelope = testPerimeter.Envelope;
                            message  = string.Format("Polygon extent: {0} x {1}",
                                                     envelope.Width, envelope.Height);
                        }
                        else
                        {
                            message = string.Format("Extent: {0} x {1}",
                                                    envelope.Width, envelope.Height);
                        }

                        using (_msg.IncrementIndentation(message))
                        {
                            _msg.InfoFormat("X-Min: {0}", envelope.XMin);
                            _msg.InfoFormat("Y-Min: {0}", envelope.YMin);
                            _msg.InfoFormat("X-Max: {0}", envelope.XMax);
                            _msg.InfoFormat("Y-Max: {0}", envelope.YMax);
                        }
                    }
                }
            }
        }
Exemplo n.º 5
0
        public void Cut([NotNull] IPolyline cutPolyline,
                        [CanBeNull] ITrackCancel trackCancel = null)
        {
            foreach (IFeature feature in GetFeaturesToCut(cutPolyline))
            {
                if (trackCancel != null && !trackCancel.Continue())
                {
                    return;
                }

                try
                {
                    CutFeature(feature, cutPolyline);
                }
                catch (Exception e)
                {
                    if (!ContinueOnFailure)
                    {
                        throw;
                    }

                    _msg.Warn($"Feature {feature.OID}: {e.Message}", e);

                    FailedCutOperations.Add(
                        new KeyValuePair <int, string>(feature.OID, e.Message));
                }
            }

            AddToRefreshArea(cutPolyline);
        }
Exemplo n.º 6
0
        void IVerificationReportBuilder.EndVerification(bool cancelled)
        {
            if (cancelled)
            {
                _msg.Warn("The verification was cancelled");
            }

            if (_errors.Count == 0)
            {
                _msg.Info("No errors found");
            }
            else
            {
                _msg.WarnFormat(_errors.Count == 1
                                                        ? "{0:N0} error found:"
                                                        : "{0:N0} errors found:", _errors.Count);

                if (_rowsWithStopConditions > 0)
                {
                    _msg.WarnFormat(
                        "Number of rows with stop conditions (not completely tested): {0:N0}",
                        _rowsWithStopConditions);
                }
            }

            ReportErrors(_errors);
        }
Exemplo n.º 7
0
        private async Task StartRequest(string peerName, object request)
        {
            CurrentLoad?.StartRequest();

            _msg.InfoFormat("Starting verification request from {0}", peerName);

            if (_msg.IsVerboseDebugEnabled)
            {
                _msg.VerboseDebugFormat("Request details: {0}", request);
            }

            bool licensed = await EnsureLicenseAsync();

            if (!licensed)
            {
                _msg.Warn("Could not check out the specified license");
            }
        }
Exemplo n.º 8
0
 public static T Try <T>(
     [NotNull] Func <CallOptions, T> func,
     CancellationToken cancellationToken,
     int deadlineMilliseconds = 30000,
     bool noWarn = false)
 {
     if (cancellationToken.IsCancellationRequested)
     {
         _msg.Warn("Operation cancelled");
         return(default);
 protected void RaiseChanged(CancelEventArgs e)
 {
     try
     {
         ElementValueChanged();
     }
     catch (Exception ex)
     {
         e.Cancel = true;
         _msg.Warn(ex.Message, ex);
     }
 }
Exemplo n.º 10
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);
        }
Exemplo n.º 11
0
        private void RestorePreviousSketch()
        {
            if (!SupportRestoreLastSketch)
            {
                return;
            }

            if (_previousSketch == null || _previousSketch.IsEmpty)
            {
                _msg.Warn("There is no previous sketch to restore.");

                return;
            }

            if (!IsInSketchMode)
            {
                // If a non-rectangular sketch is set while SketchType is rectangle (or probably generally the wrong type)
                // sketching is not possible any more and the application appears hanging

                // Try start sketch mode:
                IList <Feature> selection =
                    SelectionUtils.GetSelectedFeatures(ActiveMapView).ToList();

                if (CanUseSelection(selection))
                {
                    AfterSelection(selection, null);
                }
            }

            if (IsInSketchMode)
            {
                SetCurrentSketchAsync(_previousSketch);
            }
            else
            {
                _msg.Warn("Sketch cannot be restored in selection phase. " +
                          "Please try again in the sketch phase.");
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Shows the warning dialog.
        /// </summary>
        /// <param name="owner">The owner.</param>
        /// <param name="message">The message.</param>
        /// <param name="title">The title.</param>
        public void ShowWarning(IWin32Window owner, string title, string message)
        {
            Assert.ArgumentNotNullOrEmpty(title, nameof(title));
            Assert.ArgumentNotNullOrEmpty(message, nameof(message));

            _msg.Warn(message);

            Show(owner,
                 MsgBase.ReplaceBreakTags(message), title,
                 MessageBoxButtons.OK,
                 MessageBoxIcon.Warning,
                 MessageBoxDefaultButton.Button1);
        }
Exemplo n.º 13
0
        public static void WithTransaction([NotNull] IDbConnection connection,
                                           [NotNull] IDbCommand command,
                                           [NotNull] Action procedure,
                                           IsolationLevel isolationLevel =
                                           IsolationLevel.Unspecified)
        {
            Assert.ArgumentNotNull(connection, nameof(connection));
            Assert.ArgumentNotNull(command, nameof(command));
            Assert.ArgumentNotNull(procedure, nameof(procedure));

            using (IDbTransaction transaction =
                       BeginTransaction(connection, isolationLevel))
            {
                command.Transaction = transaction;

                try
                {
                    procedure();
                }
                catch (Exception)
                {
                    try
                    {
                        transaction.Rollback();
                    }
                    catch (Exception e)
                    {
                        _msg.Warn(
                            string.Format("Error rolling back transaction: {0}",
                                          e.Message), e);
                    }

                    throw;
                }

                transaction.Commit();
            }
        }
Exemplo n.º 14
0
 protected void RaiseChanged(CancelEventArgs e)
 {
     try
     {
         ElementValueChanged();
     }
     catch (Exception ex)
     {
         e.Cancel = true;
         _msg.Warn(ex.Message, ex);
         // TODO -- data does not parse
         //SetError(Notification.INVALID_FORMAT);
     }
 }
Exemplo n.º 15
0
        private static void Execute([NotNull] string statement, [NotNull] IDbCommand cmd)
        {
            Assert.ArgumentNotNullOrEmpty(statement, nameof(statement));
            Assert.ArgumentNotNull(cmd, nameof(cmd));

            _msg.Info(statement);

            try
            {
                cmd.CommandText = statement;
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                _msg.Warn(e.Message);
            }
        }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            try
            {
                IServiceHealth   health;
                Grpc.Core.Server server = Run(args, out health);

                _msg.Info("Type Q(uit) to stop the server.");

                while (true)
                {
                    // Avoid mindless spinning
                    Thread.Sleep(100);

                    if (System.Console.KeyAvailable)
                    {
                        if (System.Console.ReadKey(true).Key == ConsoleKey.Q)
                        {
                            _msg.Warn("Shutting down due to user input");
                            break;
                        }
                    }

                    // TODO: Uncomment after next pull
                    //if (health.IsAnyServiceUnhealthy())
                    //{
                    //	_msg.Warn("Shutting down due to service state NOT_SERVING");
                    //	break;
                    //}
                }

                if (server != null)
                {
                    GrpcServerUtils.GracefullyStop(server);
                }
            }
            catch (Exception ex)
            {
                _msg.Error("An error occurred in microservice.", ex);
                Environment.ExitCode = -1;
            }
            finally
            {
                _msg.Debug("License released, shutting down...");
            }
        }
Exemplo n.º 17
0
        public bool InitializeApplication(
            [NotNull] esriLicenseProductCode[] productCodes,
            [NotNull] esriLicenseExtensionCode[] extensionLicenseCodes)
        {
            try
            {
                TryBindProduct(productCodes);
            }
            catch (Exception ex)
            {
                _msg.Debug("Exception while binding ArcGIS 10 product.", ex);
            }

            if (_aoInitialize == null)
            {
                try
                {
                    // If the next line fails with error code -2147221164: make sure that exe's are compiled for x86
                    // Otherwise on 64bit systems this error occurs.
                    _aoInitialize = new AoInitializeClass();
                }
                catch (Exception e)
                {
                    _msg.Debug("Error initializing ArcObjects", e);

                    _msg.Warn("Unable to initialize ArcGIS. This application cannot run! " +
                              "Please check that ArcGIS (Desktop, Engine or Server) is installed.");
                    return(false);
                }
            }

            //Initialize the application
            _productsCodes   = productCodes;
            _extensionsCodes = extensionLicenseCodes;

            esriLicenseStatus licenseStatus = CheckOutLicenses();

            if (licenseStatus != esriLicenseStatus.esriLicenseCheckedOut)
            {
                _msg.WarnFormat("ESRI License Initializer: {0}", LicenseMessage(licenseStatus));
                return(false);
            }

            return(true);
        }
Exemplo n.º 18
0
        private bool SelectTargets(List <Feature> selectedFeatures, Geometry sketch,
                                   CancelableProgressor progressor)
        {
            const TargetFeatureSelection targetFeatureSelection =
                TargetFeatureSelection.VisibleFeatures;

            sketch = ToolUtils.SketchToSearchGeometry(sketch, GetSelectionTolerancePixels(),
                                                      out bool _);

            Predicate <Feature> canUseAsTargetFeature =
                t => CanUseAsTargetFeature(selectedFeatures, t);

            SpatialRelationship spatialRel =
                SketchType == SketchGeometryType.Polygon
                                        ? SpatialRelationship.Contains
                                        : SpatialRelationship.Intersects;

            var foundOidsByLayer =
                MapUtils.FindFeatures(ActiveMapView, sketch, spatialRel,
                                      targetFeatureSelection, CanUseAsTargetLayer,
                                      canUseAsTargetFeature, selectedFeatures, progressor);

            // TODO: Picker if single click and several found

            if (progressor != null && progressor.CancellationToken.IsCancellationRequested)
            {
                _msg.Warn("Calculation of reshape lines was cancelled.");
                return(false);
            }

            IList <Feature> allTargetFeatures =
                GetDistinctSelectedFeatures(foundOidsByLayer, _changeAlongCurves?.TargetFeatures,
                                            KeyboardUtils.IsModifierPressed(Keys.Shift));

            _changeAlongCurves =
                allTargetFeatures.Count > 0
                                        ? CalculateReshapeCurves(selectedFeatures, allTargetFeatures, progressor)
                                        : new ChangeAlongCurves(new List <CutSubcurve>(),
                                                                ReshapeAlongCurveUsability.NoTarget);

            _feedback.Update(_changeAlongCurves);

            return(true);
        }
Exemplo n.º 19
0
        private void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (_health == null)
            {
                return;
            }

            if (_health.IsAnyServiceUnhealthy())
            {
                _health = null;

                _msg.Warn("Shutting down due to unhealthy service...");

                GrpcServerUtils.GracefullyStop(_server);

                // This allows the auto-restart to kick in:
                Environment.Exit(-1);
            }
        }
Exemplo n.º 20
0
        protected void Notify()
        {
            object currentControlValue = GetValueFromControl();

            if (_msg.IsVerboseDebugEnabled)
            {
                _msg.DebugFormat(
                    "Notify() {0}: _lastValue={1} GetValueFromControl()={2}",
                    Accessor.Name, _lastValue, currentControlValue);
            }

            if (Equals(_lastValue, currentControlValue))
            {
                return;
            }

            WithinLatch(
                delegate
            {
                _binder.Validate(this);

                try
                {
                    _lastValue = GetValueFromModel();

                    // ORIGINAL >>
                    //if (_lastValue != null)
                    //{
                    //    _binder.OnChange();
                    //}
                    // << ORIGINAL

                    _binder.OnChange();
                }
                catch (Exception e)
                {
                    ShowErrorMessages(e.Message);

                    _msg.Warn("Exception in Notify() ignored", e);
                }
            });
        }
Exemplo n.º 21
0
        public static bool TryApplySortState([NotNull] DataGridView dataGridView,
                                             [CanBeNull] string sortedColumnName,
                                             ListSortDirection direction)
        {
            Assert.ArgumentNotNull(dataGridView, nameof(dataGridView));

            if (string.IsNullOrEmpty(sortedColumnName))
            {
                return(false);
            }

            try
            {
                if (dataGridView.Columns.Contains(sortedColumnName))
                {
                    DataGridViewColumn columnToSort =
                        dataGridView.Columns[sortedColumnName];

                    Assert.NotNull(columnToSort, nameof(columnToSort));

                    // NOTE this is very slow (not due to the actual binding to row properties or sorting the binding list, but
                    // apparently due to the datagridview implementation itself (observed for standard data grid views also)
                    dataGridView.Sort(columnToSort, direction);

                    return(true);
                }

                _msg.DebugFormat("Sort column not found: {0}", sortedColumnName);
            }
            catch (Exception e)
            {
                _msg.Warn($"Error applying data grid sort order: {e.Message}", e);
            }

            return(false);
        }
Exemplo n.º 22
0
        public static IList <IGeometry> TryCut([NotNull] IPolygon inputPolygon,
                                               [NotNull] IPolyline cutLine,
                                               bool verifyTargetZs = true)
        {
            var result = new List <IGeometry>();

            try
            {
                IGeometryCollection resultCollection;

                try
                {
                    resultCollection =
                        ((ITopologicalOperator4)inputPolygon).Cut2(cutLine);
                }
                catch (COMException comEx)
                {
                    const int cannotBePerfomredOnNonSimpleGeometry = -2147220968;

                    if (comEx.ErrorCode == cannotBePerfomredOnNonSimpleGeometry)
                    {
                        _msg.Debug("Cut2 failed. Trying again after simplify...", comEx);

                        GeometryUtils.Simplify(inputPolygon);

                        // and try again
                        resultCollection =
                            ((ITopologicalOperator4)inputPolygon).Cut2(cutLine);
                    }
                    else
                    {
                        throw;
                    }
                }

                if (verifyTargetZs)
                {
                    // TOP-4666: Sometimes NaN or 0 Z values are introduced instead of the Z values from the sketch
                    if (!VerifyZs(inputPolygon, resultCollection, cutLine))
                    {
                        resultCollection =
                            ((ITopologicalOperator4)inputPolygon).Cut2(cutLine);
                    }

                    // The second time works correctly:
                    if (!VerifyZs(inputPolygon, resultCollection, cutLine))
                    {
                        _msg.Warn(
                            "Z verification failed. Please review Z values carefully and report in case of wrong Z values.");
                    }
                }

                result.AddRange(GeometryUtils.GetParts(resultCollection));
            }
            catch (Exception e)
            {
                // TODO: Catch specific exception only
                // Typically:
                // A polygon cut operation could not classify all parts of the polygon as left or right of the cutting line.
                _msg.Debug("Unable to cut polygon", e);

                return(null);
            }

            return(result);
        }
        internal static void LogQualityVerification(
            [NotNull] QualityVerification verification)
        {
            try
            {
                var sb = new StringBuilder();

                sb.AppendLine(verification.Cancelled
                                                      ? "The quality verification was cancelled"
                                                      : "Quality verified");

                int conditionCount = verification.ConditionVerifications.Count;

                sb.AppendFormat("- {0:N0} quality condition{1} verified",
                                conditionCount, conditionCount == 1
                                                                        ? ""
                                                                        : "s");
                sb.AppendLine();

                int issueCount = verification.IssueCount;
                if (issueCount == 0)
                {
                    sb.AppendLine("- No issues found");
                }
                else
                {
                    sb.AppendFormat(issueCount == 1
                                                                ? "- {0:N0} issue found"
                                                                : "- {0:N0} issues found",
                                    issueCount);
                    sb.AppendLine();

                    sb.AppendFormat("  - Errors: {0:N0}", verification.ErrorCount);
                    sb.AppendLine();

                    sb.AppendFormat("  - Warnings: {0:N0}", verification.WarningCount);
                    sb.AppendLine();

                    if (verification.RowsWithStopConditions > 0)
                    {
                        sb.AppendFormat("  - Number of rows with a stop condition error: {0:N0}",
                                        verification.RowsWithStopConditions);
                        sb.AppendLine();
                    }
                }

                if (!verification.Cancelled)
                {
                    sb.AppendLine(verification.Fulfilled
                                                              ? "- The quality specification is fulfilled"
                                                              : "- The quality specification is not fulfilled");
                }

                if (verification.Fulfilled)
                {
                    _msg.InfoFormat(sb.ToString());
                }
                else
                {
                    _msg.WarnFormat(sb.ToString());
                }

                LogVerificationDetails(verification);
            }
            catch (Exception e)
            {
                _msg.Warn("Error writing report to log", e);
                // continue
            }
        }
Exemplo n.º 24
0
        private IList <IGeometry> RemoveOverlap(
            [NotNull] IPolycurve fromGeometry,
            [NotNull] IPolycurve overlaps,
            ChangeAlongZSource zSource,
            out IList <IGeometry> overlappingResults)
        {
            Assert.ArgumentNotNull(fromGeometry, nameof(fromGeometry));
            Assert.ArgumentNotNull(overlaps, nameof(overlaps));

            overlaps = ChangeAlongZUtils.PrepareCutPolylineZs(overlaps, zSource);

            Plane3D plane = null;

            if (zSource == ChangeAlongZSource.SourcePlane)
            {
                plane = ChangeAlongZUtils.GetSourcePlane(
                    GeometryConversionUtils.GetPntList(fromGeometry),
                    GeometryUtils.GetZTolerance(fromGeometry));
            }

            IGeometry rawResult = GetDifference(fromGeometry, overlaps);

            if (plane != null)
            {
                ChangeAlongZUtils.AssignZ((IPointCollection)rawResult, plane);
            }

            int originalPartCount = GetRelevantPartCount(fromGeometry);
            int resultPartCount   = GetRelevantPartCount(rawResult);

            // TODO: This works for simple cases. To be correct the difference operation and part comparison would have to be
            //       done on a per-part basis, because in the same operation one part could be added and one removed.
            //       Just comparing part counts before and after is misleading in such cases.
            if (resultPartCount > originalPartCount)
            {
                Result.ResultHasMultiparts = true;
            }

            IList <IGeometry> result = new List <IGeometry>();

            // TODO explode only those input parts that where cut into more than one result part
            // --> preserve other input parts in original geometry

            if (rawResult is IPolycurve && _explodeMultipartResult &&
                IsMultipart(rawResult))
            {
                // Exploding all selected multipart geos
                // to explode geos only if not avoidable,
                // use GetPositivePartCount and compare counts before and after cut operation
                foreach (IGeometry geometry in GeometryUtils.Explode(rawResult))
                {
                    var part = (IPolycurve)geometry;
                    result.Add(part);
                }

                if (((IGeometryCollection)fromGeometry).GeometryCount > 1)
                {
                    // TODO: Fix this situation by checking which individual parts were split by the overlap and only turn them into a new feature
                    _msg.Warn(
                        "The selection included multi-part geometry. Storing this geometry generated several copies of the feature.");
                }
            }
            else
            {
                result.Add(rawResult);
            }

            overlappingResults = _storeOverlapsAsNewFeatures
                                                     ? CalculateOverlappingGeometries(fromGeometry,
                                                                                      overlaps)
                                                     : null;
            return(result);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Executes a procedure in an edit operation
        /// </summary>
        /// <param name="workspace">The workspace in which the operation is executed</param>
        /// <param name="procedure">The operation.</param>
        /// <param name="state">The state.</param>
        /// <param name="description">The description for the edit operation.</param>
        /// <param name="trackCancel">The cancel tracker (optional).</param>
        /// <returns>
        ///     <c>true</c> if the operation succeeded, <c>false</c> if it was aborted.
        /// </returns>
        public bool Execute(IWorkspace workspace, Action <ITrackCancel> procedure,
                            EditStateInfo state, string description,
                            ITrackCancel trackCancel)
        {
            Assert.ArgumentNotNull(workspace, nameof(workspace));
            Assert.ArgumentNotNull(procedure, nameof(procedure));
            Assert.ArgumentNotNullOrEmpty(description, nameof(description));

            if (trackCancel != null)
            {
                Assert.True(trackCancel.Continue(), "Cancel tracker already cancelled");
            }

            using (EditWorkspace(workspace))
            {
                var editWs  = (IWorkspaceEdit)workspace;
                var editWs2 = workspace as IWorkspaceEdit2;                 // not implemented for shapefiles

                bool isBeingEdited     = editWs.IsBeingEdited();
                bool isInEditOperation = (editWs2 != null && editWs2.IsInEditOperation);

                if ((state & EditStateInfo.MustNotBeEditing) != 0)
                {
                    Assert.False(isBeingEdited, "Edit Session already open");
                }

                if ((state & EditStateInfo.MustBeEditing) != 0)
                {
                    Assert.True(isBeingEdited, "Edit Session not open");
                }

                if ((state & EditStateInfo.MustNotBeInOperation) != 0)
                {
                    if (isInEditOperation)
                    {
                        AbortEditOperation();
                        _msg.Warn("Rolled back unexpected existing edit operation");
                    }

                    isInEditOperation = false;
                }

                if ((state & EditStateInfo.MustBeInOperation) != 0)
                {
                    Assert.True(isInEditOperation, "Edit Session not in Operation");
                }

                _aborted = false;

                IWorkspaceEditEvents_Event workspaceEditEvents = null;

                try
                {
                    #region check reset current state

                    if (isInEditOperation)
                    {
                        if ((state & EditStateInfo.AbortExistingOperation) != 0)
                        {
                            Assert.True(
                                (state & EditStateInfo.StopExistingOperation) == 0,
                                "Cannot specify both " +
                                EditStateInfo.AbortExistingOperation + " and " +
                                EditStateInfo.StopExistingOperation);
                            AbortEditOperation();
                            isInEditOperation = false;
                        }
                        else if ((state & EditStateInfo.StopExistingOperation) != 0)
                        {
                            StopEditOperation(description);
                            isInEditOperation = false;
                        }
                    }

                    if (isBeingEdited)
                    {
                        if ((state & EditStateInfo.AbortExistingEditing) != 0)
                        {
                            Assert.True((state & EditStateInfo.StopExistingEditing) == 0,
                                        "Cannot specify both " +
                                        EditStateInfo.AbortExistingEditing + " and " +
                                        EditStateInfo.StopExistingEditing);

                            StopEditing(false);
                            isBeingEdited = false;
                        }
                        else if ((state & EditStateInfo.StopExistingEditing) != 0)
                        {
                            StopEditing(true);
                            isBeingEdited = false;
                        }
                    }

                    #endregion

                    if (!isBeingEdited)
                    {
                        StartEditing();
                    }

                    if (!isInEditOperation && (state & EditStateInfo.DontStartOperation) == 0)
                    {
                        StartEditOperation();
                    }

                    // this may fail (COM object that has been separated from its underlying RCW cannot be used)
                    workspaceEditEvents = (IWorkspaceEditEvents_Event)workspace;
                    workspaceEditEvents.OnAbortEditOperation += editEvents_OnAbortEditOperation;

                    procedure(trackCancel);

                    if (trackCancel != null && !trackCancel.Continue())
                    {
                        _msg.WarnFormat("Operation cancelled: {0}", description);

                        // cancel was called in procedure
                        if (!_aborted)
                        {
                            // The operation is not yet aborted. Abort it now.
                            AbortEditOperation();
                        }
                    }

                    if (!_aborted &&
                        (!isInEditOperation &&
                         (state & EditStateInfo.KeepOperation) == 0) ||
                        (state & EditStateInfo.StopOperation) != 0)
                    {
                        // if the edit operation violates rule engine rules, the edit operation won't succeed. However
                        // no exception is reported when calling StopEditOperation --> the OnAbort handler is mandatory
                        // to detect this situation.
                        StopEditOperation(description);
                    }

                    if ((!isBeingEdited &&
                         (state & EditStateInfo.KeepEditing) == 0) ||
                        (state & EditStateInfo.StopEditing) != 0)
                    {
                        StopEditing(true);
                    }

                    return(!_aborted);
                }
                catch (Exception ex)
                {
                    try                     // Clean up
                    {
                        var    comEx   = ex as COMException;
                        string message =
                            comEx == null
                                                                ? string.Format("Error executing operation: {0} ({1})",
                                                                                description, ex.Message)
                                                                : string.Format(
                                "Error executing operation: {0} ({1}; Error Code: {2})",
                                description, comEx.Message, comEx.ErrorCode);

                        _msg.Debug(message);

                        if (!isInEditOperation)
                        {
                            // if the error occurred in StopEditOperation(), then
                            // that edit operation might already be aborted -> check
                            if (editWs2 != null && editWs2.IsInEditOperation)
                            {
                                AbortEditOperation();
                            }
                        }

                        if (!isBeingEdited)
                        {
                            StopEditing(false);
                        }
                    }
                    catch (Exception e2)
                    {
                        // exception intentionally suppressed.
                        _msg.Error("Error cleaning up after failed gdb function", e2);
                    }

                    throw;
                }
                finally
                {
                    try
                    {
                        if (workspaceEditEvents != null)
                        {
                            workspaceEditEvents.OnAbortEditOperation -=
                                editEvents_OnAbortEditOperation;
                        }
                    }
                    catch (AccessViolationException e)
                    {
                        // exception intentionally suppressed.
                        _msg.Warn("Error unregistering event handler", e);
                    }
                }
            }
        }
Exemplo n.º 26
0
        public static void Import(
            [CanBeNull] string importWhereClause,
            [NotNull] IList <IObjectClass> targetExceptionClasses,
            [NotNull] IList <IObjectClass> importExceptionClasses,
            [NotNull] string importOriginValue,
            DateTime importDate)
        {
            IIssueTableFields importFields = GetImportFields(importExceptionClasses);
            IIssueTableFields targetFields = GetTargetFields(targetExceptionClasses);

            IDictionary <Guid, QualityConditionExceptions> targetExceptionsByConditionVersion;

            using (_msg.IncrementIndentation(
                       "Reading existing exceptions in target workspace"))
            {
                targetExceptionsByConditionVersion = ReadTargetExceptions(targetExceptionClasses,
                                                                          targetFields);
            }

            var replacedExceptionObjects = new Dictionary <esriGeometryType, HashSet <int> >();

            using (_msg.IncrementIndentation("Importing new exceptions from issue datasets...")
                   )
            {
                foreach (ITable importTable in importExceptionClasses.Cast <ITable>())
                {
                    using (_msg.IncrementIndentation("from {0}...",
                                                     DatasetUtils.GetName(importTable)))
                    {
                        ITable targetTable = GetTargetTable(importTable, targetExceptionClasses);
                        if (targetTable == null)
                        {
                            _msg.Warn(
                                "No matching table in target workspace, ignoring import table");
                            continue;
                        }

                        var factory = new ExceptionObjectFactory(
                            importTable, importFields,
                            defaultStatus: ExceptionObjectStatus.Inactive);

                        var newCount     = 0;
                        var updateCount  = 0;
                        var ignoredCount = 0;

                        using (var writer = new ExceptionWriter(importTable, importFields,
                                                                targetTable, targetFields))
                        {
                            foreach (IRow row in GdbQueryUtils.GetRows(importTable,
                                                                       GetQueryFilter(
                                                                           importWhereClause),
                                                                       recycle: true))
                            {
                                int  matchCount;
                                bool added = ImportException(row, importOriginValue, importDate,
                                                             factory,
                                                             targetExceptionsByConditionVersion,
                                                             replacedExceptionObjects,
                                                             writer,
                                                             out matchCount);
                                if (!added)
                                {
                                    ignoredCount++;
                                }
                                else if (matchCount == 0)
                                {
                                    newCount++;
                                }
                                else
                                {
                                    updateCount++;
                                }
                            }
                        }

                        _msg.InfoFormat("{0:N0} exception(s) imported as new", newCount);
                        _msg.InfoFormat("{0:N0} exception(s) imported as updates", updateCount);
                        if (ignoredCount > 0)
                        {
                            _msg.InfoFormat("{0:N0} exception(s) ignored", ignoredCount);
                        }
                    }
                }
            }

            using (_msg.IncrementIndentation("Processing replaced exceptions..."))
            {
                foreach (ITable targetTable in targetExceptionClasses.Cast <ITable>())
                {
                    using (_msg.IncrementIndentation("Target table {0}...",
                                                     DatasetUtils.GetName(targetTable)))
                    {
                        int fixedStatusCount;
                        int updateCount = ProcessReplacedExceptions(targetTable, targetFields,
                                                                    replacedExceptionObjects,
                                                                    importDate,
                                                                    out fixedStatusCount);

                        _msg.InfoFormat("{0:N0} replaced exception(s) updated", updateCount);
                        if (fixedStatusCount > 0)
                        {
                            _msg.InfoFormat("Status value of {0:N0} old exception version(s) fixed",
                                            fixedStatusCount);
                        }
                    }
                }
            }
        }
Exemplo n.º 27
0
        public static IList <TestParameter> CreateParameters([NotNull] Type type,
                                                             int constructorId)
        {
            ConstructorInfo constr = type.GetConstructors()[constructorId];

            ParameterInfo[] constructorParameters = constr.GetParameters();
            PropertyInfo[]  properties            = type.GetProperties();

            var testParameterProperties =
                new Dictionary <PropertyInfo, TestParameterAttribute>();

            foreach (PropertyInfo propertyInfo in properties)
            {
                if (!propertyInfo.CanRead || !propertyInfo.CanWrite)
                {
                    continue;
                }

                var testParameterAttribute =
                    ReflectionUtils.GetAttribute <TestParameterAttribute>(
                        propertyInfo);

                if (testParameterAttribute == null)
                {
                    continue;
                }

                var isValid = true;
                foreach (ParameterInfo constructorParameter in constructorParameters)
                {
                    if (string.Equals(constructorParameter.Name, propertyInfo.Name,
                                      StringComparison.InvariantCultureIgnoreCase))
                    {
                        isValid = false;

                        _msg.Warn(GetMessageConstructorParameterExistsAlsoAsProperty(
                                      type, constructorId, constructorParameter));
                    }
                }

                if (isValid)
                {
                    testParameterProperties.Add(propertyInfo, testParameterAttribute);
                }
            }

            var testParameters =
                new List <TestParameter>(constructorParameters.Length +
                                         testParameterProperties.Count);

            foreach (ParameterInfo parameter in constructorParameters)
            {
                var testParameter = new TestParameter(
                    parameter.Name, parameter.ParameterType,
                    TestImplementationUtils.GetDescription(parameter),
                    isConstructorParameter: true);

                object defaultValue;
                if (ReflectionUtils.TryGetDefaultValue(parameter, out defaultValue))
                {
                    testParameter.DefaultValue = defaultValue;
                }

                testParameters.Add(testParameter);
            }

            foreach (KeyValuePair <PropertyInfo, TestParameterAttribute> pair in
                     testParameterProperties)
            {
                PropertyInfo           property  = pair.Key;
                TestParameterAttribute attribute = pair.Value;

                var testParameter = new TestParameter(
                    property.Name, property.PropertyType,
                    TestImplementationUtils.GetDescription(property),
                    isConstructorParameter: false);

                testParameter.DefaultValue = attribute.DefaultValue;

                testParameters.Add(testParameter);
            }

            return(new ReadOnlyList <TestParameter>(testParameters));
        }
Exemplo n.º 28
0
        private Polygon GetIntersection([NotNull] Polygon[] perimeters, int index)
        {
            Assert.ArgumentNotNull(perimeters, nameof(perimeters));

            if (_msg.IsVerboseDebugEnabled)
            {
                _msg.DebugFormat("Intersecting perimeters {0} to {1}",
                                 index, perimeters.Length - 1);
            }

            Polygon intersection = GeometryFactory.Clone(perimeters[index]);

            // todo daro old implementation
            //GeometryUtils.EnsureSpatialReference(intersection, SpatialReference, true);

            // intersect with all following perimeters, if any
            int nextIndex = index + 1;

            if (nextIndex < perimeters.Length)
            {
                for (int combineIndex = nextIndex;
                     combineIndex < perimeters.Length;
                     combineIndex++)
                {
                    //Polygon projectedPerimeter =
                    //	GetInWorkListSpatialReference(perimeters[combineIndex]);

                    Polygon projectedPerimeter = perimeters[combineIndex];

                    if (intersection.IsEmpty)
                    {
                        // no further intersection, result is empty
                        return(intersection);
                    }
                    if (projectedPerimeter.IsEmpty)
                    {
                        // no further intersection, result is empty
                        return(projectedPerimeter);
                    }

                    // both are not empty; calculate intersection
                    try
                    {
                        // todo daro: old implementation
                        //var topoOp = (ITopologicalOperator)intersection;

                        //intersection =
                        //	(IPolygon)topoOp.Intersect(
                        //		projectedPerimeter,
                        //		esriGeometryDimension.esriGeometry2Dimension);

                        intersection =
                            (Polygon)GeometryEngine.Instance.Intersection(
                                intersection, projectedPerimeter,
                                GeometryDimension.esriGeometry2Dimension);
                    }
                    catch (Exception e)
                    {
                        try
                        {
                            _msg.ErrorFormat(
                                "Error intersecting perimeters ({0}). See log file for details",
                                e.Message);

                            _msg.DebugFormat("Perimeter index={0}:", combineIndex);
                            // todo daro: old implementation
                            //_msg.Debug(GeometryUtils.ToString(projectedPerimeter));

                            _msg.DebugFormat(
                                "Input intersection at nextIndex={0}:", nextIndex);
                            // todo daro: old implementation
                            //_msg.Debug(GeometryUtils.ToString(intersection));

                            // leave intersection as is, and continue
                        }
                        catch (Exception e1)
                        {
                            _msg.Warn("Error writing details to log", e1);
                        }
                    }

                    // todo daro: old implementation
                    //if (_msg.IsVerboseDebugEnabled)
                    //{
                    //	_msg.DebugFormat("Intersection {0}: {1}",
                    //					 combineIndex,
                    //					 IntersectionToString(intersection));
                    //}
                }
            }

            return(intersection);
        }
        private ServiceCallStatus VerifyStandaloneXmlCore(
            StandaloneVerificationRequest request,
            IServerStreamWriter <StandaloneVerificationResponse> responseStream,
            ITrackCancel trackCancel)
        {
            // Machine login
            SetupUserNameProvider(Environment.UserName);

            try
            {
                VerificationParametersMsg parameters = request.Parameters;

                IGeometry perimeter =
                    ProtobufGeometryUtils.FromShapeMsg(parameters.Perimeter);

                XmlBasedVerificationService qaService =
                    CreateXmlBasedStandaloneService(request);

                XmlQualitySpecificationMsg xmlSpecification = request.Specification;

                var dataSources = new List <DataSource>();
                foreach (string replacement in xmlSpecification.DataSourceReplacements)
                {
                    List <string> replacementStrings = StringUtils.SplitAndTrim(replacement, '>');
                    Assert.AreEqual(2, replacementStrings.Count,
                                    "Data source workspace is not of the format workspace_id > catalog_path");

                    var dataSource = new DataSource(replacementStrings[0], replacementStrings[0])
                    {
                        WorkspaceAsText = replacementStrings[1]
                    };

                    dataSources.Add(dataSource);
                }

                var aoi = perimeter == null ? null : new AreaOfInterest(perimeter);

                try
                {
                    qaService.ExecuteVerification(
                        xmlSpecification.Xml,
                        xmlSpecification.SelectedSpecificationName,
                        dataSources, aoi, null, parameters.TileSize,
                        parameters.IssueFileGdbPath, IssueRepositoryType.FileGdb,
                        true, trackCancel);
                }
                catch (ArgumentException argumentException)
                {
                    _msg.Warn("Argument exception", argumentException);

                    return(ServiceCallStatus.Failed);
                }
            }
            catch (Exception e)
            {
                _msg.DebugFormat("Error during processing of request {0}", request);
                _msg.Error("Error verifying quality: ", e);

                if (!EnvironmentUtils.GetBooleanEnvironmentVariableValue(
                        "PROSUITE_QA_SERVER_KEEP_SERVING_ON_ERROR"))
                {
                    SetUnhealthy();
                }

                return(ServiceCallStatus.Failed);
            }

            return(trackCancel.Continue()
                                       ? ServiceCallStatus.Finished
                                       : ServiceCallStatus.Cancelled);
        }
Exemplo n.º 30
0
 public void ReportWarning(string text, Exception exception = null)
 {
     _msg.Warn(text, exception);
 }