/// <summary>
        /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed.
        /// </summary>
        /// <param name="paramValues"></param>
        /// <param name="trackCancel"></param>
        /// <param name="envMgr"></param>
        /// <param name="msgs"></param>
        public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs)
        {
            // Do some common error-checking
            base.Execute(paramValues, trackCancel, envMgr, msgs);

            // Close the requested job
            try
            {
                IJTXJobManager     jobManager = this.WmxDatabase.JobManager;
                IJTXJob3           job        = jobManager.GetJob(m_jobToClose) as IJTXJob3;
                IJTXConfiguration3 configMgr  = this.WmxDatabase.ConfigurationManager as IJTXConfiguration3;

                if (job.Stage != jtxJobStage.jtxJobStageClosed && !job.CanClose())
                {
                    throw new WmauException(WmauErrorCodes.C_CANNOT_CLOSE_JOB_ERROR);
                }

                msgs.AddMessage("Closing job " + m_jobToClose + " (" + job.Name + ")");
                job.Close();

                // Once the job is closed, do the other things that still need to be handled
                // separately (status updates, notifications, ...)
                Common.WmauHelperFunctions.UpdateJobStatus(this.WmxDatabase, job);
                job.Store();

                job.LogJobAction(
                    configMgr.GetActivityType(ESRI.ArcGIS.JTX.Utilities.Constants.ACTTYPE_CLOSE_JOB),
                    null,
                    string.Empty);
                Common.WmauHelperFunctions.SendNotification(
                    ESRI.ArcGIS.JTX.Utilities.Constants.NOTIF_JOB_CLOSED,
                    this.WmxDatabase,
                    job);

                // Set the output parameter
                WmauParameterMap  paramMap     = new WmauParameterMap(paramValues);
                IGPParameterEdit3 outParamEdit = paramMap.GetParamEdit(C_PARAM_JOB_CLOSED);
                IGPLong           outValue     = new GPLongClass();
                outValue.Value     = m_jobToClose;
                outParamEdit.Value = outValue as IGPValue;

                msgs.AddMessage(Properties.Resources.MSG_DONE);
            }
            catch (WmauException wmEx)
            {
                try
                {
                    msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message);
                }
                catch
                {
                    // Catch anything else that possibly happens
                }
            }
            catch (Exception ex)
            {
                WmauError error = new WmauError(WmauErrorCodes.C_UNSPECIFIED_ERROR);
                msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message);
            }
        }
Example #2
0
        // The execute part of the algorithm
        public void Execute(ISchematicLayer schematicLayer, ITrackCancel CancelTracker)
        {
            if (schematicLayer == null)
            {
                return;
            }

            // Before Execute part
            ISchematicInMemoryDiagram inMemoryDiagram;

            inMemoryDiagram = schematicLayer.SchematicInMemoryDiagram;

            // Core algorithm
            InternalExecute(schematicLayer, inMemoryDiagram, CancelTracker);

            // Release the COM objects
            if (inMemoryDiagram != null)
            {
                while (System.Runtime.InteropServices.Marshal.ReleaseComObject(inMemoryDiagram) > 0)
                {
                }
            }

            while (System.Runtime.InteropServices.Marshal.ReleaseComObject(schematicLayer) > 0)
            {
            }
        }
        private static IList <CutSubcurve> CalculateReshapeLines(
            [NotNull] IList <IFeature> sourceFeatures,
            [NotNull] IList <IFeature> targetFeatures,
            [NotNull] CalculateReshapeLinesRequest request,
            [CanBeNull] ITrackCancel trackCancel,
            out ReshapeAlongCurveUsability usability)
        {
            Stopwatch watch = Stopwatch.StartNew();

            IEnvelope visibleExtent;
            ReshapeCurveFilterOptions filterOptions =
                GetLineFilterOptions(request.FilterOptions, out visibleExtent);

            TargetBufferOptions targetBufferOptions =
                GetTargetBufferOptions(request.TargetBufferOptions);

            IList <CutSubcurve> resultLines = new List <CutSubcurve>();

            usability = ChangeGeometryAlongUtils.CalculateReshapeCurves(
                sourceFeatures, targetFeatures, visibleExtent,
                request.Tolerance, targetBufferOptions, filterOptions,
                resultLines, trackCancel);

            _msg.DebugStopTiming(watch, "Calculated {0} reshape lines", resultLines.Count);

            return(resultLines);
        }
Example #4
0
        private static BackgroundVerificationService CreateVerificationService(
            IBackgroundVerificationInputs backgroundVerificationInputs,
            ConcurrentBag <IssueMsg> issueCollection,
            Action <VerificationResponse> writeAction, ITrackCancel trackCancel)
        {
            var qaService = new BackgroundVerificationService(
                backgroundVerificationInputs.DomainTransactions,
                backgroundVerificationInputs.DatasetLookup)
            {
                CustomErrorFilter = backgroundVerificationInputs.CustomErrorFilter
            };

            var currentProgress = new VerificationProgressMsg();

            qaService.IssueFound +=
                (sender, args) =>
                issueCollection.Add(CreateIssueProto(args, backgroundVerificationInputs));

            qaService.Progress += (sender, args) =>
                                  SendProgress(
                sender, args, issueCollection,
                currentProgress, writeAction, trackCancel);

            return(qaService);
        }
Example #5
0
        public ProgressDialog(bool a_EnableCancel, int a_MinValue, int a_MaxValue, string a_Title,
                              string a_Description)
        {
            var a_ProgressDialogFactory = new ProgressDialogFactoryClass();

            m_TrackCancel                  = new CancelTracker();
            m_StepProgressor               = a_ProgressDialogFactory.Create(m_TrackCancel, 0);
            m_ProgressDialog               = (IProgressDialog2)m_StepProgressor;
            m_TrackCancel.CancelOnClick    = a_EnableCancel;
            m_TrackCancel.CancelOnKeyPress = a_EnableCancel;

            m_StepProgressor.MinRange  = a_MinValue;
            m_StepProgressor.MaxRange  = a_MaxValue;
            m_StepProgressor.StepValue = 1;
            m_StepProgressor.Position  = m_StepProgressor.MinRange;
            if (a_MinValue == a_MaxValue)
            {
                m_StepProgressor.Hide();
            }

            m_ProgressDialog.CancelEnabled = a_EnableCancel;
            m_ProgressDialog.Title         = a_Title;
            m_ProgressDialog.Description   = a_Description;
            m_ProgressDialog.Animation     = esriProgressAnimationTypes.esriProgressSpiral;
        }
Example #6
0
        /// <summary>
        ///     Executes the geoprocessing function using the given array of parameter values.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="trackCancel">The track cancel.</param>
        /// <param name="environmentManager">Provides access to all the current environments and settings of the current client.</param>
        /// <param name="messages">The messages that are reported to the user.</param>
        /// <param name="utilities">
        ///     The utilities object that provides access to the properties and methods of a geoprocessing
        ///     objects.
        /// </param>
        protected override void Execute(Dictionary <string, IGPValue> parameters, ITrackCancel trackCancel, IGPEnvironmentManager environmentManager, IGPMessages messages, IGPUtilities2 utilities)
        {
            IGPValue      field      = parameters["in_field"];
            IObjectClass  table      = utilities.OpenTable(parameters["in_table"]);
            IGPMultiValue modelNames = (IGPMultiValue)parameters["in_field_model_names"];

            if (!field.IsEmpty() && modelNames.Count > 0)
            {
                var fieldName = field.GetAsText();
                int index     = table.FindField(fieldName);

                foreach (var modelName in modelNames.AsEnumerable().Select(o => o.GetAsText()))
                {
                    messages.Add(esriGPMessageType.esriGPMessageTypeInformative, "Removing the {0} field model name from the {1} field.", modelName, fieldName);

                    ModelNameManager.Instance.RemoveFieldModelName(table, table.Fields.Field[index], modelName);
                }

                // Success.
                parameters["out_results"].SetAsText("true");
            }
            else
            {
                // Failure.
                parameters["out_results"].SetAsText("false");
            }
        }
Example #7
0
        /// <summary>
        ///     Executes the geoprocessing function using the given array of parameter values.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="trackCancel">The track cancel.</param>
        /// <param name="environmentManager">Provides access to all the current environments and settings of the current client.</param>
        /// <param name="messages">The messages that are reported to the user.</param>
        /// <param name="utilities">
        ///     The utilities object that provides access to the properties and methods of a geoprocessing
        ///     objects.
        /// </param>
        protected override void Execute(Dictionary <string, IGPValue> parameters, ITrackCancel trackCancel, IGPEnvironmentManager environmentManager, IGPMessages messages, IGPUtilities2 utilities)
        {
            IGPMultiValue tables     = (IGPMultiValue)parameters["in_tables"];
            IGPMultiValue modelNames = (IGPMultiValue)parameters["in_class_model_names"];
            int           addedCount = 0;

            if (tables.Count > 0 && modelNames.Count > 0)
            {
                foreach (var table in tables.AsEnumerable())
                {
                    IObjectClass dataElement = utilities.OpenTable(table);

                    foreach (var modelName in modelNames.AsEnumerable().Select(o => o.GetAsText()))
                    {
                        messages.Add(esriGPMessageType.esriGPMessageTypeInformative, "Adding the {0} class model name to the {1} table.", modelName, dataElement.AliasName);

                        ModelNameManager.Instance.AddClassModelName(dataElement, modelName);
                        addedCount++;
                    }
                }
            }

            if (addedCount == tables.Count)
            {
                // Success
                parameters["out_results"].SetAsText("true");
            }
            else
            {
                // Failure.
                parameters["out_results"].SetAsText("false");
            }
        }
        /// <summary>
        ///     Adds the fields POINT_X and POINT_Y to the point input features and calculates their values. It also appends the
        ///     POINT_Z and POINT_M fields if the input features are Z- and M-enabled.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="trackCancel">The track cancel.</param>
        /// <param name="eventHandler">The events.</param>
        public static void AddXY(this IFeatureClass source, ITrackCancel trackCancel, IGeoProcessorEvents eventHandler)
        {
            AddXY gp = new AddXY();

            gp.in_features = source;
            gp.Run(trackCancel, eventHandler);
        }
        /// <summary>
        /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed.
        /// </summary>
        /// <param name="paramValues"></param>
        /// <param name="trackCancel"></param>
        /// <param name="envMgr"></param>
        /// <param name="msgs"></param>
        public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs)
        {
            // Do some common error-checking
            base.Execute(paramValues, trackCancel, envMgr, msgs);

            try
            {
                // Update the internal parameters used by this GP tool
                string styleFileName = this.DetermineStyleFileName(this.m_xmlFilePath);

                // Retrieve the TA workbook
                IJTXConfiguration3 defaultDbReadonly      = WmxDatabase.ConfigurationManager as IJTXConfiguration3;
                IJTXTaskAssistantWorkflowRecord tamRecord = defaultDbReadonly.GetTaskAssistantWorkflowRecord(this.m_sourceName);

                // Delete any existing workflow or style files that we're going to replace
                this.DeleteFile(this.m_xmlFilePath);
                this.DeleteFile(styleFileName);

                // Save the TAM workbook data out to file
                this.SaveStringToXmlFile(tamRecord.WorkflowXML, this.m_xmlFilePath);
                this.SaveStringToXmlFile(tamRecord.StyleXML, styleFileName);

                msgs.AddMessage(Properties.Resources.MSG_DONE);
            }
            catch (System.IO.IOException ioEx)
            {
                try
                {
                    WmauError error = new WmauError(WmauErrorCodes.C_FILE_ACCESS_ERROR);
                    msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ioEx.Message);
                }
                catch
                {
                    // Catch anything else that possibly happens
                }
            }
            catch (WmauException wmEx)
            {
                try
                {
                    msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message);
                }
                catch
                {
                    // Catch anything else that possibly happens
                }
            }
            catch (Exception ex)
            {
                try
                {
                    WmauError error = new WmauError(WmauErrorCodes.C_TAM_DOWNLOAD_ERROR);
                    msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message);
                }
                catch
                {
                    // Catch anything else that possibly happens
                }
            }
        }
Example #10
0
        /// <summary>
        /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed.
        /// </summary>
        /// <param name="paramValues"></param>
        /// <param name="trackCancel"></param>
        /// <param name="envMgr"></param>
        /// <param name="msgs"></param>
        public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs)
        {
            // Do some common error-checking
            base.Execute(paramValues, trackCancel, envMgr, msgs);

            try
            {
                // Ensure that the current user has admin access to the current Workflow Manager DB
                if (!CurrentUserIsWmxAdministrator())
                {
                    throw new WmauException(WmauErrorCodes.C_USER_NOT_ADMIN_ERROR);
                }

                // Retrieve the parameter in which the list of MXDs will be stored
                WmauParameterMap  paramMap  = new WmauParameterMap(paramValues);
                IGPParameter3     param     = paramMap.GetParam(C_PARAM_MAP_DOCUMENT_LIST);
                IGPParameterEdit3 paramEdit = paramMap.GetParamEdit(C_PARAM_MAP_DOCUMENT_LIST);

                // Set up the multi-value objects
                IGPMultiValue mvValue = new GPMultiValueClass();
                mvValue.MemberDataType = param.DataType;

                // Get the list of MXD names and add them all to the multivalue
                SortedList <string, string> mapDocuments = this.ListMapDocumentsInDatabase();
                foreach (string mapDocName in mapDocuments.Keys)
                {
                    IGPString strVal = new GPStringClass();
                    strVal.Value = mapDocName;
                    mvValue.AddValue(strVal as IGPValue);
                    msgs.AddMessage("Map Document: " + mapDocName);
                }

                paramEdit.Value = (IGPValue)mvValue;

                msgs.AddMessage(Properties.Resources.MSG_DONE);
            }
            catch (WmauException wmEx)
            {
                try
                {
                    msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message);
                }
                catch
                {
                    // Catch anything else that possibly happens
                }
            }
            catch (Exception ex)
            {
                try
                {
                    WmauError error = new WmauError(WmauErrorCodes.C_UNSPECIFIED_ERROR);
                    msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message);
                }
                catch
                {
                    // Catch anything else that possibly happens
                }
            }
        }
Example #11
0
        public QualityVerification Verify(
            [NotNull] IBackgroundVerificationInputs backgroundVerificationInputs,
            [CanBeNull] ITrackCancel trackCancel)
        {
            QualitySpecification qualitySpecification = null;

            _backgroundVerificationInputs = backgroundVerificationInputs;

            _domainTransactions.UseTransaction(
                delegate
            {
                backgroundVerificationInputs.LoadInputsTx(
                    _domainTransactions, trackCancel, OnProgress);

                qualitySpecification =
                    PrepareQualitySpecificationTx(backgroundVerificationInputs);
            });

            IVerificationContext verificationContext =
                Assert.NotNull(backgroundVerificationInputs.VerificationContext);

            VerificationServiceParameters parameters =
                Assert.NotNull(backgroundVerificationInputs.VerificationParameters);

            QualityVerification verification = Verify(
                verificationContext, qualitySpecification, parameters,
                backgroundVerificationInputs.VerifiedObjects);

            if (parameters.SaveVerificationStatistics && !verification.Cancelled)
            {
                backgroundVerificationInputs.SaveVerification(verification, _domainTransactions);
            }

            return(verification);
        }
Example #12
0
        /// <summary>
        ///     Executes the geoprocessing function using the given array of parameter values.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="trackCancel">The track cancel.</param>
        /// <param name="environmentManager">Provides access to all the current environments and settings of the current client.</param>
        /// <param name="messages">The messages that are reported to the user.</param>
        /// <param name="utilities">
        ///     The utilities object that provides access to the properties and methods of a geoprocessing
        ///     objects.
        /// </param>
        protected override void Execute(Dictionary <string, IGPValue> parameters, ITrackCancel trackCancel, IGPEnvironmentManager environmentManager, IGPMessages messages, IGPUtilities2 utilities)
        {
            IGPValue           value    = parameters["in_table"];
            IRelationshipClass relClass = utilities.OpenRelationshipClass(value);

            if (relClass != null)
            {
                IMMConfigTopLevel configTopLevel = ConfigTopLevel.Instance;
                configTopLevel.Workspace = utilities.GetWorkspace(value);

                IGPMultiValue onCreate = (IGPMultiValue)parameters["in_create"];
                IGPMultiValue onDelete = (IGPMultiValue)parameters["in_delete"];

                var uids = new Dictionary <mmEditEvent, IEnumerable <IUID> >();
                uids.Add(mmEditEvent.mmEventRelationshipCreated, onCreate.AsEnumerable().Cast <IGPAutoValue>().Select(o => o.UID));
                uids.Add(mmEditEvent.mmEventRelationshipDeleted, onDelete.AsEnumerable().Cast <IGPAutoValue>().Select(o => o.UID));

                // Update the list to have these UIDs.
                ID8List list = (ID8List)configTopLevel.GetRelationshipClass(relClass);
                base.Add(uids, list, messages);

                // Commit the changes to the database.
                configTopLevel.SaveRelationshipClasstoDB(relClass);

                // Success.
                parameters["out_results"].SetAsText("true");
            }
            else
            {
                // Failure.
                parameters["out_results"].SetAsText("false");
            }
        }
Example #13
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);
        }
        public NetworkDataset(string configXML, IDataset osmDataset, string ndsName, IGPMessages messages, ITrackCancel trackCancel)
        {
            _xml = new NetworkDatasetXML(configXML, RESMGR);

            _osmDataset = osmDataset;
            _ndsName = ndsName;
            _messages = messages;
            _trackCancel = trackCancel;

            IDataElement deOSM = GPUtil.MakeDataElementFromNameObject(_osmDataset.FullName);
            _dsPath = deOSM.CatalogPath;

            _osmLineName = _osmDataset.Name + "_osm_ln";
            _osmLinePath = _dsPath + "\\" + _osmLineName;
            _osmPointName = _osmDataset.Name + "_osm_pt";
            _osmPointPath = _dsPath + "\\" + _osmPointName;

            // Get the extent from the point feature class
            // NOTE: the feature dataset is not used for this because exceptions occur (SDE only)
            //       if a feature class was recently deleted from the feature dataset.
            IFeatureClass fcPoint = ((IFeatureWorkspace)_osmDataset.Workspace).OpenFeatureClass(_osmPointName);
            IGeoDataset gds = (IGeoDataset)fcPoint;
            _extent = gds.Extent;
            _spatialReference = gds.SpatialReference;
        }
Example #15
0
 /// <summary>
 /// </summary>
 /// <param name="Display"></param>
 /// <param name="trackCancel"></param>
 public void Draw(IDisplay Display, ITrackCancel trackCancel)
 {
     Display.SetSymbol(null);
     Display.SetSymbol(this.m_pFractionTextSymbol as ISymbol);
     Display.DrawText(this.m_pGeometry, "");
     Display.SetSymbol(null);
 }
Example #16
0
        public NetworkDataset(string configXML, IDataset osmDataset, string ndsName, IGPMessages messages, ITrackCancel trackCancel)
        {
            _xml = new NetworkDatasetXML(configXML, RESMGR);

            _osmDataset  = osmDataset;
            _ndsName     = ndsName;
            _messages    = messages;
            _trackCancel = trackCancel;

            IDataElement deOSM = GPUtil.MakeDataElementFromNameObject(_osmDataset.FullName);

            _dsPath = deOSM.CatalogPath;

            _osmLineName  = _osmDataset.Name + "_osm_ln";
            _osmLinePath  = _dsPath + "\\" + _osmLineName;
            _osmPointName = _osmDataset.Name + "_osm_pt";
            _osmPointPath = _dsPath + "\\" + _osmPointName;

            // Get the extent from the point feature class
            // NOTE: the feature dataset is not used for this because exceptions occur (SDE only)
            //       if a feature class was recently deleted from the feature dataset.
            IFeatureClass fcPoint = ((IFeatureWorkspace)_osmDataset.Workspace).OpenFeatureClass(_osmPointName);
            IGeoDataset   gds     = (IGeoDataset)fcPoint;

            _extent           = gds.Extent;
            _spatialReference = gds.SpatialReference;
        }
Example #17
0
        private static bool RunTool(IGPProcess process, ITrackCancel TC, out IEnumerable <string> messages)
        {
            if (gp == null)
            {
                gp = new Geoprocessor
                {
                    AddOutputsToMap = false
                };

                gp.SetEnvironmentValue(environmentName, temporaryWorkspace);
            }

            gp.OverwriteOutput = true; // Set the overwrite output option to true
            bool result = true;

            try
            {
                IGeoProcessorResult pResult = (IGeoProcessorResult)gp.Execute(process, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                result = false;
            }

            messages = ReturnMessages(gp).ToArray();
            return(result);
        }
Example #18
0
        /// <summary>
        /// </summary>
        /// <param name="Display"></param>
        /// <param name="trackCancel"></param>
        public void Draw(IDisplay Display, ITrackCancel trackCancel)
        {
            int    num;
            int    num1;
            int    num2;
            int    num3;
            IPoint pointClass = new Point();

            pointClass.PutCoords(this.m_pGeometry.XMin, this.m_pGeometry.YMin);
            Display.DisplayTransformation.FromMapPoint(pointClass, out num, out num1);
            pointClass.PutCoords(this.m_pGeometry.XMax, this.m_pGeometry.YMax);
            Display.DisplayTransformation.FromMapPoint(pointClass, out num2, out num3);
            double mRadio  = (double)(num2 - num);
            double mRadio1 = (double)(num1 - num3);

            if (mRadio < mRadio1)
            {
                mRadio1 = mRadio / this.m_radio;
            }
            else if (mRadio > mRadio1)
            {
                mRadio = mRadio1 * this.m_radio;
            }
            this.m_oleclient.Draw(Display.hDC, (double)num, (double)num3, (double)num + mRadio,
                                  (double)num3 + mRadio1);
        }
Example #19
0
        public void Cut([NotNull] IList <CutSubcurve> cutSubcurves,
                        [CanBeNull] ITrackCancel trackCancel = null)
        {
            Assert.ArgumentNotNull(cutSubcurves, nameof(cutSubcurves));
            Assert.ArgumentCondition(_featuresToCut.Count > 0, "No polygon to cut");

            if (cutSubcurves.Count == 0)
            {
                return;
            }

            // simplify the curves to connect several yellow cut subcurves into a proper path
            IGeometry geometryPrototype = _featuresToCut[0].Shape;

            IGeometryCollection simplifiedCurves =
                ReshapeUtils.GetSimplifiedReshapeCurves(
                    cutSubcurves, geometryPrototype.SpatialReference);

            if (simplifiedCurves.GeometryCount == 0)
            {
                return;
            }

            Cut((IPolyline)simplifiedCurves, trackCancel);

            if (TargetFeatures != null && ResultGeometriesByFeature.Count > 0)
            {
                InsertIntersectingVerticesInTargets(TargetFeatures,
                                                    (IGeometry)simplifiedCurves);
            }
        }
Example #20
0
        /// <summary>
        /// Calculates the result geometries and adds them to the relevant dictionaries.
        /// </summary>
        /// <param name="fromFeatures"></param>
        /// <param name="overlap"></param>
        /// <param name="targetFeaturesForVertexInsertion"></param>
        /// <param name="trackCancel"></param>
        public void CalculateResults(
            [NotNull] IEnumerable <IFeature> fromFeatures,
            [NotNull] IPolycurve overlap,
            [CanBeNull] IEnumerable <IFeature> targetFeaturesForVertexInsertion = null,
            [CanBeNull] ITrackCancel trackCancel = null)
        {
            Assert.ArgumentNotNull(fromFeatures, nameof(fromFeatures));
            Assert.ArgumentNotNull(overlap, nameof(overlap));

            GeometryUtils.AllowIndexing(overlap);

            foreach (IFeature feature in fromFeatures)
            {
                if (trackCancel != null && !trackCancel.Continue())
                {
                    return;
                }

                ProcessFeature(feature, overlap);
            }

            if (targetFeaturesForVertexInsertion != null)
            {
                InsertIntersectingVerticesInTargets(targetFeaturesForVertexInsertion,
                                                    overlap);
            }
        }
Example #21
0
        private bool CalculateReshapeSubcurves(
            [NotNull] IPolyline preprocessedSourcePolyline,
            [NotNull] IPolyline targetPolyline,
            [NotNull] IGeometryCollection differences,
            [NotNull] IPointCollection intersectionPoints,
            [NotNull] ICollection <CutSubcurve> resultList,
            [CanBeNull] ITrackCancel trackCancel)
        {
            var canReshape = false;

            foreach (
                CutSubcurve subcurve in
                CalculateReshapeSubcurves(preprocessedSourcePolyline, differences,
                                          intersectionPoints, targetPolyline))
            {
                if (trackCancel != null && !trackCancel.Continue())
                {
                    return(canReshape);
                }

                if (subcurve.CanReshape)
                {
                    canReshape = true;
                }

                subcurve.IsFiltered = SubcurveFilter != null &&
                                      SubcurveFilter.IsExcluded(subcurve);

                resultList.Add(subcurve);
            }

            return(canReshape);
        }
Example #22
0
        public void Cut3D([NotNull] IMultiPatch cutSurfaces,
                          [CanBeNull] ITrackCancel trackCancel = null)
        {
            foreach (IFeature feature in GetFeaturesToCut(cutSurfaces))
            {
                if (trackCancel != null && !trackCancel.Continue())
                {
                    return;
                }

                try
                {
                    CutFeature3D(feature, cutSurfaces);
                }
                catch (Exception e)
                {
                    if (!ContinueOnFailure)
                    {
                        throw;
                    }

                    FailedCutOperations.Add(
                        new KeyValuePair <int, string>(feature.OID, e.Message));
                }
            }
        }
        public static ShapeMsg GetOpenJawReshapeReplaceEndPoint(
            [NotNull] OpenJawReshapeLineReplacementRequest request,
            [CanBeNull] ITrackCancel trackCancel = null)
        {
            var polylineToReshape =
                (IPolyline)ProtobufGeometryUtils.FromShapeMsg(request.Feature.Shape);
            var reshapeLine =
                (IPolyline)ProtobufGeometryUtils.FromShapeMsg(request.ReshapePath);

            IPoint endPoint = null;

            if (polylineToReshape != null && reshapeLine != null)
            {
                endPoint = ReshapeUtils.GetOpenJawReshapeLineReplaceEndPoint(
                    polylineToReshape, reshapeLine, request.UseNonDefaultReshapeSide);
            }

            if (endPoint == null)
            {
                return(new ShapeMsg());
            }

            ShapeMsg result = ProtobufGeometryUtils.ToShapeMsg(endPoint);

            return(result);
        }
        public static void WriteBuildErrorsToTurnFC(string outputFileGdbPath, string fdsName, string turnFCName,
                                                    IGPMessages messages, ITrackCancel trackcancel)
        {
            messages.AddMessage("Writing build errors to the turn feature class...");

            // Create a new field on the turn feature class for the build errors

            Geoprocessor gp = new Geoprocessor();

            gp.AddOutputsToMap = false;
            AddField addFieldTool = new AddField();

            addFieldTool.in_table   = outputFileGdbPath + "\\" + fdsName + "\\" + turnFCName;
            addFieldTool.field_name = "BuildError";
            addFieldTool.field_type = "SHORT";
            gp.Execute(addFieldTool, trackcancel);

            // Open the turn feature class in the file geodatabase and find the BuildError field on it

            Type          factoryType     = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
            var           wsf             = Activator.CreateInstance(factoryType) as IWorkspaceFactory;
            var           fws             = wsf.OpenFromFile(outputFileGdbPath, 0) as IFeatureWorkspace;
            IFeatureClass turnFC          = fws.OpenFeatureClass(turnFCName);
            int           buildErrorField = turnFC.FindField("BuildError");

            // Open the BuildErrors.txt file generated from building the network dataset

            string   s, leftTrimmedString, oidString;
            int      leftTrimAmt = 24 + turnFCName.Length;
            IFeature feat        = null;

            string[] buildErrorsFiles = System.IO.Directory.GetFiles(Environment.GetEnvironmentVariable("TEMP"), "BuildErrors.txt", System.IO.SearchOption.AllDirectories);
            string   buildErrorsFile  = buildErrorsFiles[0];

            System.IO.StreamReader f = new System.IO.StreamReader(buildErrorsFile);

            // Loop through the BuildErrors.txt file and write the value 1 for each entry found.

            while ((s = f.ReadLine()) != null)
            {
                // ignore blank lines
                if (s.Length == 0)
                {
                    continue;
                }

                // ignore build errors not dealing with the turn source
                if (s.Remove(leftTrimAmt) != ("SourceName: " + turnFCName + ", ObjectID: "))
                {
                    continue;
                }

                leftTrimmedString = s.Substring(leftTrimAmt);
                oidString         = leftTrimmedString.Remove(leftTrimmedString.IndexOf(", "));
                feat = turnFC.GetFeature(Convert.ToInt32(oidString, System.Globalization.CultureInfo.InvariantCulture));
                feat.set_Value(buildErrorField, 1);
                feat.Store();
            }
            f.Close();
        }
Example #25
0
        public override void Draw(esriDrawPhase drawPhase, IDisplay display, ITrackCancel trackCancel)
        {
            if (drawPhase == esriDrawPhase.esriDPGeography)
            {
                if (Visible)
                {
                    var mxdoc         = (IMxDocument)_application.Document;
                    var map           = mxdoc.FocusMap;
                    var activeView    = map as IActiveView;
                    var tileInfosMeta = TileCalculator.GetTiles(activeView, _tileSource);
                    tileInfos = tileInfosMeta.Tiles;
                    tiles     = new Dictionary <TileInfo, List <VectorTileLayer> >();

                    Logger.Debug("Mapbox vector tile, number of tiles: " + tileInfos.Count);
                    Logger.Debug("Mapbox vector tile, start downloading...");

                    var downloadFinished = new ManualResetEvent(false);
                    var t = new Thread(DownloadTiles);
                    t.Start(downloadFinished);
                    downloadFinished.WaitOne();
                    Logger.Debug("Mapbox vector tile, downloading finished.");
                    Logger.Debug("Mapbox vector tile, start drawing ...");

                    foreach (var tile in tiles)
                    {
                        DrawVectorTile(display, tile);
                    }
                    Logger.Debug("Mapbox vector tile, drawing finished.");
                }
            }
        }
Example #26
0
        private bool RunProcess(IGPProcess inProcess, ITrackCancel inCancel)
        {
            bool wasSuccessful = false;
            //try
            //{
            string toolbox = inProcess.ToolboxName;

            mLog.Debug("inside run process");
            mLog.Debug("the process I want to run is " + inProcess.ToolName);
            mLog.Debug("the tool box is " + toolbox);
            myProcessor.OverwriteOutput = true;
            myProcessor.Execute(inProcess, null);
            wasSuccessful = ReturnMessages(myProcessor);
#if DEBUG
            //if (!wasSuccessful)
            //  System.Windows.Forms.MessageBox.Show("Data error");
#endif

            //}
            //catch (Exception ex)
            //{
            //wasSuccessful = false;
            //Console.WriteLine(ex.Message);
            //ReturnMessages(myProcessor);
            //}
            return(wasSuccessful);
        }
Example #27
0
        public bool RunTool(string toolName, IVariantArray parameters, ITrackCancel TC, bool showResultDialog)
        {
            GeoProcessor        gp     = new GeoProcessor();
            IGeoProcessorResult result = null;

            // Execute the tool
            try
            {
                result = (IGeoProcessorResult)gp.Execute(toolName, parameters, TC);
                string re = result.GetOutput(0).GetAsText();
                if (showResultDialog)
                {
                    ReturnMessages(result, "");
                }
                if (result.MaxSeverity == 2) //error
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
            catch (COMException err)
            {
                MessageBox.Show(err.Message + " in RunTool");
                ReturnMessages(result, "");
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message + " in RunTool");
                ReturnMessages(result, "");
            }
            return(false);
        }
Example #28
0
        private IFeatureClass RunProcessGetFeatureClass(IGPProcess inProcess, ITrackCancel inCancel, string ignoreMessage)
        {
            IFeatureClass       fc     = null;
            IQueryFilter        qf     = null;
            IGeoProcessorResult result = null;
            IGPUtilities        util   = null;

            try
            {
                string toolbox = inProcess.ToolboxName;
                mLog.Debug("inside run process");
                mLog.Debug("the process I want to run is " + inProcess.ToolName);
                mLog.Debug("the tool box is " + toolbox);
                myProcessor.OverwriteOutput = true;
                result = (IGeoProcessorResult)myProcessor.Execute(inProcess, null);
                ReturnMessages(myProcessor);
                //if result is null then there are no viable areas
                if (result != null)
                {
                    util = new GPUtilitiesClass();
                    util.DecodeFeatureLayer(result.GetOutput(0), out fc, out qf);
                    ReturnMessages(myProcessor, ignoreMessage);
                }
            }
            catch (Exception ex)
            {
                eLog.Debug(ex);
                ReturnMessages(myProcessor);
            }
            return(fc);
        }
Example #29
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 #30
0
        /// <summary>
        /// </summary>
        /// <param name="Display"></param>
        /// <param name="trackCancel"></param>
        public void Draw(IDisplay Display, ITrackCancel trackCancel)
        {
            double num;
            double num1;
            double num2;
            double num3;

            this.m_pGeometry.QueryCoords(out num, out num1, out num2, out num3);
            IPoint pointClass = new ESRI.ArcGIS.Geometry.Point()
            {
                Y = (num3 + num1) / 2,
                X = (num + num2) / 2
            };

            Display.SetSymbol(null);
            Display.SetSymbol(this.m_NumeratorTextSymbol as ISymbol);
            Display.DrawText(pointClass, this.m_NumeratorText);
            Display.SetSymbol(null);
            Display.SetSymbol(this.m_DenominatorTextSymbol as ISymbol);
            Display.DrawText(pointClass, this.m_DenominatorText);
            IPointCollection polylineClass = new Polyline();
            object           value         = Missing.Value;

            pointClass.X = num;
            pointClass.Y = (num3 + num1) / 2;
            polylineClass.AddPoint(pointClass, ref value, ref value);
            pointClass.X = num2;
            polylineClass.AddPoint(pointClass, ref value, ref value);
            Display.SetSymbol(null);
            Display.SetSymbol(this.m_LineSymbol as ISymbol);
            Display.DrawPolyline(polylineClass as IPolyline);
            Display.SetSymbol(null);
        }
        public void AddConnectivity(
            [NotNull] IEnumerable <IFeature> lineFeatures,
            bool respectLineOrientation,
            [CanBeNull] ITrackCancel trackCancel = null)
        {
            Stopwatch stopwatch =
                _msg.DebugStartTiming("Building / Enlarging connectivity graph...");

            var count = 0;

            foreach (IFeature lineFeature in lineFeatures)
            {
                if (trackCancel != null && !trackCancel.Continue())
                {
                    _msg.DebugStopTiming(stopwatch,
                                         "Building connectivity graph cancelled after {0} features",
                                         count);
                    return;
                }

                AddConnectivity(lineFeature, respectLineOrientation);
                count++;
            }

            _msg.DebugStopTiming(stopwatch,
                                 "Added connectivity information for {0} features. Total node count: {1}",
                                 count, Nodes.Count);
        }
        public static void WriteBuildErrorsToTurnFC(string outputFileGdbPath, string fdsName, string turnFCName,
                                                    IGPMessages messages, ITrackCancel trackcancel)
        {
            messages.AddMessage("Writing build errors to the turn feature class...");

            // Create a new field on the turn feature class for the build errors

            Geoprocessor gp = new Geoprocessor();
            gp.AddOutputsToMap = false;
            AddField addFieldTool = new AddField();
            addFieldTool.in_table = outputFileGdbPath + "\\" + fdsName + "\\" + turnFCName;
            addFieldTool.field_name = "BuildError";
            addFieldTool.field_type = "SHORT";
            gp.Execute(addFieldTool, trackcancel);

            // Open the turn feature class in the file geodatabase and find the BuildError field on it

            Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
            var wsf = Activator.CreateInstance(factoryType) as IWorkspaceFactory;
            var fws = wsf.OpenFromFile(outputFileGdbPath, 0) as IFeatureWorkspace;
            IFeatureClass turnFC = fws.OpenFeatureClass(turnFCName);
            int buildErrorField = turnFC.FindField("BuildError");

            // Open the BuildErrors.txt file generated from building the network dataset

            string s, leftTrimmedString, oidString;
            int leftTrimAmt = 24 + turnFCName.Length;
            IFeature feat = null;
            string[] buildErrorsFiles = System.IO.Directory.GetFiles(Environment.GetEnvironmentVariable("TEMP"), "BuildErrors.txt", System.IO.SearchOption.AllDirectories);
            string buildErrorsFile = buildErrorsFiles[0];
            System.IO.StreamReader f = new System.IO.StreamReader(buildErrorsFile);

            // Loop through the BuildErrors.txt file and write the value 1 for each entry found.

            while ((s = f.ReadLine()) != null)
            {
                // ignore blank lines
                if (s.Length == 0)
                    continue;

                // ignore build errors not dealing with the turn source
                if (s.Remove(leftTrimAmt) != ("SourceName: " + turnFCName + ", ObjectID: "))
                    continue;

                leftTrimmedString = s.Substring(leftTrimAmt);
                oidString = leftTrimmedString.Remove(leftTrimmedString.IndexOf(", "));
                feat = turnFC.GetFeature(Convert.ToInt32(oidString, System.Globalization.CultureInfo.InvariantCulture));
                feat.set_Value(buildErrorField, 1);
                feat.Store();
            }
            f.Close();
        }
        public RunTaskManager(ITrackCancel trackCancel, IGPMessages messages)
        {
            if (trackCancel == null)
                throw new ArgumentNullException("TrackCancel");
            if (messages == null)
                throw new ArgumentNullException("Messages");

            _trackCancel = trackCancel;
            _messages = messages;
            _taskMessages = new List<string>();

            StepProgressor = _trackCancel as IStepProgressor;
        }
Example #34
0
 void IElement.Draw(IDisplay Display, ITrackCancel TrackCancel)
 {
     ITransparencyDisplayFilter filter = new TransparencyDisplayFilterClass
     {
         Transparency = (short)((this._Opacity * 0xff) / 100)
     };
     IDisplayFilter filter2 = null;
     if (Display.Filter != null)
     {
         filter2 = (Display.Filter as IClone).Clone() as IDisplayFilter;
     }
     Display.Filter = filter;
     base.Draw(Display, TrackCancel);
     Display.Filter = filter2;
 }
 /// <summary>
 /// 运行地理分析工具
 /// </summary>
 /// <param name="gp"></param>
 /// <param name="process"></param>
 /// <param name="trackCancel"></param>
 /// <returns></returns>
 public static IGeoProcessorResult2 RunGeoProcessor(Geoprocessor gp, IGPProcess process, ITrackCancel trackCancel)
 {
     IGeoProcessorResult2 gpResult = null;
     try
     {
         gpResult = gp.Execute(process, trackCancel) as IGeoProcessorResult2; //执行分析
         return gpResult;
     }
     catch (Exception ex)
     {
     #if DEBUG
         System.Diagnostics.Debug.WriteLine(string.Format("#RunGP:{0};{1}", ex.Message, ex.StackTrace));
     #endif
         return gpResult;
     }
 }
Example #36
0
        protected virtual void runTool(Geoprocessor geoprocessor, string name, IGPProcess process, IVariantArray param, ITrackCancel TC)
        {
            // Set the overwrite output option to true
            geoprocessor.OverwriteOutput = true;

            // Execute the tool
            try
            {
                geoprocessor.Execute(name, param, TC);//"Clip_analysis"
                ReturnMessages(geoprocessor);

            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
                ReturnMessages(geoprocessor);
            }
        }
Example #37
0
        protected virtual void runTool(Geoprocessor geoprocessor, IGPProcess process, ITrackCancel TC)
        {
            // Set the overwrite output option to true
            geoprocessor.OverwriteOutput = true;

            // Execute the tool
            try
            {
                geoprocessor.Execute(process, TC);
                ReturnMessages(geoprocessor);

            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
                ReturnMessages(geoprocessor);
            }
        }
        /// <summary>IDisposable - dispose of open assets</summary>
        public void Dispose()
        {
            _xml = null;
            _osmDataset = null;
            _messages = null;
            _trackCancel = null;

            if (_edgeSources != null)
            {
                foreach (var efs in _edgeSources)
                    ComReleaser.ReleaseCOMObject(efs);

                _edgeSources.Clear();
                _edgeSources = null;
            }

            if (_junctionSources != null)
            {
                foreach (var jfs in _junctionSources)
                    ComReleaser.ReleaseCOMObject(jfs);

                _junctionSources.Clear();
                _junctionSources = null;
            }

            ComReleaser.ReleaseCOMObject(_turnSource);
            _turnSource = null;

            if (_networkAttrs != null)
            {
                foreach (var na in _networkAttrs)
                    ComReleaser.ReleaseCOMObject(na);

                _networkAttrs.Clear();
                _networkAttrs = null;
            }

            ComReleaser.ReleaseCOMObject(_networkDataset);
            _networkDataset = null;
        }
        public bool ChangeDatesOnTableMulti(ICursor pCursor, List<bool> HistorySettings, List<string> sDate, bool Unversioned, 
      Dictionary<int, string> ParcelToHistory_DICT,IStepProgressor m_pStepProgressor, ITrackCancel m_pTrackCancel)
        {
            bool bSystemEndDate_Clear = HistorySettings[0];
              bool bLegalStDate_Clear = HistorySettings[1];
              bool bLegalEndDate_Clear = HistorySettings[2];
              bool bSystemEndDate_Set = HistorySettings[3];
              bool bLegalStDate_Set = HistorySettings[4];
              bool bLegalEndDate_Set = HistorySettings[5];

              object dbNull = DBNull.Value;

              int FldIdxSystemEnd = pCursor.FindField("systemenddate");
              int iHistorical = pCursor.FindField("historical");
              int FldIdxLegalSt =pCursor.FindField("legalstartdate");
              int FldIdxLegalEnd = pCursor.FindField("legalenddate");
              bool bHasSysEndDateFld = (FldIdxSystemEnd > -1);
              bool bHasHistoricFld = (iHistorical > -1);
              bool bCont = true;
              bool m_bShowProgressor = (m_pStepProgressor!=null);

              IRow pRow = pCursor.NextRow();
              while (pRow != null)
              {
            //Check if the cancel button was pressed. If so, stop process
            if (m_bShowProgressor)
            {
              bCont = m_pTrackCancel.Continue();
              if (!bCont)
            break;
            }

            string sHistoryInfo = "";
            string[] sUpdateDictionaryDates = null;
            bool bTryGetTrue = false;
            if (ParcelToHistory_DICT.TryGetValue(pRow.OID, out sHistoryInfo))
            {
              //update the strings in the dictionary
              sUpdateDictionaryDates = sHistoryInfo.Split(',');
              bTryGetTrue = true;
            }

            if (bSystemEndDate_Set && bTryGetTrue)
            {
              pRow.set_Value(FldIdxSystemEnd, sDate[0]);
              if (bHasHistoricFld)                          // if writing date to SystemEndDate field
            pRow.set_Value(iHistorical, 1);             //then set the Historical flag to true = 1
              //update the dictionary
              //find the location of the System End Date
              string x= ParcelToHistory_DICT[pRow.OID];
              int i1 = x.IndexOf(",", 0);
              int i2 = x.IndexOf(",", i1+1);
              string s1= x.Remove(i1 + 1, i2 - i1);
              string s2=s1.Insert(i1 + 1, sDate[0] + ",");
              ParcelToHistory_DICT[pRow.OID] = s2;
            }

            if (bSystemEndDate_Clear && bTryGetTrue)
            {
              pRow.set_Value(FldIdxSystemEnd, dbNull);
              if (bHasHistoricFld)                          // if writing date to SystemEndDate field
            pRow.set_Value(iHistorical, 0);             //then set the Historical flag to true = 1

              //update the dictionary
              //find the location of the System End Date
              string x = ParcelToHistory_DICT[pRow.OID];
              int i1 = x.IndexOf(",", 0);
              int i2 = x.IndexOf(",", i1 + 1);
              string s1 = x.Remove(i1 + 1, i2 - i1);
              string s2 = s1.Insert(i1 + 1, ",");
              ParcelToHistory_DICT[pRow.OID] = s2;
            }

            if (bLegalStDate_Set && bTryGetTrue)
            {
              pRow.set_Value(FldIdxLegalSt, sDate[1]);
              //update the dictionary
              //find the location of the System End Date
              string x = ParcelToHistory_DICT[pRow.OID];
              int i1 = x.IndexOf(",", 0);
              int i2 = x.IndexOf(",", i1 + 1);
              int i3 = x.IndexOf(",", i2 + 1);
              string s1 = x.Remove(i2 + 1, i3 - i2);
              string s2 = s1.Insert(i2 + 1,sDate[1]  + ",");
              ParcelToHistory_DICT[pRow.OID] = s2;
            }

            if (bLegalStDate_Clear && bTryGetTrue)
            {
              pRow.set_Value(FldIdxLegalSt, dbNull);
              //update the dictionary
              //find the location of the System End Date
              string x = ParcelToHistory_DICT[pRow.OID];
              int i1 = x.IndexOf(",", 0);
              int i2 = x.IndexOf(",", i1 + 1);
              int i3 = x.IndexOf(",", i2 + 1);
              string s1 = x.Remove(i2 + 1, i3 - i2);
              string s2 = s1.Insert(i2 + 1, ",");
              ParcelToHistory_DICT[pRow.OID] = s2;
            }

            if (bLegalEndDate_Set && bTryGetTrue)
            {
              pRow.set_Value(FldIdxLegalEnd, sDate[2]);
              //update the dictionary
              //find the location of the System End Date
              string x = ParcelToHistory_DICT[pRow.OID];
              int i1 = x.IndexOf(",", 0);
              int i2 = x.IndexOf(",", i1 + 1);
              int i3 = x.IndexOf(",", i2 + 1);
              int i4 = x.IndexOf(",", i3 + 1);

              string s1 = x.Remove(i3 + 1, i4 - i3);
              string s2 = s1.Insert(i3 + 1, sDate[2] + ",");
              ParcelToHistory_DICT[pRow.OID] = s2;
            }

            if (bLegalEndDate_Clear && bTryGetTrue)
            {
              pRow.set_Value(FldIdxLegalEnd, dbNull);
              //update the dictionary
              //find the location of the System End Date
              string x = ParcelToHistory_DICT[pRow.OID];
              int i1 = x.IndexOf(",", 0);
              int i2 = x.IndexOf(",", i1 + 1);
              int i3 = x.IndexOf(",", i2 + 1);
              int i4 = x.IndexOf(",", i3 + 1);

              string s1 = x.Remove(i3 + 1, i4 - i3);
              string s2 = s1.Insert(i3 + 1, ",");
              ParcelToHistory_DICT[pRow.OID] = s2;
            }

            if (Unversioned)
              pCursor.UpdateRow(pRow);
            else
              pRow.Store();

            Marshal.ReleaseComObject(pRow);
            pRow = pCursor.NextRow();
            if (m_bShowProgressor)
            {
              if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange)
            m_pStepProgressor.Step();
            }
              }
              Marshal.ReleaseComObject(pCursor);
              if (!bCont)
            return false;
              return true;
        }
        public void Execute(IArray paramvalues, ITrackCancel trackcancel,
                            IGPEnvironmentManager envMgr, IGPMessages messages)
        {
            // Remember the original GP environment settings and temporarily override these settings

            var gpSettings = envMgr as IGeoProcessorSettings;
            bool origAddOutputsToMapSetting = gpSettings.AddOutputsToMap;
            bool origLogHistorySetting = gpSettings.LogHistory;
            gpSettings.AddOutputsToMap = false;
            gpSettings.LogHistory = false;

            // Create the Geoprocessor

            Geoprocessor gp = new Geoprocessor();

            try
            {
                // Validate our values

                IGPMessages validateMessages = ((IGPFunction2)this).Validate(paramvalues, false, envMgr);
                if ((validateMessages as IGPMessage).IsError())
                {
                    messages.AddError(1, "Validate failed");
                    return;
                }

                // Unpack values

                IGPParameter gpParam = paramvalues.get_Element(InputMtdDSTTable) as IGPParameter;
                IGPValue inputMtdDSTTableValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputMtdCntryRefTable) as IGPParameter;
                IGPValue inputMtdCntryRefTableValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputMtdAreaTable) as IGPParameter;
                IGPValue inputMtdAreaTableValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputAdminBndyFeatureClasses) as IGPParameter;
                var inputAdminBndyFeatureClassesMultiValue = m_gpUtils.UnpackGPValue(gpParam) as IGPMultiValue;
                gpParam = paramvalues.get_Element(OutputFileGDB) as IGPParameter;
                IGPValue outputFileGDBValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputStreetsFeatureClass) as IGPParameter;
                IGPValue inputStreetsFeatureClassValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputTimeZoneIDBaseFieldName) as IGPParameter;
                IGPValue inputTimeZoneIDBaseFieldNameValue = m_gpUtils.UnpackGPValue(gpParam);

                bool processStreetsFC = (!(inputStreetsFeatureClassValue.IsEmpty()));
                string timeZoneIDBaseFieldName = "";
                if (!(inputTimeZoneIDBaseFieldNameValue.IsEmpty()))
                    timeZoneIDBaseFieldName = inputTimeZoneIDBaseFieldNameValue.GetAsText();

                // Get the path to the output file GDB

                string outputFileGdbPath = outputFileGDBValue.GetAsText();

                // Create the new file geodatabase

                AddMessage("Creating the file geodatabase...", messages, trackcancel);

                int lastBackslash = outputFileGdbPath.LastIndexOf("\\");
                CreateFileGDB createFGDBTool = new CreateFileGDB();
                createFGDBTool.out_folder_path = outputFileGdbPath.Remove(lastBackslash);
                createFGDBTool.out_name = outputFileGdbPath.Substring(lastBackslash + 1);
                gp.Execute(createFGDBTool, trackcancel);

                // Copy the MtdDST table to the file geodatabase and add the ADMIN_LVL and AREACODE fields to it

                AddMessage("Copying the MtdDST table to the file geodatabase...", messages, trackcancel);

                TableToTable importTableTool = new TableToTable();
                string inputMtdDSTTablePath = inputMtdDSTTableValue.GetAsText();
                importTableTool.in_rows = inputMtdDSTTablePath;
                importTableTool.out_path = outputFileGdbPath;
                importTableTool.out_name = "MtdDST";
                importTableTool.field_mapping = "AREA_ID \"AREA_ID\" true true false 4 Long 0 0 ,First,#," + inputMtdDSTTablePath + ",AREA_ID,-1,-1;" +
                                                "TIME_ZONE \"TIME_ZONE\" true true false 4 Text 0 0 ,First,#," + inputMtdDSTTablePath + ",TIME_ZONE,-1,-1;" +
                                                "DST_EXIST \"DST_EXIST\" true true false 1 Text 0 0 ,First,#," + inputMtdDSTTablePath + ",DST_EXIST,-1,-1";
                gp.Execute(importTableTool, trackcancel);

                string mtdDSTTablePath = outputFileGdbPath + "\\MtdDST";

                AddField addFieldTool = new AddField();
                addFieldTool.in_table = mtdDSTTablePath;
                addFieldTool.field_name = "ADMIN_LVL";
                addFieldTool.field_type = "SHORT";
                gp.Execute(addFieldTool, trackcancel);

                addFieldTool = new AddField();
                addFieldTool.in_table = mtdDSTTablePath;
                addFieldTool.field_name = "AREACODE";
                addFieldTool.field_type = "TEXT";
                addFieldTool.field_length = 76;
                gp.Execute(addFieldTool, trackcancel);

                // Copy the MtdArea table to the file geodatabase and index the AREA_ID field

                AddMessage("Copying the MtdArea table to the file geodatabase...", messages, trackcancel);

                importTableTool = new TableToTable();
                importTableTool.in_rows = inputMtdAreaTableValue.GetAsText();
                importTableTool.out_path = outputFileGdbPath;
                importTableTool.out_name = "MtdArea";
                gp.Execute(importTableTool, trackcancel);

                string mtdAreaTablePath = outputFileGdbPath + "\\MtdArea";

                AddIndex addIndexTool = new AddIndex();
                addIndexTool.in_table = mtdAreaTablePath;
                addIndexTool.fields = "AREA_ID";
                addIndexTool.index_name = "AREA_ID";
                gp.Execute(addIndexTool, trackcancel);

                // Calculate the ADMIN_LVL and AREACODE fields on the MtdDST table

                MakeTableView makeTableViewTool = new MakeTableView();
                makeTableViewTool.in_table = mtdDSTTablePath;
                makeTableViewTool.out_view = "MtdDST_Layer";
                gp.Execute(makeTableViewTool, trackcancel);

                AddJoin addJoinTool = new AddJoin();
                addJoinTool.in_layer_or_view = "MtdDST_Layer";
                addJoinTool.in_field = "AREA_ID";
                addJoinTool.join_table = mtdAreaTablePath;
                addJoinTool.join_field = "AREA_ID";
                addJoinTool.join_type = "KEEP_COMMON";
                gp.Execute(addJoinTool, trackcancel);

                AddMessage("Calculating the ADMIN_LVL field...", messages, trackcancel);

                CalculateField calcFieldTool = new CalculateField();
                calcFieldTool.in_table = "MtdDST_Layer";
                calcFieldTool.field = "MtdDST.ADMIN_LVL";
                calcFieldTool.expression = "[MtdArea.ADMIN_LVL]";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                AddMessage("Calculating the AREACODE field...", messages, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = "MtdDST_Layer";
                calcFieldTool.field = "MtdDST.AREACODE";
                calcFieldTool.code_block = "lvl = [MtdArea.ADMIN_LVL]\n" +
                                           "s = CStr([MtdArea.AREACODE_1])\n" +
                                           "If lvl >= 2 Then s = s & \".\" & CStr([MtdArea.AREACODE_2])\n" +
                                           "If lvl >= 3 Then s = s & \".\" & CStr([MtdArea.AREACODE_3])\n" +
                                           "If lvl >= 4 Then s = s & \".\" & CStr([MtdArea.AREACODE_4])\n" +
                                           "If lvl >= 5 Then s = s & \".\" & CStr([MtdArea.AREACODE_5])\n" +
                                           "If lvl >= 6 Then s = s & \".\" & CStr([MtdArea.AREACODE_6])\n" +
                                           "If lvl >= 7 Then s = s & \".\" & CStr([MtdArea.AREACODE_7])";
                calcFieldTool.expression = "s";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                RemoveJoin removeJoinTool = new RemoveJoin();
                removeJoinTool.in_layer_or_view = "MtdDST_Layer";
                removeJoinTool.join_name = "MtdArea";
                gp.Execute(removeJoinTool, trackcancel);

                Delete deleteTool = new Delete();
                deleteTool.in_data = "MtdDST_Layer";
                gp.Execute(deleteTool, trackcancel);

                // Create the MtdDST# tables by admin levels and index the AREACODE field

                TableSelect tableSelectTool = null;
                for (int i = 1; i <= 7; i++)
                {
                    string iAsString = Convert.ToString(i, System.Globalization.CultureInfo.InvariantCulture);

                    AddMessage("Extracting level " + iAsString + " MtdDST rows...", messages, trackcancel);

                    tableSelectTool = new TableSelect();
                    tableSelectTool.in_table = mtdDSTTablePath;
                    tableSelectTool.out_table = mtdDSTTablePath + iAsString;
                    tableSelectTool.where_clause = "ADMIN_LVL = " + iAsString;
                    gp.Execute(tableSelectTool, trackcancel);

                    addIndexTool = new AddIndex();
                    addIndexTool.in_table = mtdDSTTablePath + iAsString;
                    addIndexTool.fields = "AREACODE";
                    addIndexTool.index_name = "AREACODE";
                    gp.Execute(addIndexTool, trackcancel);
                }

                deleteTool = new Delete();
                deleteTool.in_data = mtdDSTTablePath;
                gp.Execute(deleteTool, trackcancel);

                // Copy the MtdCntryRef table to the file geodatabase (use Statistics tool to remove duplicate rows)

                AddMessage("Copying the MtdCntryRef table to the file geodatabase...", messages, trackcancel);

                string inputMtdCntryRefTablePath = inputMtdCntryRefTableValue.GetAsText();
                string mtdCntryRefTablePath = outputFileGdbPath + "\\MtdCntryRef";
                Statistics statsTool = new Statistics();
                statsTool.in_table = inputMtdCntryRefTablePath;
                statsTool.out_table = mtdCntryRefTablePath;
                statsTool.statistics_fields = "ISO_CODE COUNT";
                statsTool.case_field = "GOVT_CODE;ISO_CODE;DRIVING_SD;ADMINLEVEL";
                gp.Execute(statsTool, trackcancel);

                DeleteField deleteFieldTool = new DeleteField();
                deleteFieldTool.in_table = mtdCntryRefTablePath;
                deleteFieldTool.drop_field = "FREQUENCY;COUNT_ISO_CODE";
                gp.Execute(deleteFieldTool, trackcancel);

                // Index the GOVT_CODE field

                addIndexTool = new AddIndex();
                addIndexTool.in_table = mtdCntryRefTablePath;
                addIndexTool.fields = "GOVT_CODE";
                addIndexTool.index_name = "GOVT_CODE";
                gp.Execute(addIndexTool, trackcancel);

                // Extract the top level (country) records from the MtdArea table and index the AREACODE_1 field

                AddMessage("Extracting the top-level rows from the MtdArea table...", messages, trackcancel);

                string mtdTopAreaTablePath = outputFileGdbPath + "\\TopArea";

                tableSelectTool = new TableSelect();
                tableSelectTool.in_table = mtdAreaTablePath;
                tableSelectTool.out_table = mtdTopAreaTablePath;
                tableSelectTool.where_clause = "AREACODE_2 = 0 AND AREA_TYPE = 'B'";
                gp.Execute(tableSelectTool, trackcancel);

                addIndexTool = new AddIndex();
                addIndexTool.in_table = mtdTopAreaTablePath;
                addIndexTool.fields = "AREACODE_1";
                addIndexTool.index_name = "AREACODE_1";
                gp.Execute(addIndexTool, trackcancel);

                // Create and calculate the TOP_GOVT_CODE field on the MtdArea table

                addFieldTool = new AddField();
                addFieldTool.in_table = mtdAreaTablePath;
                addFieldTool.field_name = "TOP_GOVT_CODE";
                addFieldTool.field_type = "LONG";
                gp.Execute(addFieldTool, trackcancel);

                makeTableViewTool = new MakeTableView();
                makeTableViewTool.in_table = mtdAreaTablePath;
                makeTableViewTool.out_view = "MtdArea_Layer";
                gp.Execute(makeTableViewTool, trackcancel);

                addJoinTool = new AddJoin();
                addJoinTool.in_layer_or_view = "MtdArea_Layer";
                addJoinTool.in_field = "AREACODE_1";
                addJoinTool.join_table = mtdTopAreaTablePath;
                addJoinTool.join_field = "AREACODE_1";
                addJoinTool.join_type = "KEEP_COMMON";
                gp.Execute(addJoinTool, trackcancel);

                AddMessage("Calculating the TOP_GOVT_CODE field...", messages, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = "MtdArea_Layer";
                calcFieldTool.field = "MtdArea.TOP_GOVT_CODE";
                calcFieldTool.expression = "[TopArea.GOVT_CODE]";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                removeJoinTool = new RemoveJoin();
                removeJoinTool.in_layer_or_view = "MtdArea_Layer";
                removeJoinTool.join_name = "TopArea";
                gp.Execute(removeJoinTool, trackcancel);

                deleteTool = new Delete();
                deleteTool.in_data = mtdTopAreaTablePath;
                gp.Execute(deleteTool, trackcancel);

                // Create and calculate the ISO_CODE and DRIVING_SD string fields

                addFieldTool = new AddField();
                addFieldTool.in_table = mtdAreaTablePath;
                addFieldTool.field_name = "ISO_CODE";
                addFieldTool.field_type = "TEXT";
                addFieldTool.field_length = 3;
                gp.Execute(addFieldTool, trackcancel);

                addFieldTool = new AddField();
                addFieldTool.in_table = mtdAreaTablePath;
                addFieldTool.field_name = "DRIVING_SD";
                addFieldTool.field_type = "TEXT";
                addFieldTool.field_length = 1;
                gp.Execute(addFieldTool, trackcancel);

                addJoinTool = new AddJoin();
                addJoinTool.in_layer_or_view = "MtdArea_Layer";
                addJoinTool.in_field = "TOP_GOVT_CODE";
                addJoinTool.join_table = mtdCntryRefTablePath;
                addJoinTool.join_field = "GOVT_CODE";
                addJoinTool.join_type = "KEEP_COMMON";
                gp.Execute(addJoinTool, trackcancel);

                AddMessage("Calculating the ISO_CODE field...", messages, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = "MtdArea_Layer";
                calcFieldTool.field = "MtdArea.ISO_CODE";
                calcFieldTool.expression = "[MtdCntryRef.ISO_CODE]";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                AddMessage("Calculating the DRIVING_SD field...", messages, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = "MtdArea_Layer";
                calcFieldTool.field = "MtdArea.DRIVING_SD";
                calcFieldTool.expression = "[MtdCntryRef.DRIVING_SD]";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                removeJoinTool = new RemoveJoin();
                removeJoinTool.in_layer_or_view = "MtdArea_Layer";
                removeJoinTool.join_name = "MtdCntryRef";
                gp.Execute(removeJoinTool, trackcancel);

                // Create and calculate the FullAREACODE# string fields and the UTCOffset and DST fields

                addFieldTool = new AddField();
                addFieldTool.in_table = mtdAreaTablePath;
                addFieldTool.field_type = "SHORT";
                addFieldTool.field_name = "UTCOffset";
                gp.Execute(addFieldTool, trackcancel);
                addFieldTool.field_name = "DST";
                gp.Execute(addFieldTool, trackcancel);

                string codeBlock = "lvl = [ADMIN_LVL]\ns = CStr([AREACODE_1])";
                for (int i = 1; i <= 7; i++)
                {
                    string iAsString = Convert.ToString(i, System.Globalization.CultureInfo.InvariantCulture);
                    string iPlusOne = Convert.ToString(i+1, System.Globalization.CultureInfo.InvariantCulture);
                    string fullAreaCodeFieldName = "FullAREACODE" + iAsString;
                    addFieldTool = new AddField();
                    addFieldTool.in_table = mtdAreaTablePath;
                    addFieldTool.field_name = fullAreaCodeFieldName;
                    addFieldTool.field_type = "TEXT";
                    addFieldTool.field_length = 76;
                    gp.Execute(addFieldTool, trackcancel);

                    AddMessage("Calculating the FullAREACODE" + iAsString + " field...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = mtdAreaTablePath;
                    calcFieldTool.field = fullAreaCodeFieldName;
                    calcFieldTool.code_block = codeBlock;
                    calcFieldTool.expression = "s";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);
                    codeBlock = codeBlock + "\nIf lvl >= " + iPlusOne + " Then s = s & \".\" & CStr([AREACODE_" + iPlusOne + "])";

                    string dstJoinTableName = "MtdDST" + iAsString;
                    string dstJoinTablePath = outputFileGdbPath + "\\" + dstJoinTableName;

                    addJoinTool = new AddJoin();
                    addJoinTool.in_layer_or_view = "MtdArea_Layer";
                    addJoinTool.in_field = fullAreaCodeFieldName;
                    addJoinTool.join_table = dstJoinTablePath;
                    addJoinTool.join_field = "AREACODE";
                    addJoinTool.join_type = "KEEP_COMMON";
                    gp.Execute(addJoinTool, trackcancel);

                    AddMessage("Calculating the UTCOffset field (" + iAsString + " of 7)...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "MtdArea_Layer";
                    calcFieldTool.field = "MtdArea.UTCOffset";
                    calcFieldTool.code_block = "s = [MtdArea.UTCOffset]\n" +
                                               "joinValue = [" + dstJoinTableName + ".TIME_ZONE]\n" +
                                               "If Not IsNull(joinValue) Then\n" +
                                               "  If Trim(joinValue) <> \"\" Then s = CInt(joinValue) * 6\n" +
                                               "End If";
                    calcFieldTool.expression = "s";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    AddMessage("Calculating the DST field (" + iAsString + " of 7)...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "MtdArea_Layer";
                    calcFieldTool.field = "MtdArea.DST";
                    calcFieldTool.code_block = "s = [MtdArea.DST]\n" +
                                               "joinValue = [" + dstJoinTableName + ".DST_EXIST]\n" +
                                               "If Not IsNull(joinValue) Then\n" +
                                               "  Select Case Trim(joinValue)\n" +
                                               "    Case \"Y\": s = 1\n    Case \"N\": s = 0\n" +
                                               "  End Select\n" +
                                               "End If";
                    calcFieldTool.expression = "s";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    removeJoinTool = new RemoveJoin();
                    removeJoinTool.in_layer_or_view = "MtdArea_Layer";
                    removeJoinTool.join_name = dstJoinTableName;
                    gp.Execute(removeJoinTool, trackcancel);

                    deleteTool = new Delete();
                    deleteTool.in_data = dstJoinTablePath;
                    gp.Execute(deleteTool, trackcancel);
                }

                deleteTool = new Delete();
                deleteTool.in_data = "MtdArea_Layer";
                gp.Execute(deleteTool, trackcancel);

                // Create and calculate the sortable MSTIMEZONE field on the MtdArea table

                addFieldTool = new AddField();
                addFieldTool.in_table = mtdAreaTablePath;
                addFieldTool.field_name = "SortableMSTIMEZONE";
                addFieldTool.field_type = "TEXT";
                addFieldTool.field_length = 60;
                gp.Execute(addFieldTool, trackcancel);

                AddMessage("Calculating the time zones...", messages, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = mtdAreaTablePath;
                calcFieldTool.field = "SortableMSTIMEZONE";
                calcFieldTool.code_block = TimeZoneUtilities.MakeSortableMSTIMEZONECode("ISO_CODE");
                calcFieldTool.expression = "z";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                // Extract the MtdArea rows to be used for generating the time zone polygons and index the AREA_ID field

                string mtdAreaForTZPolysTablePath = outputFileGdbPath + "\\MtdAreaForTZPolys";
                tableSelectTool = new TableSelect();
                tableSelectTool.in_table = mtdAreaTablePath;
                tableSelectTool.out_table = mtdAreaForTZPolysTablePath;
                tableSelectTool.where_clause = CreateWhereClauseForAdminLvlByCountry(outputFileGdbPath, "MtdCntryRef");
                gp.Execute(tableSelectTool, trackcancel);

                addIndexTool = new AddIndex();
                addIndexTool.in_table = mtdAreaForTZPolysTablePath;
                addIndexTool.fields = "AREA_ID";
                addIndexTool.index_name = "AREA_ID";
                gp.Execute(addIndexTool, trackcancel);

                // We no longer need the MtdCntryRef table anymore

                deleteTool = new Delete();
                deleteTool.in_data = mtdCntryRefTablePath;
                gp.Execute(deleteTool, trackcancel);

                // Merge the AdminBndy feature classes together into one feature class

                int numAdminBndyFCs = inputAdminBndyFeatureClassesMultiValue.Count;
                string mergeToolInputs = "";
                for (int i = 0; i < numAdminBndyFCs; i++)
                {
                    mergeToolInputs = mergeToolInputs + inputAdminBndyFeatureClassesMultiValue.get_Value(i).GetAsText() + ";";
                }
                mergeToolInputs = mergeToolInputs.Remove(mergeToolInputs.Length - 1);
                string adminBndyFCPath = outputFileGdbPath + "\\AdminBndy";

                AddMessage("Merging the Administrative Boundary feature classes...", messages, trackcancel);

                Merge mergeTool = new Merge();
                mergeTool.inputs = mergeToolInputs;
                mergeTool.output = adminBndyFCPath;
                gp.Execute(mergeTool, trackcancel);

                // Join the AdminBndy polygons to the MtdArea rows to be used for generating the time zone polygons

                MakeFeatureLayer makeFeatureLayerTool = new MakeFeatureLayer();
                makeFeatureLayerTool.in_features = adminBndyFCPath;
                makeFeatureLayerTool.out_layer = "AdminBndy_Layer";
                gp.Execute(makeFeatureLayerTool, trackcancel);

                addJoinTool = new AddJoin();
                addJoinTool.in_layer_or_view = "AdminBndy_Layer";
                addJoinTool.in_field = "AREA_ID";
                addJoinTool.join_table = mtdAreaForTZPolysTablePath;
                addJoinTool.join_field = "AREA_ID";
                addJoinTool.join_type = "KEEP_COMMON";
                gp.Execute(addJoinTool, trackcancel);

                FeatureClassToFeatureClass importFCTool = new FeatureClassToFeatureClass();
                importFCTool.in_features = "AdminBndy_Layer";
                importFCTool.out_path = outputFileGdbPath;
                importFCTool.out_name = "UndissolvedTZPolys";
                importFCTool.field_mapping = "SortableMSTIMEZONE \"SortableMSTIMEZONE\" true true false 60 Text 0 0 ,First,#," +
                                             mtdAreaForTZPolysTablePath + ",MtdAreaForTZPolys.SortableMSTIMEZONE,-1,-1";
                gp.Execute(importFCTool, trackcancel);
                string undissolvedTZPolysFCPath = outputFileGdbPath + "\\UndissolvedTZPolys";

                removeJoinTool = new RemoveJoin();
                removeJoinTool.in_layer_or_view = "AdminBndy_Layer";
                removeJoinTool.join_name = "MtdAreaForTZPolys";
                gp.Execute(removeJoinTool, trackcancel);

                deleteTool = new Delete();
                deleteTool.in_data = "AdminBndy_Layer";
                gp.Execute(deleteTool, trackcancel);

                deleteTool = new Delete();
                deleteTool.in_data = adminBndyFCPath;
                gp.Execute(deleteTool, trackcancel);
                deleteTool.in_data = mtdAreaForTZPolysTablePath;
                gp.Execute(deleteTool, trackcancel);

                // Dissolve the time zone polygons together

                AddMessage("Dissolving the time zones...", messages, trackcancel);

                string timeZoneFCPath = outputFileGdbPath + "\\" + TimeZoneFCName;
                Dissolve dissolveTool = new Dissolve();
                dissolveTool.in_features = undissolvedTZPolysFCPath;
                dissolveTool.out_feature_class = timeZoneFCPath;
                dissolveTool.dissolve_field = "SortableMSTIMEZONE";
                dissolveTool.multi_part = "MULTI_PART";
                gp.Execute(dissolveTool, trackcancel);

                deleteTool = new Delete();
                deleteTool.in_data = undissolvedTZPolysFCPath;
                gp.Execute(deleteTool, trackcancel);

                // Create and calculate the MSTIMEZONE field

                addFieldTool = new AddField();
                addFieldTool.in_table = timeZoneFCPath;
                addFieldTool.field_name = "MSTIMEZONE";
                addFieldTool.field_type = "TEXT";
                addFieldTool.field_length = 50;
                gp.Execute(addFieldTool, trackcancel);

                AddMessage("Calculating the time zones...", messages, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = timeZoneFCPath;
                calcFieldTool.field = "MSTIMEZONE";
                calcFieldTool.expression = "Mid([SortableMSTIMEZONE], 7)";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                // Delete the old sortable MSTIMEZONE field

                deleteFieldTool = new DeleteField();
                deleteFieldTool.in_table = timeZoneFCPath;
                deleteFieldTool.drop_field = "SortableMSTIMEZONE";
                gp.Execute(deleteFieldTool, trackcancel);

                if (processStreetsFC)
                {
                    // Create the network dataset time zone table

                    AddMessage("Creating the time zones table...", messages, trackcancel);

                    importTableTool = new TableToTable();
                    importTableTool.in_rows = timeZoneFCPath;
                    importTableTool.out_path = outputFileGdbPath;
                    importTableTool.out_name = TimeZonesTableName;
                    importTableTool.field_mapping = "MSTIMEZONE \"MSTIMEZONE\" true true false 50 Text 0 0 ,First,#," +
                                                    timeZoneFCPath + ",MSTIMEZONE,-1,-1";
                    gp.Execute(importTableTool, trackcancel);

                    // Separate the MtdArea table by driving side and index the AREA_ID field on each

                    AddMessage("Extracting rows for the left-side driving areas...", messages, trackcancel);

                    string drivingLTablePath = mtdAreaTablePath + "DrivingL";
                    string drivingRTablePath = mtdAreaTablePath + "DrivingR";

                    tableSelectTool = new TableSelect();
                    tableSelectTool.in_table = mtdAreaTablePath;
                    tableSelectTool.out_table = drivingLTablePath;
                    tableSelectTool.where_clause = "DRIVING_SD = 'L'";
                    gp.Execute(tableSelectTool, trackcancel);

                    addIndexTool = new AddIndex();
                    addIndexTool.in_table = drivingLTablePath;
                    addIndexTool.fields = "AREA_ID";
                    addIndexTool.index_name = "AREA_ID";
                    gp.Execute(addIndexTool, trackcancel);

                    AddMessage("Extracting rows for the right-side driving areas...", messages, trackcancel);

                    tableSelectTool = new TableSelect();
                    tableSelectTool.in_table = mtdAreaTablePath;
                    tableSelectTool.out_table = drivingRTablePath;
                    tableSelectTool.where_clause = "DRIVING_SD = 'R'";
                    gp.Execute(tableSelectTool, trackcancel);

                    addIndexTool = new AddIndex();
                    addIndexTool.in_table = drivingRTablePath;
                    addIndexTool.fields = "AREA_ID";
                    addIndexTool.index_name = "AREA_ID";
                    gp.Execute(addIndexTool, trackcancel);

                    // Import the Streets feature class to the file geodatabase and
                    // add the FT_TimeZoneID and TF_TimeZoneID fields

                    AddMessage("Copying the Streets feature class to the geodatabase...", messages, trackcancel);

                    importFCTool = new FeatureClassToFeatureClass();
                    importFCTool.in_features = inputStreetsFeatureClassValue.GetAsText();
                    importFCTool.out_path = outputFileGdbPath;
                    importFCTool.out_name = StreetsFCName;
                    gp.Execute(importFCTool, trackcancel);

                    string pathToStreetsFC = outputFileGdbPath + "\\" + StreetsFCName;

                    addFieldTool = new AddField();
                    addFieldTool.in_table = pathToStreetsFC;
                    addFieldTool.field_name = "FT_" + timeZoneIDBaseFieldName;
                    addFieldTool.field_type = "SHORT";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "TF_" + timeZoneIDBaseFieldName;
                    addFieldTool.field_type = "SHORT";
                    gp.Execute(addFieldTool, trackcancel);

                    // Calculate the TimeZoneID fields

                    makeFeatureLayerTool = new MakeFeatureLayer();
                    makeFeatureLayerTool.in_features = pathToStreetsFC;
                    makeFeatureLayerTool.out_layer = "Streets_Layer";
                    gp.Execute(makeFeatureLayerTool, trackcancel);

                    addJoinTool = new AddJoin();
                    addJoinTool.in_layer_or_view = "Streets_Layer";
                    addJoinTool.in_field = "R_AREA_ID";
                    addJoinTool.join_table = drivingLTablePath;
                    addJoinTool.join_field = "AREA_ID";
                    addJoinTool.join_type = "KEEP_COMMON";
                    gp.Execute(addJoinTool, trackcancel);

                    AddMessage("Calculating the FT_" + timeZoneIDBaseFieldName + " field for left driving side roads...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "Streets_Layer";
                    calcFieldTool.field = StreetsFCName + ".FT_" + timeZoneIDBaseFieldName;
                    calcFieldTool.code_block = TimeZoneUtilities.MakeTimeZoneIDCode(outputFileGdbPath, TimeZonesTableName, "MtdAreaDrivingL.SortableMSTIMEZONE");
                    calcFieldTool.expression = "tzID";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    removeJoinTool = new RemoveJoin();
                    removeJoinTool.in_layer_or_view = "Streets_Layer";
                    removeJoinTool.join_name = "MtdAreaDrivingL";
                    gp.Execute(removeJoinTool, trackcancel);

                    addJoinTool = new AddJoin();
                    addJoinTool.in_layer_or_view = "Streets_Layer";
                    addJoinTool.in_field = "L_AREA_ID";
                    addJoinTool.join_table = drivingRTablePath;
                    addJoinTool.join_field = "AREA_ID";
                    addJoinTool.join_type = "KEEP_COMMON";
                    gp.Execute(addJoinTool, trackcancel);

                    AddMessage("Calculating the FT_" + timeZoneIDBaseFieldName + " field for right driving side roads...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "Streets_Layer";
                    calcFieldTool.field = StreetsFCName + ".FT_" + timeZoneIDBaseFieldName;
                    calcFieldTool.code_block = TimeZoneUtilities.MakeTimeZoneIDCode(outputFileGdbPath, TimeZonesTableName, "MtdAreaDrivingR.SortableMSTIMEZONE");
                    calcFieldTool.expression = "tzID";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    removeJoinTool = new RemoveJoin();
                    removeJoinTool.in_layer_or_view = "Streets_Layer";
                    removeJoinTool.join_name = "MtdAreaDrivingR";
                    gp.Execute(removeJoinTool, trackcancel);

                    addJoinTool = new AddJoin();
                    addJoinTool.in_layer_or_view = "Streets_Layer";
                    addJoinTool.in_field = "L_AREA_ID";
                    addJoinTool.join_table = drivingLTablePath;
                    addJoinTool.join_field = "AREA_ID";
                    addJoinTool.join_type = "KEEP_COMMON";
                    gp.Execute(addJoinTool, trackcancel);

                    AddMessage("Calculating the TF_" + timeZoneIDBaseFieldName + " field for left driving side roads...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "Streets_Layer";
                    calcFieldTool.field = StreetsFCName + ".TF_" + timeZoneIDBaseFieldName;
                    calcFieldTool.code_block = TimeZoneUtilities.MakeTimeZoneIDCode(outputFileGdbPath, TimeZonesTableName, "MtdAreaDrivingL.SortableMSTIMEZONE");
                    calcFieldTool.expression = "tzID";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    removeJoinTool = new RemoveJoin();
                    removeJoinTool.in_layer_or_view = "Streets_Layer";
                    removeJoinTool.join_name = "MtdAreaDrivingL";
                    gp.Execute(removeJoinTool, trackcancel);

                    addJoinTool = new AddJoin();
                    addJoinTool.in_layer_or_view = "Streets_Layer";
                    addJoinTool.in_field = "R_AREA_ID";
                    addJoinTool.join_table = drivingRTablePath;
                    addJoinTool.join_field = "AREA_ID";
                    addJoinTool.join_type = "KEEP_COMMON";
                    gp.Execute(addJoinTool, trackcancel);

                    AddMessage("Calculating the TF_" + timeZoneIDBaseFieldName + " field for right driving side roads...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "Streets_Layer";
                    calcFieldTool.field = StreetsFCName + ".TF_" + timeZoneIDBaseFieldName;
                    calcFieldTool.code_block = TimeZoneUtilities.MakeTimeZoneIDCode(outputFileGdbPath, TimeZonesTableName, "MtdAreaDrivingR.SortableMSTIMEZONE");
                    calcFieldTool.expression = "tzID";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    removeJoinTool = new RemoveJoin();
                    removeJoinTool.in_layer_or_view = "Streets_Layer";
                    removeJoinTool.join_name = "MtdAreaDrivingR";
                    gp.Execute(removeJoinTool, trackcancel);

                    deleteTool = new Delete();
                    deleteTool.in_data = "Streets_Layer";
                    gp.Execute(deleteTool, trackcancel);

                    deleteTool = new Delete();
                    deleteTool.in_data = drivingLTablePath;
                    gp.Execute(deleteTool, trackcancel);
                    deleteTool.in_data = drivingRTablePath;
                    gp.Execute(deleteTool, trackcancel);
                }
                else
                {
                    // Create a dummy TimeZones table and a dummy Streets feature class

                    CreateTable createTableTool = new CreateTable();
                    createTableTool.out_path = outputFileGdbPath;
                    createTableTool.out_name = TimeZonesTableName;
                    gp.Execute(createTableTool, trackcancel);

                    CreateFeatureclass createFCTool = new CreateFeatureclass();
                    createFCTool.out_path = outputFileGdbPath;
                    createFCTool.out_name = StreetsFCName;
                    createFCTool.geometry_type = "POLYLINE";
                    gp.Execute(createFCTool, trackcancel);
                }

                deleteTool = new Delete();
                deleteTool.in_data = mtdAreaTablePath;
                gp.Execute(deleteTool, trackcancel);

                // Compact the output file geodatabase

                AddMessage("Compacting the output file geodatabase...", messages, trackcancel);

                Compact compactTool = new Compact();
                compactTool.in_workspace = outputFileGdbPath;
                gp.Execute(compactTool, trackcancel);
            }
            catch (Exception e)
            {
                if (gp.MaxSeverity == 2)
                {
                    object missing = System.Type.Missing;
                    messages.AddError(1, gp.GetMessages(ref missing));
                }
                messages.AddError(1, e.Message);
                messages.AddError(1, e.StackTrace);
            }
            finally
            {
                // Restore the original GP environment settings

                gpSettings.AddOutputsToMap = origAddOutputsToMapSetting;
                gpSettings.LogHistory = origLogHistorySetting;
            }
            GC.Collect();
            return;
        }
        // Execute: Execute the function given the array of the parameters
        public void Execute(IArray paramvalues, ITrackCancel trackcancel, IGPEnvironmentManager envMgr, IGPMessages message)
        {
            
            // Get the first Input Parameter
            IGPParameter parameter = (IGPParameter)paramvalues.get_Element(0);

            // UnPackGPValue. This ensures you get the value either form the dataelement or GpVariable (ModelBuilder)
           IGPValue parameterValue = m_GPUtilities.UnpackGPValue(parameter);

            // Open Input Dataset
            IFeatureClass inputFeatureClass;
            IQueryFilter qf;
            m_GPUtilities.DecodeFeatureLayer(parameterValue, out inputFeatureClass, out qf);

            if (inputFeatureClass == null)
            {
                message.AddError(2, "Could not open input dataset.");
                return;
            } 
                
            // Add the field if it does not exist.
            int indexA;

            parameter = (IGPParameter)paramvalues.get_Element(1);
            string field = parameter.Value.GetAsText();

            
            indexA = inputFeatureClass.FindField(field);
            if (indexA < 0)
            {
                IFieldEdit fieldEdit = new FieldClass();
                fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
                fieldEdit.Name_2 = field;
                inputFeatureClass.AddField(fieldEdit);
            }

             int featcount = inputFeatureClass.FeatureCount(null);     
      
             //Set the properties of the Step Progressor
            IStepProgressor pStepPro = (IStepProgressor)trackcancel;
            pStepPro.MinRange = 0;
            pStepPro.MaxRange = featcount;
            pStepPro.StepValue = (1);
            pStepPro.Message = "Calculating Area";
            pStepPro.Position = 0;
            pStepPro.Show();

            // Create an Update Cursor
            indexA = inputFeatureClass.FindField(field);
            IFeatureCursor updateCursor = inputFeatureClass.Update(qf, false);
            IFeature updateFeature = updateCursor.NextFeature();
            IGeometry geometry;
            IArea area;
            double dArea;   
            
            while (updateFeature != null)
            {
                geometry = updateFeature.Shape;
                area = (IArea)geometry;
                dArea = area.Area;
                updateFeature.set_Value(indexA, dArea);
                updateCursor.UpdateFeature(updateFeature);
                updateFeature.Store();
                updateFeature = updateCursor.NextFeature();
                pStepPro.Step();
            }

           pStepPro.Hide();
            
            // Release the update cursor to remove the lock on the input data.
           System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor);
        }
        /// <summary>
        /// Uses MatchAddress to geocode a cursor of addresses to a RecordSet 
        /// This is called by ArcGIS Server Geocode Addresses
        /// </summary>
        /// <param name="addressCursor">Cursor containing address to be geocoded</param>
        /// <param name="addressFieldNames">The address fields that make up a record in the cursor</param>
        /// <param name="outputRecordSet">The output record set</param>
        /// <param name="outputFieldNames">The output field names</param>
        /// <param name="fieldsToCopy"></param>
        /// <param name="cancelTracker"></param>
        public void MatchRecordSet(ICursor addressCursor, string addressFieldNames, IRecordSetInit outputRecordSet,
          string outputFieldNames, IPropertySet fieldsToCopy, ITrackCancel cancelTracker)
        {
            _log.Debug("IBatchGeocoding MatchRecordSet");

              _log.Debug("MatchRecordSet addressFieldNames:" + addressFieldNames);
              _log.Debug("MatchRecordSet outputFieldNames:" + outputFieldNames);

              ICursor resultCursor = outputRecordSet.Insert();
              IRow row = addressCursor.NextRow();
              IRowBuffer rowBuffer = null;
              IFields fields = row.Fields;
              IFields bufferFields = null;
              String[] fieldNames = addressFieldNames.Split(',');
              String[] outputFields = outputFieldNames.Split(',');
              int addressFieldsSize = fieldNames.Length;
              int outputFieldsSize = outputFields.Length;
              int copyFieldsSize = 0;
              String addressValue = "";
              IPropertySet addressProperty;
              IPropertySet results;
              object value, values, names;
              String[] nameArray;
              object[] valueArray;
              Dictionary<string, int> addressFieldInds = new Dictionary<string,int>();
              Dictionary<string, int> outputFieldInds = new Dictionary<string, int>();
              string fieldName;
              string outFieldName;

              // Get all address field indexes
              for (int i = 0; i < addressFieldsSize; i++)
              {
              fieldName = fieldNames[i].Trim();
              if(!addressFieldInds.ContainsKey(fieldName))
                  addressFieldInds.Add(fieldName, fields.FindField(fieldName));
              }

              //loop through each record
              while (row != null)
              {
              addressProperty = new PropertySetClass();
              rowBuffer = outputRecordSet.CreateRowBuffer();
              bufferFields = rowBuffer.Fields;

              //populate a property set of search values
              for (int i = 0; i < addressFieldsSize; i++)
              {
                  fieldName = fieldNames[i].Trim();
                  addressValue = row.get_Value(addressFieldInds[fieldName])  as String;

                  if(!string.IsNullOrEmpty(addressValue))
                      addressProperty.SetProperty(fieldName, addressValue);
              }

              // Geocode the Address
              results = MatchAddress(addressProperty);

              // Get all output field indexes, only do this once to save processing
              if (outputFieldInds.Count == 0)
              {
                  for (int i = 0; i < outputFieldsSize; i++)
                  {
                      outFieldName = outputFields[i].Trim();
                      outputFieldInds.Add(outFieldName, bufferFields.FindField(outFieldName));
                  }
              }

              //add the result to the recordset
              for (int i = 0; i < outputFieldsSize; i++)
              {
                  outFieldName = outputFields[i].Trim();
                  value = results.GetProperty(outFieldName);
                  _log.Debug("MatchRecordSet outputFields[i]:" + outFieldName);
                  rowBuffer.set_Value(outputFieldInds[outFieldName], value);
              }

              //copy extra fields
              fieldsToCopy.GetAllProperties(out names, out values);
              nameArray = names as String[];
              valueArray = values as object[];
              copyFieldsSize = nameArray.Length;

              for (int i = 0; i < copyFieldsSize; i++)
              {
                  string fieldToCopy = nameArray[i];
                  if(fieldToCopy == "ResultID")
                      rowBuffer.set_Value(bufferFields.FindField(fieldToCopy), row.OID);
                  else
                      rowBuffer.set_Value(bufferFields.FindField(fieldToCopy), row.get_Value(fields.FindField(fieldToCopy)));
              }

              //insert row
              resultCursor.InsertRow(rowBuffer);

              row = addressCursor.NextRow();
              }

              // Clean up the cursors
              resultCursor.Flush();
              Marshal.ReleaseComObject(resultCursor);
              Marshal.ReleaseComObject(addressCursor);
        }
 private void AddMessage(string messageString, IGPMessages messages, ITrackCancel trackcancel)
 {
     messages.AddMessage(messageString);
     IStepProgressor sp = trackcancel as IStepProgressor;
     if (sp != null)
         sp.Message = messageString;
 }
        public static void WriteTurnGeometry(string outputFileGdbPath, string StreetsFCName, string TurnFCName,
                                             int numAltIDFields, double trimRatio, IGPMessages messages, ITrackCancel trackcancel)
        {
            messages.AddMessage("Writing turn geometries...");

            // Open the feature classes in the file geodatabase

            Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
            var wsf = Activator.CreateInstance(factoryType) as IWorkspaceFactory;
            var fws = wsf.OpenFromFile(outputFileGdbPath, 0) as IFeatureWorkspace;
            IFeatureClass streetsFC = fws.OpenFeatureClass(StreetsFCName);
            IFeatureClass turnFC = fws.OpenFeatureClass(TurnFCName);

            // Look up the Edge1End, EdgeFCID and EdgeFID fields on the turn feature class

            int edge1EndField = turnFC.FindField("Edge1End");
            int[] edgeFCIDFields = new int[numAltIDFields];
            int[] edgeFIDFields = new int[numAltIDFields];
            for (int i = 0; i < numAltIDFields; i++)
            {
                edgeFCIDFields[i] = turnFC.FindField("Edge" + (i + 1) + "FCID");
                edgeFIDFields[i] = turnFC.FindField("Edge" + (i + 1) + "FID");
            }

            // Look up the FCID of the Streets feature class and open a random access cursor on it

            int streetsFCID = streetsFC.FeatureClassID;
            IRandomAccessCursor rac = (streetsFC as IRandomAccessTable).GetRandomRows("", true);

            // Create an update cursor on the turn feature class

            var qf = new QueryFilterClass() as IQueryFilter;
            IFeatureCursor featCursor = turnFC.Update(qf, false);
            IFeature turnFeat = null;
            int numFeatures = 0;
            double lastCurveLength = 0.0;
            while ((turnFeat = featCursor.NextFeature()) != null)
            {
                // Get the geometry of the first line in the turn, rotate and trim it
                var lineFeat = rac.GetRow((int)turnFeat.get_Value(edgeFIDFields[0])) as IFeature;
                var featCurve = lineFeat.ShapeCopy as ICurve;
                ICurve workingCurve = null;
                switch ((string)turnFeat.get_Value(edge1EndField))
                {
                    case "Y":
                        featCurve.GetSubcurve(1.0 - trimRatio, 1.0, true, out workingCurve);
                        break;
                    case "N":
                        featCurve.GetSubcurve(0.0, trimRatio, true, out workingCurve);
                        workingCurve.ReverseOrientation();
                        break;
                    default:
                        messages.AddWarning("ERROR: Invalid Edge1End value!  Turn OID: " + turnFeat.OID);
                        break;
                }
                if (workingCurve == null)
                {
                    continue;
                }

                // Create a new polyline and add the trimmed first line to it
                var segColl = new PolylineClass() as ISegmentCollection;
                segColl.AddSegmentCollection(workingCurve as ISegmentCollection);

                // Remember the last point of the curve
                IPoint lastCurveEnd = workingCurve.ToPoint;

                bool earlyExit = false;
                for (int i = 1; i < numAltIDFields; i++)
                {
                    if ((int)turnFeat.get_Value(edgeFCIDFields[i]) != streetsFCID)
                    {
                        // This was the last part of the turn -- break out and finalize the geometry
                        break;
                    }

                    // Otherwise get the geometry of this line in the turn, rotate it if necessary,
                    // and add it to the segment collection
                    lineFeat = rac.GetRow((int)turnFeat.get_Value(edgeFIDFields[i])) as IFeature;
                    var poly = lineFeat.ShapeCopy as IPolycurve;
                    bool splitHappened;
                    int newPart, newSeg;
                    poly.SplitAtDistance(0.5, true, false, out splitHappened, out newPart, out newSeg);
                    featCurve = poly as ICurve;
                    IPoint myPoint = featCurve.FromPoint;
                    if (EqualPoints(myPoint, lastCurveEnd))
                    {
                        segColl.AddSegmentCollection(featCurve as ISegmentCollection);
                    }
                    else
                    {
                        myPoint = featCurve.ToPoint;
                        if (EqualPoints(myPoint, lastCurveEnd))
                        {
                            featCurve.ReverseOrientation();
                            segColl.AddSegmentCollection(featCurve as ISegmentCollection);
                        }
                        else
                        {
                            messages.AddWarning("ERROR: Edge " + (i+1) + " is discontinuous with the previous curve!  Turn OID: " + turnFeat.OID);
                            earlyExit = true;
                            break;
                        }
                    }

                    // Remember the length of the last curve added, and the last point of the curve
                    lastCurveLength = featCurve.Length;
                    lastCurveEnd = featCurve.ToPoint;
                }
                // If the edges of the turn were read in successfully...
                if (!earlyExit)
                {
                    // Trim the segment such that the last curve is the length of the trim ratio
                    workingCurve = segColl as ICurve;
                    workingCurve.GetSubcurve(0.0, workingCurve.Length - ((1.0 - trimRatio) * lastCurveLength), false, out featCurve);
                    turnFeat.Shape = featCurve as IGeometry;

                    // Write out the turn geometry and increment the count
                    featCursor.UpdateFeature(turnFeat);
                    numFeatures++;

                    if ((numFeatures % 100) == 0)
                    {
                        // check for user cancel

                        if (trackcancel != null && !trackcancel.Continue())
                            throw (new COMException("Function cancelled."));
                    }
                }
            }
        }
        public override void Draw(esriDrawPhase drawPhase, IDisplay display, ITrackCancel trackCancel)
        {
            switch (drawPhase)
            {
                case esriDrawPhase.esriDPGeography:
                    if (Valid)
                    {
                        if (Visible)
                        {
                                Logger.Debug("Draw event Layer name: " + Name);
                                var activeView = (IActiveView)_map;
                                var clipEnvelope = display.ClipEnvelope;
                                Logger.Debug("Layer spatial reference: " + SpatialReference.FactoryCode);
                                Logger.Debug("Map spatial reference: " + _map.SpatialReference.FactoryCode);
                                var mapWidth = activeView.ExportFrame.right;
                                var resolution = clipEnvelope.GetMapResolution(mapWidth);
                                var ext = new Extent(clipEnvelope.XMin, clipEnvelope.YMin, clipEnvelope.XMax, clipEnvelope.YMax);
                                //_fetcher.ViewChanged(ext, resolution);
                                _simplefilefetcher.Fetch(ext,resolution);
                                var level = Utilities.GetNearestLevel(_tileSource.Schema.Resolutions, resolution);
                                var tileInfos = _tileSource.Schema.GetTilesInView(ext, level);
                                tileInfos = SortByPriority(tileInfos, ext.CenterX, ext.CenterY);

                                foreach (var tileInfo in tileInfos)
                                {
                                    var tile = _fileCache.Find(tileInfo.Index);
                                    if (tile != null)
                                    {
                                        var filename = _fileCache.GetFileName(tileInfo.Index);
                                        DrawRaster(filename, display);
                                    }
                                }

                        }
                    }
                    break;
                case esriDrawPhase.esriDPAnnotation:
                    break;
            }
        }
        public static Hashtable FillFeatureCache(ITable inputSignsTable, int inFromIDFI, int inToIDFI,
                                                 IFeatureClass inputLineFeatures, string linesIDFieldName,
                                                 ITrackCancel trackcancel)
        {
            // make and fill a SortedList from the IDs referenced in the table

            // for MultiNet data, there is only one ID field, so its index will be
            // passed in as inFromIDFI, while -1 will be passed in to inToIDFI.

            SortedList IDs = new System.Collections.SortedList();

            ICursor inCursor = inputSignsTable.Search(null, true);
            IRow row;

            long fromID, toID;
            bool exists;
            int cancelCheckInterval = 100;

            if (inToIDFI == -1)
            {
                while ((row = inCursor.NextRow()) != null)
                {
                    fromID = Convert.ToInt64(row.get_Value(inFromIDFI));

                    exists = IDs.Contains(fromID);
                    if (!exists)
                        IDs.Add(fromID, fromID);
                }
            }
            else
            {
                while ((row = inCursor.NextRow()) != null)
                {
                    fromID = Convert.ToInt64(row.get_Value(inFromIDFI));
                    toID = Convert.ToInt64(row.get_Value(inToIDFI));

                    exists = IDs.Contains(fromID);
                    if (!exists)
                        IDs.Add(fromID, fromID);

                    exists = IDs.Contains(toID);
                    if (!exists)
                        IDs.Add(toID, toID);
                }
            }

            // make the query filter for fetching features

            IQueryFilter queryFilter = new QueryFilterClass();
            queryFilter.SubFields = "*";

            // Now fetch batches of features

            long currID;
            int numFeaturesPerQuery = 200;
            int numToFetch = IDs.Count;
            int totalRemaining, totalDone = 0;

            int linesIDFieldIndex = inputLineFeatures.FindField(linesIDFieldName);

            Hashtable outputFeatures = new System.Collections.Hashtable((int)numToFetch);

            if (numFeaturesPerQuery > numToFetch)
                numFeaturesPerQuery = numToFetch;

            while (totalDone < numToFetch)
            {
                // Populate the QueryDef Where clause IN() statement for the current batch of features.
                // This is going to be very slow unless linesIDFieldName is indexed and this is why
                // we added a warning to the GP message window if this is the case.  If you cannot
                // index linesIDFieldName, then this code would run faster scanning the whole feature
                // class looking for the records we need (no Where clause).

                string whereClause = linesIDFieldName + " IN(";

                for (int i = 0; i < numFeaturesPerQuery; i++)
                {
                    currID = Convert.ToInt64(IDs.GetByIndex(totalDone + i), System.Globalization.CultureInfo.InvariantCulture);
                    whereClause += Convert.ToString(currID, System.Globalization.CultureInfo.InvariantCulture);
                    if (i != (numFeaturesPerQuery - 1))
                        whereClause += ",";
                    else
                        whereClause += ")";
                }

                queryFilter.WhereClause = whereClause;

                // select the features

                IFeatureCursor inputFeatureCursor = inputLineFeatures.Search(queryFilter, false);

                // get the features

                IFeature feature;

                while ((feature = inputFeatureCursor.NextFeature()) != null)
                {
                    // keep a copy of the OID and shape of feature - skip records that cause errors
                    // (perhaps pass the GPMessages in and log warnings in there if you need to log exceptions)

                    try
                    {
                        FeatureData data = new FeatureData(feature.OID, feature.ShapeCopy);
                        outputFeatures.Add(Convert.ToInt64(feature.get_Value(linesIDFieldIndex)), data);
                    }
                    catch
                    {
                    }

                    if ((totalDone % cancelCheckInterval) == 0)
                    {
                        // check for user cancel

                        if (trackcancel != null && !trackcancel.Continue())
                            throw (new COMException("Function cancelled."));
                    }
                }

                // finished? set up for next batch

                totalDone += numFeaturesPerQuery;

                totalRemaining = numToFetch - totalDone;
                if (totalRemaining > 0)
                {
                    if (numFeaturesPerQuery > totalRemaining)
                        numFeaturesPerQuery = totalRemaining;
                }
            }

            return outputFeatures;
        }
    /// <summary>
    /// Draws the layer to the specified display for the given draw phase. 
    /// </summary>
    /// <param name="drawPhase"></param>
    /// <param name="Display"></param>
    /// <param name="trackCancel"></param>
    /// <remarks>the draw method is set as an abstract method and therefore must be overridden</remarks>
		public override void Draw(esriDrawPhase drawPhase, IDisplay Display, ITrackCancel trackCancel)
		{
			if(drawPhase != esriDrawPhase.esriDPGeography) return;
			if(Display == null) return;
			if(m_table == null || m_symbolTable == null) return;

			m_display = Display;
			
			IEnvelope envelope = Display.DisplayTransformation.FittedBounds as IEnvelope;	
			
			double lat, lon;
			int iconCode;
			bool selected;
			ISymbol symbol = null;

			//loop through the rows. Draw each row that has a shape
			foreach (DataRow row in m_table.Rows)
			{
				//get the Lat/Lon of the item
				lat = Convert.ToDouble(row[3]);
				lon = Convert.ToDouble(row[4]);
				//get the icon ID
				iconCode = Convert.ToInt32(row[8]);

				//get the selection state of the item
				selected = Convert.ToBoolean(row[13]);
				
				if(lon >= envelope.XMin && lon <= envelope.XMax && lat >= envelope.YMin && lat <= envelope.YMax) 
				{	
					//search for the symbol in the symbology table
					symbol = GetSymbol(iconCode, row);
					if(null == symbol)
						continue;

          m_point.X = lon;
          m_point.Y = lat;
          m_point.SpatialReference = m_spatialRef;

					//reproject the point to the DataFrame's spatial reference
					if (null != m_mapSpatialRef && m_mapSpatialRef.FactoryCode != m_layerSRFactoryCode)
            m_point.Project(m_mapSpatialRef);

					Display.SetSymbol(symbol);
          Display.DrawPoint(m_point);

					if(selected)
					{
						Display.SetSymbol(m_selectionSymbol);
            Display.DrawPoint(m_point);
					}
				}
			}
		}
Example #48
0
        /// <summary>
        /// 运行GP工具箱
        /// </summary>
        /// <param name="geoprocessor"></param>
        /// <param name="process"></param>
        /// <param name="TC"></param>
        private static void RunTool(Geoprocessor geoprocessor, IGPProcess process, ITrackCancel TC)
        {
            // Set the overwrite output option to true
            geoprocessor.OverwriteOutput = true;

            try
            {
                geoprocessor.Execute(process, null);
                ReturnMessages(geoprocessor);

            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
                ReturnMessages(geoprocessor);
            }
        }
        public bool UpdateHistoryOnLines(ITable pLinesTable, ITable pPointsTable,
         int iParcelCount, ICadastralFabric pCadFabric, List<string> sOIDList, 
      Dictionary<int, string> ParcelToHistory_DICT, IStepProgressor m_pStepProgressor, ITrackCancel m_pTrackCancel)
        {
            bool m_bShowProgressor = (iParcelCount > 10);
              sOIDList.Add("");
              int tokenLimit = 995;
              bool bCont = true;
              int j = 0;
              int iCounter = 0;
              ICadastralFabricSchemaEdit2 pSchemaEd = null;

              try
              {
            #region update line table history
            //Get the line table history fields
            //SystemStart, SystemEnd, LegalStart, LegalEnd, Historic
            int iParcelID = pLinesTable.FindField("parcelid");
            string sParcelID = pLinesTable.Fields.get_Field(iParcelID).Name;

            int iLineSysStartDate = pLinesTable.FindField("systemstartdate");
            string sLineSysStartDate = pLinesTable.Fields.get_Field(iLineSysStartDate).Name;

            int iLineSysEndDate = pLinesTable.FindField("systemenddate");
            string sLineSysEndDate = pLinesTable.Fields.get_Field(iLineSysEndDate).Name;

            int iLineLegalStartDate = pLinesTable.FindField("legalstartdate");
            string sLineLegalStartDate = pLinesTable.Fields.get_Field(iLineLegalStartDate).Name;

            int iLineLegalEndDate = pLinesTable.FindField("legalenddate");
            string sLineLegalEndDate = pLinesTable.Fields.get_Field(iLineLegalEndDate).Name;

            int iLineHistorical = pLinesTable.FindField("historical");
            string sLineHistorical = pLinesTable.Fields.get_Field(iLineHistorical).Name;

            int iFromPoint = pLinesTable.FindField("frompointid");
            string sFromPoint = pLinesTable.Fields.get_Field(iFromPoint).Name;

            int iToPoint = pLinesTable.FindField("topointid");
            string sToPoint = pLinesTable.Fields.get_Field(iToPoint).Name;

            IQueryFilter pQueryFilter = new QueryFilterClass();
            pQueryFilter.SubFields = pLinesTable.OIDFieldName + ", parcelid," + sLineSysStartDate +
              "," + sLineSysEndDate + "," + sLineLegalStartDate + "," + sLineLegalEndDate +
              "," + sLineHistorical + "," + sFromPoint + "," + sToPoint;

            pSchemaEd = (ICadastralFabricSchemaEdit2)pCadFabric;
            pSchemaEd.ReleaseReadOnlyFields(pLinesTable, esriCadastralFabricTable.esriCFTLines); //release safety-catch

            Dictionary<int, string> PointToHistory_DICT = new Dictionary<int, string>(iParcelCount);

            List<string> sPointOIDList = new List<string>();
            List<int> iLinesOIDList = new List<int>();
            sPointOIDList.Add("");
            j = iCounter = 0;
            ICursor pCur = null;
            object obj = null;
            foreach (string sHistory in sOIDList)
            {
              if (sHistory.Trim() == "")
            continue;

              pQueryFilter.WhereClause = sParcelID + " IN (" + sHistory + ")";
              pCur = pLinesTable.Update(pQueryFilter, false);
              IRow pLine = pCur.NextRow();
              while (pLine != null)
              {
            //Check if the cancel button was pressed. If so, stop process
            if (m_bShowProgressor)
            {
              bCont = m_pTrackCancel.Continue();
              if (!bCont)
                break;
            }
            iLinesOIDList.Add(pLine.OID);
            string sParcHistory = "";
            if (ParcelToHistory_DICT.TryGetValue((int)pLine.get_Value(iParcelID), out sParcHistory))
            {
              string[] sHistoryItems = sParcHistory.Split(',');
              if (sHistoryItems[0].Trim() == "")
                obj = DBNull.Value;
              else
                obj = sHistoryItems[0];
              pLine.set_Value(iLineSysStartDate, obj);

              if (sHistoryItems[1].Trim() == "")
                obj = DBNull.Value;
              else
                obj = sHistoryItems[1];
              pLine.set_Value(iLineSysEndDate, obj);

              if (sHistoryItems[2].Trim() == "")
                obj = DBNull.Value;
              else
                obj = sHistoryItems[2];
              pLine.set_Value(iLineLegalStartDate, obj);

              if (sHistoryItems[3].Trim() == "")
                obj = DBNull.Value;
              else
                obj = sHistoryItems[3];
              pLine.set_Value(iLineLegalEndDate, obj);

              if (sHistoryItems[4].Trim() == "")
                obj = DBNull.Value;
              else
              {
                bool x = (sHistoryItems[4].Trim().ToLower() == "true") ? true : false;
                if (x)
                  obj = 1;
                else
                  obj = 0;
              }
              pLine.set_Value(iLineHistorical, obj);
              pLine.Store();

              int iVal = (int)pLine.get_Value(iToPoint);
              if (!PointToHistory_DICT.ContainsKey(iVal))
              {
                PointToHistory_DICT.Add(iVal, sParcHistory);

                if (iCounter <= tokenLimit)
                {
                  if (sPointOIDList[j].Trim() == "")
                    sPointOIDList[j] = Convert.ToString(iVal);
                  else
                    sPointOIDList[j] = sPointOIDList[j] + "," + Convert.ToString(iVal);
                  iCounter++;
                }
                else
                {//maximum tokens reached
                  iCounter = 0;
                  //set up the next OIDList
                  j++;
                  sPointOIDList.Add("");
                  sPointOIDList[j] = sPointOIDList[j] + Convert.ToString(iVal);
                }
              }
              else //if the point is here already
              {
                //Since the lines that have the shared points may have different
                //history these points need a different treatment. The approach in this code will make updates
                //in favour of non-historic data.
                UpdateHistoryOnPoints(pLine, iVal, PointToHistory_DICT, iLineSysEndDate,
                  iLineLegalEndDate, iLineHistorical);
              }

              iVal = (int)pLine.get_Value(iFromPoint);
              if (!PointToHistory_DICT.ContainsKey(iVal))
              {
                PointToHistory_DICT.Add(iVal, sParcHistory);

                if (iCounter <= tokenLimit)
                {
                  if (sPointOIDList[j].Trim() == "")
                    sPointOIDList[j] = Convert.ToString(iVal);
                  else
                    sPointOIDList[j] = sPointOIDList[j] + "," + Convert.ToString(iVal);
                  iCounter++;
                }
                else
                {//maximum tokens reached
                  iCounter = 0;
                  //set up the next OIDList
                  j++;
                  sPointOIDList.Add("");
                  sPointOIDList[j] = sPointOIDList[j] + Convert.ToString(iVal);
                }
              }
              else //if the point is here already
              {
                //Since the lines that have the shared points may have different
                //history these points need a different treatment. The approach in this code will make updates
                //in favour of non-historic data.
                UpdateHistoryOnPoints(pLine, iVal, PointToHistory_DICT, iLineSysEndDate,
                  iLineLegalEndDate, iLineHistorical);
              }
            }
            Marshal.ReleaseComObject(pLine);
            pLine = pCur.NextRow();
            if (m_bShowProgressor)
            {
              if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange)
                m_pStepProgressor.Step();
            }
              }
              Marshal.FinalReleaseComObject(pCur);
            }
            if (!bCont)
              return false;
            #endregion
            #region Find other lines connected to these points and Update the dictionary values
            //search back on lines with points list
            iLinesOIDList.Sort();
            foreach (string sPointsQuery in sPointOIDList)
            {
              if (sPointsQuery.Trim() == "")
            continue;
              pQueryFilter.WhereClause = sToPoint + " IN (" + sPointsQuery + ")";
              pCur = pLinesTable.Search(pQueryFilter, false);
              IRow pLine = pCur.NextRow();
              while (pLine != null)
              {
            int iPos = iLinesOIDList.BinarySearch(pLine.OID);
            if (iPos < 0) //not found < 0
            {//if this line is not in the original line list, its points are shared outside of
              //the original selection. Since the lines that have the shared points may have different
              //history these points need a different treatment. The approach in this code will make updates
              //in favour of non-historic parcels.
              int iVal = (int)pLine.get_Value(iFromPoint);
              UpdateHistoryOnPoints(pLine, iVal, PointToHistory_DICT, iLineSysEndDate,
                  iLineLegalEndDate, iLineHistorical);
              iVal = (int)pLine.get_Value(iToPoint);
              UpdateHistoryOnPoints(pLine, iVal, PointToHistory_DICT, iLineSysEndDate,
                  iLineLegalEndDate, iLineHistorical);
            }
            Marshal.FinalReleaseComObject(pLine);
            pLine = pCur.NextRow();
              }
              Marshal.FinalReleaseComObject(pCur);

              //Now redo the same search with the From point. These are separate searches because using OR with
              //2 separate in clauses is slow.

              pQueryFilter.WhereClause = sFromPoint + " IN (" + sPointsQuery + ")";
              pCur = pLinesTable.Search(pQueryFilter, false);
              pLine = pCur.NextRow();
              while (pLine != null)
              {
            int iPos = iLinesOIDList.BinarySearch(pLine.OID);
            if (iPos < 0) //not found < 0
            {//if this line is not in the original list, its points are shared outside of
              //the original selection and should be removed from the point update list
              int iVal = (int)pLine.get_Value(iFromPoint);
              UpdateHistoryOnPoints(pLine, iVal, PointToHistory_DICT, iLineSysEndDate,
                  iLineLegalEndDate, iLineHistorical);
              iVal = (int)pLine.get_Value(iToPoint);
              UpdateHistoryOnPoints(pLine, iVal, PointToHistory_DICT, iLineSysEndDate,
                  iLineLegalEndDate, iLineHistorical);
            }
            Marshal.FinalReleaseComObject(pLine);
            pLine = pCur.NextRow();
              }
              Marshal.FinalReleaseComObject(pCur);
            }
            #endregion
            #region Update the Points
            //update the points with the values in the dictionary.
            pSchemaEd.ReleaseReadOnlyFields(pPointsTable, esriCadastralFabricTable.esriCFTPoints);
            //declare the smaller points list
            List<string> sPointOIDSubsetList = new List<string>();
            sPointOIDSubsetList.Add("");
            iCounter = j = 0;

            foreach (KeyValuePair<int, String> entry in PointToHistory_DICT)
            {
              string s = entry.Key.ToString();
              if (iCounter <= tokenLimit)
              {
            if (sPointOIDSubsetList[j].Trim() == "")
              sPointOIDSubsetList[j] = s;
            else
              sPointOIDSubsetList[j] = sPointOIDSubsetList[j] + "," + s;
            iCounter++;
              }
              else
              {//maximum tokens reached
            iCounter = 0;
            //set up the next OIDList
            j++;
            sPointOIDSubsetList.Add("");
            sPointOIDSubsetList[j] = sPointOIDSubsetList[j] + s;
              }
            }

            //Get the point table history fields
            //SystemStart, SystemEnd, LegalStart, LegalEnd, Historic
            int iPointSysStartDate = pPointsTable.FindField("systemstartdate");
            string sPointSysStartDate = pPointsTable.Fields.get_Field(iPointSysStartDate).Name;

            int iPointSysEndDate = pPointsTable.FindField("systemenddate");
            string sPointSysEndDate = pPointsTable.Fields.get_Field(iPointSysEndDate).Name;

            int iPointLegalStartDate = pPointsTable.FindField("legalstartdate");
            string sPointLegalStartDate = pPointsTable.Fields.get_Field(iPointLegalStartDate).Name;

            int iPointLegalEndDate = pPointsTable.FindField("legalenddate");
            string sPointLegalEndDate = pPointsTable.Fields.get_Field(iPointLegalEndDate).Name;

            int iPointHistorical = pPointsTable.FindField("historical");
            string sPointHistorical = pPointsTable.Fields.get_Field(iPointHistorical).Name;

            string sOIDFld = pPointsTable.OIDFieldName;
            pQueryFilter.SubFields = sOIDFld + "," + sPointSysStartDate +
              "," + sPointSysEndDate + "," + sPointLegalStartDate + "," + iPointLegalEndDate +
              "," + sPointHistorical;

            foreach (string sPointsQuery in sPointOIDSubsetList)
            {
              if (sPointsQuery.Trim() == "")
            continue;
              pQueryFilter.WhereClause = sOIDFld + " IN (" + sPointsQuery + ")";
              pCur = pPointsTable.Update(pQueryFilter, false);
              IRow pPoint = pCur.NextRow();
              while (pPoint != null)
              {
            //Check if the cancel button was pressed. If so, stop process
            if (m_bShowProgressor)
            {
              bCont = m_pTrackCancel.Continue();
              if (!bCont)
                break;
            }
            string sPointHistory = "";
            if (PointToHistory_DICT.TryGetValue((int)pPoint.OID, out sPointHistory))
            {
              string[] sHistoryItems = sPointHistory.Split(',');
              if (sHistoryItems[0].Trim() == "")
                obj = DBNull.Value;
              else
                obj = sHistoryItems[0];
              pPoint.set_Value(iPointSysStartDate, obj);

              if (sHistoryItems[1].Trim() == "")
                obj = DBNull.Value;
              else
                obj = sHistoryItems[1];
              pPoint.set_Value(iPointSysEndDate, obj);

              if (sHistoryItems[2].Trim() == "")
                obj = DBNull.Value;
              else
                obj = sHistoryItems[2];
              pPoint.set_Value(iPointLegalStartDate, obj);

              if (sHistoryItems[3].Trim() == "")
                obj = DBNull.Value;
              else
                obj = sHistoryItems[3];
              pPoint.set_Value(iPointLegalEndDate, obj);

              if (sHistoryItems[4].Trim() == "")
                obj = DBNull.Value;
              else
              {
                bool x = (sHistoryItems[4].Trim().ToLower() == "true") ? true : false;
                if (x)
                  obj = 1;
                else
                  obj = 0;
              }
              pPoint.set_Value(iPointHistorical, obj);
              pPoint.Store();
            }
            Marshal.ReleaseComObject(pPoint);
            pPoint = pCur.NextRow();
            if (m_bShowProgressor)
            {
              if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange)
                m_pStepProgressor.Step();
            }
              }
              Marshal.FinalReleaseComObject(pCur);
              if (!bCont)
            return false;
              else
            return true;
            }
            #endregion
            if (!bCont)
              return false;
            else
              return true;
              }

              catch (Exception ex)
              {
            MessageBox.Show(ex.Message);
            return false;
              }

              finally
              {
            pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints);//set safety back on
            pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTLines);//set safety back on
              }
        }
        private void BuildSpatialIndex(IGPValue gpFeatureClass, Geoprocessor.Geoprocessor geoProcessor, IGPUtilities gpUtil,
            ITrackCancel trackCancel, IGPMessages message)
        {
            if ((gpFeatureClass == null) || (geoProcessor == null) || (gpUtil == null))
                return;

            // Check if the feature class supports spatial index grids
            IFeatureClass fc = gpUtil.OpenDataset(gpFeatureClass) as IFeatureClass;
            if (fc == null)
                return;

            int idxShapeField = fc.FindField(fc.ShapeFieldName);
            if (idxShapeField >= 0)
            {
                IField shapeField = fc.Fields.get_Field(idxShapeField);
                if (shapeField.GeometryDef.GridCount > 0)
                {
                    if (shapeField.GeometryDef.get_GridSize(0) == -2.0)
                        return;
                }
            }

            // Create the new spatial index grid
            bool storedOriginal = geoProcessor.AddOutputsToMap;

            try
            {
                geoProcessor.AddOutputsToMap = false;

                DataManagementTools.CalculateDefaultGridIndex calculateDefaultGridIndex =
                    new DataManagementTools.CalculateDefaultGridIndex(gpFeatureClass);
                IGeoProcessorResult2 gpResults2 =
                    geoProcessor.Execute(calculateDefaultGridIndex, trackCancel) as IGeoProcessorResult2;
                message.AddMessages(gpResults2.GetResultMessages());

                if (gpResults2 != null)
                {
                    DataManagementTools.RemoveSpatialIndex removeSpatialIndex =
                        new DataManagementTools.RemoveSpatialIndex(gpFeatureClass.GetAsText());
                    removeSpatialIndex.out_feature_class = gpFeatureClass.GetAsText();
                    gpResults2 = geoProcessor.Execute(removeSpatialIndex, trackCancel) as IGeoProcessorResult2;
                    message.AddMessages(gpResults2.GetResultMessages());

                    DataManagementTools.AddSpatialIndex addSpatialIndex =
                        new DataManagementTools.AddSpatialIndex(gpFeatureClass.GetAsText());
                    addSpatialIndex.out_feature_class = gpFeatureClass.GetAsText();

                    addSpatialIndex.spatial_grid_1 = calculateDefaultGridIndex.grid_index1;
                    addSpatialIndex.spatial_grid_2 = calculateDefaultGridIndex.grid_index2;
                    addSpatialIndex.spatial_grid_3 = calculateDefaultGridIndex.grid_index3;

                    gpResults2 = geoProcessor.Execute(addSpatialIndex, trackCancel) as IGeoProcessorResult2;
                    message.AddMessages(gpResults2.GetResultMessages());
                }
            }
            catch (Exception ex)
            {
                message.AddWarning(ex.Message);
            }
            finally
            {
                geoProcessor.AddOutputsToMap = storedOriginal;
            }
        }
Example #51
0
        public void Draw(esriDrawPhase drawPhase, IDisplay display, ITrackCancel trackCancel)
        {
            switch (drawPhase)
            {
                case esriDrawPhase.esriDPGeography:
                    if (Valid)
                    {
                        if (Visible)
                        {
                            try
                            {
                                var clipEnvelope = display.ClipEnvelope;

                                // when loading from a file the active map doesn't exist yet
                                // so just deal with it here.
                                if (_map == null)
                                {
                                    var mxdoc = (IMxDocument)_application.Document;
                                    _map = mxdoc.FocusMap;
                                }

                                Debug.WriteLine("Draw event");
                                var activeView = _map as IActiveView;
                                Logger.Debug("Layer name: " + Name);

                                if (activeView != null)
                                {
                                    //_envelope = activeView.Extent;
                                    _envelope = clipEnvelope;

                                    Logger.Debug("Draw extent: xmin:" + _envelope.XMin +
                                                 ", ymin:" + _envelope.YMin +
                                                 ", xmax:" + _envelope.XMax +
                                                 ", ymax:" + _envelope.YMax
                                        );
                                    if (SpatialReference != null)
                                    {
                                        Logger.Debug("Layer spatial reference: " + SpatialReference.FactoryCode);
                                    }
                                    if (_map.SpatialReference != null)
                                    {
                                        Logger.Debug("Map spatial reference: " + _map.SpatialReference.FactoryCode);
                                    }

                                    var bruTileHelper = new BruTileHelper(_tileTimeOut);
                                    //_displayFilter.Transparency = (short)(255 - ((_transparency * 255) / 100));
                                    //if (display.Filter == null)
                                    //{
                                    //    display.Filter = _displayFilter;
                                    //}
                                    var fileCache = CacheDirectory.GetFileCache(_cacheDir,_config,_enumBruTileLayer);
                                    bruTileHelper.Draw(_application.StatusBar.ProgressBar, activeView, fileCache, trackCancel, SpatialReference, ref _currentLevel, _tileSource, display);
                                }
                            }
                            catch (Exception ex)
                            {
                                var mbox = new ExceptionMessageBox(ex);
                                mbox.Show(null);
                            }
                        } // isVisible
                    }  // isValid
                    break;
                case esriDrawPhase.esriDPAnnotation:
                    break;
            }
        }
        /// <summary>
        /// Uses MatchTable to rematch addresses in a feature class
        /// </summary>
        /// <param name="pInputTable">Input table containing addresses</param>
        /// <param name="inputFieldNames">In put tables fields</param>
        /// <param name="inputJoinFieldName">Input join field name</param>
        /// <param name="resultTable">The rematch result table</param>
        /// <param name="outputFieldNames">Output field names</param>
        /// <param name="outputJoinFieldName">Output join field name</param>
        /// <param name="whereClause">Where Clause for the Match Table method</param>
        /// <param name="cancelTracker"></param>
        public void RematchTable(ITable pInputTable, string inputFieldNames, string inputJoinFieldName, IFeatureClass resultTable,
          string outputFieldNames, string outputJoinFieldName, string whereClause, ITrackCancel cancelTracker)
        {
            _log.Debug("IBatchGeocoding RematchTable");

              if (inputJoinFieldName == null && inputJoinFieldName == "")
              inputJoinFieldName = pInputTable.OIDFieldName;

              if (outputJoinFieldName == null && outputJoinFieldName == "")
              outputJoinFieldName = resultTable.OIDFieldName;

              // Setup the edit session
              IWorkspaceEdit workspaceEdit = setupEditSession(resultTable);
              IPropertySet fieldsToCopy = new PropertySetClass();

              try
              {
              m_needToUpdate = true;
              MatchTable(pInputTable, inputFieldNames, whereClause, resultTable, outputFieldNames, fieldsToCopy, cancelTracker);
              m_needToUpdate = false;
              }
              catch (Exception e)
              {
              m_needToUpdate = false;
              workspaceEdit.AbortEditOperation();
              workspaceEdit.StopEditing(false);
              throw new Exception("Failed to Rematch the table. ", e);
              }

              workspaceEdit.StopEditOperation();
              workspaceEdit.StopEditing(true);
        }
        public void Execute(IArray paramvalues, ITrackCancel TrackCancel, IGPEnvironmentManager envMgr, IGPMessages message)
        {
            IAoInitialize aoInitialize = new AoInitializeClass();
            esriLicenseStatus naStatus = esriLicenseStatus.esriLicenseUnavailable;

            IGPUtilities2 gpUtil = null;
            IDataset osmDataset = null;

            try
            {
                if (!aoInitialize.IsExtensionCheckedOut(esriLicenseExtensionCode.esriLicenseExtensionCodeNetwork))
                    naStatus = aoInitialize.CheckOutExtension(esriLicenseExtensionCode.esriLicenseExtensionCodeNetwork);

                gpUtil = new GPUtilitiesClass();

                // OSM Dataset Param
                IGPParameter osmDatasetParam = paramvalues.get_Element(in_osmFeatureDataset) as IGPParameter;
                IDEDataset2 osmDEDataset = gpUtil.UnpackGPValue(osmDatasetParam) as IDEDataset2;
                if (osmDEDataset == null)
                {
                    message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), osmDatasetParam.Name));
                    return;
                }

                osmDataset = gpUtil.OpenDatasetFromLocation(((IDataElement)osmDEDataset).CatalogPath) as IDataset;

                // Network Config File Param
                IGPParameter osmNetConfigParam = paramvalues.get_Element(in_NetworkConfigurationFile) as IGPParameter;
                IGPValue osmNetConfigFile = gpUtil.UnpackGPValue(osmNetConfigParam) as IGPValue;
                if ((osmNetConfigFile == null) || (string.IsNullOrEmpty(osmNetConfigFile.GetAsText())))
                {
                    message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), osmNetConfigParam.Name));
                    return;
                }

                // Target Network Dataset Param
                IGPParameter ndsParam = paramvalues.get_Element(out_NetworkDataset) as IGPParameter;
                IDataElement deNDS = gpUtil.UnpackGPValue(ndsParam) as IDataElement;
                if (deNDS == null)
                {
                    message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), ndsParam.Name));
                    return;
                }

                // Create Network Dataset
                using (NetworkDataset nd = new NetworkDataset(osmNetConfigFile.GetAsText(), osmDataset, deNDS.Name, message, TrackCancel))
                {
                    if (nd.CanCreateNetworkDataset())
                        nd.CreateNetworkDataset();
                }
            }
            catch (UserCancelException ex)
            {
                message.AddWarning(ex.Message);
            }
            catch (Exception ex)
            {
                message.AddError(120008, ex.Message);
#if DEBUG
                message.AddError(120008, ex.StackTrace);
#endif
            }
            finally
            {
                if (osmDataset != null)
                    ComReleaser.ReleaseCOMObject(osmDataset);

                if (naStatus == esriLicenseStatus.esriLicenseCheckedOut)
                    aoInitialize.CheckInExtension(esriLicenseExtensionCode.esriLicenseExtensionCodeNetwork);

                if (gpUtil != null)
                    ComReleaser.ReleaseCOMObject(gpUtil);

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }
        }
        /// <summary>
        /// Draws the input geometry using the specified colors.
        /// </summary>
        /// <param name="geometry">The input IGeometry to draw. Supported geometry types are GeometryBag, Polygon, Polyline, Point and Multipoint.</param>
        /// <param name="fillColor">An IRgbColor reference for the fill color</param>
        /// <param name="lineColor">An IRgbColor reference for the line or outline color</param>
        /// <param name="display">An IDisplay reference</param>
        /// <param name="cancelTracker">An ITrackCancel reference</param>
        private static void DrawGeometry(IGeometry geometry, IRgbColor fillColor, IRgbColor lineColor, IDisplay display, ITrackCancel cancelTracker)
        {
            bool continueDrawing = true;
            switch (geometry.GeometryType)
            {
                case esriGeometryType.esriGeometryBag:
                    {
                        IEnumGeometry enumGeometry = (IEnumGeometry)geometry;
                        IGeometry innerGeometry = enumGeometry.Next();
                        while (innerGeometry != null && continueDrawing == true)
                        {
                            DrawGeometry(innerGeometry, fillColor, lineColor, display, cancelTracker); // Recursive method call
                            innerGeometry = enumGeometry.Next();
                            if (cancelTracker != null)
                            {
                                continueDrawing = cancelTracker.Continue();
                            }
                        }
                        break;
                    }
                case esriGeometryType.esriGeometryPolygon:
                    {
                        // Set the input polygon geometry's symbol.
                        ISimpleFillSymbol fillSymbol = new SimpleFillSymbolClass();
                        fillSymbol.Color = (IColor)fillColor;
                        ILineSymbol lineSymbol = new SimpleLineSymbolClass();
                        lineSymbol.Color = lineColor;
                        fillSymbol.Outline = lineSymbol;

                        // Draw the input polygon geometry.
                        display.SetSymbol((ISymbol)fillSymbol);
                        display.DrawPolygon(geometry);
                        break;
                    }
                case esriGeometryType.esriGeometryPolyline:
                    {
                        // Set the input polyline geometry's symbol.
                        IMultiLayerLineSymbol multiLineSymbol = new MultiLayerLineSymbolClass();
                        ISimpleLineSymbol simpleLineSymbol1 = new SimpleLineSymbolClass();
                        ISimpleLineSymbol simpleLineSymbol2 = new SimpleLineSymbolClass();
                        simpleLineSymbol1.Width = 3;
                        simpleLineSymbol1.Color = fillColor;
                        simpleLineSymbol2.Width = 5;
                        simpleLineSymbol2.Color = lineColor;
                        multiLineSymbol.AddLayer((ILineSymbol)simpleLineSymbol2);
                        multiLineSymbol.AddLayer((ILineSymbol)simpleLineSymbol1);

                        // Draw the input polyline geometry.
                        display.SetSymbol((ISymbol)multiLineSymbol);
                        display.DrawPolyline(geometry);
                        break;
                    }
                case esriGeometryType.esriGeometryPoint:
                    {
                        // Set the input point geometry's symbol.
                        ISimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbolClass();
                        simpleMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
                        simpleMarkerSymbol.Size = 12;
                        simpleMarkerSymbol.Color = fillColor;
                        simpleMarkerSymbol.Outline = true;
                        simpleMarkerSymbol.OutlineColor = lineColor;

                        // Draw the input point geometry.
                        display.SetSymbol((ISymbol)simpleMarkerSymbol);
                        display.DrawPoint(geometry);
                        break;
                    }
                case esriGeometryType.esriGeometryMultipoint:
                    {
                        // Set the input multipoint geometry's symbol.
                        ISimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbolClass();
                        simpleMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
                        simpleMarkerSymbol.Size = 8;
                        simpleMarkerSymbol.Color = fillColor;
                        simpleMarkerSymbol.Outline = true;
                        simpleMarkerSymbol.OutlineColor = lineColor;

                        // Draw the input multipoint geometry.
                        display.SetSymbol((ISymbol)simpleMarkerSymbol);
                        display.DrawMultipoint(geometry);
                        break;
                    }
            }
        }
        public bool UpdateInconsistentHistoryOnParcels(ITable pParcelsTable, int iParcelCount, 
      ICadastralFabric pCadFabric, List<string> sOIDUpdateList, 
      Dictionary<int, string> ParcelToHistory_DICT, 
      IStepProgressor m_pStepProgressor, ITrackCancel m_pTrackCancel)
        {
            bool m_bShowProgressor = (iParcelCount > 10);
              bool bCont = true;
              ICadastralFabricSchemaEdit2 pSchemaEd=null;
              try
              {
              #region update line table history
            //Get the line table history fields
            //SystemStart, SystemEnd, LegalStart, LegalEnd, Historic

            int iParcelSysEndDate = pParcelsTable.FindField("systemenddate");
            string sParcelSysEndDate = pParcelsTable.Fields.get_Field(iParcelSysEndDate).Name;

            int iParcelHistorical = pParcelsTable.FindField("historical");
            string sParcelHistorical = pParcelsTable.Fields.get_Field(iParcelHistorical).Name;

            IQueryFilter pQueryFilter = new QueryFilterClass();
            pQueryFilter.SubFields = pParcelsTable.OIDFieldName + "," + sParcelSysEndDate + ","
              + sParcelHistorical;

            pSchemaEd = (ICadastralFabricSchemaEdit2)pCadFabric;
            pSchemaEd.ReleaseReadOnlyFields(pParcelsTable, esriCadastralFabricTable.esriCFTParcels); //release safety-catch

            ICursor pCur = null;
            object obj = null;
            foreach (string sOIDSet in sOIDUpdateList)
            {
              if (sOIDSet.Trim() == "")
            continue;

              pQueryFilter.WhereClause = pParcelsTable.OIDFieldName + " IN (" + sOIDSet + ")";
              pCur = pParcelsTable.Update(pQueryFilter, false);
              IRow pParcel = pCur.NextRow();
              while (pParcel != null)
              {
            //Check if the cancel button was pressed. If so, stop process
            if (m_bShowProgressor)
            {
              bCont = m_pTrackCancel.Continue();
              if (!bCont)
                break;
            }
            string sParcHistory = "";
            if (ParcelToHistory_DICT.TryGetValue((int)pParcel.OID, out sParcHistory))
            {
              string[] sHistoryItems = sParcHistory.Split(',');

              if (sHistoryItems[1].Trim() == "")
                obj = DBNull.Value;
              else
                obj = sHistoryItems[1];
              pParcel.set_Value(iParcelSysEndDate, obj);

              if (sHistoryItems[4].Trim() == "")
                obj = DBNull.Value;
              else
              {
                bool x = (sHistoryItems[4].Trim().ToLower() == "true") ? true : false;
                if (x)
                  obj = 1;
                else
                  obj = 0;
              }
              pParcel.set_Value(iParcelHistorical, obj);
              pParcel.Store();

            }
            Marshal.ReleaseComObject(pParcel);
            pParcel = pCur.NextRow();
            if (m_bShowProgressor)
            {
              if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange)
                m_pStepProgressor.Step();
            }
              }
              Marshal.FinalReleaseComObject(pCur);
            }
            if (!bCont)
              return false;
            else
              return true;
              #endregion
              }
              catch (Exception ex)
              {
            MessageBox.Show(ex.Message);
            return false;
              }
              finally
              {
            pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTParcels);//set safety back on
              }
        }
        bool FindEmptyPlans(ICadastralFabric Fabric, IStepProgressor StepProgressor,
      ITrackCancel TrackCancel, out IFIDSet EmptyPlans)
        {
            ICursor pPlansCur = null;
              ICursor pParcelCur = null;
              IFIDSet pEmptyPlansFIDSet = new FIDSetClass();
              List<int> pNonEmptyPlansList = new List<int>();
              IDataset pDS=(IDataset)Fabric;
              IWorkspace pWS = pDS.Workspace;

              ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS;
              string sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix);
              string sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix);

              try
              {
            ITable pPlansTable = Fabric.get_CadastralTable(esriCadastralFabricTable.esriCFTPlans);
            ITable pParcelsTable = Fabric.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels);

            ////build a list of ids for all the plans found via parcels
            //if a Personal GDB then don't try to use DISTINCT
            if (pWS.Type == esriWorkspaceType.esriLocalDatabaseWorkspace && pWS.PathName.ToLower().EndsWith(".mdb"))
            {
              pParcelCur = pParcelsTable.Search(null, false);
            }
            else
            {
              IQueryFilter pQuF = new QueryFilterClass();
              pQuF.SubFields = "PLANID";
              IQueryFilterDefinition2 queryFilterDef = (IQueryFilterDefinition2)pQuF;
              queryFilterDef.PrefixClause = "DISTINCT PLANID";
              pParcelCur = pParcelsTable.Search(pQuF, true); //Recycling set to true

            }

            Int32 iPlanIDX = pParcelCur.Fields.FindField("PLANID");
            IRow pParcRow = pParcelCur.NextRow();

            while (pParcRow != null)
            {
              //Create a collection of planIDs from Parcels table that we know are not empty
              Int32 iPlanID = -1;
              object Attr_val = pParcRow.get_Value(iPlanIDX);
              if (Attr_val != DBNull.Value)
              {
            iPlanID = (Int32)Attr_val;
            if (iPlanID > -1)
            {
              if (!pNonEmptyPlansList.Contains(iPlanID))
                pNonEmptyPlansList.Add(iPlanID);
            }
              }
              Marshal.ReleaseComObject(pParcRow);
              pParcRow = pParcelCur.NextRow();
            }

            if (pParcelCur != null)
              Marshal.FinalReleaseComObject(pParcelCur);

            pPlansCur = pPlansTable.Search(null, false);

            IRow pPlanRow = pPlansCur.NextRow();
            while (pPlanRow != null)
            {
              bool bFound = false;
              bFound = pNonEmptyPlansList.Contains(pPlanRow.OID);
              if (!bFound) //This plan was not found in our parcel-referenced plans
              {
            //check if this is the default map plan, so it can be excluded from deletion
            Int32 iPlanNameIDX = pPlanRow.Fields.FindField("NAME");
            string sPlanName = (string)pPlanRow.get_Value(iPlanNameIDX);
            if (sPlanName.ToUpper() != "<MAP>")
              pEmptyPlansFIDSet.Add(pPlanRow.OID);
              }
              Marshal.ReleaseComObject(pPlanRow);
              pPlanRow = pPlansCur.NextRow();
            }
            EmptyPlans = pEmptyPlansFIDSet;

            return true;
              }
              catch (Exception ex)
              {
            MessageBox.Show(Convert.ToString(ex.Message), "Find Empty Plans");
            EmptyPlans = null;
            return false;
              }
              finally
              {
            if (pParcelCur != null)
            {
              do { }
              while (Marshal.ReleaseComObject(pParcelCur) > 0);
            }

            if (pNonEmptyPlansList != null)
            {
              pNonEmptyPlansList.Clear();
              pNonEmptyPlansList = null;
            }

            if (pParcelCur != null)
            {
              do { }
              while (Marshal.ReleaseComObject(pParcelCur) > 0);
            }
              }
        }
        public bool ChangeDatesOnTable(ICursor pCursor, string FieldName, string sDate, bool Unversioned, 
      IStepProgressor m_pStepProgressor, ITrackCancel m_pTrackCancel)
        {
            bool bWriteNull = (sDate.Trim() == "");
              object dbNull = DBNull.Value;
              int FldIdx = pCursor.FindField(FieldName);
              int iSysEndDate = pCursor.FindField("systemenddate");
              int iHistorical = pCursor.FindField("historical");

              bool bIsSysEndDate = (FieldName.ToLower() == "systemenddate");
              bool bIsHistorical = (FieldName.ToLower() == "historical");
              bool bHasSysEndDateFld = (iSysEndDate > -1);
              bool bHasHistoricFld = (iHistorical > -1);

              bool bCont = true;
              bool m_bShowProgressor = (m_pStepProgressor != null);

              if (bWriteNull)
              {
            IField pfld = pCursor.Fields.get_Field(FldIdx);
            if (!pfld.IsNullable)
              return false;
              }

              DateTime localNow = DateTime.Now;

              IRow pRow = pCursor.NextRow();
              while (pRow != null)
              {
            //Check if the cancel button was pressed. If so, stop process
            if (m_bShowProgressor)
            {
              bCont = m_pTrackCancel.Continue();
              if (!bCont)
            break;
            }

            if (bWriteNull)
            {
              if (bIsHistorical) //if writing null to Historical field, use 0 instead
            pRow.set_Value(FldIdx, 0);
              else
            pRow.set_Value(FldIdx, dbNull);

              if (bIsHistorical && bHasSysEndDateFld)   // if writing null to Historical field
            pRow.set_Value(iSysEndDate, dbNull);   // then also Null system end date
              if (bIsSysEndDate && bHasHistoricFld)     // if writing null to SystemEndDate field
            pRow.set_Value(iHistorical, 0);            //then set the Historical flag to false = 0
            }
            else
            {
              pRow.set_Value(FldIdx, sDate);
              if (bIsSysEndDate && bHasHistoricFld)     // if writing date to SystemEndDate field
            pRow.set_Value(iHistorical, 1);            //then set the Historical flag to true = 1
            }

            if (Unversioned)
              pCursor.UpdateRow(pRow);
            else
              pRow.Store();

            Marshal.ReleaseComObject(pRow);
            pRow = pCursor.NextRow();
            if (m_bShowProgressor)
            {
              if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange)
            m_pStepProgressor.Step();
            }
              }
              Marshal.ReleaseComObject(pCursor);
              if (!bCont)
            return false;
              return true;
        }
        /// <summary>
        /// Geocodes a table of addresses
        /// </summary>
        /// <param name="addressTable">Input address table</param>
        /// <param name="addressFieldNames">Fields defined in the table</param>
        /// <param name="whereClause">Query filter where clause</param>
        /// <param name="outputFeatureClass">Output feature class for matched addresses</param>
        /// <param name="outputFieldNames">Output field names</param>
        /// <param name="fieldsToCopy"></param>
        /// <param name="cancelTracker"></param>
        public virtual void MatchTable(ITable addressTable, String addressFieldNames, String whereClause,
          IFeatureClass outputFeatureClass, String outputFieldNames, IPropertySet fieldsToCopy, ITrackCancel cancelTracker)
        {
            _log.Debug("IAddressGeocoding MatchTable");

              // Obtain the read and insert cursors
              IQueryFilter queryFilter = new QueryFilterClass();
              queryFilter.WhereClause = whereClause;
              ICursor readCursor = null;
              IFeatureCursor insertCursor = null;
              IFeatureCursor updateCursor = null;

              // m_needToUpdate will be True when a Rematch is being preformed
              if (m_needToUpdate)
              {
              // Create update cursor to update matched records
              updateCursor = outputFeatureClass.Update(queryFilter, false);
              if (isSameObject(addressTable, outputFeatureClass))
                  readCursor = updateCursor as ICursor;
              else
                  readCursor = addressTable.Search(queryFilter, true);
              }
              else
              {
              // Create insert cursor to add new records
              readCursor = addressTable.Search(queryFilter, true);
              insertCursor = outputFeatureClass.Insert(true);
              }

              int count = addressTable.RowCount(queryFilter);

              // Progress dialog setup
              IStepProgressor progressor = null;
              if (cancelTracker != null)
              progressor = cancelTracker.Progressor as IStepProgressor;
              IProgressStatistics progStats = cancelTracker as IProgressStatistics;
              if (progressor != null)
              {
              progressor.StepValue = 1;
              progressor.MaxRange = addressTable.RowCount(null);
              }

              // Separate the input field names
              string[] multilineFields = addressFieldNames.Split(',');

              // Read the first row and get the address field
              IRow row = readCursor.NextRow();

              Dictionary<int, string> addressFieldIndexes = new Dictionary<int, string>();

              // Get the index of each valid field
              for (int i = 0; i < multilineFields.Length; i++)
              {
              if (multilineFields[i].Trim().Length > 0)
                  addressFieldIndexes.Add(row.Fields.FindField(multilineFields[i].Trim()), multilineFields[i].Trim());
              }

              string address;
              IPropertySet addressProperties = new PropertySetClass();
              IPropertySet resultSet;
              IFeatureBuffer featureBuffer;
              object copyTo, copyFrom, key, value;

              // Get the name and value of all the properties in the property set
              fieldsToCopy.GetAllProperties(out copyTo, out copyFrom);
              string[] copyToArray = copyTo as string[];
              object[] copyFromArray = copyFrom as object[];
              string matchStatus = "U";

              // Populate the output feature class
              while (row != null)
              {
              featureBuffer = outputFeatureClass.CreateFeatureBuffer();
              foreach (KeyValuePair<int,string> entry in addressFieldIndexes)
              {
                  if (entry.Key != -1)
                      address = row.get_Value(entry.Key) as string;
                  else
                      address = row.get_Value(0) as string;

                  addressProperties.SetProperty(entry.Value, address);
              }

              resultSet = MatchAddress(addressProperties);

              // Get all of the fields and values of the result
              resultSet.GetAllProperties(out key, out value);
              string[] names = key as string[];
              object[] items = value as object[];

              // Output match fields and values
              // Insert the Feature into the output featureClass and get the next row
              if (m_needToUpdate)
              {
                  _log.Debug("IAddressGeocoding Updating Feature" + row.OID.ToString());

                  // Record is being rematched so find record to update
                  IFeature feature = outputFeatureClass.GetFeature(row.OID);

                  for (int i = 0; i < names.Length; i++)
                  {
                      if (names[i] == "Shape")
                          feature.Shape = items[i] as IGeometry;
                      else
                      {
                          if (names[i] == "Status")
                          {
                              matchStatus = items[i] as string;
                              feature.set_Value(outputFeatureClass.FindField(names[i]), items[i]);
                          }
                      }
                  }

                  // Set the match type
                  if (outputFeatureClass.FindField("Match_type") != -1)
                  {
                      feature.set_Value(outputFeatureClass.FindField("Match_type"), "A");
                  }

                  // Copy over values from address table
                  for (int j = 0; j < copyToArray.Length; j++)
                  {
                      feature.set_Value(outputFeatureClass.FindField(copyToArray[j]),
                      row.get_Value(addressTable.FindField(copyFromArray[j] as string)));
                  }

                  updateCursor.UpdateFeature(feature);
              }
              else
              {
                  // set shape and status of matched record
                  for (int i = 0; i < names.Length; i++)
                  {
                      if (names[i] == "Shape")
                          featureBuffer.Shape = items[i] as IGeometry;
                      else
                      {
                          if (names[i] == "Status")
                          matchStatus = items[i] as string;
                          featureBuffer.set_Value(outputFeatureClass.FindField(names[i]), items[i]);
                      }
                  }

                  // Set the match type
                  if (outputFeatureClass.FindField("Match_type") != -1)
                  {
                      featureBuffer.set_Value(outputFeatureClass.FindField("Match_type"), "A");
                  }

                  // Copy over values from address table
                  for (int j = 0; j < copyToArray.Length; j++)
                  {
                      try
                      {
                          featureBuffer.set_Value(outputFeatureClass.FindField(copyToArray[j]),
                              row.get_Value(addressTable.FindField(copyFromArray[j] as string)));
                      }
                      catch (Exception ex)
                      {
                          _log.Error("An error occurred copying values from the address table: " + ex.Message);
                      }
                  }

                  insertCursor.InsertFeature(featureBuffer);
              }

              row = readCursor.NextRow();

              // Update the MatchTable progress
              if (progStats != null)
              {
                  progStats.StepByValue(matchStatus);
                  progStats.Update();
              }
              if (cancelTracker != null)
              {
                  if (!cancelTracker.Continue())
                      break;
              }
              }

              _log.Debug("IAddressGeocoding MatchTable End of updating features.");

              // Clean up the cursors
              if (insertCursor != null)
              {
              insertCursor.Flush();
              Marshal.ReleaseComObject(insertCursor);
              }
              if (updateCursor != null)
              {
              updateCursor.Flush();
              Marshal.ReleaseComObject(updateCursor);
              }
              if (readCursor != null)
              Marshal.ReleaseComObject(readCursor);
        }
        private string retrieveAdditionalRelations(string osmID, ref ITrackCancel TrackCancel, ESRI.ArcGIS.Geodatabase.IGPMessages message, IGPString baseURLString, HttpWebRequest httpClient, ref HttpWebResponse httpResponse)
        {
            string osmDocumentLocation = String.Empty;

            try
            {
                if (TrackCancel.Continue() == false)
                {
                    return osmDocumentLocation;
                }

                httpClient = HttpWebRequest.Create(baseURLString.Value + "/api/0.6/relation/" + osmID + "/full") as HttpWebRequest;
                httpClient = AssignProxyandCredentials(httpClient);

                httpResponse = httpClient.GetResponse() as HttpWebResponse;

                osmDocumentLocation = System.IO.Path.GetTempFileName();

                using (System.IO.FileStream fileStream = new System.IO.FileStream(osmDocumentLocation, FileMode.Append, FileAccess.Write))
                {
                    using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        UTF8Encoding encoding = new UTF8Encoding();

                        byte[] byteBuffer = encoding.GetBytes(streamReader.ReadToEnd());
                        fileStream.Write(byteBuffer, 0, byteBuffer.Length);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                message.AddWarning(ex.Message);

                if (ex is WebException)
                {
                    WebException webException = ex as WebException;
                    string serverErrorMessage = webException.Response.Headers["Error"];
                    if (!String.IsNullOrEmpty(serverErrorMessage))
                    {
                        message.AddWarning(serverErrorMessage);
                    }
                }

            }

            return osmDocumentLocation;
        }
Example #60
0
        private static bool RunTool(Geoprocessor geoprocessor, IGPProcess process, ITrackCancel TC)
        {
            // Set the overwrite output option to true
            geoprocessor.OverwriteOutput = true;

            // Execute the tool
            try
            {
                geoprocessor.Execute(process, null);
                return ReturnMessages(geoprocessor);

            }
            catch (Exception err)
            {
                Debug.WriteLine(err.Message);
                ReturnMessages(geoprocessor);
            }
            return false;
        }