Example #1
0
        private static void AddOrUpdateAttribute(
            [NotNull] AttributedAssociation attributedAssociation,
            [NotNull] IField field,
            int fieldIndex)
        {
            Assert.ArgumentNotNull(field, nameof(field));

            const bool           includeDeleted = true;
            AssociationAttribute attribute      =
                attributedAssociation.GetAttribute(field.Name, includeDeleted);

            if (attribute == null)
            {
                _msg.InfoFormat("Adding attribute {0}", field.Name);

                attribute = attributedAssociation.AddAttribute(field.Name, (FieldType)field.Type);
            }
            else
            {
                // attribute already registered
                if (attribute.Deleted)
                {
                    _msg.WarnFormat(
                        "Attribute {0} was registered as deleted, but exists now. " +
                        "Resurrecting it...", attribute.Name);

                    attribute.RegisterExisting();
                }

                attribute.FieldType = (FieldType)field.Type;
            }

            // configure the attribute
            attribute.SortOrder = fieldIndex;
        }
Example #2
0
        public static double Clip(double value, double min, double max,
                                  [CanBeNull] string parameter = null)
        {
            if (value < min)
            {
                if (!string.IsNullOrEmpty(parameter))
                {
                    _msg.WarnFormat("{0} was {1}, clipped to {2}", parameter, value, min);
                }

                return(min);
            }

            if (value > max)
            {
                if (!string.IsNullOrEmpty(parameter))
                {
                    _msg.WarnFormat("{0} was {1}, clipped to {2}", parameter, value, max);
                }

                return(max);
            }

            return(value);
        }
Example #3
0
        void IVerificationReportBuilder.AddIssue(Issue issue, IGeometry errorGeometry)
        {
            _errors.Add(issue);

            _msg.WarnFormat(issue.Allowable
                                                ? "Error ({0}, soft): {1}"
                                                : "Error ({0}, hard): {1}",
                            issue.QualityCondition.Name, issue);
        }
Example #4
0
        private static void AddOrUpdateObjectType([NotNull] ObjectDataset objectDataset,
                                                  [NotNull] Subtype subtype,
                                                  int subtypeIndex,
                                                  [NotNull] IEnumerable <Subtype> allSubtypes)
        {
            Assert.ArgumentNotNull(subtype, nameof(subtype));
            Assert.ArgumentNotNull(allSubtypes, nameof(allSubtypes));

            ObjectType objectType = GetObjectType(objectDataset, subtype, allSubtypes);

            if (objectType == null)
            {
                objectType = new ObjectType(objectDataset, subtype.Code, subtype.Name);

                _msg.InfoFormat("Adding object type {0}", objectType.Name);

                objectDataset.AddObjectType(subtype.Code, subtype.Name);
            }
            else
            {
                // object type already registered

                if (objectType.Deleted)
                {
                    _msg.WarnFormat(
                        "Object type {0} ({1}) was registered as deleted, but exists now. " +
                        "Resurrecting it...",
                        objectType.Name, objectType.SubtypeCode);

                    objectType.RegisterExisting();
                }

                // update properties
                if (!Equals(objectType.Name, subtype.Name))
                {
                    _msg.InfoFormat("Updating name of object type {0} to {1}",
                                    objectType.Name, subtype.Name);

                    objectType.UpdateName(subtype.Name);
                }

                if (!Equals(objectType.SubtypeCode, subtype.Code))
                {
                    _msg.InfoFormat("Updating subtype code of object type {0} from {1} to {2}",
                                    objectType.Name, objectType.SubtypeCode, subtype.Code);

                    objectType.UpdateSubtypeCode(subtype.Code);
                }
            }

            // configure the object type
            objectType.SortOrder = subtypeIndex;
        }
        private static void LogResults(
            [NotNull] IEnumerable <QualitySpecificationElement> qualitySpecificationElements,
            [NotNull] IssueProcessor issueProcessor,
            int qualityConditionCount, int datasetCount,
            bool fulfilled, bool cancelled,
            [CanBeNull] IExceptionStatistics exceptionStatistics)
        {
            using (_msg.IncrementIndentation("Quality verification finished"))
            {
                _msg.InfoFormat("Number of verified datasets: {0:N0}", datasetCount);
                using (_msg.IncrementIndentation("Number of verified quality conditions: {0:N0}",
                                                 qualityConditionCount))
                {
                    LogVerifiedConditions(qualitySpecificationElements,
                                          issueProcessor,
                                          exceptionStatistics);
                }

                _msg.InfoFormat("Warning count: {0:N0}", issueProcessor.WarningCount);
                _msg.InfoFormat("Error count: {0:N0}", issueProcessor.ErrorCount);

                if (issueProcessor.RowsWithStopConditionsCount > 0)
                {
                    _msg.WarnFormat("Number of features with stop errors: {0:N0}",
                                    issueProcessor.RowsWithStopConditionsCount);
                }

                if (exceptionStatistics != null &&
                    exceptionStatistics.TablesWithNonUniqueKeys.Count > 0)
                {
                    _msg.WarnFormat(
                        "Number of tables with non-unique keys referenced by exception objects: {0}",
                        exceptionStatistics.TablesWithNonUniqueKeys.Count);
                }

                if (cancelled)
                {
                    _msg.Warn("The quality verification was cancelled");
                }
                else if (fulfilled)
                {
                    _msg.Info("The quality specification is fulfilled");
                }
                else
                {
                    _msg.Warn("The quality specification is not fulfilled");
                }
            }
        }
        public void GetConfigurations([CanBeNull] out T localConfiguration,
                                      [CanBeNull] out T centralConfiguration,
                                      bool suppressXmlSchemaWarning = false)
        {
            centralConfiguration = null;

            var issueNotifications = new NotificationCollection();

            if (ConfigurationExists(CentralConfigDirectory, ConfigFileName))
            {
                _centralConfiguration = GetConfiguration(
                    CentralConfigDirectory, ConfigFileName,
                    issueText => issueNotifications.Add(issueText));

                if (issueNotifications.Count > 0 && !suppressXmlSchemaWarning)
                {
                    // This could happen if the schema changes other than just adding new nodes:
                    _msg.WarnFormat(
                        "The central configuration file {0} in {1} could not be read completely ({2}). Please review its structure and ensure it conforms to the current schema.",
                        ConfigFileName, CentralConfigDirectory,
                        issueNotifications.Concatenate(". "));
                }

                centralConfiguration = _centralConfiguration;
            }
            else if (_hardCodedDefaults != null)
            {
                centralConfiguration = _hardCodedDefaults;
            }

            localConfiguration = null;

            issueNotifications.Clear();
            if (ConfigurationExists(LocalConfigDirectory, ConfigFileName))
            {
                localConfiguration = GetConfiguration(
                    LocalConfigDirectory, ConfigFileName,
                    issueText => issueNotifications.Add(issueText));

                if (issueNotifications.Count > 0 && !suppressXmlSchemaWarning)
                {
                    // Could happen if the schema changes other than just adding new nodes:
                    _msg.WarnFormat(
                        "The local configuration file {0} in {1} could not be read completely ({2}). Please review and accept the current settings in the options dialog.",
                        ConfigFileName, CentralConfigDirectory,
                        issueNotifications.Concatenate(". "));
                }
            }
        }
Example #7
0
        public FieldConfigurator(
            [NotNull] IEnumerable <XmlFieldOptions> fieldOptionsCollection)
        {
            Assert.ArgumentNotNull(fieldOptionsCollection, nameof(fieldOptionsCollection));

            foreach (XmlFieldOptions fieldOptions in fieldOptionsCollection)
            {
                if (string.IsNullOrEmpty(fieldOptions.Field))
                {
                    continue;
                }

                string trimmedField = fieldOptions.Field.Trim();

                if (trimmedField.StartsWith(_rolePrefix))
                {
                    string roleName = trimmedField.Substring(1);

                    IssueAttribute role;
                    if (!EnumUtils.TryParse(roleName, ignoreCase: true, result: out role))
                    {
                        _msg.WarnFormat("Unknown attribute role: {0}", roleName);
                        continue;
                    }

                    if (_fieldOptionsByRole.ContainsKey(role))
                    {
                        _msg.WarnFormat(
                            "Duplicate field options configuration for attribute role {0}",
                            role);
                        continue;
                    }

                    _fieldOptionsByRole.Add(role, fieldOptions);
                }
                else
                {
                    if (_fieldOptionsByName.ContainsKey(trimmedField))
                    {
                        _msg.WarnFormat("Duplicate field options configuration for field name {0}",
                                        trimmedField);
                        continue;
                    }

                    _fieldOptionsByName.Add(trimmedField, fieldOptions);
                }
            }
        }
Example #8
0
        public static Plane3D GetSourcePlane([NotNull] IList <Pnt3D> pntList,
                                             double coplanarityTolerance,
                                             bool warnIfNotPlanar = true)
        {
            Plane3D sourcePlane = Plane3D.TryFitPlane(pntList);

            if (sourcePlane == null)
            {
                return(null);
            }

            double maxDeviation;
            string message;

            bool?coplanar = AreCoplanar(
                pntList, sourcePlane, coplanarityTolerance, out maxDeviation,
                out message);

            if (coplanar == null || !coplanar.Value)
            {
                if (warnIfNotPlanar)
                {
                    _msg.WarnFormat(
                        "Input geometry contains non-coplanar points. The result will not be co-planar either.");
                }

                _msg.DebugFormat(
                    "Input points are not planar w.r.t. tolerance {0}: {1}",
                    coplanarityTolerance, StringUtils.Concatenate(pntList, ", "));
            }

            return(sourcePlane);
        }
Example #9
0
        private static void CreateIndex([NotNull] IssueFeatureWriter writer,
                                        [CanBeNull] ITrackCancel trackCancel,
                                        bool ignoreErrors)
        {
            _msg.InfoFormat(writer.WriteCount == 1
                                                ? "Creating spatial index for {0} issue feature in '{1}'"
                                                : "Creating spatial index for {0} issue features in '{1}'",
                            writer.WriteCount, writer.Name);

            try
            {
                writer.CreateSpatialIndex(trackCancel);
            }
            catch (Exception e)
            {
                if (!ignoreErrors)
                {
                    throw;
                }

                _msg.Debug("Error creating spatial index", e);
                _msg.WarnFormat("Error creating spatial index for feature class {0}: {1}",
                                writer.Name, e.Message);
            }
        }
Example #10
0
        public T ReadFromFile([NotNull] string xmlFile)
        {
            Action <string> logWarn =
                text => _msg.WarnFormat("Reading config file {0}: {1}", xmlFile, text);

            return(ReadFromFile(xmlFile, logWarn));
        }
Example #11
0
        private static void TryMoveLegacyFolderContent()
        {
            if (!Directory.Exists(LegacyFolderPath))
            {
                return;
            }

            if (!Directory.Exists(FolderPath))
            {
                if (!TryCreateFormStateDirectory())
                {
                    return;
                }
            }

            string searchPattern = string.Format("*.{0}", _fileExtension);

            foreach (string legacyFilePath in Directory.GetFiles(
                         LegacyFolderPath, searchPattern))
            {
                string fileName = Assert.NotNull(Path.GetFileName(legacyFilePath));

                string targetFilePath = Path.Combine(FolderPath, fileName);

                if (!File.Exists(targetFilePath))
                {
                    _msg.DebugFormat("Moving form state file {0} to {1}", legacyFilePath,
                                     FolderPath);

                    try
                    {
                        File.Move(legacyFilePath, targetFilePath);
                    }
                    catch (Exception ex)
                    {
                        _msg.WarnFormat("Error moving form state file {0} to {1}: {2}",
                                        legacyFilePath, FolderPath, ex.Message);
                    }
                }
                else
                {
                    TryDeleteLegacyFile(legacyFilePath);
                }
            }

            TryDeleteLegacyFolderIfEmpty();
        }
Example #12
0
        public int Compare(object value1, object value2, int fieldIndex, int fieldSortIndex)
        {
            // TODO: sometimes the OID gets provided (with fieldSortIndex == 1) -> we never asked for it!
            //		 test whether we can safely ignore it by if (fieldSortIndex > 0) return 0;
            try
            {
                if (fieldSortIndex > 0)
                {
                    _msg.VerboseDebugFormat(
                        "Assuming equal IDs: value1 {0}, value2 {1}, fieldIndex {2}, fieldSortIndex {3}",
                        value1, value2, fieldIndex, fieldSortIndex);

                    return(0);
                }

                if (Convert.IsDBNull(value1))
                {
                    _msg.WarnFormat("Sort field (fieldindex {0}) contains NULL (value1).",
                                    fieldIndex);

                    return(Convert.IsDBNull(value2) ? 0 : -1);
                }

                if (Convert.IsDBNull(value2))
                {
                    _msg.WarnFormat("Sort field (fieldindex {0}) contains NULL (value2).",
                                    fieldIndex);

                    return(Convert.IsDBNull(value1) ? 0 : 1);
                }

                // NOTE: To avoid exception with explicit cast
                // TODO: Check performance
                string value1String = Convert.ToString(value1);
                string value2String = Convert.ToString(value2);

                return(string.Compare(value1String, value2String,
                                      StringComparison.InvariantCultureIgnoreCase));
            }
            catch (Exception e)
            {
                _msg.Debug(
                    string.Format("Error comparing object values {0} and {1}", value1, value2), e);
                throw;
            }
        }
        public static bool TryDeleteOutputDirectory([NotNull] string directoryPath)
        {
            try
            {
                _msg.DebugFormat("Trying to delete the generated output directory: {0}",
                                 directoryPath);

                const bool recursive = true;
                Directory.Delete(directoryPath, recursive);

                _msg.Debug("Directory successfully deleted");
                return(true);
            }
            catch (Exception e)
            {
                _msg.WarnFormat("Error cleaning up generated output directory: {0}", e.Message);
                return(false);
            }
        }
Example #14
0
        private static IEnumerable <IGeometry> GetReferenceGeometries(
            [NotNull] IObject obj,
            [NotNull] IList <IRelationshipClass> relationshipChainToFeatureClass)
        {
            if (relationshipChainToFeatureClass.Count == 0)
            {
                yield break;
            }

            if (relationshipChainToFeatureClass.Count == 1)
            {
                foreach (IObject relatedObject in
                         GdbQueryUtils.GetRelatedObjects(obj, relationshipChainToFeatureClass))
                {
                    var relatedFeature = relatedObject as IFeature;

                    if (relatedFeature != null)
                    {
                        yield return(relatedFeature.Shape);
                    }
                    else
                    {
                        _msg.DebugFormat("Related object in spatial relation is not a feature: {0}",
                                         GdbObjectUtils.ToString(relatedObject));
                    }
                }
            }
            else
            {
                int?shapeFieldIndex = null;

                foreach (IRow joinedRow in GetJoinedRows(obj, relationshipChainToFeatureClass))
                {
                    // determine shape field index based on the first row
                    if (shapeFieldIndex == null)
                    {
                        int index;
                        if (TryGetShapeFieldIndex(joinedRow.Fields, out index))
                        {
                            shapeFieldIndex = index;
                        }
                        else
                        {
                            _msg.WarnFormat(
                                "Shape field not found in joined table for getting reference geometry for {0}",
                                DatasetUtils.GetName(obj.Class));
                            yield break;
                        }
                    }

                    yield return(joinedRow.Value[shapeFieldIndex.Value] as IGeometry);
                }
            }
        }
Example #15
0
        public static T Deserialize <T>([NotNull] TextReader textReader,
                                        [NotNull] XmlSchema xmlSchema)
        {
            Assert.ArgumentNotNull(textReader, nameof(textReader));
            Assert.ArgumentNotNull(xmlSchema, nameof(xmlSchema));

            var schemas = new XmlSchemaSet();

            schemas.Add(xmlSchema);

            var settings = new XmlReaderSettings
            {
                Schemas         = schemas,
                ValidationType  = ValidationType.Schema,
                ValidationFlags =
                    XmlSchemaValidationFlags.ProcessIdentityConstraints |
                    XmlSchemaValidationFlags.ReportValidationWarnings |
                    XmlSchemaValidationFlags.AllowXmlAttributes
            };

            Exception firstException = null;

            settings.ValidationEventHandler +=
                delegate(object sender, ValidationEventArgs args)
            {
                if (args.Severity == XmlSeverityType.Error)
                {
                    firstException = args.Exception;
                }
                else
                {
                    _msg.WarnFormat(args.Message);
                }
            };

            var serializer = new XmlSerializer(typeof(T));

            T document;

            using (XmlReader reader = XmlReader.Create(textReader, settings))
            {
                document = (T)serializer.Deserialize(reader);
            }

            if (firstException != null)
            {
                throw firstException;
            }

            return(document);
        }
        public static ApplyCutLinesResponse ApplyCutLines(
            [NotNull] ApplyCutLinesRequest request,
            [CanBeNull] ITrackCancel trackCancel)
        {
            IList <CutSubcurve> cutCurves = request.CutLines.Select(FromReshapeLineMsg).ToList();

            FeatureCutter cutter = CreateFeatureCutter(request, out IList <IFeature> targetFeatures);

            cutter.Cut(cutCurves);

            List <IFeature> storedFeatures = new List <IFeature>();

            var response = new ApplyCutLinesResponse();

            if (cutter.ResultGeometriesByFeature.Count > 0)
            {
                cutter.StoreResultFeatures(storedFeatures);

                cutter.LogSuccessfulCut();

                ICollection <KeyValuePair <IFeature, IList <IFeature> > > insertsByOriginal =
                    cutter.InsertedFeaturesByOriginal;

                IList <ResultObjectMsg> ResultObjectMsgs =
                    GetResultFeatureMessages(insertsByOriginal, storedFeatures);

                response.ResultFeatures.AddRange(ResultObjectMsgs);

                // Calculate the new cut lines:
                List <IFeature> newSourceFeatures = new List <IFeature>(cutter.SourceFeatures);

                newSourceFeatures.AddRange(
                    insertsByOriginal.SelectMany(kvp => kvp.Value));

                var newSubcurves =
                    CalculateCutLines(newSourceFeatures, targetFeatures,
                                      request.CalculationRequest, trackCancel,
                                      out ReshapeAlongCurveUsability usability);

                response.CutLinesUsability = (int)usability;

                response.NewCutLines.AddRange(newSubcurves.Select(ToReshapeLineMsg));

                return(response);
            }

            _msg.WarnFormat("The selection was not cut. Please select the lines to cut along");

            return(response);
        }
Example #17
0
        public static double Clamp(this double value, double min, double max, string name = null)
        {
            if (value < min)
            {
                if (!string.IsNullOrEmpty(name))
                {
                    _msg.WarnFormat("{0} was {1}, clamped to {2}", name, value, min);
                }

                return(min);
            }

            if (value > max)
            {
                if (!string.IsNullOrEmpty(name))
                {
                    _msg.WarnFormat("{0} was {1}, clamped to {2}", name, value, max);
                }

                return(max);
            }

            return(value);
        }
Example #18
0
 private void HandleValidationResult(bool valid,
                                     [NotNull] NotificationCollection notifications)
 {
     if (!valid)
     {
         if (WeakValidation)
         {
             _msg.WarnFormat("Invalid linear network features:{0}{1}", Environment.NewLine,
                             NotificationUtils.Concatenate(
                                 notifications, Environment.NewLine));
         }
         else
         {
             throw new RuleViolationException(notifications);
         }
     }
 }
        private static AdvancedReshapeResponse NoReshapeResponse(
            NotificationCollection notifications)
        {
            string notificationMessage =
                notifications.Count > 0
                                        ? $"{Environment.NewLine}{notifications.Concatenate(Environment.NewLine)}"
                                        : string.Empty;

            string noReshapeMessage = $"Unable to perform reshape{notificationMessage}";

            _msg.WarnFormat(noReshapeMessage);

            return(new AdvancedReshapeResponse()
            {
                WarningMessage = noReshapeMessage
            });
        }
Example #20
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);
        }
Example #21
0
        private void Write([NotNull] IFeature feature,
                           AttributeRole role,
                           [CanBeNull] object value)
        {
            Assert.ArgumentNotNull(feature, nameof(feature));

            int    fieldIndex;
            IField field = GetField(feature.Fields, role, out fieldIndex);

            if (value == null || value is DBNull)
            {
                if (field.IsNullable)
                {
                    feature.Value[fieldIndex] = DBNull.Value;
                }

                return;
            }

            if (field.Type != esriFieldType.esriFieldTypeString)
            {
                feature.Value[fieldIndex] = value;
                return;
            }

            var stringValue = value as string;

            Assert.NotNull(stringValue, "Unexpected value for text field: {0}", value);

            bool requiresTrim = stringValue.Length > field.Length;

            if (requiresTrim)
            {
                _msg.WarnFormat("Text is too long for field '{0}', cutting off: {1}",
                                field.Name, stringValue);
            }

            string writeValue = requiresTrim
                                                    ? stringValue.Substring(0, field.Length)
                                                    : stringValue;

            feature.Value[fieldIndex] = writeValue;
        }
        public T Read()
        {
            if (!File.Exists(_filePath))
            {
                return(new T());
            }

            var serializer = new XmlSerializationHelper <T>();

            try
            {
                return(serializer.ReadFromFile(_filePath));
            }
            catch (Exception e)
            {
                _msg.WarnFormat("Error reading options from file: {0}", e.Message);

                return(new T());
            }
        }
Example #23
0
        public static BoundDataGridSelectionState <TRow> GetSelectionState <TRow>(
            [NotNull] DataGridView grid, bool rowsMustAlsoBeVisible = true)
            where TRow : class
        {
            var set = new HashSet <TRow>();

            string firstErrorMessage = null;
            int    errorCount        = 0;

            foreach (DataGridViewRow row in grid.SelectedRows)
            {
                if (rowsMustAlsoBeVisible && !row.Visible)
                {
                    continue;
                }

                TRow   item;
                string message;
                if (!TryGetDataBoundItem(row, out item, out message))
                {
                    errorCount++;
                    if (firstErrorMessage == null)
                    {
                        firstErrorMessage = message;
                    }
                }
                else if (item != null)
                {
                    set.Add(item);
                }
            }

            if (errorCount > 0)
            {
                _msg.WarnFormat("{0} error(s) getting bound items. First message: {1}",
                                errorCount, firstErrorMessage);
            }

            return(new BoundDataGridSelectionState <TRow>(set));
        }
        protected override void CollectCurrentUserSearchPaths(ICollection <string> paths)
        {
            // if environment variable exists, add the path it contains
            string dirPath = Environment.GetEnvironmentVariable(
                EnvironmentVariables.ConfigDirectoryVariableName);

            if (!StringUtils.IsNullOrEmptyOrBlank(dirPath))
            {
                if (FileSystemUtils.HasInvalidPathChars(dirPath))
                {
                    _msg.WarnFormat(
                        "The path specified in variable {0} contains invalid characters: {1}",
                        EnvironmentVariables.ConfigDirectoryVariableName, dirPath);
                }
                else
                {
                    paths.Add(dirPath);
                }
            }

            base.CollectCurrentUserSearchPaths(paths);
        }
Example #25
0
        private void ProcessFinalResult(Task <bool> task, SubResponse subVerification)
        {
            if (task.IsFaulted)
            {
                _msg.WarnFormat("Sub-verification has faulted: {0}", subVerification);

                CancellationTokenSource.Cancel();
                CancellationMessage = task.Exception?.InnerException?.Message;
            }

            if (!string.IsNullOrEmpty(subVerification.CancellationMessage))
            {
                CancellationMessage = subVerification.CancellationMessage;
            }

            QualityVerificationMsg verificationMsg = subVerification.VerificationMsg;

            if (verificationMsg != null)
            {
                AddVerification(verificationMsg, QualityVerification);
            }

            DrainIssues(subVerification);
        }
Example #26
0
        private static IEnumerable <IRow> GetInvolvedRows(
            [NotNull] IErrorObject errorObject,
            [NotNull] IDatasetContext datasetContext,
            [NotNull] IQualityConditionRepository qualityConditionRepository,
            [NotNull] IQualityConditionObjectDatasetResolver datasetResolver)
        {
            IList <InvolvedRow> involved = RowParser.Parse(errorObject.RawInvolvedObjects);

            QualityCondition qualityCondition = GetQualityCondition(errorObject,
                                                                    qualityConditionRepository);

            if (qualityCondition == null)
            {
                yield break;
            }

            foreach (KeyValuePair <string, IList <int> > pair in
                     GetInvolvedObjectIDsByTableName(involved))
            {
                string      tableName = pair.Key;
                IList <int> objectIDs = pair.Value;

                IObjectDataset dataset =
                    datasetResolver.GetDatasetByInvolvedRowTableName(tableName, qualityCondition);
                if (dataset == null)
                {
                    continue;
                }

                ITable table;
                try
                {
                    table = datasetContext.OpenTable(dataset);
                }
                catch (Exception e)
                {
                    _msg.WarnFormat("Error getting involved rows for table {0}: {1}", tableName,
                                    e.Message);
                    continue;
                }

                if (table == null)
                {
                    continue;
                }

                IEnumerable <IRow> rows = TryGetRows(table, objectIDs);

                if (rows == null)
                {
                    // error already logged in TryGetRows()
                    continue;
                }

                foreach (IRow row in rows)
                {
                    if (GdbObjectUtils.IsDeleted(row))
                    {
                        // don't return deleted rows
                        continue;
                    }

                    yield return(row);
                }
            }
        }
        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
            }
        }
Example #28
0
        /// <summary>
        /// Calculates the DifferenceLines and adds the subcurves to the provided result list.
        /// </summary>
        /// <param name="sourceGeometry"></param>
        /// <param name="targetPolyline"></param>
        /// <param name="resultList">All resulting subcurves including the ones that cannot be used to reshape</param>
        /// <param name="trackCancel"></param>
        /// <returns></returns>
        public ReshapeAlongCurveUsability CalculateSubcurves(
            IGeometry sourceGeometry,
            IPolyline targetPolyline,
            IList <CutSubcurve> resultList,
            ITrackCancel trackCancel)
        {
            Assert.ArgumentNotNull(sourceGeometry);
            Assert.ArgumentNotNull(targetPolyline);
            Assert.ArgumentNotNull(resultList);

            Stopwatch watch = _msg.DebugStartTiming();

            IPolyline preprocessedSourcePolyline =
                ChangeGeometryAlongUtils.GetPreprocessedGeometryForExtent(
                    sourceGeometry, ClipExtent);

            if (preprocessedSourcePolyline.IsEmpty)
            {
                _msg.WarnFormat("Source feature is outside the processing extent.");
                return(ReshapeAlongCurveUsability.NoSource);
            }

            IPointCollection    intersectionPoints;
            IGeometryCollection differences = CalculateDifferences(
                preprocessedSourcePolyline,
                targetPolyline,
                trackCancel,
                out intersectionPoints);

            if (trackCancel != null && !trackCancel.Continue())
            {
                return(ReshapeAlongCurveUsability.Undefined);
            }

            if (differences == null)
            {
                return(ReshapeAlongCurveUsability.AlreadyCongruent);
            }

            SubcurveFilter?.PrepareForSource(sourceGeometry);

            bool canReshape = CalculateReshapeSubcurves(
                preprocessedSourcePolyline, targetPolyline, differences,
                intersectionPoints, resultList, trackCancel);

            JoinNonForkingSubcurves(resultList);

            Marshal.ReleaseComObject(preprocessedSourcePolyline);
            Marshal.ReleaseComObject(differences);

            _msg.DebugStopTiming(
                watch, "RecalculateReshapableSubcurves: Total number of curves: {0}.",
                resultList.Count);

            if (canReshape)
            {
                return(ReshapeAlongCurveUsability.CanReshape);
            }

            return(resultList.Count == 0
                                       ? ReshapeAlongCurveUsability.NoReshapeCurves
                                       : ReshapeAlongCurveUsability.InsufficientOrAmbiguousReshapeCurves);
        }
Example #29
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);
                    }
                }
            }
        }
Example #30
0
        public static void Update(
            [CanBeNull] string whereClause,
            [NotNull] IList <IObjectClass> targetExceptionClasses,
            [NotNull] IList <IObjectClass> updateExceptionClasses,
            [NotNull] string updateOriginValue,
            DateTime updateDate,
            bool requireOriginalVersionExists = true)
        {
            IIssueTableFields updateFields = GetUpdateFields(updateExceptionClasses);
            IIssueTableFields targetFields = GetTargetFields(targetExceptionClasses);

            var editableAttributes = new[]
            {
                IssueAttribute.ExceptionStatus,
                IssueAttribute.ExceptionCategory,
                IssueAttribute.ExceptionNotes,
                IssueAttribute.ExceptionOrigin,
                IssueAttribute.ExceptionDefinitionDate,
                IssueAttribute.ExceptionLastRevisionDate,
                IssueAttribute.ExceptionRetirementDate,
                IssueAttribute.IssueAssignment
            };

            using (_msg.IncrementIndentation(
                       "Updating exceptions based on exported exception datasets..."))
            {
                foreach (ITable updateTable in updateExceptionClasses.Cast <ITable>())
                {
                    using (_msg.IncrementIndentation("from {0}...",
                                                     DatasetUtils.GetName(updateTable)))
                    {
                        ITable targetTable = GetTargetTable(updateTable, targetExceptionClasses);
                        if (targetTable == null)
                        {
                            _msg.Warn(
                                "No matching table in target workspace, ignoring import table");
                            continue;
                        }

                        var targetExceptionFactory = new ManagedExceptionVersionFactory(
                            targetTable, targetFields, editableAttributes);
                        var updateExceptionFactory = new ManagedExceptionVersionFactory(
                            updateTable, updateFields, editableAttributes);

                        ExceptionUpdateDetector updateDetector = GetUpdateDetector(
                            targetTable,
                            targetExceptionFactory,
                            editableAttributes);

                        var replacedOids = new HashSet <int>();

                        var updatedRowsCount       = 0;
                        var rowsWithConflictsCount = 0;

                        using (var exceptionWriter = new ExceptionWriter(updateTable, updateFields,
                                                                         targetTable, targetFields))
                        {
                            foreach (IRow updateRow in GdbQueryUtils.GetRows(
                                         updateTable, GetQueryFilter(whereClause), recycle: true))
                            {
                                ManagedExceptionVersion updateExceptionVersion =
                                    updateExceptionFactory.CreateExceptionVersion(updateRow);

                                ManagedExceptionVersion            mergedException;
                                ManagedExceptionVersion            replacedExceptionVersion;
                                IList <ExceptionAttributeConflict> conflicts;

                                if (updateDetector.HasChange(updateExceptionVersion,
                                                             out mergedException,
                                                             out replacedExceptionVersion,
                                                             out conflicts))
                                {
                                    if (replacedExceptionVersion == null)
                                    {
                                        string message = string.Format(
                                            "Exception version {0} not found in lineage {1} (target table: {2})",
                                            ExceptionObjectUtils.FormatGuid(
                                                updateExceptionVersion.VersionUuid),
                                            ExceptionObjectUtils.FormatGuid(
                                                updateExceptionVersion.LineageUuid),
                                            DatasetUtils.GetName(targetTable));

                                        if (requireOriginalVersionExists)
                                        {
                                            throw new InvalidDataException(message);
                                        }

                                        _msg.WarnFormat(
                                            "{0}. Creating new version with attributes from update row.",
                                            message);
                                    }

                                    updatedRowsCount++;

                                    string versionImportStatus;
                                    if (conflicts.Count == 0)
                                    {
                                        versionImportStatus = null;
                                    }
                                    else
                                    {
                                        versionImportStatus =
                                            FormatConflicts(conflicts, targetFields);

                                        rowsWithConflictsCount++;

                                        LogConflicts(conflicts, targetFields);
                                    }

                                    exceptionWriter.Write(updateRow, updateDate, mergedException,
                                                          FormatOriginValue(updateOriginValue,
                                                                            replacedExceptionVersion),
                                                          updateOriginValue, versionImportStatus);

                                    if (replacedExceptionVersion != null)
                                    {
                                        replacedOids.Add(replacedExceptionVersion.ObjectID);
                                    }
                                }
                            }
                        }

                        _msg.InfoFormat("{0:N0} exception(s) updated", updatedRowsCount);
                        if (rowsWithConflictsCount > 0)
                        {
                            _msg.WarnFormat("{0:N0} exception(s) with conflicts",
                                            rowsWithConflictsCount);
                        }

                        if (replacedOids.Count > 0)
                        {
                            int fixedStatusCount;
                            int updateCount = ProcessReplacedExceptions(targetTable, targetFields,
                                                                        updateDate, replacedOids,
                                                                        out fixedStatusCount);

                            _msg.DebugFormat("{0:N0} replaced exception version(s) updated",
                                             updateCount);
                            if (fixedStatusCount > 0)
                            {
                                _msg.WarnFormat(
                                    "Status value of {0:N0} old exception version(s) fixed",
                                    fixedStatusCount);
                            }
                        }
                    }
                }
            }
        }