protected override void OnUpdate()
        {
            CustomizelHelperExtension v = CustomizelHelperExtension.GetExtension();

            if (m_pEd == null)
            {
                m_pEd = v.TheEditor;
            }
            if (m_pCadExtMan == null)
            {
                m_pCadExtMan = v.TheCadastralExtensionManager;
            }

            bool bEnabled = (m_pEd.EditState == esriEditState.esriStateEditing);

            ICadastralPacketManager pCadPacMan = (ICadastralPacketManager)m_pCadExtMan;

            if (pCadPacMan.PacketOpen)
            {
                this.Enabled = false;
            }
            else
            {
                this.Enabled = bEnabled;
            }

            v.CommandIsEnabled = this.Enabled;
        }
Exemple #2
0
        protected override void OnClick()
        {
            IEditor pEd = (IEditor)ArcMap.Application.FindExtensionByName("esriEditor.Editor");

            if (pEd.EditState == esriEditState.esriStateNotEditing)
            {
                MessageBox.Show("Please start editing and try again.");
                return;
            }

            ICadastralEditor    pCadEd         = (ICadastralEditor)ArcMap.Application.FindExtensionByName("esriCadastralUI.CadastralEditorExtension");
            IParcelEditManager  pParcEditorMan = (IParcelEditManager)pCadEd;
            ICadastralSelection pCadaSel       = (ICadastralSelection)pCadEd;

            try
            {
                ICadastralPacketManager pCadPacketMan = (ICadastralPacketManager)pCadEd;
                bool bStartedWithPacketOpen           = pCadPacketMan.PacketOpen;
                if (!bStartedWithPacketOpen)
                {
                    pEd.StartOperation();
                }

                //1. Start map edit session
                ICadastralMapEdit pCadMapEdit = (ICadastralMapEdit)pCadEd;
                pCadMapEdit.StartMapEdit(esriMapEditType.esriMEParcelSelection, "Merge Parcel", false);

                //2.	Get job packet
                ICadastralPacket pCadaPacket = pCadPacketMan.JobPacket;

                //3.	Create Plan (new)
                string sPlanName = "My New Plan";

                //first check to ensure plan is not already in the database.
                IGSPlan        pGSPlan   = FindFabricPlanByName(sPlanName, pCadEd);
                ICadastralPlan pCadaPlan = (ICadastralPlan)pCadaPacket;
                if (pGSPlan == null)
                {
                    //if plan is null, it was not found and can be created
                    pGSPlan = new GSPlanClass();
                    // 3.a set values
                    pGSPlan.Accuracy        = 4;
                    pGSPlan.Name            = sPlanName;
                    pGSPlan.DirectionFormat = esriDirectionType.esriDTQuadrantBearing;
                    pGSPlan.AngleUnits      = esriDirectionUnits.esriDUDegreesMinutesSeconds;
                    pGSPlan.AreaUnits       = esriCadastralAreaUnits.esriCAUAcre;
                    pGSPlan.Description     = "My Test Plan for Merge";
                    pGSPlan.DistanceUnits   = esriCadastralDistanceUnits.esriCDUFoot;
                }

                //3.b Add the plan to the job packet
                pCadaPlan.AddPlan(pGSPlan);

                ICadastralPoints           pCadaPoints           = (ICadastralPoints)pCadaPacket;
                IConstructParcelFunctions3 constrParcelFunctions = new ParcelFunctions() as IConstructParcelFunctions3;

                IEnumGSParcels selectedParcels = pCadaSel.SelectedParcels; //get selected parcels AFTER calling ::StartMapEdit to get the in-mem packet representation.
                IGSParcel      gsParcel        = constrParcelFunctions.MergeParcels(pGSPlan, pCadaPoints, selectedParcels, pCadaPacket);
                gsParcel.Type = 7;                                         //7 = Tax parcel in the Local Government Information Model
                gsParcel.Lot  = "My Merged Tax Parcel";

                ICadastralObjectSetup pCadaObjSetup = (ICadastralObjectSetup)pParcEditorMan;
                //Make sure that any extended attributes on the new merged parcel have their default values set
                IGSAttributes pGSAttributes = (IGSAttributes)gsParcel;
                pCadaObjSetup.AddExtendedAttributes(pGSAttributes);
                pCadaObjSetup.SetDefaultValues(pGSAttributes);

                ICadastralParcel pCadaParcel = (ICadastralParcel)pCadaPacket;
                pCadaParcel.AddParcel(gsParcel);

                //set the original parcels to historic
                selectedParcels.Reset();
                IGSParcel selParcel = selectedParcels.Next();
                while (selParcel != null)
                {
                    selParcel.Historical = true;
                    //set SystemEndDate
                    pGSAttributes = (IGSAttributes)selParcel;
                    if (pGSAttributes != null)
                    {
                        pGSAttributes.SetProperty("systemenddate", DateTime.Now);
                    }
                    selParcel = selectedParcels.Next();
                }

                try
                {
                    pCadMapEdit.StopMapEdit(true);
                }
                catch
                {
                    if (!bStartedWithPacketOpen)
                    {
                        pEd.AbortOperation();
                    }
                    return;
                }
                if (!bStartedWithPacketOpen)
                {
                    pEd.StopOperation("Merge Parcel");
                }
                pCadPacketMan.PartialRefresh();
            }
            catch (Exception ex)
            {
                pEd.AbortOperation();
                MessageBox.Show(ex.Message);
            }
        }
        private void CreateParcelFromSegmentCollection(ISegmentCollection Segments, string PlanName)
        {
            int iCnt = Segments.SegmentCount;

            ISegment[] pSegmentArr = new ISegment[iCnt];
            for (int j = 0; j < iCnt; j++)
            {
                pSegmentArr[j] = Segments.get_Segment(j);
            }

            ICadastralEditor   pCadEd         = (ICadastralEditor)ArcMap.Application.FindExtensionByName("esriCadastralUI.CadastralEditorExtension");
            IParcelEditManager pParcEditorMan = (IParcelEditManager)pCadEd;

            try
            {
                ICadastralPacketManager pCadPacketMan = (ICadastralPacketManager)pCadEd;
                bool bStartedWithPacketOpen           = pCadPacketMan.PacketOpen;
                if (!bStartedWithPacketOpen)
                {
                    m_editor.StartOperation();
                }

                //1. Start map edit session
                ICadastralMapEdit pCadMapEdit = (ICadastralMapEdit)pCadEd;
                pCadMapEdit.StartMapEdit(esriMapEditType.esriMEEmpty, "NewParcel", false);

                //2.	Get job packet
                ICadastralPacket pCadaPacket = pCadPacketMan.JobPacket;

                //3.	Create Plan (new)
                string sPlanName = PlanName;
                //first check to ensure plan is not already in the database.
                IGSPlan pGSPlan = FindFabricPlanByName(sPlanName, pCadEd);

                if (pGSPlan == null)
                {
                    //if plan is null, it was not found and can be created
                    pGSPlan = new GSPlanClass();
                    // 3.a set values
                    pGSPlan.Accuracy = 4;
                    pGSPlan.Name     = sPlanName;
                }

                //3.b Add the plan to the job packet
                ICadastralPlan pCadaPlan = (ICadastralPlan)pCadaPacket;
                pCadaPlan.AddPlan(pGSPlan);

                //4.	Create Parcel
                ICadastralParcel pCadaParcel  = (ICadastralParcel)pCadaPacket;
                IGSParcel        pNewGSParcel = new GSParcelClass();
                //Make sure that any extended attributes on the parcel have their default values set
                IGSAttributes pGSAttributes = (IGSAttributes)pNewGSParcel;
                if (pGSAttributes != null)
                {
                    ICadastralObjectSetup pCadaObjSetup = (ICadastralObjectSetup)pParcEditorMan;
                    pCadaObjSetup.AddExtendedAttributes(pGSAttributes);
                    pCadaObjSetup.SetDefaultValues(pGSAttributes);
                }

                //4a.	Add the parcel to the packet. (do this before addlines)
                // - This will enable us to Acquire the parcel ID,
                // - Having the parcel attached to the packet allows InsertLine to function.
                pCadaParcel.AddParcel(pNewGSParcel);
                pNewGSParcel.Lot  = "NewParcel";
                pNewGSParcel.Type = 7;
                //4b.	Set Plan (created above)
                IGSPlan thePlan = pCadaPlan.GetPlan(sPlanName);
                pNewGSParcel.Plan = thePlan;
                //4c.	Insert GSLines (from new) into GSParcel
                //4d. To bypass join, you can create GSPoints and assign those point IDs to the GSLines.
                ICadastralPoints     pCadaPoints     = (ICadastralPoints)pCadaPacket;
                IMetricUnitConverter pMetricUnitConv = (IMetricUnitConverter)pCadEd;

                //Set up the initial start point, POB

                IPoint pPt1 = Segments.get_Segment(0).FromPoint;

                IZAware pZAw = (IZAware)pPt1;
                pZAw.ZAware = true;
                pPt1.Z      = 0; //defaulting to 0

                //Convert the point into metric units, and get a new (in-mem) point id
                IGSPoint pGSPointFrom = pMetricUnitConv.SetGSPoint(pPt1);
                pCadaPoints.AddPoint(pGSPointFrom);
                int iID1      = pGSPointFrom.Id;
                int iID1_Orig = iID1;

                int     index   = 0;
                IGSLine pGSLine = null;
                //++++++++++++ Add Courses ++++++++++++++
                int  iID2    = -1;
                bool bIsLoop = (Math.Abs(pPt1.X - Segments.get_Segment(iCnt - 1).ToPoint.X)) < 0.01 &&
                               (Math.Abs(pPt1.Y - Segments.get_Segment(iCnt - 1).ToPoint.Y)) < 0.01;

                IAngularConverter pAngConv = new AngularConverterClass();

                for (int j = 0; j < iCnt; j++)
                {
                    pSegmentArr[j] = Segments.get_Segment(j);

                    double dDir         = 0; //radians north azimuth
                    ILine  pLineOrChord = new LineClass();
                    pLineOrChord.PutCoords(pSegmentArr[j].FromPoint, pSegmentArr[j].ToPoint);

                    if (pAngConv.SetAngle(pLineOrChord.Angle, esriDirectionType.esriDTPolar, esriDirectionUnits.esriDURadians))
                    {
                        dDir = pAngConv.GetAngle(esriDirectionType.esriDTNorthAzimuth, esriDirectionUnits.esriDURadians);
                    }

                    double dDist         = pLineOrChord.Length;
                    double dRadius       = 0;
                    int    iAccuracy     = -1;
                    int    iUserLineType = -1;
                    int    iCategory     = -1;

                    if (pSegmentArr[j] is ICircularArc)
                    {
                        ICircularArc pCircArc = pSegmentArr[j] as ICircularArc;
                        dRadius = pCircArc.Radius;
                        if (pCircArc.IsCounterClockwise)
                        {
                            dRadius = dRadius * -1;
                        }
                    }
                    bool bComputeToPoint = (bIsLoop && (j < iCnt - 1)) || !bIsLoop;
                    //From, Direction (NAz Radians), Distance (map's projection units), Radius
                    pGSLine = CreateGSLine(pMetricUnitConv, pCadaPoints, ref pPt1,
                                           iID1, dDir, dDist, dRadius, iAccuracy, iUserLineType, iCategory, bComputeToPoint, out iID2);

                    if (j < iCnt - 1 || !bIsLoop)
                    {
                        iID1 = iID2;
                    }
                    else if ((j == iCnt - 1) && bIsLoop)
                    {
                        pGSLine.ToPoint = iID1_Orig; //closing the traverse back to the POB
                    }
                    iID2 = -1;

                    //Add the line to the new parcel
                    if (pGSLine != null)
                    {
                        pNewGSParcel.InsertLine(++index, pGSLine);
                    }
                }


                //Add radial lines for circular curves
                pNewGSParcel.AddRadialLines();

                // 4.e then set join=true on the parcel.
                pNewGSParcel.Joined = true;

                //let the packet know that a change has been made
                pCadPacketMan.SetPacketModified(true);

                //save the new parcel
                try
                {
                    pCadMapEdit.StopMapEdit(true);
                }
                catch
                {
                    if (!bStartedWithPacketOpen)
                    {
                        m_editor.AbortOperation();
                    }
                    return;
                }
                if (!bStartedWithPacketOpen)
                {
                    m_editor.StopOperation("New Parcel");
                }
                pCadPacketMan.PartialRefresh();
            }
            catch (Exception ex)
            {
                m_editor.AbortOperation();
                MessageBox.Show(ex.Message);
            }
        }
Exemple #4
0
        protected override void OnClick()
        {
            bool            bShowProgressor = false;
            IStepProgressor pStepProgressor = null;
            //Create a CancelTracker.
            ITrackCancel           pTrackCancel = null;
            IProgressDialogFactory pProgressorDialogFact;

            IMouseCursor pMouseCursor = new MouseCursorClass();

            pMouseCursor.SetCursor(2);

            //first get the selected parcel features
            UID pUID = new UIDClass();

            pUID.Value = "{114D685F-99B7-4B63-B09F-6D1A41A4DDC1}";
            ICadastralExtensionManager2 pCadExtMan = (ICadastralExtensionManager2)ArcMap.Application.FindExtensionByCLSID(pUID);
            ICadastralEditor            pCadEd     = (ICadastralEditor)ArcMap.Application.FindExtensionByCLSID(pUID);

            //check if there is a Manual Mode "modify" job active ===========
            ICadastralPacketManager pCadPacMan = (ICadastralPacketManager)pCadExtMan;

            if (pCadPacMan.PacketOpen)
            {
                MessageBox.Show("The Delete Control command cannot be used when there is an open job.\r\nPlease finish or discard the open job, and try again.",
                                "Delete Selected Control");
                return;
            }

            IEditor pEd = (IEditor)ArcMap.Application.FindExtensionByName("esri object editor");

            IActiveView      pActiveView       = ArcMap.Document.ActiveView;
            IMap             pMap              = pActiveView.FocusMap;
            ICadastralFabric pCadFabric        = null;
            clsFabricUtils   FabricUTILS       = new clsFabricUtils();
            IProgressDialog2 pProgressorDialog = null;

            //if we're in an edit session then grab the target fabric
            if (pEd.EditState == esriEditState.esriStateEditing)
            {
                pCadFabric = pCadEd.CadastralFabric;
            }

            if (pCadFabric == null)
            {//find the first fabric in the map
                if (!FabricUTILS.GetFabricFromMap(pMap, out pCadFabric))
                {
                    MessageBox.Show
                        ("No Parcel Fabric found in the map.\r\nPlease add a single fabric to the map, and try again.");
                    return;
                }
            }

            IArray CFControlLayers = new ArrayClass();

            if (!(FabricUTILS.GetControlLayersFromFabric(pMap, pCadFabric, out CFControlLayers)))
            {
                return; //no fabric sublayers available for the targeted fabric
            }
            bool       bIsFileBasedGDB = false; bool bIsUnVersioned = false; bool bUseNonVersionedDelete = false;
            IWorkspace pWS           = null;
            ITable     pPointsTable  = null;
            ITable     pControlTable = null;

            try
            {
                if (pEd.EditState == esriEditState.esriStateEditing)
                {
                    try
                    {
                        pEd.StartOperation();
                    }
                    catch
                    {
                        pEd.AbortOperation();//abort any open edit operations and try again
                        pEd.StartOperation();
                    }
                }

                IFeatureLayer pFL = (IFeatureLayer)CFControlLayers.get_Element(0);
                IDataset      pDS = (IDataset)pFL.FeatureClass;
                pWS = pDS.Workspace;

                if (!FabricUTILS.SetupEditEnvironment(pWS, pCadFabric, pEd, out bIsFileBasedGDB,
                                                      out bIsUnVersioned, out bUseNonVersionedDelete))
                {
                    return;
                }

                //loop through each control layer and
                //Get the selection of control
                int iCnt = 0;
                int iTotalSelectionCount = 0;
                for (; iCnt < CFControlLayers.Count; iCnt++)
                {
                    pFL = (IFeatureLayer)CFControlLayers.get_Element(iCnt);
                    IFeatureSelection pFeatSel = (IFeatureSelection)pFL;
                    ISelectionSet2    pSelSet  = (ISelectionSet2)pFeatSel.SelectionSet;
                    iTotalSelectionCount += pSelSet.Count;
                }

                if (iTotalSelectionCount == 0)
                {
                    MessageBox.Show("Please select some fabric control points and try again.", "No Selection",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    if (bUseNonVersionedDelete)
                    {
                        pCadEd.CadastralFabricLayer = null;
                        CFControlLayers             = null;
                    }
                    return;
                }

                bShowProgressor = (iTotalSelectionCount > 10);

                if (bShowProgressor)
                {
                    pProgressorDialogFact       = new ProgressDialogFactoryClass();
                    pTrackCancel                = new CancelTrackerClass();
                    pStepProgressor             = pProgressorDialogFact.Create(pTrackCancel, ArcMap.Application.hWnd);
                    pProgressorDialog           = (IProgressDialog2)pStepProgressor;
                    pStepProgressor.MinRange    = 1;
                    pStepProgressor.MaxRange    = iTotalSelectionCount * 2; //(runs through selection twice)
                    pStepProgressor.StepValue   = 1;
                    pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral;
                }

                //loop through each control layer and
                //delete from its selection
                m_pQF = new QueryFilterClass();
                iCnt  = 0;
                for (; iCnt < CFControlLayers.Count; iCnt++)
                {
                    pFL = (IFeatureLayer)CFControlLayers.get_Element(iCnt);
                    IFeatureSelection pFeatSel = (IFeatureSelection)pFL;
                    ISelectionSet2    pSelSet  = (ISelectionSet2)pFeatSel.SelectionSet;

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

                    if (bShowProgressor)
                    {
                        pProgressorDialog.ShowDialog();
                        pStepProgressor.Message = "Collecting Control point data...";
                    }

                    //Add the OIDs of all the selected control points into a new feature IDSet
                    string[] sOIDListPoints = { "(" };
                    int      tokenLimit     = 995;
                    //int tokenLimit = 5; //temp for testing
                    bool bCont    = true;
                    int  j        = 0;
                    int  iCounter = 0;

                    m_pFIDSetControl = new FIDSetClass();

                    ICursor pCursor = null;
                    pSelSet.Search(null, false, out pCursor);//code deletes all selected control points
                    IFeatureCursor pControlFeatCurs = (IFeatureCursor)pCursor;
                    IFeature       pControlFeat     = pControlFeatCurs.NextFeature();
                    int            iPointID         = pControlFeatCurs.FindField("POINTID");

                    while (pControlFeat != null)
                    {
                        //Check if the cancel button was pressed. If so, stop process
                        if (bShowProgressor)
                        {
                            bCont = pTrackCancel.Continue();
                            if (!bCont)
                            {
                                break;
                            }
                        }
                        bool bExists = false;
                        m_pFIDSetControl.Find(pControlFeat.OID, out bExists);
                        if (!bExists)
                        {
                            m_pFIDSetControl.Add(pControlFeat.OID);
                            object obj = pControlFeat.get_Value(iPointID);

                            if (iCounter <= tokenLimit)
                            {
                                //if the PointID is not null add it to a query string as well
                                if (obj != DBNull.Value)
                                {
                                    sOIDListPoints[j] += Convert.ToString(obj) + ",";
                                }
                                iCounter++;
                            }
                            else
                            {//maximum tokens reached
                                //set up the next OIDList
                                sOIDListPoints[j] = sOIDListPoints[j].Trim();
                                iCounter          = 0;
                                j++;
                                FabricUTILS.RedimPreserveString(ref sOIDListPoints, 1);
                                sOIDListPoints[j] = "(";
                                if (obj != DBNull.Value)
                                {
                                    sOIDListPoints[j] += Convert.ToString(obj) + ",";
                                }
                            }
                        }
                        Marshal.ReleaseComObject(pControlFeat); //garbage collection
                        pControlFeat = pControlFeatCurs.NextFeature();

                        if (bShowProgressor)
                        {
                            if (pStepProgressor.Position < pStepProgressor.MaxRange)
                            {
                                pStepProgressor.Step();
                            }
                        }
                    }
                    Marshal.ReleaseComObject(pCursor); //garbage collection

                    if (!bCont)
                    {
                        AbortEdits(bUseNonVersionedDelete, pEd, pWS);
                        return;
                    }

                    if (bUseNonVersionedDelete)
                    {
                        if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned))
                        {
                            if (bUseNonVersionedDelete)
                            {
                                pCadEd.CadastralFabricLayer = null;
                            }
                            return;
                        }
                    }

                    //first delete all the control point records
                    if (bShowProgressor)
                    {
                        pStepProgressor.Message = "Deleting control points...";
                    }

                    bool bSuccess = true;
                    pPointsTable  = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints);
                    pControlTable = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTControl);

                    if (!bUseNonVersionedDelete)
                    {
                        bSuccess = FabricUTILS.DeleteRowsByFIDSet(pControlTable, m_pFIDSetControl, pStepProgressor, pTrackCancel);
                    }
                    if (bUseNonVersionedDelete)
                    {
                        bSuccess = FabricUTILS.DeleteRowsUnversioned(pWS, pControlTable,
                                                                     m_pFIDSetControl, pStepProgressor, pTrackCancel);
                    }
                    if (!bSuccess)
                    {
                        AbortEdits(bUseNonVersionedDelete, pEd, pWS);
                        return;
                    }
                    //next need to use an in clause to update the points, ...
                    ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)pCadFabric;
                    //...for each item in the sOIDListPoints array
                    foreach (string inClause in sOIDListPoints)
                    {
                        string sClause = inClause.Trim().TrimEnd(',');
                        if (sClause.EndsWith("("))
                        {
                            continue;
                        }
                        if (sClause.Length < 3)
                        {
                            continue;
                        }
                        pSchemaEd.ReleaseReadOnlyFields(pPointsTable, esriCadastralFabricTable.esriCFTPoints);
                        m_pQF.WhereClause = (sPref + pPointsTable.OIDFieldName + sSuff).Trim() + " IN " + sClause + ")";

                        if (!FabricUTILS.ResetPointAssociations(pPointsTable, m_pQF, bIsUnVersioned))
                        {
                            pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints);
                            return;
                        }
                        pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints);
                    }
                }

                if (bUseNonVersionedDelete)
                {
                    FabricUTILS.StopEditing(pWS);
                }

                if (pEd.EditState == esriEditState.esriStateEditing)
                {
                    pEd.StopOperation("Delete Control Points");
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            finally
            {
                RefreshMap(pActiveView, CFControlLayers);

                //update the TOC
                IMxDocument mxDocument = (ESRI.ArcGIS.ArcMapUI.IMxDocument)(ArcMap.Application.Document);
                for (int i = 0; i < mxDocument.ContentsViewCount; i++)
                {
                    IContentsView pCV = (IContentsView)mxDocument.get_ContentsView(i);
                    pCV.Refresh(null);
                }

                if (pProgressorDialog != null)
                {
                    pProgressorDialog.HideDialog();
                }

                if (bUseNonVersionedDelete)
                {
                    pCadEd.CadastralFabricLayer = null;
                    CFControlLayers             = null;
                }

                if (pMouseCursor != null)
                {
                    pMouseCursor.SetCursor(0);
                }
            }
        }
        protected override void OnClick()
        {
            #region Prepare for editing
            IMouseCursor pMouseCursor = new MouseCursorClass();
            pMouseCursor.SetCursor(2);

            UID pUID = new UIDClass();
            pUID.Value = "{114D685F-99B7-4B63-B09F-6D1A41A4DDC1}";
            ICadastralExtensionManager2 pCadExtMan = (ICadastralExtensionManager2)ArcMap.Application.FindExtensionByCLSID(pUID);
            ICadastralEditor            pCadEd     = (ICadastralEditor)ArcMap.Application.FindExtensionByCLSID(pUID);

            //check if there is a Manual Mode "modify" job active ===========
            ICadastralPacketManager pCadPacMan = (ICadastralPacketManager)pCadExtMan;
            if (pCadPacMan.PacketOpen)
            {
                MessageBox.Show("This command cannot be used when there is an open job.\r\nPlease finish or discard the open job, and try again.",
                                "Delete Selected Parcels");
                return;
            }

            IEditor pEd = (IEditor)ArcMap.Application.FindExtensionByName("esri object editor");

            IActiveView      pActiveView       = ArcMap.Document.ActiveView;
            IMap             pMap              = pActiveView.FocusMap;
            ICadastralFabric pCadFabric        = null;
            clsFabricUtils   FabricUTILS       = new clsFabricUtils();
            IProgressDialog2 pProgressorDialog = null;

            //if we're in an edit session then grab the target fabric
            if (pEd.EditState == esriEditState.esriStateEditing)
            {
                pCadFabric = pCadEd.CadastralFabric;
            }
            else
            {
                MessageBox.Show("Please start editing and try again.");
                return;
            }

            if (pCadFabric == null)
            {//find the first fabric in the map
                if (!FabricUTILS.GetFabricFromMap(pMap, out pCadFabric))
                {
                    MessageBox.Show
                        ("No Parcel Fabric found in the map.\r\nPlease add a single fabric to the map, and try again.");
                    return;
                }
            }

            IArray CFParcelLayers = new ArrayClass();

            if (!(FabricUTILS.GetFabricSubLayersFromFabric(pMap, pCadFabric, out CFPointLayer, out CFLineLayer,
                                                           out CFParcelLayers, out CFControlLayer, out CFLinePointLayer)))
            {
                return; //no fabric sublayers available for the targeted fabric
            }

            //bool bIsFileBasedGDB = false; bool bIsUnVersioned = false; bool bUseNonVersionedDelete = false;
            //ICadastralFabricLayer pCFLayer = null;

            IWorkspace pWS           = null;
            ITable     pParcelsTable = null;
            ITable     pLinesTable   = null;
            ITable     pLinePtsTable = null;
            ITable     pPointsTable  = null;
            pParcelsTable = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels);
            pLinesTable   = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTLines);
            pLinePtsTable = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTLinePoints);
            pPointsTable  = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints);
            #endregion

            dlgChangeParcelHistory pChangeHistoryDialog = new dlgChangeParcelHistory();
            // ********  Display the dialog  *********
            DialogResult pDialogResult = pChangeHistoryDialog.ShowDialog();
            if (pDialogResult != DialogResult.OK)
            {
                return;
            }
            //************************

            #region Get Selection
            //Get the selection of parcels
            IFeatureLayer pFL = (IFeatureLayer)CFParcelLayers.get_Element(0);

            IDataset pDS = (IDataset)pFL.FeatureClass;
            pWS = pDS.Workspace;

            ICadastralSelection pCadaSel       = (ICadastralSelection)pCadEd;
            IEnumGSParcels      pEnumGSParcels = pCadaSel.SelectedParcels;// need to get the parcels before trying to get the parcel count: BUG workaround

            IFeatureSelection           pFeatSel  = (IFeatureSelection)pFL;
            ISelectionSet2              pSelSet   = (ISelectionSet2)pFeatSel.SelectionSet;
            ICadastralFabricSchemaEdit2 pSchemaEd = null;
            try
            {
                int  iParcelCount      = pCadaSel.SelectedParcelCount;
                bool m_bShowProgressor = (iParcelCount > 10);

                if (m_bShowProgressor)
                {
                    m_pProgressorDialogFact     = new ProgressDialogFactoryClass();
                    m_pTrackCancel              = new CancelTrackerClass();
                    m_pStepProgressor           = m_pProgressorDialogFact.Create(m_pTrackCancel, ArcMap.Application.hWnd);
                    pProgressorDialog           = (IProgressDialog2)m_pStepProgressor;
                    m_pStepProgressor.MinRange  = 1;
                    m_pStepProgressor.MaxRange  = iParcelCount * 14; //(estimate 7 lines per parcel, 4 pts per parcel)
                    m_pStepProgressor.StepValue = 1;
                    pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral;
                }

                if (m_bShowProgressor)
                {
                    pProgressorDialog.ShowDialog();
                    m_pStepProgressor.Message = "Initializing...";
                }

                #endregion

                #region Get Parcel History Fields
                //Get the parcel table history fields
                //SystemStart, SystemEnd, LegalStart, LegalEnd, Historic
                int iParcSysStartDate   = pParcelsTable.FindField("systemstartdate");
                int iParcSysEndDate     = pParcelsTable.FindField("systemenddate");
                int iParcLegalStartDate = pParcelsTable.FindField("legalstartdate");
                int iParcLegalEndDate   = pParcelsTable.FindField("legalenddate");
                int iParcHistorical     = pParcelsTable.FindField("historical");

                //Add the OIDs of all the selected parcels into a new feature IDSet
                //Need a Lookup for the History information
                Dictionary <int, string> ParcelToHistory_DICT = new Dictionary <int, string>();
                List <string>            sOIDList             = new List <string>();
                sOIDList.Add("");
                int  tokenLimit = 995;
                bool bCont      = true;
                int  j          = 0;
                int  iCounter   = 0;

                m_pFIDSetParcels = new FIDSetClass();

                pEnumGSParcels.Reset();
                IGSParcel pGSParcel = pEnumGSParcels.Next();
                while (pGSParcel != null)
                {
                    //Check if the cancel button was pressed. If so, stop process
                    if (m_bShowProgressor)
                    {
                        bCont = m_pTrackCancel.Continue();
                        if (!bCont)
                        {
                            break;
                        }
                    }
                    m_pFIDSetParcels.Add(pGSParcel.DatabaseId);

                    if (iCounter <= tokenLimit)
                    {
                        if (sOIDList[j].Trim() == "")
                        {
                            sOIDList[j] = Convert.ToString(pGSParcel.DatabaseId);
                        }
                        else
                        {
                            sOIDList[j] = sOIDList[j] + "," + Convert.ToString(pGSParcel.DatabaseId);
                        }
                        iCounter++;
                    }
                    else
                    {//maximum tokens reached
                        iCounter = 0;
                        //set up the next OIDList
                        j++;
                        sOIDList.Add("");
                        sOIDList[j] = Convert.ToString(pGSParcel.DatabaseId);
                    }

                    //add to the lookup
                    IGSAttributes pGSParcelAttributes = (IGSAttributes)pGSParcel;
                    object        pObj = pGSParcelAttributes.GetProperty("systemstartdate");
                    string        sSystemStartParcel = "";
                    if (pObj != null)
                    {
                        sSystemStartParcel = pObj.ToString();
                    }

                    pObj = pGSParcelAttributes.GetProperty("systemenddate");
                    string sSystemEndParcel = "";
                    if (pObj != null)
                    {
                        sSystemEndParcel = pObj.ToString();
                    }

                    string sLegalStartParcel = pGSParcel.LegalStartDate.ToString();
                    string sLegalEndParcel   = pGSParcel.LegalEndDate.ToString();
                    string sHistorical       = pGSParcel.Historical.ToString();

                    ParcelToHistory_DICT.Add(pGSParcel.DatabaseId, sSystemStartParcel + "," +
                                             sSystemEndParcel + "," + sLegalStartParcel + "," + sLegalEndParcel + "," +
                                             sHistorical);

                    Marshal.ReleaseComObject(pGSParcel); //garbage collection
                    pGSParcel = pEnumGSParcels.Next();
                    if (m_bShowProgressor)
                    {
                        if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange)
                        {
                            m_pStepProgressor.Step();
                        }
                    }
                }
                Marshal.ReleaseComObject(pEnumGSParcels); //garbage collection

                #endregion

                #region Confirm Edit Locks
                bool bIsFileBasedGDB  = false;
                bool bIsUnVersioned   = false;
                bool bUseNonVersioned = false;

                if (!FabricUTILS.SetupEditEnvironment(pWS, pCadFabric, pEd, out bIsFileBasedGDB,
                                                      out bIsUnVersioned, out bUseNonVersioned))
                {
                    return;
                }
                //if we're in an enterprise then test for edit locks
                string sTime = "";
                if (!bIsUnVersioned && !bIsFileBasedGDB)
                {
                    //see if parcel locks can be obtained on the selected parcels. First create a job.
                    DateTime localNow = DateTime.Now;
                    sTime = Convert.ToString(localNow);
                    ICadastralJob pJob = new CadastralJobClass();
                    pJob.Name        = sTime;
                    pJob.Owner       = System.Windows.Forms.SystemInformation.UserName;
                    pJob.Description = "Delete selected parcels";
                    try
                    {
                        Int32 jobId = pCadFabric.CreateJob(pJob);
                    }
                    catch (COMException ex)
                    {
                        if (ex.ErrorCode == (int)fdoError.FDO_E_CADASTRAL_FABRIC_JOB_ALREADY_EXISTS)
                        {
                            MessageBox.Show("Job named: '" + pJob.Name + "', already exists");
                        }
                        else
                        {
                            MessageBox.Show(ex.Message);
                        }
                        m_pStepProgressor = null;
                        if (!(pProgressorDialog == null))
                        {
                            pProgressorDialog.HideDialog();
                        }
                        pProgressorDialog = null;
                        Marshal.ReleaseComObject(pJob);
                        if (bUseNonVersioned)
                        {
                            pCadEd.CadastralFabricLayer = null;
                        }
                        return;
                    }
                    Marshal.ReleaseComObject(pJob);
                }
                ICadastralFabricLocks pFabLocks = (ICadastralFabricLocks)pCadFabric;
                if (!bIsUnVersioned && !bIsFileBasedGDB)
                {
                    pFabLocks.LockingJob = sTime;
                    ILongArray pLocksInConflict    = null;
                    ILongArray pSoftLcksInConflict = null;

                    ILongArray pParcelsToLock = new LongArrayClass();

                    FabricUTILS.FIDsetToLongArray(m_pFIDSetParcels, ref pParcelsToLock, m_pStepProgressor);
                    if (m_bShowProgressor && !bIsFileBasedGDB)
                    {
                        m_pStepProgressor.Message = "Testing for edit locks on parcels...";
                    }

                    try
                    {
                        pFabLocks.AcquireLocks(pParcelsToLock, true, ref pLocksInConflict, ref pSoftLcksInConflict);
                    }
                    catch (COMException pCOMEx)
                    {
                        if (pCOMEx.ErrorCode == (int)fdoError.FDO_E_CADASTRAL_FABRIC_JOB_LOCK_ALREADY_EXISTS ||
                            pCOMEx.ErrorCode == (int)fdoError.FDO_E_CADASTRAL_FABRIC_JOB_CURRENTLY_EDITED)
                        {
                            MessageBox.Show("Edit Locks could not be acquired on all selected parcels.");
                            // since the operation is being aborted, release any locks that were acquired
                            pFabLocks.UndoLastAcquiredLocks();
                        }
                        else
                        {
                            MessageBox.Show(pCOMEx.Message + Environment.NewLine + Convert.ToString(pCOMEx.ErrorCode));
                        }

                        if (bUseNonVersioned)
                        {
                            pCadEd.CadastralFabricLayer = null;
                        }
                        return;
                    }
                    Marshal.ReleaseComObject(pSoftLcksInConflict);
                    Marshal.ReleaseComObject(pParcelsToLock);
                    Marshal.ReleaseComObject(pLocksInConflict);
                }
                #endregion

                string sParcelSysEndDate     = pParcelsTable.Fields.get_Field(iParcSysEndDate).Name;
                string sParcelLegalStartDate = pParcelsTable.Fields.get_Field(iParcLegalStartDate).Name;
                string sParcelLegalEndDate   = pParcelsTable.Fields.get_Field(iParcLegalEndDate).Name;
                string sParcelHistoric       = pParcelsTable.Fields.get_Field(iParcHistorical).Name;

                if (m_bShowProgressor)
                {
                    pProgressorDialog.ShowDialog();
                    m_pStepProgressor.Message = "Updating parcel history...";
                }

                pEd.StartOperation();

                #region The Edit

                //make change to parcels
                bool         bSuccess  = false;
                ICursor      pCurs     = null;
                IQueryFilter pQuFilter = new QueryFilterClass();
                pQuFilter.SubFields = pParcelsTable.OIDFieldName + "," + sParcelLegalEndDate + "," + sParcelLegalStartDate
                                      + "," + sParcelSysEndDate + "," + sParcelHistoric;

                bool bSystemEndDate_Clear = pChangeHistoryDialog.chkSystemEndDate.Checked &&
                                            pChangeHistoryDialog.optClearSEDate.Checked;
                bool bLegalStDate_Clear = pChangeHistoryDialog.chkLegalStartDate.Checked &&
                                          pChangeHistoryDialog.optClearLSDate.Checked;
                bool bLegalEndDate_Clear = pChangeHistoryDialog.chkLegalEndDate.Checked &&
                                           pChangeHistoryDialog.optClearLEDate.Checked;

                bool bSystemEndDate_Set = pChangeHistoryDialog.chkSystemEndDate.Checked &&
                                          pChangeHistoryDialog.optChooseSEDate.Checked;
                bool bLegalStDate_Set = pChangeHistoryDialog.chkLegalStartDate.Checked &&
                                        pChangeHistoryDialog.optChooseLSDate.Checked;
                bool bLegalEndDate_Set = pChangeHistoryDialog.chkLegalEndDate.Checked &&
                                         pChangeHistoryDialog.optChooseLEDate.Checked;

                List <bool> bHistory = new List <bool>();
                bHistory.Add(bSystemEndDate_Clear);
                bHistory.Add(bLegalStDate_Clear);
                bHistory.Add(bLegalEndDate_Clear);
                bHistory.Add(bSystemEndDate_Set);
                bHistory.Add(bLegalStDate_Set);
                bHistory.Add(bLegalEndDate_Set);

                List <string> sDates = new List <string>();
                sDates.Add(pChangeHistoryDialog.dtSEDatePicker.Text);
                sDates.Add(pChangeHistoryDialog.dtLSDatePicker.Text);
                sDates.Add(pChangeHistoryDialog.dtLEDatePicker.Text);

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

                foreach (string sInClause in sOIDList)
                {
                    if (sInClause.Trim() == "")
                    {
                        continue;
                    }
                    pQuFilter.WhereClause = pParcelsTable.OIDFieldName + " IN (" + sInClause + ")";
                    pCurs    = pParcelsTable.Update(pQuFilter, false);
                    bSuccess = FabricUTILS.ChangeDatesOnTableMulti(pCurs, bHistory, sDates, bUseNonVersioned,
                                                                   ParcelToHistory_DICT, m_pStepProgressor, m_pTrackCancel);

                    if (!bSuccess)
                    {
                        if (!bIsUnVersioned)
                        {
                            pFabLocks.UndoLastAcquiredLocks();
                        }
                        if (bUseNonVersioned)
                        {
                            FabricUTILS.AbortEditing(pWS);
                        }
                        else
                        {
                            pEd.AbortOperation();
                        }
                        //clear selection, to make sure the parcel explorer is updated and refreshed properly

                        return;
                    }
                }

                //make change to points and lines
                if (!FabricUTILS.UpdateHistoryOnLines(pLinesTable, pPointsTable, iParcelCount,
                                                      pCadFabric, sOIDList, ParcelToHistory_DICT, m_pStepProgressor, m_pTrackCancel))
                {
                    if (!bIsUnVersioned)
                    {
                        pFabLocks.UndoLastAcquiredLocks();
                    }
                    if (bUseNonVersioned)
                    {
                        FabricUTILS.AbortEditing(pWS);
                    }
                    else
                    {
                        pEd.AbortOperation();
                    }
                }
                else
                {
                    pEd.StopOperation("Change Parcel History");
                }

                #endregion

                //now refresh the map layers
                RefreshMap(pActiveView, CFParcelLayers, CFPointLayer, CFLineLayer, CFControlLayer, CFLinePointLayer);
            }

            catch (Exception ex)
            {
                pEd.AbortOperation();
                MessageBox.Show("Error:" + ex.Message);
            }
            finally
            {
                if (!(pProgressorDialog == null))
                {
                    pProgressorDialog.HideDialog();
                }
                pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints);  //set safety back on
                pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTLines);   //set safety back on
                pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTParcels); //set safety back on
            }
        }
Exemple #6
0
        protected override void OnClick()
        {
            ICadastralEditor   pCadEd         = (ICadastralEditor)ArcMap.Application.FindExtensionByName("esriCadastralUI.CadastralEditorExtension");
            IParcelEditManager pParcEditorMan = (IParcelEditManager)pCadEd;

            ICadastralPacketManager pCadPacketMan = (ICadastralPacketManager)pCadEd;

            //bool bStartedWithPacketOpen = pCadPacketMan.PacketOpen;

            if (pParcEditorMan == null)
            {
                return;
            }

            IEditor pEd = (IEditor)ArcMap.Application.FindExtensionByName("esri object editor");

            if (pEd.EditState == esriEditState.esriStateNotEditing)
            {
                MessageBox.Show("Please start editing and try again.");
                return;
            }

            IParcelConstruction       pConstr                   = pParcEditorMan.ParcelConstruction;
            IParcelConstruction4      pConstr4                  = pConstr as IParcelConstruction4;
            ICadastralPoints          pCadastralPts             = pConstr4 as ICadastralPoints;
            ICadastralEditorSettings2 pCadastralEditorSettings2 = pCadEd as ICadastralEditorSettings2;

            ICadastralFixedPoints pFixedPoints = pCadastralPts as ICadastralFixedPoints;
            IPointCalculation     pPointCalc   = new PointCalculationClass();

            if (pConstr == null)
            {
                return;
            }

            IGSLine pParcelLine = null;
            IMetricUnitConverter pMetricUnitConv = (IMetricUnitConverter)pCadEd;
            IGSPoint             pStartPoint     = null;
            List <int>           lstPointIds     = new List <int>();

            List <IVector3D> Traverse = new List <IVector3D>();

            //get rotation here
            IParcelConstructionData    pConstrData = pConstr4.ConstructionData;
            IConstructionParentParcels pConstructionParentParcels = pConstrData as IConstructionParentParcels;

            ICadastralUndoRedo pCadUndoRedo = pConstr as ICadastralUndoRedo;

            try
            {
                int iParcelID = -1;
                if (pConstructionParentParcels.ParentParcelCount > 0)
                {
                    pConstructionParentParcels.GetParentParcel(0, ref iParcelID);
                }

                ICadastralParcel pCadaParcel = pCadPacketMan.JobPacket as ICadastralParcel;

                IGSParcel pGSParcel = null;

                if (pCadaParcel != null)
                {
                    pGSParcel = pCadaParcel.GetParcel(iParcelID);
                }
                //if in measurement view then rotation is 0
                double TheRotation = 0;

                if (pGSParcel == null)
                {
                    pGSParcel = pConstr.Parcel;
                }

                if (!pCadastralEditorSettings2.MeasurementView)
                {
                    TheRotation = pGSParcel.Rotation;//radians
                }
                if (TheRotation == 123456789)
                {
                    TheRotation = 0;
                }

                pPointCalc.Rotation = TheRotation;
                IGSPoint pClosingPoint = null;

                #region simple method as fall-back
                bool bUseSimpleStackSelection = false;
                if (bUseSimpleStackSelection)
                {
                    //bool bLineSelectionSequence = false;
                    //IGSLine pLastSelectedGSLineInGrid = null;
                    //for (int i = 0; i < pConstr.LineCount; i++)
                    //{
                    //  if (pConstr.GetLineSelection(i))
                    //  {
                    //    if (pConstr.GetLine(i, ref pParcelLine))
                    //    {
                    //      if (!bLineSelectionSequence) //first line
                    //      {
                    //        pStartPoint = pCadastralPts.GetPoint(pParcelLine.FromPoint);
                    //        pToPoint = pCadastralPts.GetPoint(pParcelLine.ToPoint);
                    //      }

                    //      pPointCalc.AddLine(pParcelLine);

                    //      pLastSelectedGSLineInGrid = pParcelLine;
                    //      pToPoint = pCadastralPts.GetPoint(pParcelLine.ToPoint);
                    //      lstPointIds.Add(pToPoint.Id);

                    //    }
                    //    bLineSelectionSequence = true;

                    //    double dBear = pParcelLine.Bearing; //Azimuth of IVector3D is north azimuth radians zero degrees north
                    //    double dDist = pParcelLine.Distance;
                    //    IVector3D vec = new Vector3DClass();
                    //    vec.PolarSet(dBear, 0, dDist); ////Azimuth of IVector3D is north azimuth radians zero degrees north
                    //    Traverse.Add(vec);
                    //  }
                    //  else
                    //  {
                    //    if (bLineSelectionSequence && pConstr.GetLine(i, ref pParcelLine) && HasLineSelectionAfter(pConstr, i))
                    //    //if there was a prior selection and this line is a complete line, and there is no later selection
                    //    {
                    //      MessageBox.Show("Please select a continuous set of lines for closure.");
                    //      return;
                    //    }
                    //  }
                    //}
                    //pClosingPoint = pCadastralPts.GetPoint(pLastSelectedGSLineInGrid.ToPoint);
                }
                else
                #endregion

                {//build a forward star for the selected lines
                    IEnumCELines pCELines     = new EnumCELinesClass();
                    IEnumGSLines pEnumGSLines = (IEnumGSLines)pCELines;
                    ILongArray   pLongArray   = new LongArrayClass();
                    int          iFirstToNode = -1;
                    for (int i = 0; i < pConstr.LineCount; i++)
                    {
                        if (pConstr.GetLineSelection(i))
                        {
                            if (pConstr.GetLine(i, ref pParcelLine))
                            {
                                if (iFirstToNode < 0)
                                {
                                    iFirstToNode = pParcelLine.ToPoint;
                                }
                                pLongArray.Add(i);
                                pCELines.Add(pParcelLine);
                            }
                        }
                    }

                    if (pCELines.Count == 0)
                    {
                        MessageBox.Show("No lines selected. Please select a continuous set of lines for closure." + Environment.NewLine +
                                        "Line selection should not have branches.", "Traverse");
                        return;
                    }

                    IParcelLineFunctions3 ParcelLineFx = new ParcelFunctionsClass();
                    IGSForwardStar        pFwdStar     = ParcelLineFx.CreateForwardStar(pEnumGSLines);
                    //forward star object is now created for all the selected lines,
                    //need to first re-sequence the lines, and test for branching and discontinuity

                    int           iBranches = 0; int iTracedLines = 0;
                    int           iLoops = 0; int iTerminals = 0;
                    List <int>    LineIDList = new List <int>();
                    List <int>    FromList   = new List <int>();
                    List <int>    ToList     = new List <int>();
                    List <string> FromToLine = new List <string>();

                    bool bTraceSucceeded = TraceLines(ref pFwdStar, iFirstToNode, ref iBranches, ref iTracedLines,
                                                      ref iLoops, ref iTerminals, ref FromToLine, ref FromList, ref ToList, 0);

                    if (iBranches > 0)
                    {
                        MessageBox.Show("Please select a continuous set of lines for closure." + Environment.NewLine +
                                        "Line selection should not have branches.", "Traverse");
                        return;
                    }

                    if (iTracedLines < pLongArray.Count)
                    {
                        MessageBox.Show("Please select a continuous set of lines for closure." + Environment.NewLine +
                                        "Selected Lines should be connected in a single sequence without branches.", "Traverse");
                        return;
                    }

                    //if it's a single loop check to see if the sequence needs to be reversed
                    //CW or CCW based on bearings
                    if (iLoops == 1)
                    {
                        bool bIsReversed = false;
                        foreach (int i in FromList)
                        {
                            if (i < 0)
                            {
                                bIsReversed = true;
                            }
                            else
                            {
                                bIsReversed = false;
                                break;
                            }
                        }
                        if (bIsReversed)
                        {//all courses are running reversed, so reverse the whole sequence
                            FromToLine.Clear();
                            FromList.Reverse();
                            ToList.Reverse();
                            int    iNewFrom   = -ToList[ToList.Count - 1];
                            int    iNewTo     = -FromList[ToList.Count - 1];
                            string sNewFromTo = iNewFrom.ToString() + "," + iNewTo.ToString();
                            FromToLine.Add(sNewFromTo);
                            for (int i = 1; i < ToList.Count; i++)
                            {
                                iNewFrom   = -ToList[i - 1];
                                iNewTo     = -FromList[i - 1];
                                sNewFromTo = iNewFrom.ToString() + "," + iNewTo.ToString();
                                FromToLine.Add(sNewFromTo);
                            }
                        }
                    }

                    LineIDList.Clear();
                    FromList.Clear();
                    ToList.Clear();
                    pLongArray.RemoveAll();

                    pCadUndoRedo.StartUndoRedoSession("Adjust Traverse");

                    if (iLoops == 0)
                    {
                        //re-sequence using TraceLines function based on either end point, because the order of
                        //selected construction lines in grid don't control start or end point
                        FromToLine.Clear();
                        int iTerminus = -1;
                        iTracedLines = 0;
                        iBranches    = 0;
                        iLoops       = 0; iTerminals = 0;
                        FindTerminusForSequence(ref pFwdStar, iFirstToNode, ref iTerminus, 0);
                        if (iTerminus == -1)
                        {
                            pCadUndoRedo.WriteUndoRedoSession(false);
                            return;
                        }
                        TraceLines(ref pFwdStar, iTerminus, ref iBranches, ref iTracedLines, ref iLoops, ref iTerminals,
                                   ref FromToLine, ref FromList, ref ToList, 0);
                    }

                    List <IVector3D> SequencedTraverse = new List <IVector3D>();
                    IGSLine          pGSLineInPath     = null;
                    foreach (string s in FromToLine)
                    {
                        string[] sFromTo = s.Split(',');
                        int      iFrom   = Convert.ToInt32(sFromTo[0]);
                        int      iTo     = Convert.ToInt32(sFromTo[1]);

                        bool bReversed = pFwdStar.GetLine(iFrom, iTo, ref pGSLineInPath);
                        if (bReversed)
                        {
                            IGSLine pGSLine180 = new GSLineClass();
                            pGSLine180.FromPoint = pGSLineInPath.ToPoint;
                            pGSLine180.ToPoint   = pGSLineInPath.FromPoint;
                            pGSLine180.Bearing   = pGSLineInPath.Bearing + Math.PI;
                            pGSLine180.Distance  = pGSLineInPath.Distance;

                            IVector3D vec180 = new Vector3DClass();
                            vec180.PolarSet(pGSLine180.Bearing, 0, pGSLine180.Distance); //Azimuth of IVector3D is north azimuth radians zero degrees north
                            Traverse.Add(vec180);
                            lstPointIds.Add(pGSLine180.ToPoint);
                            pPointCalc.AddLine(pGSLine180);
                        }
                        else
                        {
                            double    dBear = pGSLineInPath.Bearing;
                            double    dDist = pGSLineInPath.Distance;
                            IVector3D vec   = new Vector3DClass();
                            vec.PolarSet(dBear, 0, dDist); //Azimuth of IVector3D is north azimuth radians zero degrees north
                            Traverse.Add(vec);
                            lstPointIds.Add(pGSLineInPath.ToPoint);
                            pPointCalc.AddLine(pGSLineInPath);
                        }

                        if (pStartPoint == null)
                        {
                            if (bReversed)
                            {
                                pStartPoint = pCadastralPts.GetPoint(pGSLineInPath.ToPoint);
                            }
                            else
                            {
                                pStartPoint = pCadastralPts.GetPoint(pGSLineInPath.FromPoint);
                            }
                        }

                        if (bReversed)
                        {
                            pClosingPoint = pCadastralPts.GetPoint(pGSLineInPath.FromPoint);
                        }
                        else
                        {
                            pClosingPoint = pCadastralPts.GetPoint(pGSLineInPath.ToPoint);
                        }
                    }
                }

                if (pStartPoint == null)
                {
                    pCadUndoRedo.WriteUndoRedoSession(false);
                    return;
                }
                IPoint pStart = new PointClass();
                pStart.X = pStartPoint.X;
                pStart.Y = pStartPoint.Y;

                string sAdjustMethod = "Compass";
                esriParcelAdjustmentType eAdjMethod = esriParcelAdjustmentType.esriParcelAdjustmentCompass;

                if (pCadastralEditorSettings2.ParcelAdjustment == esriParcelAdjustmentType.esriParcelAdjustmentNone ||
                    pCadastralEditorSettings2.ParcelAdjustment == esriParcelAdjustmentType.esriParcelAdjustmentCompass)
                {
                    eAdjMethod = esriParcelAdjustmentType.esriParcelAdjustmentCompass;
                }
                else if (pCadastralEditorSettings2.ParcelAdjustment == esriParcelAdjustmentType.esriParcelAdjustmentCrandall)
                {
                    sAdjustMethod = "Crandall";
                    eAdjMethod    = pCadastralEditorSettings2.ParcelAdjustment;
                }
                else if (pCadastralEditorSettings2.ParcelAdjustment == esriParcelAdjustmentType.esriParcelAdjustmentTransit)
                {
                    sAdjustMethod = "Transit";
                    eAdjMethod    = pCadastralEditorSettings2.ParcelAdjustment;
                }

                pPointCalc.CalculatePoints(eAdjMethod, pStartPoint.Id, pStartPoint, pClosingPoint.Id, pClosingPoint, true);
                ITraverseClosure pClose = pPointCalc.Closure;
                List <string>    lstCoursesFromTo = new List <string>();
                List <IVector3D> AdjustedTraverse = new List <IVector3D>();
                double           dAdjustedPointX = 0; double dAdjustedPointY = 0;
                double           dPreviousPointX = 0; double dPreviousPointY = 0;

                for (int i = 0; i < pClose.CourseCount; i++)
                {
                    IGSPoint pPt = pCadastralPts.GetPoint(lstPointIds[i]);
                    dAdjustedPointY = pPointCalc.GetCalculatedPoint(lstPointIds[i], ref dAdjustedPointX);
                    string    sFromTo       = "";
                    IVector3D pAdjustedLine = new Vector3DClass();
                    if (i == 0)
                    {
                        sFromTo = pStartPoint.Id.ToString() + "-" + lstPointIds[i].ToString();
                        pAdjustedLine.SetComponents(dAdjustedPointX - pStartPoint.X, dAdjustedPointY - pStartPoint.Y, 0);
                    }
                    else
                    {
                        sFromTo = lstPointIds[i - 1].ToString() + "-" + lstPointIds[i].ToString();
                        pAdjustedLine.SetComponents(dAdjustedPointX - dPreviousPointX, dAdjustedPointY - dPreviousPointY, 0);
                    }
                    lstCoursesFromTo.Add(sFromTo);

                    IVector3D Z_Axis = new Vector3DClass();
                    Z_Axis.SetComponents(0, 0, 100);

                    pAdjustedLine.Rotate(TheRotation, Z_Axis);
                    AdjustedTraverse.Add(pAdjustedLine);

                    dPreviousPointX = dAdjustedPointX;
                    dPreviousPointY = dAdjustedPointY;

                    pPt.X = dAdjustedPointX;
                    pPt.Y = dAdjustedPointY;

                    if (!pCadastralEditorSettings2.MeasurementView)
                    {
                        pFixedPoints.SetFixedPoint(lstPointIds[i], true);
                    }
                }

                double  dMisclosureDistance = pClose.MisclosureDistance; double dMisclosureBearing = pClose.MisclosureDirection;
                IVector MiscloseVector = new Vector3DClass();

                IEditProperties2 pEdProps = pEd as IEditProperties2;

                IAngularConverter pAngConv = new AngularConverterClass();
                pAngConv.SetAngle(dMisclosureBearing, esriDirectionType.esriDTNorthAzimuth, esriDirectionUnits.esriDURadians);
                //int iPrec = 7;
                //if (pConstr.Parcel.Plan.AngleUnits == esriDirectionUnits.esriDUDegreesMinutesSeconds)
                //  iPrec = 0;

                string sMiscloseBearing = pAngConv.GetString(pEdProps.DirectionType, pEdProps.DirectionUnits, pEdProps.AngularUnitPrecision);

                Utilities UTIL   = new Utilities();
                string    sRatio = "High Accuracy";

                if (pClose.RelativeErrorRatio < 10000)
                {
                    sRatio = "1:" + pClose.RelativeErrorRatio.ToString("0");
                }

                if (dMisclosureDistance >= 0.001)
                {
                    sMiscloseBearing = UTIL.FormatDirectionDashesToDegMinSecSymbols(sMiscloseBearing);
                }
                else
                {
                    sMiscloseBearing = "----";
                }

                ICadastralUnitConversion pCadUnitConverter = new CadastralUnitConversionClass();
                double dMetersPerUnit = pCadUnitConverter.ConvertDouble(1, pConstr.Parcel.Plan.DistanceUnits, esriCadastralDistanceUnits.esriCDUMeter);

                string sReport = "Closure:" + Environment.NewLine +
                                 "        error:  " + sRatio + Environment.NewLine +
                                 "        distance:  " + (dMisclosureDistance / dMetersPerUnit).ToString("0.000") + Environment.NewLine +
                                 "        bearing:  " + sMiscloseBearing + Environment.NewLine +
                                 "        xdist:  " + (pClose.MisclosureX / dMetersPerUnit).ToString("0.000") + Environment.NewLine +
                                 "        ydist:  " + (pClose.MisclosureY / dMetersPerUnit).ToString("0.000") + Environment.NewLine +
                                 "        courses: " + (pClose.CourseCount) + Environment.NewLine +
                                 Environment.NewLine + "Adjustment:" + Environment.NewLine +
                                 "        method: " + sAdjustMethod;

                dlgTraverseResults dlgTraverseResults = new dlgTraverseResults();
                AddTraverseInfoToGrid(pConstr.Parcel.Plan, dlgTraverseResults.dataGridView1, Traverse, AdjustedTraverse, lstCoursesFromTo);
                dlgTraverseResults.txtMiscloseReport.Text = sReport;
                DialogResult dRes = dlgTraverseResults.ShowDialog();
                if (dRes == DialogResult.Cancel)
                {
                    //since we cancelled, set the points back
                    foreach (int i in lstPointIds)
                    {
                        pFixedPoints.SetFixedPoint(i, false);
                    }
                    pCadUndoRedo.WriteUndoRedoSession(false);
                }
                else
                {
                    pCadUndoRedo.WriteUndoRedoSession(true);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + "Line number:" + ex.LineNumber().ToString()
                                + " in " + ex.TargetSite.Name, "Traverse");
                pCadUndoRedo.WriteUndoRedoSession(false);
            }
        }
        protected override void OnClick()
        {
            ICadastralEditor           pCadEd         = (ICadastralEditor)ArcMap.Application.FindExtensionByName("esriCadastralUI.CadastralEditorExtension");
            IParcelEditManager         pParcEditorMan = (IParcelEditManager)pCadEd;
            ICadastralExtensionManager pCadMan        = pCadEd as ICadastralExtensionManager;
            ICadastralPacketManager    pCadPacketMan  = (ICadastralPacketManager)pCadEd;

            //bool bStartedWithPacketOpen = pCadPacketMan.PacketOpen;

            if (!(pCadMan.ContextItem is IGSLine))
            {
                return;
            }

            IGSLine pGSLine = pCadMan.ContextItem as IGSLine;

            if (pParcEditorMan == null)
            {
                return;
            }

            IEditor pEd = (IEditor)ArcMap.Application.FindExtensionByName("esri object editor");

            if (pEd.EditState == esriEditState.esriStateNotEditing)
            {
                MessageBox.Show("Please start editing and try again.");
                return;
            }

            IParcelConstruction     pConstr   = pParcEditorMan.ParcelConstruction;
            ICadastralLinePoints2Ex pCadLPsEx = pConstr as ICadastralLinePoints2Ex;

            ILongArray pLngArrBefore = pCadLPsEx.LinePoints;
            List <int> lstLPBefore   = new List <int>();

            for (int i = 0; i < pLngArrBefore.Count; i++)
            {
                lstLPBefore.Add(pLngArrBefore.get_Element(i));
            }

            //first get the current set of breakpoints
            Utilities FabUTILS = new Utilities();

            FabUTILS.ExecuteCommand("{9987F18B-8CC4-4548-8C41-7DB51F289BB3}"); //Run COTS Breakline command

            ILongArray pLngArrAfter = pCadLPsEx.LinePoints;
            List <int> lstLPAfter   = new List <int>();

            for (int i = 0; i < pLngArrAfter.Count; i++)
            {
                lstLPAfter.Add(pLngArrAfter.get_Element(i));
            }

            List <int> lstNewBreakPoints = lstLPAfter.Except(lstLPBefore).ToList();

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

            IParcelConstruction4 pConstr4      = pConstr as IParcelConstruction4;
            ICadastralPoints     pCadastralPts = pConstr4 as ICadastralPoints;

            IEnumCELines pCELines     = new EnumCELinesClass();
            IEnumGSLines pEnumGSLines = (IEnumGSLines)pCELines;

            pCELines.Add(pGSLine);

            //check if it's a construction line or parent line
            bool         bIsParentLine            = true;
            IEnumGSLines pEnumGSConstructionLines = pConstr4.GetLines(false, false);

            IGSLine   pGSTestLine = null;
            IGSParcel pGSParc     = null;

            pEnumGSConstructionLines.Reset();
            pEnumGSConstructionLines.Next(ref pGSParc, ref pGSTestLine);
            while (pGSTestLine != null)
            {
                if ((pGSLine.FromPoint == pGSTestLine.FromPoint) && (pGSLine.ToPoint == pGSTestLine.ToPoint))
                {
                    bIsParentLine = false;
                    break;
                }
                pEnumGSConstructionLines.Next(ref pGSParc, ref pGSTestLine);
            }

            IParcelLineFunctions3 pParcLineFunctions = new ParcelFunctionsClass();
            IEnumGSLines          pNewLinesEnum      = pParcLineFunctions.BreakLinesAtLinePoints(pEnumGSLines, pCadastralPts, true, false);

            IGSParcel          pGSParcel    = null;
            IGSLine            pGSNewLine   = null;
            ICadastralUndoRedo pCadUndoRedo = pConstr as ICadastralUndoRedo;

            pCadUndoRedo.StartUndoRedoSession("Break-line");

            pNewLinesEnum.Reset();
            pNewLinesEnum.Next(ref pGSParcel, ref pGSNewLine);
            while (pGSNewLine != null)
            {
                pConstr4.InsertGridRow(-1, pGSNewLine, true);
                pNewLinesEnum.Next(ref pGSParcel, ref pGSNewLine);
            }

            ICadastralUnbuildableLines pUnbuildable = pConstr4 as ICadastralUnbuildableLines;

            if (bIsParentLine)
            {
                pUnbuildable.AddLine(pGSLine);
            }
            else
            {
                pConstr4.Planarize(0.001); //delete the original construction line
            }
            pCadUndoRedo.WriteUndoRedoSession(true);
        }
    private bool RunAdjustment(ICadastralPacketManager pCadastralPacketManager,
      ICadastralAdjustment pCadAdj, ICadastralAdjustment3 pCadAdjEx, int Iteration, out double MaxShift, out string Summary)
    {
      esriCadastralDistanceUnits eDistUnits =esriCadastralDistanceUnits.esriCDUUSSurveyFoot;
      esriDirectionType eDirectType  =esriDirectionType.esriDTNorthAzimuth;
      esriCadastralAreaUnits eAreaUnits = esriCadastralAreaUnits.esriCAUAcre;

      ICadastralPlan pCadPlan = (ICadastralPlan)pCadAdj;
      IEnumGSPlans pGSPlans =pCadPlan.GetPlans(enumGSPlansType.enumGSPlansWithParcels);
      pGSPlans.Reset();
      IGSPlan pGSPlan=pGSPlans.Next();

      while (pGSPlan!=null)
      {
        eDistUnits = pGSPlan.DistanceUnits;
        eDirectType = pGSPlan.DirectionFormat;
        eAreaUnits = esriCadastralAreaUnits.esriCAUAcre;
        break; //just use the first one
      }

      double dMaxShift=-999;
      string sSummary="";
      MaxShift=dMaxShift;
      try
      {
        //get the units from the map plan
                
        sSummary=
        pCadAdj.PerformAdjustment(false,m_sBrowseFilePath,null,eDistUnits, eDirectType,eAreaUnits);

        double dMaxEast=-999;
        double dMaxNorth=-999;
        int iPt=-999;
        pCadAdjEx.GetMaxShiftData(ref iPt, ref dMaxEast, ref dMaxNorth);

        double dDistEast=-999;
        double dDistNorth=-999;

        IMetricUnitConverter pUnitConversion = (IMetricUnitConverter)pCadastralPacketManager;
        pUnitConversion.ConvertDistance(esriCadastralUnitConversionType.esriCUCFromMetric, 
        dMaxEast, ref dDistEast);
        pUnitConversion.ConvertDistance(esriCadastralUnitConversionType.esriCUCFromMetric, 
        dMaxNorth, ref dDistNorth);

        dMaxShift = Math.Sqrt((dDistEast * dDistEast) + (dDistNorth * dDistNorth));

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

      finally
      {
        MaxShift = dMaxShift;
        Summary=sSummary;
      }
    }
        private bool RunAdjustment(ICadastralPacketManager pCadastralPacketManager,
                                   ICadastralAdjustment pCadAdj, ICadastralAdjustment3 pCadAdjEx, int Iteration, out double MaxShift, out string Summary)
        {
            esriCadastralDistanceUnits eDistUnits  = esriCadastralDistanceUnits.esriCDUUSSurveyFoot;
            esriDirectionType          eDirectType = esriDirectionType.esriDTNorthAzimuth;
            esriCadastralAreaUnits     eAreaUnits  = esriCadastralAreaUnits.esriCAUAcre;

            ICadastralPlan pCadPlan = (ICadastralPlan)pCadAdj;
            IEnumGSPlans   pGSPlans = pCadPlan.GetPlans(enumGSPlansType.enumGSPlansWithParcels);

            pGSPlans.Reset();
            IGSPlan pGSPlan = pGSPlans.Next();

            while (pGSPlan != null)
            {
                eDistUnits  = pGSPlan.DistanceUnits;
                eDirectType = pGSPlan.DirectionFormat;
                eAreaUnits  = esriCadastralAreaUnits.esriCAUAcre;
                break; //just use the first one
            }

            double dMaxShift = -999;
            string sSummary  = "";

            MaxShift = dMaxShift;
            try
            {
                //get the units from the map plan

                sSummary =
                    pCadAdj.PerformAdjustment(false, m_sBrowseFilePath, null, eDistUnits, eDirectType, eAreaUnits);

                double dMaxEast  = -999;
                double dMaxNorth = -999;
                int    iPt       = -999;
                pCadAdjEx.GetMaxShiftData(ref iPt, ref dMaxEast, ref dMaxNorth);

                double dDistEast  = -999;
                double dDistNorth = -999;

                IMetricUnitConverter pUnitConversion = (IMetricUnitConverter)pCadastralPacketManager;
                pUnitConversion.ConvertDistance(esriCadastralUnitConversionType.esriCUCFromMetric,
                                                dMaxEast, ref dDistEast);
                pUnitConversion.ConvertDistance(esriCadastralUnitConversionType.esriCUCFromMetric,
                                                dMaxNorth, ref dDistNorth);

                dMaxShift = Math.Sqrt((dDistEast * dDistEast) + (dDistNorth * dDistNorth));

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

            finally
            {
                MaxShift = dMaxShift;
                Summary  = sSummary;
            }
        }
        private void btnRun_Click(object sender, EventArgs e)
        {
            double dConvTol     = 0.003;
            int    iRepeatCount = 2;
            double dMaxShift    = 0;

            double dVal = 0;

            if (Double.TryParse(this.txtMainDistResReport.Text, out dVal))
            {
                //write to registry
                Utilities FabUTILS = new Utilities();
                string    sVersion = FabUTILS.GetDesktopVersionFromRegistry();
                FabUTILS.WriteToRegistry(RegistryHive.CurrentUser,
                                         "Software\\ESRI\\Desktop" + sVersion + "\\ArcMap\\Cadastral\\AddIn.ParcelEditHelper",
                                         "LSADistanceToleranceReport", this.txtMainDistResReport.Text, true);
                FabUTILS = null;
            }

            bool   bAdjResult = true;
            string sSummary   = "";

            #region Setup Adjustment & Verify that there's enough information

            ICadastralPacketManager pCadastralPacketManager = null;
            ICadastralAdjustment    pCadAdj     = null;
            ICadastralAdjustment3   pCadAdjEx   = null;
            ICadastralMapEdit       pCadMapEdit = null;

            LoadValuesFromRegistry();

            UID pUID = new UIDClass();
            pUID.Value = "{114D685F-99B7-4B63-B09F-6D1A41A4DDC1}";
            ICadastralEditor pCadEd     = (ICadastralEditor)ArcMap.Application.FindExtensionByCLSID(pUID);
            ICadastralFabric pCadFabric = pCadEd.CadastralFabric;

            pCadastralPacketManager = (ICadastralPacketManager)pCadEd;
            bool open = pCadastralPacketManager.PacketOpen;

            ISelectionSet     pBeforeSS        = null;
            IFeatureSelection pParcelSelection = null;

            if (!open)
            {
                ICadastralSelection pSelection = (ICadastralSelection)pCadEd;
                IEnumGSParcels      pParcels   = pSelection.SelectedParcels;
                IEnumCEParcels      pCEParcels = (IEnumCEParcels)pParcels;
                if (pCEParcels != null)
                {
                    long count = pCEParcels.Count;
                    if (count == 0)
                    {
                        MessageBox.Show("There are no parcels selected to adjust." + Environment.NewLine
                                        + "Please select parcels and try again.", "Fabric Adjustment");
                        return;
                    }
                }

                ICadastralFabricLayer pCFLayer = pCadEd.CadastralFabricLayer;
                if (pCFLayer != null)
                {
                    IFeatureLayer pParcelLayer = pCFLayer.get_CadastralSubLayer(esriCadastralFabricRenderer.esriCFRParcels);
                    pParcelSelection = (IFeatureSelection)pParcelLayer;
                    if (pParcelSelection != null)
                    {
                        pBeforeSS = pParcelSelection.SelectionSet;
                    }
                }
            }

            pCadMapEdit = (ICadastralMapEdit)pCadEd;
            pCadMapEdit.StartMapEdit(esriMapEditType.esriMEParcelSelection, "Fabric Adjustment", false);

            ICadastralPacket pCadastralPacket = pCadastralPacketManager.JobPacket;
            int cpCount = 0;

            ICadastralControlPoints pCPts = (ICadastralControlPoints)pCadastralPacket;
            if (pCPts != null)
            {
                IGeometry            pGeom    = null;
                IEnumGSControlPoints pEnumCPs = pCPts.GetControlPoints(pGeom);
                pEnumCPs.Reset();
                IGSControlPoint pCP;
                if (pEnumCPs != null)
                {
                    pCP = pEnumCPs.Next();
                    while ((pCP != null) && (cpCount < 2))
                    {
                        if (pCP.Active)
                        {
                            cpCount++;
                        }
                    }
                }
            }

            if (cpCount < 2)
            {
                MessageBox.Show("Please make sure that at least 2 control points are" +
                                Environment.NewLine + "attached to the selected parcels.", "Fabric Adjustment");
                return;
            }
            pCadAdj   = (ICadastralAdjustment)pCadastralPacket;
            pCadAdjEx = (ICadastralAdjustment3)pCadastralPacket;
            ApplyAdjustmentSettings(pCadAdj, pCadAdjEx);

            #endregion

            double dHighestMaxShift = 0;

            //// Change display text depending on count
            //string itemText = count > 1 ? "items" : "item";

            for (int i = 1; i <= iRepeatCount; i++)
            {
                if (!RunAdjustment(pCadastralPacketManager, pCadAdj, pCadAdjEx, i, out dMaxShift, out sSummary))
                {
                    bAdjResult = false;
                    break;
                }
                if (dHighestMaxShift > dMaxShift)
                {
                    dHighestMaxShift = dMaxShift;
                }

                pCadAdj.AcceptAdjustment();
                if (dMaxShift < dConvTol)
                {
                    break;
                }
            }

            if (bAdjResult)
            {
                lblAdjResult.Text = "Adjustment Complete";
            }
            else
            {
                lblAdjResult.Text = "Adjustment Failed";
            }

            lblAdjResult.Visible = true;

            dlgAdjustmentResults AdjResults = new dlgAdjustmentResults();
            AdjResults.txtReport.Text = sSummary;

            //Display the dialog
            DialogResult pDialogResult = AdjResults.ShowDialog();
            if (pDialogResult != DialogResult.OK)
            {
                AdjResults = null;
                pCadMapEdit.StopMapEdit(false);
            }
            else
            {
                pCadMapEdit.StopMapEdit(true);
            }

            pParcelSelection.SelectionSet = pBeforeSS;

            Utilities FabUTILS2 = new Utilities();
            FabUTILS2.RefreshFabricLayers(ArcMap.Document.FocusMap, pCadFabric);
            FabUTILS2 = null;
        }
Exemple #11
0
        protected override void OnClick()
        {
            // **SAMPLE CODE NOTE**
            // the following code show the mechanics of creating a new parcel using the ICadastralMapEdit interface
            // there is no user interface to enter parcel record data, and the parcel line records are hard -coded
            // for the purposes of this sample code. The center of the map extent is used as the point of beginning
            // for the parcel.
            ICadastralEditor   pCadEd         = (ICadastralEditor)ArcMap.Application.FindExtensionByName("esriCadastralUI.CadastralEditorExtension");
            IParcelEditManager pParcEditorMan = (IParcelEditManager)pCadEd;

            IEditor pEd = (IEditor)ArcMap.Application.FindExtensionByName("esri object editor");

            if (pEd.EditState == esriEditState.esriStateNotEditing)
            {
                MessageBox.Show("Please start editing and try again.");
                return;
            }

            try
            {
                ICadastralPacketManager pCadPacketMan = (ICadastralPacketManager)pCadEd;
                bool bStartedWithPacketOpen           = pCadPacketMan.PacketOpen;
                if (!bStartedWithPacketOpen)
                {
                    pEd.StartOperation();
                }

                //1. Start map edit session
                ICadastralMapEdit pCadMapEdit = (ICadastralMapEdit)pCadEd;
                pCadMapEdit.StartMapEdit(esriMapEditType.esriMEEmpty, "NewParcel", false);

                //2.	Get job packet
                ICadastralPacket pCadaPacket = pCadPacketMan.JobPacket;

                //3.	Create Plan (new)
                string sPlanName = "My New Plan";
                //first check to ensure plan is not already in the database.
                IGSPlan pGSPlan = FindFabricPlanByName(sPlanName, pCadEd);

                if (pGSPlan == null)
                {
                    //if plan is null, it was not found and can be created
                    pGSPlan = new GSPlanClass();
                    // 3.a set values
                    pGSPlan.Accuracy = 4;
                    pGSPlan.Name     = sPlanName;
                }

                //3.b Add the plan to the job packet
                ICadastralPlan pCadaPlan = (ICadastralPlan)pCadaPacket;
                pCadaPlan.AddPlan(pGSPlan);

                //4.	Create Parcel
                ICadastralParcel pCadaParcel  = (ICadastralParcel)pCadaPacket;
                IGSParcel        pNewGSParcel = new GSParcelClass();
                //Make sure that any extended attributes on the parcel have their default values set
                IGSAttributes pGSAttributes = (IGSAttributes)pNewGSParcel;
                if (pGSAttributes != null)
                {
                    ICadastralObjectSetup pCadaObjSetup = (ICadastralObjectSetup)pParcEditorMan;
                    pCadaObjSetup.AddExtendedAttributes(pGSAttributes);
                    pCadaObjSetup.SetDefaultValues(pGSAttributes);
                }

                //4a.	Add the parcel to the packet. (do this before addlines)
                // - This will enable us to Acquire the parcel ID,
                // - Having the parcel attached to the packet allows InsertLine to function.
                pCadaParcel.AddParcel(pNewGSParcel);
                pNewGSParcel.Lot  = "NewParcel";
                pNewGSParcel.Type = 7;
                //4b.	Set Plan (created above)
                IGSPlan thePlan = pCadaPlan.GetPlan(sPlanName);
                pNewGSParcel.Plan = thePlan;
                //4c.	Insert GSLines (from new) into GSParcel
                //4d. To bypass join, you can create GSPoints and assign those point IDs to the GSLines.
                ICadastralPoints     pCadaPoints     = (ICadastralPoints)pCadaPacket;
                IMetricUnitConverter pMetricUnitConv = (IMetricUnitConverter)pCadEd;

                //Set up the initial start point, POB
                //This sample code starts from the middle of the map, and defines 4 lines of a parcel
                //The first course is a straight line, the other 3 courses are circular arcs
                IArea  pArea = (IArea)ArcMap.Document.ActiveView.Extent;
                IPoint pPt1  = pArea.Centroid;

                IZAware pZAw = (IZAware)pPt1;
                pZAw.ZAware = true;
                pPt1.Z      = 0; //defaulting to 0

                //Convert the point into metric units, and get a new (in-mem) point id
                IGSPoint pGSPointFrom = pMetricUnitConv.SetGSPoint(pPt1);
                pCadaPoints.AddPoint(pGSPointFrom);
                int iID1 = pGSPointFrom.Id;

                int index = 0;
                //++++++++++++ Course 1 ++++++++++++++
                int iID2 = -1;
                //From, Direction (NAz Radians), Distance (map's projection units), Radius
                IGSLine pGSLine = CreateGSLine(pMetricUnitConv, pCadaPoints, ref pPt1,
                                               iID1, 0, 100, 0, -1, -1, -1, true, out iID2);
                //Add the line to the new parcel
                if (pGSLine != null)
                {
                    pNewGSParcel.InsertLine(++index, pGSLine);
                }

                //++++++++++++ Course 2 ++++++++++++++
                int iID3 = -1;
                pGSLine = CreateGSLine(pMetricUnitConv, pCadaPoints, ref pPt1,
                                       iID2, (Math.PI / 2), 100, -80, -1, -1, -1, true, out iID3);
                if (pGSLine != null)
                {
                    pNewGSParcel.InsertLine(++index, pGSLine);
                }

                //++++++++++++ Course 3 ++++++++++++++
                int iID4 = -1;
                pGSLine = CreateGSLine(pMetricUnitConv, pCadaPoints, ref pPt1,
                                       iID3, Math.PI, 100, 80, -1, -1, -1, true, out iID4);
                if (pGSLine != null)
                {
                    pNewGSParcel.InsertLine(++index, pGSLine);
                }

                //++++++++++++ Course 4 ++++++++++++++
                //close back to point of beginning
                int i = -1;
                pGSLine = CreateGSLine(pMetricUnitConv, pCadaPoints, ref pPt1,
                                       iID4, (3 * Math.PI / 2), 100, 200, -1, -1, -1, false, out i);
                pGSLine.ToPoint = iID1; //closing the traverse back to the POB
                if (pGSLine != null)
                {
                    pNewGSParcel.InsertLine(++index, pGSLine);
                }

                //Add radial lines for circular curves
                pNewGSParcel.AddRadialLines();

                // 4.e then set join=true on the parcel.
                pNewGSParcel.Joined = true;

                //let the packet know that a change has been made
                pCadPacketMan.SetPacketModified(true);

                //save the new parcel
                try
                {
                    pCadMapEdit.StopMapEdit(true);
                }
                catch
                {
                    if (!bStartedWithPacketOpen)
                    {
                        pEd.AbortOperation();
                    }
                    return;
                }
                if (!bStartedWithPacketOpen)
                {
                    pEd.StopOperation("New Parcel");
                }
                pCadPacketMan.PartialRefresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        protected override void OnMouseDown(MouseEventArgs arg)
        {
            IFeatureLayer pPointLayer     = null;
            IFeatureLayer pLineLayer      = null;
            IArray        pParcelLayers   = null;
            IFeatureLayer pControlLayer   = null;
            IFeatureLayer pLinePointLayer = null;

            double         dXYTol      = 0.003;
            clsFabricUtils FabricUTILS = new clsFabricUtils();
            IEditor        pEd         = (IEditor)ArcMap.Application.FindExtensionByName("esri object editor");

            //first get the extension
            UID pUID = new UIDClass();

            pUID.Value = "{114D685F-99B7-4B63-B09F-6D1A41A4DDC1}";
            ICadastralExtensionManager2 pCadExtMan = (ICadastralExtensionManager2)ArcMap.Application.FindExtensionByCLSID(pUID);
            ICadastralEditor            pCadEd     = (ICadastralEditor)ArcMap.Application.FindExtensionByCLSID(pUID);

            //check if there is a Manual Mode "modify" job active ===========
            ICadastralPacketManager pCadPacMan = (ICadastralPacketManager)pCadExtMan;

            if (pCadPacMan.PacketOpen)
            {
                FabricUTILS.ExecuteCommand(m_CommUID);
                MessageBox.Show("This tool cannot be used when there is an open parcel, construction, or job.\r\nPlease complete or discard the open items, and try again.");
                return;
            }

            ICadastralFabric pCadFabric = null;

            //if we're in an edit session then grab the target fabric
            if (pEd.EditState == esriEditState.esriStateEditing)
            {
                pCadFabric = pCadEd.CadastralFabric;
            }
            else
            {
                FabricUTILS.ExecuteCommand(m_CommUID);
                MessageBox.Show("This tool works on a parcel fabric in an edit session.\r\nPlease start editing and try again.");
                return;
            }

            if (pCadFabric == null)
            {//find the first fabric in the map
                if (!FabricUTILS.GetFabricFromMap(ArcMap.Document.ActiveView.FocusMap, out pCadFabric))
                {
                    FabricUTILS.ExecuteCommand(m_CommUID);
                    MessageBox.Show("No Parcel Fabric found in the map.\r\nPlease add a single fabric to the map, and try again.");
                    return;
                }
            }

            IGeoDataset pGeoDS = (IGeoDataset)pCadFabric;
            ISpatialReferenceTolerance pSpatRefTol = (ISpatialReferenceTolerance)pGeoDS.SpatialReference;

            if (pSpatRefTol.XYToleranceValid == esriSRToleranceEnum.esriSRToleranceOK)
            {
                dXYTol = pSpatRefTol.XYTolerance;
            }

            IMouseCursor          pMouseCursor        = null;
            ISpatialFilter        pSpatFilt           = null; //spatial filter query hinging off the dragged rectangle selection
            IQueryFilter          pQuFilter           = null; //used for the non-spatial query for radial lines, as they have no geometry
            IRubberBand2          pRubberRect         = null;
            IGeometryBag          pGeomBag            = null;
            ITopologicalOperator5 pUnionedPolyine     = null;
            IPolygon      pBufferedToolSelectGeometry = null;         //geometry used to search for parents
            IFIDSet       pLineFIDs            = null;                //the FIDSet used to collect the lines that'll be deleted
            IFIDSet       pPointFIDs           = null;                // the FIDSet used to collect the points that'll be deleted
            IFIDSet       pLinePointFIDs       = null;                // the FIDSet used to collect the line-points that'll be deleted
            List <int>    pDeletedLinesPoints  = new List <int>();    //list used to stage the ids for points that are referenced by lines
            List <int>    pUsedPoints          = new List <int>();    //list used to collect pointids that are referenced by existing lines
            List <int>    CtrPointIDList       = new List <int>();    //list for collecting the ids of center points
            List <int>    pParcelsList         = new List <int>();    //used only to avoid adding duplicates to IN clause string for, based on ties to radial lines
            List <int>    pOrphanPointsList    = new List <int>();    //list of orphan points defined from radial ines
            List <int>    pPointsInsideBoxList = new List <int>();    //list of parcels that exist and that intersect the drag-box
            List <string> sFromToPair          = new List <string>(); //list of from/to pairs for manging line points
            List <int>    pLineToParcelIDRef   = new List <int>();    //list of parcel id refs stored on lines

            IInvalidArea3 pInvArea = null;

            IFeatureClass pLines      = null;
            IFeatureClass pPoints     = null;
            IFeatureClass pParcels    = null;
            IFeatureClass pLinePoints = null;
            IWorkspace    pWS         = null;

            try
            {
                #region define the rubber envelope geometry
                pRubberRect = new RubberEnvelopeClass();
                IGeometry ToolSelectEnvelope = pRubberRect.TrackNew(ArcMap.Document.ActiveView.ScreenDisplay, null);

                if (ToolSelectEnvelope == null)
                {
                    return;
                }

                ISegmentCollection pSegmentColl = new PolygonClass();
                pSegmentColl.SetRectangle(ToolSelectEnvelope.Envelope);
                IPolygon ToolSelectGeometry = (IPolygon)pSegmentColl;

                if (pCadFabric == null)
                {
                    return;
                }

                pMouseCursor = new MouseCursorClass();
                pMouseCursor.SetCursor(2);

                #endregion

                FabricUTILS.GetFabricSubLayersFromFabric(ArcMap.Document.ActiveView.FocusMap, pCadFabric,
                                                         out pPointLayer, out pLineLayer, out pParcelLayers, out pControlLayer,
                                                         out pLinePointLayer);

                #region get tables and field indexes
                pLines      = (IFeatureClass)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTLines);
                pPoints     = (IFeatureClass)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints);
                pParcels    = (IFeatureClass)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels);
                pLinePoints = (IFeatureClass)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTLinePoints);
                string sPref = "";
                string sSuff = "";

                int iCtrPtFldIDX  = pLines.FindField("CENTERPOINTID");
                int iFromPtFldIDX = pLines.FindField("FROMPOINTID");
                int iToPtFldIDX   = pLines.FindField("TOPOINTID");
                int iCatFldIDX    = pLines.FindField("CATEGORY");
                int iParcelIDX    = pLines.FindField("PARCELID");
                int iDistanceIDX  = pLines.FindField("DISTANCE");


                pWS = pLines.FeatureDataset.Workspace;
                ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS;
                sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix);
                sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix);

                pSpatFilt            = new SpatialFilterClass();
                pSpatFilt.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                pSpatFilt.Geometry   = ToolSelectGeometry;
                #endregion

                #region center point
                //need to make sure that center points are correctly handled for cases where the center point
                //is inside the select box, but the curve itself is not. The following is used to build an
                //IN CLAUSE for All the center points that are found within the tool's select geometry.
                int    iIsCtrPtIDX    = pPoints.FindField("CENTERPOINT");
                int    iCount         = 0;
                int    iCntCtrPoint   = 0;
                string sCtrPntIDList1 = "";

                IFeatureCursor pFeatCursPoints = pPoints.Search(pSpatFilt, false);
                IFeature       pFeat7          = pFeatCursPoints.NextFeature();
                while (pFeat7 != null)
                {
                    iCount++;
                    int    iVal     = -1;
                    object Attr_val = pFeat7.get_Value(iIsCtrPtIDX);

                    if (Attr_val != DBNull.Value)
                    {
                        iVal = Convert.ToInt32(pFeat7.get_Value(iIsCtrPtIDX));
                    }

                    if (iVal == 1)
                    {
                        if (sCtrPntIDList1.Trim() == "")
                        {
                            sCtrPntIDList1 += pFeat7.OID.ToString();
                        }
                        else
                        {
                            sCtrPntIDList1 += "," + pFeat7.OID.ToString();
                        }
                        iCntCtrPoint++;
                    }
                    pPointsInsideBoxList.Add(pFeat7.OID); //used to check for orphan linepoints
                    pOrphanPointsList.Add(pFeat7.OID);    //this gets whittled down till only "pure" orphan points remain
                    Marshal.ReleaseComObject(pFeat7);
                    pFeat7 = pFeatCursPoints.NextFeature();
                }
                Marshal.FinalReleaseComObject(pFeatCursPoints);
                #endregion

                #region create convex hull of lines
                //get the lines that intersect the search box and build a
                //polygon search geometry being the convex hull of those lines.
                IFeatureCursor pFeatCursLines = pLines.Search(pSpatFilt, false);
                pGeomBag = new GeometryBagClass();
                IGeometryCollection pGeomColl = (IGeometryCollection)pGeomBag;
                IFeature            pFeat1    = pFeatCursLines.NextFeature();
                m_sDebug = "Add lines to Geometry Collection.";
                string sParcelRefOnLines = "";
                object missing           = Type.Missing;
                while (pFeat1 != null)
                {
                    int    iVal    = (int)pFeat1.get_Value(iFromPtFldIDX);
                    string sFromTo = iVal.ToString() + ":";

                    if (pOrphanPointsList.Contains(iVal)) //Does this need to be done...will remove fail if it's not there?
                    {
                        pOrphanPointsList.Remove(iVal);   //does this need to be in the if block?
                    }
                    iVal     = (int)pFeat1.get_Value(iToPtFldIDX);
                    sFromTo += iVal.ToString();
                    if (pOrphanPointsList.Contains(iVal))
                    {
                        pOrphanPointsList.Remove(iVal);
                    }

                    sFromToPair.Add(sFromTo);
                    pGeomColl.AddGeometry(pFeat1.ShapeCopy, missing, missing);

                    if (sParcelRefOnLines.Trim() == "")
                    {
                        sParcelRefOnLines = pFeat1.get_Value(iParcelIDX).ToString();
                    }
                    else
                    {
                        sParcelRefOnLines += "," + pFeat1.get_Value(iParcelIDX).ToString();
                    }

                    Marshal.ReleaseComObject(pFeat1);
                    pFeat1 = pFeatCursLines.NextFeature();
                }
                Marshal.FinalReleaseComObject(pFeatCursLines);

                #endregion

                #region Add Center Points for curves outside map extent

                if (iCntCtrPoint > 999)
                {
                    throw new InvalidOperationException("The Delete Orphans tool works with smaller amounts of data." + Environment.NewLine +
                                                        "Please try again, by selecting fewer fabric lines and points. (More than 1000 center points returned.)");
                }

                //If there is no line geometry found, and there are also no points found, then nothing to do...
                if (pGeomColl.GeometryCount == 0 && iCount == 0)
                {
                    return;
                }

                //Radial lines have no geometry so there is a special treatment for those;
                //that special treatment takes two forms,
                //1. if a circular arc is selected and it turns out that it is an orphan line, then we
                //need to take down its radial lines, and its center point as well.
                //2. if a center point is selected, we need to check if it's an orphan, by searching for its parent.
                //The parent parcel can easily be well beyond the query rectangle, so the original
                //search rectangle is buffered by the largest found radius distance, to make sure that all
                //parent parcels are "find-able."

                //The radial lines themselves are also needed; Get the radial lines from the Center Points
                //CtrPt is always TO point, so find lines CATEGORY = 4 AND TOPOINT IN ()
                string sRadialLineListParcelID = "";
                string sRadialLinesID          = "";
                string sRadialLinePoints       = "";

                double dRadiusBuff = 0;
                pQuFilter = new QueryFilterClass();
                //Find all the radial lines based on the search query
                if (sCtrPntIDList1.Trim() != "")
                {
                    pQuFilter.WhereClause = "CATEGORY = 4 AND TOPOINTID IN (" + sCtrPntIDList1 + ")";

                    //add all the *references* to Parcel ids for the radial lines,
                    //and add the ID's of the lines
                    IFeatureCursor pFeatCursLines8 = pLines.Search(pQuFilter, false);
                    IFeature       pFeat8          = pFeatCursLines8.NextFeature();
                    while (pFeat8 != null)
                    {
                        object Attr_val = pFeat8.get_Value(iDistanceIDX);
                        double dVal     = 0;
                        if (Attr_val != DBNull.Value)
                        {
                            dVal = Convert.ToDouble(Attr_val);
                        }
                        dRadiusBuff = dRadiusBuff > dVal ? dRadiusBuff : dVal;
                        int iVal = Convert.ToInt32(pFeat8.get_Value(iParcelIDX));
                        if (!pParcelsList.Contains(iVal))
                        {
                            if (sRadialLineListParcelID.Trim() == "")
                            {
                                sRadialLineListParcelID += Convert.ToString(iVal);
                            }
                            else
                            {
                                sRadialLineListParcelID += "," + Convert.ToString(iVal);
                            }
                        }
                        pParcelsList.Add(iVal);

                        //pOrphanPointsList is used for "Pure Orphan point" detection
                        //meaning that these are points that do not have ANY line, not even an orphan line.
                        iVal = (int)pFeat8.get_Value(iFromPtFldIDX);
                        if (pOrphanPointsList.Contains(iVal))
                        {
                            pOrphanPointsList.Remove(iVal);
                        }

                        iVal = (int)pFeat8.get_Value(iToPtFldIDX);
                        if (pOrphanPointsList.Contains(iVal))
                        {
                            pOrphanPointsList.Remove(iVal);
                        }

                        if (sRadialLinesID.Trim() == "")
                        {
                            sRadialLinesID += Convert.ToString(iVal);
                        }
                        else
                        {
                            sRadialLinesID += "," + Convert.ToString(iVal);
                        }

                        //Add from point to list
                        if (sRadialLinePoints.Trim() == "")
                        {
                            sRadialLinePoints += Convert.ToString(pFeat8.get_Value(iFromPtFldIDX));
                        }
                        else
                        {
                            sRadialLinePoints += "," + Convert.ToString(pFeat8.get_Value(iFromPtFldIDX));
                        }
                        //Add To point to list
                        sRadialLinePoints += "," + Convert.ToString(pFeat8.get_Value(iToPtFldIDX));

                        Marshal.ReleaseComObject(pFeat8);
                        pFeat8 = pFeatCursLines8.NextFeature();
                    }
                    Marshal.FinalReleaseComObject(pFeatCursLines8);

                    //create a polygon goeometry that is a buffer of the selection rectangle expanded
                    //to the greatest radius of all the radial lines found.
                    ITopologicalOperator topologicalOperator = (ITopologicalOperator)ToolSelectGeometry;
                    pBufferedToolSelectGeometry = topologicalOperator.Buffer(dRadiusBuff) as IPolygon;
                }
                else
                {
                    pQuFilter.WhereClause = "";
                }
                #endregion

                #region OrphanLines

                if (pGeomColl.GeometryCount != 0)
                {
                    pUnionedPolyine = new PolylineClass();
                    pUnionedPolyine.ConstructUnion((IEnumGeometry)pGeomBag);
                    ITopologicalOperator pTopoOp     = (ITopologicalOperator)pUnionedPolyine;
                    IGeometry            pConvexHull = pTopoOp.ConvexHull();
                    //With this convex hull, do a small buffer,
                    //theis search geometry is used as a spatial query on the parcel polygons
                    //and also on the parcel lines, to build IN Clauses
                    pTopoOp = (ITopologicalOperator)pConvexHull;
                    IGeometry pBufferedConvexHull = pTopoOp.Buffer(10 * dXYTol);
                    if (pBufferedToolSelectGeometry != null)
                    {
                        pTopoOp = (ITopologicalOperator)pBufferedToolSelectGeometry;
                        IGeometry pUnionPolygon = pTopoOp.Union(pBufferedConvexHull);
                        pSpatFilt.Geometry = pUnionPolygon;
                    }
                    else
                    {
                        pSpatFilt.Geometry = pBufferedConvexHull;
                    }
                }
                else
                {
                    if (pQuFilter.WhereClause.Trim() == "" && pBufferedToolSelectGeometry == null)
                    {
                        pSpatFilt.Geometry = ToolSelectGeometry;
                    }
                    else
                    {
                        pSpatFilt.Geometry = pBufferedToolSelectGeometry;
                    }
                }

                IColor pColor = new RgbColorClass();
                pColor.RGB = System.Drawing.Color.Blue.ToArgb();
                IScreenDisplay pScreenDisplay = ArcMap.Document.ActiveView.ScreenDisplay;
                FabricUTILS.FlashGeometry(pSpatFilt.Geometry, pScreenDisplay, pColor, 5, 100);

                pSpatFilt.SearchOrder = esriSearchOrder.esriSearchOrderSpatial;

                m_sDebug = "Searching Parcels table.";
                pInvArea = new InvalidAreaClass();
                IFeatureCursor pFeatCursParcels = pParcels.Search(pSpatFilt, false);
                IFeature       pFeat2           = pFeatCursParcels.NextFeature();
                string         sParcelIDList    = "";
                iCount = 0;
                //create the "NOT IN" CLAUSE for parcels that exist in the DB and that are within the search area
                //Will be used as a search on lines to get the Orphan Lines

                while (pFeat2 != null)
                {
                    iCount++;
                    if (sParcelIDList.Trim() == "")
                    {
                        sParcelIDList += pFeat2.OID.ToString();
                    }
                    else
                    {
                        sParcelIDList += "," + pFeat2.OID.ToString();
                    }

                    Marshal.ReleaseComObject(pFeat2);
                    if (iCount > 999)
                    {
                        break;
                    }
                    pFeat2 = pFeatCursParcels.NextFeature();
                }
                Marshal.FinalReleaseComObject(pFeatCursParcels);

                //if we have more than 999 in clause tokens, there will be problems on Oracle.
                //Since this is an interactive tool, we expect it not to be used on a large amount of data.
                //for this reason, the following message is displayed if more than 999 parcels are returned in this query.
                //TODO: for the future this can be made to work on larger sets of data.
                if (iCount > 999)
                {
                    throw new InvalidOperationException("The Delete Orphans tool works with smaller amounts of data." + Environment.NewLine +
                                                        "Please try again, by selecting fewer fabric lines and points. (More than 1000 parcels returned.)");
                }

                m_sDebug = "Building the used points list.";
                //This first pass contains all references to points found within the parent parcel search buffer
                //Later, points are removed from this list
                IFeatureCursor pFeatCursLargerLineSet = pLines.Search(pSpatFilt, false);
                IFeature       pFeat3 = pFeatCursLargerLineSet.NextFeature();
                while (pFeat3 != null)
                {
                    iCount++;
                    object Attr_val = pFeat3.get_Value(iCtrPtFldIDX);
                    if (Attr_val != DBNull.Value)
                    {
                        pUsedPoints.Add(Convert.ToInt32(Attr_val)); //add center point
                    }
                    int iVal = (int)pFeat3.get_Value(iFromPtFldIDX);
                    pUsedPoints.Add(iVal);//add from point

                    iVal = (int)pFeat3.get_Value(iToPtFldIDX);
                    pUsedPoints.Add(iVal);//add to point

                    Marshal.ReleaseComObject(pFeat3);
                    pFeat3 = pFeatCursLargerLineSet.NextFeature();
                }
                Marshal.FinalReleaseComObject(pFeatCursLargerLineSet);

                //pUsedPoints list is at this stage, references to points for all lines found within the search area.
                //use the IN clause of the parcel ids to search for lines within
                //the original search box, and that are also orphans that do not have a parent parcel.
                pSpatFilt.WhereClause = "";
                pSpatFilt.Geometry    = ToolSelectGeometry;
                pSpatFilt.SpatialRel  = esriSpatialRelEnum.esriSpatialRelIntersects;
                pSpatFilt.SearchOrder = esriSearchOrder.esriSearchOrderSpatial;

                IFeatureCursor pFeatCursor = null;
                if (pGeomColl.GeometryCount == 0)
                {
                    if (sParcelIDList.Trim().Length > 0 && sCtrPntIDList1.Trim().Length > 0)
                    {
                        pQuFilter.WhereClause = "(PARCELID NOT IN (" + sParcelIDList +
                                                ")) AND (CATEGORY = 4 AND TOPOINTID IN (" + sCtrPntIDList1 + "))";
                        pFeatCursor = pLines.Search(pQuFilter, false);
                    }
                    else if (sParcelIDList.Trim().Length == 0 && sCtrPntIDList1.Trim().Length > 0)
                    {
                        pQuFilter.WhereClause = "CATEGORY = 4 AND TOPOINTID IN (" + sCtrPntIDList1 + ")";
                        pFeatCursor           = pLines.Search(pQuFilter, false);
                    }
                }
                else
                {//do a spatial query
                    if (sParcelIDList.Trim().Length > 0)
                    {
                        pSpatFilt.WhereClause = "PARCELID NOT IN (" + sParcelIDList + ")";
                    }
                    else
                    {
                        pSpatFilt.WhereClause = "";
                    }
                    pFeatCursor = pLines.Search(pSpatFilt, false);
                }

                m_sDebug = "Collecting lines to be deleted.";

                //start collecting the lines that need to be deleted
                iCount = 0;
                int    iCtrPointCount         = 0;
                string sCtrPointIDList        = "";
                string sLineParcelIDReference = "";
                //Feature cursor is lines that are NOT IN the ParcelIDList

                if (pFeatCursor != null)
                {
                    pLineFIDs = new FIDSetClass();
                    IFeature pFeat4 = pFeatCursor.NextFeature();
                    while (pFeat4 != null)
                    {
                        iCount++;
                        pLineFIDs.Add(pFeat4.OID);
                        int iParcRef = Convert.ToInt32(pFeat4.get_Value(iParcelIDX));
                        if (sLineParcelIDReference.Trim() == "")
                        {
                            sLineParcelIDReference = iParcRef.ToString();
                        }
                        else
                        {
                            if (!pLineToParcelIDRef.Contains(iParcRef))
                            {
                                sLineParcelIDReference += "," + iParcRef.ToString();
                            }
                        }
                        pLineToParcelIDRef.Add(iParcRef);
                        pInvArea.Add((IObject)pFeat4);
                        //now for this line, get it's points
                        //first add the center point reference if there is one
                        object Attr_val = pFeat4.get_Value(iCtrPtFldIDX);
                        if (Attr_val != DBNull.Value)
                        {
                            iCtrPointCount++;
                            int iCtrPointID = Convert.ToInt32(Attr_val);
                            pDeletedLinesPoints.Add(iCtrPointID); //add this line's center point
                            pUsedPoints.Remove(iCtrPointID);

                            if (sCtrPointIDList.Trim() == "")
                            {
                                sCtrPointIDList = iCtrPointID.ToString();
                            }
                            else
                            {
                                if (CtrPointIDList.Contains(iCtrPointID))
                                {
                                    iCtrPointCount--;
                                }
                                else
                                {
                                    sCtrPointIDList += "," + iCtrPointID.ToString();
                                }
                            }
                            CtrPointIDList.Add(iCtrPointID);//to keep track of repeats
                        }
                        //and also add the FROM and TO point references if they exist
                        int iVal = (int)pFeat4.get_Value(iFromPtFldIDX);
                        pDeletedLinesPoints.Add(iVal);//add FROM point
                        if (pGeomColl.GeometryCount > 0)
                        {
                            pUsedPoints.Remove(iVal);
                        }

                        iVal = (int)pFeat4.get_Value(iToPtFldIDX);
                        pDeletedLinesPoints.Add(iVal);//add TO point
                        if (pGeomColl.GeometryCount > 0)
                        {
                            pUsedPoints.Remove(iVal);
                        }

                        Marshal.ReleaseComObject(pFeat4);
                        if (iCtrPointCount > 999)
                        {
                            break;
                        }
                        pFeat4 = pFeatCursor.NextFeature();
                    }
                    Marshal.FinalReleaseComObject(pFeatCursor);
                }
                if (iCtrPointCount > 999)
                {
                    throw new InvalidOperationException("The Delete Orphans tool works with smaller amounts of data." + Environment.NewLine +
                                                        "Please try again, by selecting fewer fabric lines and points. (More than 1000 center points returned.)");
                }

                m_sDebug = "Adding orphan radial lines to list.";

                if (sCtrPointIDList.Trim().Length > 0)
                {
                    //add the Radial lines at each end of the curves using the collected CtrPtIDs
                    //CtrPt is always TO point, so find lines CATEGORY = 4 AND TOPOINT IN ()

                    pQuFilter.WhereClause = "CATEGORY = 4 AND TOPOINTID IN (" + sCtrPointIDList + ")";
                    pFeatCursor           = pLines.Search(pQuFilter, false);
                    IFeature pFeat5 = pFeatCursor.NextFeature();
                    while (pFeat5 != null)
                    {
                        pLineFIDs.Add(pFeat5.OID);
                        int iParcRef = Convert.ToInt32(pFeat5.get_Value(iParcelIDX));
                        pLineToParcelIDRef.Add(iParcRef);
                        if (sLineParcelIDReference.Trim() == "")
                        {
                            sLineParcelIDReference = iParcRef.ToString();
                        }
                        else
                        {
                            if (!pLineToParcelIDRef.Contains(iParcRef))
                            {
                                sLineParcelIDReference += "," + iParcRef.ToString();
                            }
                        }
                        Marshal.ReleaseComObject(pFeat5);
                        pFeat5 = pFeatCursor.NextFeature();
                    }
                    Marshal.FinalReleaseComObject(pFeatCursor);
                }
                else
                {
                    pQuFilter.WhereClause = "";
                }

                //refine the DeletedLinesPoints list
                foreach (int i in pUsedPoints)
                {
                    if (pDeletedLinesPoints.Contains(i))
                    {
                        do
                        {
                        } while (pDeletedLinesPoints.Remove(i));
                    }
                }

                //add the points to a new FIDSet
                pPointFIDs = new FIDSetClass();
                foreach (int i in pDeletedLinesPoints)
                {
                    pPointFIDs.Add(i);
                }

                #endregion

                #region OrphanPoints
                //We already know which points to delete based on taking down the orphan lines.
                //We need to still add to the points FIDSet those points that are "pure" ophan points
                //as defined for the pOrphanPointsList variable.
                //and add the orphan points to the points FIDSet
                foreach (int i in pOrphanPointsList)
                {
                    bool bFound = false;
                    pPointFIDs.Find(i, out bFound);
                    if (!bFound)
                    {
                        pPointFIDs.Add(i);
                    }
                }
                #endregion

                #region orphan Line points
                //next check for orphan line-points
                //the line-point is deleted if there is no underlying point
                //or if the from and to point references do not exist.
                pSpatFilt.WhereClause = "";
                pSpatFilt.Geometry    = ToolSelectGeometry;
                IFeatureCursor pFeatCursLinePoints = pLinePoints.Search(pSpatFilt, false);
                IFeature       pLPFeat             = pFeatCursLinePoints.NextFeature();
                int            iLinePtPointIdIdx   = pLinePoints.FindField("LINEPOINTID");
                int            iLinePtFromPtIdIdx  = pLinePoints.FindField("FROMPOINTID");
                int            iLinePtToPtIdIdx    = pLinePoints.FindField("TOPOINTID");

                pLinePointFIDs = new FIDSetClass();
                while (pLPFeat != null)
                {
                    bool bExistsA = true;

                    bool bExists1 = true;
                    bool bExists2 = true;
                    bool bExists3 = true;

                    int iVal = (int)pLPFeat.get_Value(iLinePtPointIdIdx);
                    pPointFIDs.Find(iVal, out bExists1);
                    if (!pPointsInsideBoxList.Contains(iVal))
                    {
                        bExistsA = false;
                    }

                    iVal = (int)pLPFeat.get_Value(iLinePtFromPtIdIdx);
                    string sFrom = iVal.ToString();
                    pPointFIDs.Find(iVal, out bExists2);

                    iVal = (int)pLPFeat.get_Value(iLinePtToPtIdIdx);
                    string sTo = iVal.ToString();
                    pPointFIDs.Find(iVal, out bExists3);

                    int iOID = pLPFeat.OID;

                    if (bExists1 || bExists2 || bExists3)
                    {
                        pLinePointFIDs.Add(iOID);
                    }

                    if (!sFromToPair.Contains(sFrom + ":" + sTo) && !sFromToPair.Contains(sTo + ":" + sFrom))
                    {
                        pLinePointFIDs.Find(iOID, out bExists1);
                        if (!bExists1)
                        {
                            pLinePointFIDs.Add(iOID);
                        }
                    }

                    //if (!bExistsA || !bExistsB || !bExistsC)
                    if (!bExistsA)
                    {
                        bool bFound = true;
                        pLinePointFIDs.Find(iOID, out bFound);
                        if (!bFound)
                        {
                            pLinePointFIDs.Add(iOID);
                        }
                    }
                    pPointsInsideBoxList.Contains(iVal);

                    Marshal.ReleaseComObject(pLPFeat);
                    pLPFeat = pFeatCursLinePoints.NextFeature();
                }

                Marshal.FinalReleaseComObject(pFeatCursLinePoints);
                #endregion

                #region Refine the lines that are on the delete list
                //next step is to refine and double-check to make sure that the lines that are on the delete list
                //do not have a parcel record somewhere else (not spatially connected to the line) (example unjoined, or bad geom)
                string sFreshlyFoundParcels = "";
                if (sLineParcelIDReference.Trim() != "")
                {
                    pQuFilter.WhereClause = sPref + pParcels.OIDFieldName + sSuff + " IN (" + sLineParcelIDReference + ")";
                    pFeatCursor           = pParcels.Search(pQuFilter, false);
                    IFeature pFeat6 = pFeatCursor.NextFeature();
                    while (pFeat6 != null)
                    {
                        int iOID = pFeat6.OID;
                        if (sFreshlyFoundParcels.Trim() == "")
                        {
                            sFreshlyFoundParcels = iOID.ToString();
                        }
                        else
                        {
                            sFreshlyFoundParcels += "," + iOID.ToString();
                        }
                        Marshal.ReleaseComObject(pFeat6);
                        pFeat6 = pFeatCursor.NextFeature();
                    }
                    Marshal.FinalReleaseComObject(pFeatCursor);

                    if (sFreshlyFoundParcels.Trim() != "")
                    {
                        pQuFilter.WhereClause = "PARCELID IN (" + sFreshlyFoundParcels + ")";
                        pFeatCursor           = pLines.Search(pQuFilter, false);
                        IFeature pFeat9 = pFeatCursor.NextFeature();
                        while (pFeat9 != null)
                        {
                            int  iOID    = pFeat9.OID;
                            bool bIsHere = false;
                            pLineFIDs.Delete(iOID);
                            int iVal = Convert.ToInt32(pFeat9.get_Value(iFromPtFldIDX));
                            pPointFIDs.Find(iVal, out bIsHere);
                            if (bIsHere)
                            {
                                pPointFIDs.Delete(iVal);
                            }

                            iVal = Convert.ToInt32(pFeat9.get_Value(iToPtFldIDX));
                            pPointFIDs.Find(iVal, out bIsHere);
                            if (bIsHere)
                            {
                                pPointFIDs.Delete(iVal);
                            }

                            Marshal.ReleaseComObject(pFeat9);
                            pFeat9 = pFeatCursor.NextFeature();
                        }
                        Marshal.FinalReleaseComObject(pFeatCursor);
                    }
                }
                #endregion

                #region Make sure the points on the delete list are not part of a construction
                //For post 10.0, Make sure the points on the delete list are not part of a construction if they are then null geometry
                //pQuFilter.WhereClause=pLines.LengthField.Name + " = 0 AND CATEGORY <> 4";
                //IFeatureCursor pFeatCursLines101 = pLines.Search(pQuFilter, false);
                //this would open a new cursor and do a query on the entire
                #endregion

                #region report results and do edits
                dlgReport Report = new dlgReport();
                //Display the dialog
                System.Drawing.Color BackColorNow = Report.textBox1.BackColor;
                if (iCount == 0 && pPointFIDs.Count() == 0 && pLinePointFIDs.Count() == 0)
                {
                    Report.textBox1.BackColor = System.Drawing.Color.LightGreen;
                    Report.textBox1.Text      = "Selected area has no orphan lines or points.";
                }
                else
                {
                    int iCount1 = 0;
                    int iCount2 = 0;
                    int iCount3 = 0;
                    if (pLineFIDs != null)
                    {
                        iCount1 = pLineFIDs.Count();
                    }

                    if (pPointFIDs != null)
                    {
                        iCount2 = pPointFIDs.Count();
                    }

                    if (pLinePointFIDs != null)
                    {
                        iCount3 = pLinePointFIDs.Count();
                    }

                    iCount = iCount1 + iCount2 + iCount3;
                    if (iCount > 0)
                    {
                        pEd.StartOperation();
                        FabricUTILS.DeleteRowsByFIDSet((ITable)pLines, pLineFIDs, null, null);
                        FabricUTILS.DeleteRowsByFIDSet((ITable)pPoints, pPointFIDs, null, null);
                        if (pPointFIDs.Count() > 0)
                        {
                            //now need to update the control points associated with any deleted points.
                            ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)pCadFabric;
                            ITable     pControlTable       = pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTControl);
                            int        idxNameFldOnControl = pControlTable.FindField("POINTID");
                            string     ControlNameFldName  = pControlTable.Fields.get_Field(idxNameFldOnControl).Name;
                            int        i;
                            List <int> pPointFIDList = new List <int>();
                            pPointFIDs.Reset();
                            pPointFIDs.Next(out i);
                            while (i > -1)
                            {
                                pPointFIDList.Add(i);
                                pPointFIDs.Next(out i);
                            }
                            List <string> InClausePointsNotConnectedToLines = FabricUTILS.InClauseFromOIDsList(pPointFIDList, 995);
                            pQuFilter.WhereClause = ControlNameFldName + " IN (" + InClausePointsNotConnectedToLines[0] + ")";
                            pSchemaEd.ReleaseReadOnlyFields(pControlTable, esriCadastralFabricTable.esriCFTControl); //release safety-catch
                            if (!FabricUTILS.ResetControlAssociations(pControlTable, pQuFilter, false))
                            {
                                pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl);//set safety back on
                                pEd.AbortOperation();
                                return;
                            }
                            pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl);//set safety back on
                        }
                        pQuFilter.WhereClause = "";
                        FabricUTILS.DeleteRowsByFIDSet((ITable)pLinePoints, pLinePointFIDs, null, null);
                        pEd.StopOperation("Delete " + iCount.ToString() + " orphans");
                        Report.textBox1.Text = "Deleted:";
                        if (iCount1 > 0)
                        {
                            Report.textBox1.Text += Environment.NewLine + iCount1.ToString() + " orphaned lines";
                        }
                        if (iCount2 > 0)
                        {
                            Report.textBox1.Text += Environment.NewLine + iCount2.ToString() + " orphaned points";
                        }
                        if (iCount3 > 0)
                        {
                            Report.textBox1.Text += Environment.NewLine + iCount3.ToString() + " orphaned line points";
                        }
                    }
                    if (sFreshlyFoundParcels.Trim() != "")
                    {
                        if (Report.textBox1.Text.Trim() != "")
                        {
                            Report.textBox1.Text += Environment.NewLine;
                        }
                        Report.textBox1.Text += "Info: Line(s) that you selected are not directly" +
                                                Environment.NewLine + "touching a parent parcel geometry. Check parcels with OIDs:" +
                                                sFreshlyFoundParcels;
                    }
                }
                IArea pArea = (IArea)ToolSelectGeometry;
                if (pArea.Area > 0)
                {
                    SetDialogLocationAtPoint(Report, pArea.Centroid);
                }

                DialogResult pDialogResult = Report.ShowDialog();
                Report.textBox1.BackColor = BackColorNow;
                pInvArea.Display          = ArcMap.Document.ActiveView.ScreenDisplay;
                pInvArea.Invalidate((short)esriScreenCache.esriAllScreenCaches);

                if (pPointLayer != null)
                {
                    ArcMap.Document.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography,
                                                              pPointLayer, ArcMap.Document.ActiveView.Extent);
                }
                #endregion
            }

            catch (Exception ex)
            {
                if (pEd != null)
                {
                    pEd.AbortOperation();
                }
                MessageBox.Show(ex.Message + Environment.NewLine + m_sDebug, "Delete Orphans Tool");
                this.OnDeactivate();
            }

            #region Final Cleanup
            finally
            {
                pDeletedLinesPoints.Clear();
                pDeletedLinesPoints = null;
                pUsedPoints.Clear();
                pUsedPoints = null;
                CtrPointIDList.Clear();
                CtrPointIDList = null;
                pParcelsList.Clear();
                pParcelsList = null;
                pOrphanPointsList.Clear();
                pOrphanPointsList = null;
                pPointsInsideBoxList.Clear();
                pPointsInsideBoxList = null;
                pLineToParcelIDRef.Clear();
                pLineToParcelIDRef = null;
                sFromToPair.Clear();
                sFromToPair = null;

                FabricUTILS = null;
            }
            #endregion
        }
Exemple #13
0
        protected override void OnClick()
        {
            m_bNoUpdates = false;
            m_sReport    = "Direction Inverse Report:";
            IEditor m_pEd = (IEditor)ArcMap.Application.FindExtensionByName("esri object editor");

            if (m_pEd.EditState == esriEditState.esriStateNotEditing)
            {
                MessageBox.Show("Please start editing first, and try again.", "Start Editing");
                return;
            }

            UID pUID = new UIDClass();

            pUID.Value = "{114D685F-99B7-4B63-B09F-6D1A41A4DDC1}";
            ICadastralExtensionManager2 pCadExtMan = (ICadastralExtensionManager2)ArcMap.Application.FindExtensionByCLSID(pUID);
            ICadastralEditor            pCadEd     = (ICadastralEditor)ArcMap.Application.FindExtensionByCLSID(pUID);

            //check if there is a Manual Mode "modify" job active ===========
            ICadastralPacketManager pCadPacMan = (ICadastralPacketManager)pCadExtMan;

            if (pCadPacMan.PacketOpen)
            {
                MessageBox.Show("The Delete Parcels command cannot be used when there is an open job.\r\nPlease finish or discard the open job, and try again.",
                                "Delete Selected Parcels");
                return;
            }

            try
            {
                IEditProperties2 pEditorProps2 = (IEditProperties2)m_pEd;

                IArray           LineLyrArr;
                IMap             pMap       = m_pEd.Map;
                ICadastralFabric pCadFabric = null;
                //ISpatialReference pSpatRef = m_pEd.Map.SpatialReference;
                //IProjectedCoordinateSystem2 pPCS = null;
                IActiveView pActiveView = ArcMap.Document.ActiveView;

                //double dMetersPerUnit = 1;

                //if (pSpatRef == null)
                //  ;
                //else if (pSpatRef is IProjectedCoordinateSystem2)
                //{
                //  pPCS = (IProjectedCoordinateSystem2)pSpatRef;
                //  string sUnit = pPCS.CoordinateUnit.Name;
                //  if (sUnit.Contains("Foot") && sUnit.Contains("US"))
                //    sUnit = "U.S. Feet";

                //  dMetersPerUnit = pPCS.CoordinateUnit.MetersPerUnit;
                //}

                IAngularConverter pAngConv = new AngularConverterClass();
                Utilities         Utils    = new Utilities();

                if (!Utils.GetFabricSubLayers(pMap, esriCadastralFabricTable.esriCFTLines, out LineLyrArr))
                {
                    return;
                }

                //if we're in an edit session then grab the target fabric
                if (m_pEd.EditState == esriEditState.esriStateEditing)
                {
                    pCadFabric = pCadEd.CadastralFabric;
                }

                if (pCadFabric == null)
                {//find the first fabric in the map
                    if (!Utils.GetFabricFromMap(pMap, out pCadFabric))
                    {
                        MessageBox.Show
                            ("No Parcel Fabric found in the map.\r\nPlease add a single fabric to the map, and try again.");
                        return;
                    }
                }
                List <int> lstLineIds = new List <int>();

                IFeatureClass pFabricLinesFC = (IFeatureClass)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTLines);
                int           idxParcelIDFld = pFabricLinesFC.Fields.FindField("ParcelID");
                int           idxCENTERPTID  = pFabricLinesFC.Fields.FindField("CenterPointID");
                int           idxRADIUS      = pFabricLinesFC.Fields.FindField("Radius");
                bool          bFieldsPresent = true;
                if (idxParcelIDFld == -1)
                {
                    bFieldsPresent = false;
                }
                if (idxCENTERPTID == -1)
                {
                    bFieldsPresent = false;
                }
                if (idxRADIUS == -1)
                {
                    bFieldsPresent = false;
                }

                if (!bFieldsPresent)
                {
                    MessageBox.Show("Fields missing.");
                    return;
                }

                Dictionary <int, List <string> > dictLineToCurveNeighbourData = new Dictionary <int, List <string> >();
                m_pFIDSetParcels = new FIDSet();
                for (int i = 0; i < LineLyrArr.Count; i++)
                {
                    IFeatureSelection pFeatSel = LineLyrArr.Element[i] as IFeatureSelection;
                    ISelectionSet     pSelSet  = pFeatSel.SelectionSet;
                    ICursor           pCursor  = null;
                    pSelSet.Search(null, false, out pCursor);
                    IFeature pLineFeat = pCursor.NextRow() as IFeature;

                    while (pLineFeat != null)
                    {
                        if (!lstLineIds.Contains(pLineFeat.OID))
                        {
                            IGeometry          pGeom    = pLineFeat.ShapeCopy;
                            ISegmentCollection pSegColl = pGeom as ISegmentCollection;
                            ISegment           pSeg     = null;
                            if (pSegColl.SegmentCount == 1)
                            {
                                pSeg = pSegColl.get_Segment(0);
                            }
                            else
                            {
                                //todo: but for now, only deals with single segment short segments
                                Marshal.ReleaseComObject(pLineFeat);
                                pLineFeat = pCursor.NextRow() as IFeature;
                                continue;
                            }

                            //check geometry for circular arc
                            if (pSeg is ICircularArc)
                            {
                                object       dVal1    = pLineFeat.get_Value(idxRADIUS);
                                object       dVal2    = pLineFeat.get_Value(idxCENTERPTID);
                                ICircularArc pCircArc = pSeg as ICircularArc;
                                if (dVal1 != DBNull.Value && dVal2 != DBNull.Value)
                                {
                                    Marshal.ReleaseComObject(pLineFeat);
                                    pLineFeat = pCursor.NextRow() as IFeature;
                                    continue;
                                }
                            }

                            //query near lines
                            int           iFoundTangent            = 0;
                            List <string> sCurveInfoFromNeighbours = new List <string>();

                            if (Utils.HasTangentCurveMatchFeatures(pFabricLinesFC, (IPolycurve)pGeom, "", 1.5, 0.033, 1, (pSeg.Length * 1.1),
                                                                   out iFoundTangent, ref sCurveInfoFromNeighbours))
                            {
                                lstLineIds.Add(pLineFeat.OID);
                                int j = (int)pLineFeat.get_Value(idxParcelIDFld);
                                m_pFIDSetParcels.Add(j);
                                dictLineToCurveNeighbourData.Add(pLineFeat.OID, sCurveInfoFromNeighbours);
                            }
                            if (iFoundTangent == 1) //if there's only one tangent look further afield
                            {
                                int iFoundLinesCount = 0;
                                int iFoundParallel   = 0;
                                if (Utils.HasParallelCurveMatchFeatures(pFabricLinesFC, (IPolycurve)pGeom, "", 1.5, 70,
                                                                        out iFoundLinesCount, out iFoundParallel, ref sCurveInfoFromNeighbours))
                                {
                                    if (!dictLineToCurveNeighbourData.ContainsKey(pLineFeat.OID))
                                    {
                                        dictLineToCurveNeighbourData.Add(pLineFeat.OID, sCurveInfoFromNeighbours);
                                    }
                                }
                            }
                        }
                        Marshal.ReleaseComObject(pLineFeat);
                        pLineFeat = pCursor.NextRow() as IFeature;
                    }
                    Marshal.ReleaseComObject(pCursor);
                }

                #region line to curve candidate analysis
                if (lstLineIds.Count == 0)
                {
                    return;
                }

                RefineToBestRadiusAndCenterPoint(dictLineToCurveNeighbourData);

                #endregion

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

                bool             bIsFileBasedGDB = false; bool bIsUnVersioned = false; bool bUseNonVersionedDelete = false;
                IWorkspace       pWS               = m_pEd.EditWorkspace;
                IProgressDialog2 pProgressorDialog = null;
                IMouseCursor     pMouseCursor      = new MouseCursorClass();
                pMouseCursor.SetCursor(2);
                if (!Utils.SetupEditEnvironment(pWS, pCadFabric, m_pEd, out bIsFileBasedGDB,
                                                out bIsUnVersioned, out bUseNonVersionedDelete))
                {
                    return;
                }


                #region Create Cadastral Job
                string sTime = "";
                if (!bIsUnVersioned && !bIsFileBasedGDB)
                {
                    //see if parcel locks can be obtained on the selected parcels. First create a job.
                    DateTime localNow = DateTime.Now;
                    sTime = Convert.ToString(localNow);
                    ICadastralJob pJob = new CadastralJobClass();
                    pJob.Name        = sTime;
                    pJob.Owner       = System.Windows.Forms.SystemInformation.UserName;
                    pJob.Description = "Convert lines to curves";
                    try
                    {
                        Int32 jobId = pCadFabric.CreateJob(pJob);
                    }
                    catch (COMException ex)
                    {
                        if (ex.ErrorCode == (int)fdoError.FDO_E_CADASTRAL_FABRIC_JOB_ALREADY_EXISTS)
                        {
                            MessageBox.Show("Job named: '" + pJob.Name + "', already exists");
                        }
                        else
                        {
                            MessageBox.Show(ex.Message);
                        }
                        return;
                    }
                }
                #endregion

                #region Test for Edit Locks
                ICadastralFabricLocks pFabLocks = (ICadastralFabricLocks)pCadFabric;

                //only need to get locks for parcels that have lines that are to be changed


                int[]      pParcelIds     = new int[m_pFIDSetParcels.Count()];
                ILongArray pParcelsToLock = new LongArrayClass();
                Utils.FIDsetToLongArray(m_pFIDSetParcels, ref pParcelsToLock, ref pParcelIds, m_pStepProgressor);

                if (!bIsUnVersioned && !bIsFileBasedGDB)
                {
                    pFabLocks.LockingJob = sTime;
                    ILongArray pLocksInConflict    = null;
                    ILongArray pSoftLcksInConflict = null;

                    if (m_bShowProgressor && !bIsFileBasedGDB)
                    {
                        m_pStepProgressor.Message = "Testing for edit locks on parcels...";
                    }

                    try
                    {
                        pFabLocks.AcquireLocks(pParcelsToLock, true, ref pLocksInConflict, ref pSoftLcksInConflict);
                    }
                    catch (COMException pCOMEx)
                    {
                        if (pCOMEx.ErrorCode == (int)fdoError.FDO_E_CADASTRAL_FABRIC_JOB_LOCK_ALREADY_EXISTS ||
                            pCOMEx.ErrorCode == (int)fdoError.FDO_E_CADASTRAL_FABRIC_JOB_CURRENTLY_EDITED)
                        {
                            MessageBox.Show("Edit Locks could not be acquired on all selected parcels.");
                            // since the operation is being aborted, release any locks that were acquired
                            pFabLocks.UndoLastAcquiredLocks();
                        }
                        else
                        {
                            MessageBox.Show(pCOMEx.Message + Environment.NewLine + Convert.ToString(pCOMEx.ErrorCode));
                        }

                        return;
                    }
                }
                #endregion

                if (m_pEd.EditState == esriEditState.esriStateEditing)
                {
                    try
                    {
                        m_pEd.StartOperation();
                    }
                    catch
                    {
                        m_pEd.AbortOperation();//abort any open edit operations and try again
                        m_pEd.StartOperation();
                    }
                }
                if (bUseNonVersionedDelete)
                {
                    if (!Utils.StartEditing(pWS, bIsUnVersioned))
                    {
                        return;
                    }
                }

                ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)pCadFabric;
                pSchemaEd.ReleaseReadOnlyFields((ITable)pFabricLinesFC, esriCadastralFabricTable.esriCFTLines); //release for edits

                m_pQF = new QueryFilter();

                // m_pEd.StartOperation();

                List <string> sInClauseList = Utils.InClauseFromOIDsList(lstLineIds, 995);
                foreach (string InClause in sInClauseList)
                {
                    m_pQF.WhereClause = pFabricLinesFC.OIDFieldName + " IN (" + InClause + ")";
                    if (!UpdateCircularArcValues((ITable)pFabricLinesFC, m_pQF, bIsUnVersioned, dictLineToCurveNeighbourData))
                    {
                        ;
                    }
                }
                m_pEd.StopOperation("Insert missing circular arc information.");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                m_pEd.AbortOperation();
            }
            finally
            {
            }
        }
Exemple #14
0
        protected override void OnClick()
        {
            IMouseCursor pMouseCursor = new MouseCursorClass();

            pMouseCursor.SetCursor(2);

            //first get the selected parcel features
            UID pUID = new UIDClass();

            pUID.Value = "{114D685F-99B7-4B63-B09F-6D1A41A4DDC1}";
            ICadastralExtensionManager2 pCadExtMan = (ICadastralExtensionManager2)ArcMap.Application.FindExtensionByCLSID(pUID);
            ICadastralEditor            pCadEd     = (ICadastralEditor)ArcMap.Application.FindExtensionByCLSID(pUID);

            //check if there is a Manual Mode "modify" job active ===========
            ICadastralPacketManager pCadPacMan = (ICadastralPacketManager)pCadExtMan;

            if (pCadPacMan.PacketOpen)
            {
                MessageBox.Show("The Delete Parcels command cannot be used when there is an open job.\r\nPlease finish or discard the open job, and try again.",
                                "Delete Selected Parcels");
                return;
            }

            IEditor pEd = (IEditor)ArcMap.Application.FindExtensionByName("esri object editor");

            IActiveView      pActiveView       = ArcMap.Document.ActiveView;
            IMap             pMap              = pActiveView.FocusMap;
            ICadastralFabric pCadFabric        = null;
            clsFabricUtils   FabricUTILS       = new clsFabricUtils();
            IProgressDialog2 pProgressorDialog = null;

            //if we're in an edit session then grab the target fabric
            if (pEd.EditState == esriEditState.esriStateEditing)
            {
                pCadFabric = pCadEd.CadastralFabric;
            }

            if (pCadFabric == null)
            {//find the first fabric in the map
                if (!FabricUTILS.GetFabricFromMap(pMap, out pCadFabric))
                {
                    MessageBox.Show
                        ("No Parcel Fabric found in the map.\r\nPlease add a single fabric to the map, and try again.");
                    return;
                }
            }

            IArray CFParcelLayers = new ArrayClass();

            if (!(FabricUTILS.GetFabricSubLayersFromFabric(pMap, pCadFabric, out CFPointLayer, out CFLineLayer,
                                                           out CFParcelLayers, out CFControlLayer, out CFLinePointLayer)))
            {
                return; //no fabric sublayers available for the targeted fabric
            }

            bool                  bIsFileBasedGDB = false; bool bIsUnVersioned = false; bool bUseNonVersionedDelete = false;
            IWorkspace            pWS           = null;
            ICadastralFabricLayer pCFLayer      = null;
            ITable                pParcelsTable = null;
            ITable                pLinesTable   = null;
            ITable                pLinePtsTable = null;
            ITable                pPointsTable  = null;
            ITable                pControlTable = null;

            try
            {
                //Get the selection of parcels
                IFeatureLayer pFL = (IFeatureLayer)CFParcelLayers.get_Element(0);

                IDataset pDS = (IDataset)pFL.FeatureClass;
                pWS = pDS.Workspace;

                if (!FabricUTILS.SetupEditEnvironment(pWS, pCadFabric, pEd, out bIsFileBasedGDB,
                                                      out bIsUnVersioned, out bUseNonVersionedDelete))
                {
                    return;
                }
                if (bUseNonVersionedDelete)
                {
                    pCFLayer = new CadastralFabricLayerClass();
                    pCFLayer.CadastralFabric    = pCadFabric;
                    pCadEd.CadastralFabricLayer = pCFLayer;//NOTE: Need to set this back to NULL when done.
                }

                ICadastralSelection pCadaSel = (ICadastralSelection)pCadEd;

                IEnumGSParcels pEnumGSParcels = pCadaSel.SelectedParcels;// need to get the parcels before trying to get the parcel count: BUG workaround

                IFeatureSelection pFeatSel = (IFeatureSelection)pFL;
                ISelectionSet2    pSelSet  = (ISelectionSet2)pFeatSel.SelectionSet;

                bMoreThan995UnjoinedParcels = (pSelSet.Count > pCadaSel.SelectedParcelCount); //used for bug workaround

                if (pCadaSel.SelectedParcelCount == 0 && pSelSet.Count == 0)
                {
                    MessageBox.Show("Please select some fabric parcels and try again.", "No Selection",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    pMouseCursor.SetCursor(0);
                    if (bUseNonVersionedDelete)
                    {
                        pCadEd.CadastralFabricLayer = null;
                        CFParcelLayers   = null;
                        CFPointLayer     = null;
                        CFLineLayer      = null;
                        CFControlLayer   = null;
                        CFLinePointLayer = null;
                    }
                    return;
                }

                if (bMoreThan995UnjoinedParcels)
                {
                    m_bShowProgressor = (pSelSet.Count > 10);
                }
                else
                {
                    m_bShowProgressor = (pCadaSel.SelectedParcelCount > 10);
                }

                if (m_bShowProgressor)
                {
                    m_pProgressorDialogFact    = new ProgressDialogFactoryClass();
                    m_pTrackCancel             = new CancelTrackerClass();
                    m_pStepProgressor          = m_pProgressorDialogFact.Create(m_pTrackCancel, ArcMap.Application.hWnd);
                    pProgressorDialog          = (IProgressDialog2)m_pStepProgressor;
                    m_pStepProgressor.MinRange = 1;
                    if (bMoreThan995UnjoinedParcels)
                    {
                        m_pStepProgressor.MaxRange = pSelSet.Count * 18; //(estimate 7 lines per parcel, 4 pts per parcel, 3 line points per parcel, and there is a second loop on parcel list)
                    }
                    else
                    {
                        m_pStepProgressor.MaxRange = pCadaSel.SelectedParcelCount * 18; //(estimate 7 lines per parcel, 4 pts per parcel, 3 line points per parcel, and there is a second loop on parcel list)
                    }
                    m_pStepProgressor.StepValue = 1;
                    pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral;
                }

                m_pQF = new QueryFilterClass();
                string sPref; string sSuff;

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

                //====== need to do this for all the parcel sublayers in the map that are part of the target fabric

                if (m_bShowProgressor)
                {
                    pProgressorDialog.ShowDialog();
                    m_pStepProgressor.Message = "Collecting parcel data...";
                }

                //Add the OIDs of all the selected parcels into a new feature IDSet
                string[] sOIDList   = { "(" };
                int      tokenLimit = 995;
                bool     bCont      = true;
                int      j          = 0;
                int      iCounter   = 0;

                m_pFIDSetParcels = new FIDSetClass();

                //===================== start bug workaraound for 10.0 client ===================
                if (bMoreThan995UnjoinedParcels)
                {
                    ICursor pCursor = null;
                    pSelSet.Search(null, false, out pCursor);//code deletes all selected parcels
                    IFeatureCursor pParcelFeatCurs = (IFeatureCursor)pCursor;
                    IFeature       pParcFeat       = pParcelFeatCurs.NextFeature();

                    while (pParcFeat != null)
                    {
                        //Check if the cancel button was pressed. If so, stop process
                        if (m_bShowProgressor)
                        {
                            bCont = m_pTrackCancel.Continue();
                            if (!bCont)
                            {
                                break;
                            }
                        }
                        bool bExists = false;
                        m_pFIDSetParcels.Find(pParcFeat.OID, out bExists);
                        if (!bExists)
                        {
                            m_pFIDSetParcels.Add(pParcFeat.OID);

                            if (iCounter <= tokenLimit)
                            {
                                sOIDList[j] = sOIDList[j] + Convert.ToString(pParcFeat.OID) + ",";
                                iCounter++;
                            }
                            else
                            {//maximum tokens reached
                                sOIDList[j] = sOIDList[j].Trim();
                                iCounter    = 0;
                                //set up the next OIDList
                                j++;
                                FabricUTILS.RedimPreserveString(ref sOIDList, 1);
                                sOIDList[j] = "(";
                                sOIDList[j] = sOIDList[j] + Convert.ToString(pParcFeat.OID) + ",";
                            }
                        }
                        Marshal.ReleaseComObject(pParcFeat); //garbage collection
                        pParcFeat = pParcelFeatCurs.NextFeature();

                        if (m_bShowProgressor)
                        {
                            if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange)
                            {
                                m_pStepProgressor.Step();
                            }
                        }
                    }
                    Marshal.ReleaseComObject(pCursor); //garbage collection
                    //===================== end bug workaraound for 10.0 client ===================
                }
                else //===the following code path is preferred======
                {
                    pEnumGSParcels.Reset();
                    IGSParcel pGSParcel = pEnumGSParcels.Next();
                    while (pGSParcel != null)
                    {
                        //Check if the cancel button was pressed. If so, stop process
                        if (m_bShowProgressor)
                        {
                            bCont = m_pTrackCancel.Continue();
                            if (!bCont)
                            {
                                break;
                            }
                        }
                        m_pFIDSetParcels.Add(pGSParcel.DatabaseId);
                        if (iCounter <= tokenLimit)
                        {
                            sOIDList[j] = sOIDList[j] + Convert.ToString(pGSParcel.DatabaseId) + ",";
                            iCounter++;
                        }
                        else
                        {//maximum tokens reached
                            sOIDList[j] = sOIDList[j].Trim();
                            iCounter    = 0;
                            //set up the next OIDList
                            j++;
                            FabricUTILS.RedimPreserveString(ref sOIDList, 1);
                            sOIDList[j] = "(";
                            sOIDList[j] = sOIDList[j] + Convert.ToString(pGSParcel.DatabaseId) + ",";
                        }
                        Marshal.ReleaseComObject(pGSParcel); //garbage collection
                        pGSParcel = pEnumGSParcels.Next();
                        if (m_bShowProgressor)
                        {
                            if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange)
                            {
                                m_pStepProgressor.Step();
                            }
                        }
                    }
                    Marshal.ReleaseComObject(pEnumGSParcels); //garbage collection
                }

                if (!bCont)
                {
                    AbortEdits(bUseNonVersionedDelete, pEd, pWS);
                    return;
                }

                string sTime = "";
                if (!bIsUnVersioned && !bIsFileBasedGDB)
                {
                    //see if parcel locks can be obtained on the selected parcels. First create a job.
                    DateTime localNow = DateTime.Now;
                    sTime = Convert.ToString(localNow);
                    ICadastralJob pJob = new CadastralJobClass();
                    pJob.Name        = sTime;
                    pJob.Owner       = System.Windows.Forms.SystemInformation.UserName;
                    pJob.Description = "Delete selected parcels";
                    try
                    {
                        Int32 jobId = pCadFabric.CreateJob(pJob);
                    }
                    catch (COMException ex)
                    {
                        if (ex.ErrorCode == (int)fdoError.FDO_E_CADASTRAL_FABRIC_JOB_ALREADY_EXISTS)
                        {
                            MessageBox.Show("Job named: '" + pJob.Name + "', already exists");
                        }
                        else
                        {
                            MessageBox.Show(ex.Message);
                        }
                        return;
                    }
                }

                //if we're in an enterprise then test for edit locks
                ICadastralFabricLocks pFabLocks = (ICadastralFabricLocks)pCadFabric;
                if (!bIsUnVersioned && !bIsFileBasedGDB)
                {
                    pFabLocks.LockingJob = sTime;
                    ILongArray pLocksInConflict    = null;
                    ILongArray pSoftLcksInConflict = null;

                    ILongArray pParcelsToLock = new LongArrayClass();

                    FabricUTILS.FIDsetToLongArray(m_pFIDSetParcels, ref pParcelsToLock, m_pStepProgressor);
                    if (m_bShowProgressor && !bIsFileBasedGDB)
                    {
                        m_pStepProgressor.Message = "Testing for edit locks on parcels...";
                    }

                    try
                    {
                        pFabLocks.AcquireLocks(pParcelsToLock, true, ref pLocksInConflict, ref pSoftLcksInConflict);
                    }
                    catch (COMException pCOMEx)
                    {
                        if (pCOMEx.ErrorCode == (int)fdoError.FDO_E_CADASTRAL_FABRIC_JOB_LOCK_ALREADY_EXISTS ||
                            pCOMEx.ErrorCode == (int)fdoError.FDO_E_CADASTRAL_FABRIC_JOB_CURRENTLY_EDITED)
                        {
                            MessageBox.Show("Edit Locks could not be acquired on all selected parcels.");
                            // since the operation is being aborted, release any locks that were acquired
                            pFabLocks.UndoLastAcquiredLocks();
                        }
                        else
                        {
                            MessageBox.Show(pCOMEx.Message + Environment.NewLine + Convert.ToString(pCOMEx.ErrorCode));
                        }

                        return;
                    }
                }

                //Build an IDSet of lines for the parcel to be deleted, and build an IDSet of the points for those lines
                m_pFIDSetLines  = new FIDSetClass();
                m_pFIDSetPoints = new FIDSetClass();
                if (pEd.EditState == esriEditState.esriStateEditing)
                {
                    try
                    {
                        pEd.StartOperation();
                    }
                    catch
                    {
                        pEd.AbortOperation();//abort any open edit operations and try again
                        pEd.StartOperation();
                    }
                }
                if (bUseNonVersionedDelete)
                {
                    if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned))
                    {
                        return;
                    }
                }

                //first delete all the parcel records
                if (m_bShowProgressor)
                {
                    m_pStepProgressor.Message = "Deleting parcels...";
                }

                bool bSuccess = true;
                pParcelsTable = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels);
                pLinesTable   = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTLines);
                pLinePtsTable = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTLinePoints);
                pPointsTable  = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints);
                pControlTable = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTControl);

                if (!bUseNonVersionedDelete)
                {
                    bSuccess = FabricUTILS.DeleteRowsByFIDSet(pParcelsTable, m_pFIDSetParcels, m_pStepProgressor, m_pTrackCancel);
                }
                if (bUseNonVersionedDelete)
                {
                    bSuccess = FabricUTILS.DeleteRowsUnversioned(pWS, pParcelsTable,
                                                                 m_pFIDSetParcels, m_pStepProgressor, m_pTrackCancel);
                }

                if (!bSuccess)
                {
                    if (!bIsUnVersioned)
                    {
                        pFabLocks.UndoLastAcquiredLocks();
                    }

                    AbortEdits(bUseNonVersionedDelete, pEd, pWS);

                    if (!bIsUnVersioned)
                    {
                        //check version and if the Cancel button was not clicked and we're higher than
                        //version 10.0, then re-try the delete with the core delete command
                        string sVersion = Application.ProductVersion;
                        int    iErrCode = FabricUTILS.LastErrorCode;
                        if (!sVersion.StartsWith("10.0") && iErrCode == -2147217400)
                        {
                            FabricUTILS.ExecuteCommand("{B0A62C1C-7FAE-457A-AB25-A966B7254EF6}");
                        }
                    }
                    return;
                }

                //next need to use an in clause for lines, so ...
                string[] sPointOIDList = { "" };
                int      iCnt          = 0;
                int      iTokenCnt     = 0;
                int      iStepCnt      = 1;
                //...for each item in the sOIDList array
                foreach (string inClause in sOIDList)
                {
                    ICursor pLineCurs = FabricUTILS.GetCursorFromCommaSeparatedOIDList(pLinesTable, inClause, "PARCELID");
                    IRow    pRow      = pLineCurs.NextRow();
                    Int32   iFromPt   = pLinesTable.Fields.FindField("FROMPOINTID");
                    Int32   iToPt     = pLinesTable.Fields.FindField("TOPOINTID");

                    while (pRow != null)
                    {
                        if (iTokenCnt >= tokenLimit)
                        {
                            FabricUTILS.RedimPreserveString(ref sPointOIDList, 1);
                            iTokenCnt = 0;
                            iCnt++;
                        }

                        m_pFIDSetLines.Add(pRow.OID);
                        Int32 i = (Int32)pRow.get_Value(iFromPt);
                        if (i > -1)
                        {
                            bool bExists = false;
                            m_pFIDSetPoints.Find(i, out bExists);
                            if (!bExists)
                            {
                                m_pFIDSetPoints.Add(i);
                                sPointOIDList[iCnt] = sPointOIDList[iCnt] + Convert.ToString(i) + ",";
                                iTokenCnt++;
                            }
                        }
                        i = (Int32)pRow.get_Value(iToPt);
                        if (i > -1)
                        {
                            bool bExists = false;
                            m_pFIDSetPoints.Find(i, out bExists);
                            if (!bExists)
                            {
                                m_pFIDSetPoints.Add(i);
                                sPointOIDList[iCnt] = sPointOIDList[iCnt] + Convert.ToString(i) + ",";
                                iTokenCnt++;
                            }
                        }
                        Marshal.ReleaseComObject(pRow); //garbage collection
                        pRow = pLineCurs.NextRow();
                    }
                    Marshal.ReleaseComObject(pLineCurs); //garbage collection

                    //delete line records based on the selected parcels
                    string sMessage = "Deleting lines...";
                    int    iSetCnt  = sOIDList.GetLength(0);
                    if (iSetCnt > 1)
                    {
                        sMessage += "Step " + Convert.ToString(iStepCnt) + " of " + Convert.ToString(iSetCnt);
                    }
                    if (m_bShowProgressor)
                    {
                        m_pStepProgressor.Message = sMessage;
                    }
                    if (!bUseNonVersionedDelete)
                    {
                        bSuccess = FabricUTILS.DeleteRowsByFIDSet(pLinesTable, m_pFIDSetLines, m_pStepProgressor, m_pTrackCancel);
                    }
                    if (bUseNonVersionedDelete)
                    {
                        bSuccess = FabricUTILS.DeleteRowsUnversioned(pWS, pLinesTable, m_pFIDSetLines, m_pStepProgressor, m_pTrackCancel);
                    }
                    if (!bSuccess)
                    {
                        if (!bIsUnVersioned)
                        {
                            pFabLocks.UndoLastAcquiredLocks();
                        }

                        AbortEdits(bUseNonVersionedDelete, pEd, pWS);
                        return;
                    }

                    //delete the line points for the deleted parcels
                    //build the list of the line points that need to be deleted.
                    //IFeatureClass pFeatCLLinePoints = CFLinePointLayer.FeatureClass;
                    string NewInClause = "";
                    //remove trailing comma
                    if ((inClause.Substring(inClause.Length - 1, 1)) == ",")
                    {
                        NewInClause = inClause.Substring(0, inClause.Length - 1);
                    }

                    //m_pQF.WhereClause = (sPref + "parcelid" + sSuff).Trim() + " IN " + NewInClause + ")";
                    m_pQF.WhereClause = "PARCELID IN " + NewInClause + ")";
                    ICursor pLinePointCurs = pLinePtsTable.Search(m_pQF, false);
                    IRow    pLinePointFeat = pLinePointCurs.NextRow();

                    //Build an IDSet of linepoints for parcels to be deleted
                    IFIDSet pFIDSetLinePoints = new FIDSetClass();

                    while (pLinePointFeat != null)
                    {
                        pFIDSetLinePoints.Add(pLinePointFeat.OID);
                        Marshal.ReleaseComObject(pLinePointFeat); //garbage collection
                        pLinePointFeat = pLinePointCurs.NextRow();
                    }

                    //===========deletes linepoints associated with parcels
                    iSetCnt  = sOIDList.GetLength(0);
                    sMessage = "Deleting line-points...";
                    if (iSetCnt > 1)
                    {
                        sMessage += "Step " + Convert.ToString(iStepCnt) + " of " + Convert.ToString(iSetCnt);
                    }
                    if (m_bShowProgressor)
                    {
                        m_pStepProgressor.Message = sMessage;
                    }

                    if (!bUseNonVersionedDelete)
                    {
                        bSuccess = FabricUTILS.DeleteRowsByFIDSet(pLinePtsTable,
                                                                  pFIDSetLinePoints, m_pStepProgressor, m_pTrackCancel);
                    }
                    if (bUseNonVersionedDelete)
                    {
                        bSuccess = FabricUTILS.DeleteRowsUnversioned(pWS, pLinePtsTable,
                                                                     pFIDSetLinePoints, m_pStepProgressor, m_pTrackCancel);
                    }
                    if (!bSuccess)
                    {
                        if (!bIsUnVersioned)
                        {
                            pFabLocks.UndoLastAcquiredLocks();
                        }

                        AbortEdits(bUseNonVersionedDelete, pEd, pWS);

                        if (pLinePointCurs != null)
                        {
                            Marshal.ReleaseComObject(pLinePointCurs); //garbage
                        }
                        return;
                    }

                    ///////==============================================

                    Marshal.ReleaseComObject(pLinePointCurs); //garbage
                    iStepCnt++;
                }

                //now need to get points that should not be deleted, because they are used by lines that are not deleted.
                //first search for the remaining lines. Any that have from/to points that are in the point fidset are the points
                //that should stay
                IFIDSet pFIDSetNullGeomLinePtFrom = new FIDSetClass();
                IFIDSet pFIDSetNullGeomLinePtTo   = new FIDSetClass();
                if (m_bShowProgressor)
                {
                    m_pStepProgressor.Message = "Updating point delete list...";
                }

                for (int z = 0; z <= iCnt; z++)
                {
                    //remove trailing comma
                    if ((sPointOIDList[z].Trim() == ""))
                    {
                        break;
                    }
                    if ((sPointOIDList[z].Substring(sPointOIDList[z].Length - 1, 1)) == ",")
                    {
                        sPointOIDList[z] = sPointOIDList[z].Substring(0, sPointOIDList[z].Length - 1);
                    }
                }

                //string TheWhereClause = "(" + (sPref + "frompointid" + sSuff).Trim() + " IN (";

                //UpdateDeletePointList(ref sPointOIDList, ref m_pFIDSetPoints, "frompointid",
                //  TheWhereClause, pLinesTable, out pFIDSetNullGeomLinePtFrom);

                //TheWhereClause = "(" + (sPref + "topointid" + sSuff).Trim() + " IN (";

                //UpdateDeletePointList(ref sPointOIDList, ref m_pFIDSetPoints, "topointid",
                //  TheWhereClause, pLinesTable, out pFIDSetNullGeomLinePtTo);

                string TheWhereClause = "(FROMPOINTID IN (";

                UpdateDeletePointList(ref sPointOIDList, ref m_pFIDSetPoints, "FROMPOINTID",
                                      TheWhereClause, pLinesTable, out pFIDSetNullGeomLinePtFrom);

                TheWhereClause = "(TOPOINTID IN (";

                UpdateDeletePointList(ref sPointOIDList, ref m_pFIDSetPoints, "TOPOINTID",
                                      TheWhereClause, pLinesTable, out pFIDSetNullGeomLinePtTo);

                if (m_bShowProgressor)
                {
                    m_pStepProgressor.Message = "Deleting points...";
                }

                if (!bUseNonVersionedDelete)
                {
                    bSuccess = FabricUTILS.DeleteRowsByFIDSet(pPointsTable, m_pFIDSetPoints,
                                                              m_pStepProgressor, m_pTrackCancel);
                }
                if (bUseNonVersionedDelete)
                {
                    bSuccess = FabricUTILS.DeleteRowsUnversioned(pWS, pPointsTable, m_pFIDSetPoints,
                                                                 m_pStepProgressor, m_pTrackCancel);
                }
                if (!bSuccess)
                {
                    if (!bIsUnVersioned)
                    {
                        pFabLocks.UndoLastAcquiredLocks();
                    }

                    AbortEdits(bUseNonVersionedDelete, pEd, pWS);
                    return;
                }

                //====Phase 2 of line-point delete. Remove the Line-points that no longer have underlying points.
                if (m_bShowProgressor)
                {
                    m_pStepProgressor.Message = "Deleting line-points...";
                }
                for (int z = 0; z <= iCnt; z++)
                {
                    if ((sPointOIDList[z].Trim() == ""))
                    {
                        continue;
                    }
                    //remove line points where underlying points were deleted
                    bSuccess = FabricUTILS.DeleteByQuery(pWS, pLinePtsTable, pLinePtsTable.Fields.get_Field(pLinePtsTable.FindField("LinePointID")),
                                                         sPointOIDList, !bIsUnVersioned, m_pStepProgressor, m_pTrackCancel);
                    if (!bSuccess)
                    {
                        if (!bIsUnVersioned)
                        {
                            pFabLocks.UndoLastAcquiredLocks();
                        }

                        AbortEdits(bUseNonVersionedDelete, pEd, pWS);
                        return;
                    }
                }

                //=====

                //Empty geometry on points that are floating points on unjoined parcels
                m_pEmptyGeoms = new FIDSetClass();
                FabricUTILS.IntersectFIDSetCommonIDs(pFIDSetNullGeomLinePtTo, pFIDSetNullGeomLinePtFrom, out m_pEmptyGeoms);

                ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)pCadFabric;
                pSchemaEd.ReleaseReadOnlyFields(pPointsTable, esriCadastralFabricTable.esriCFTPoints); //release safety-catch
                if (!bUseNonVersionedDelete)
                {
                    FabricUTILS.EmptyGeometries((IFeatureClass)pPointsTable, m_pEmptyGeoms);
                }
                else
                {
                    FabricUTILS.EmptyGeometriesUnversioned(pWS, CFPointLayer.FeatureClass, m_pEmptyGeoms);
                }

                pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints);//set safety back on

                if (m_bShowProgressor)
                {
                    m_pStepProgressor.Message = "Resetting control point associations...";
                }

                for (int z = 0; z <= iCnt; z++)
                {
                    if ((sPointOIDList[z].Trim() == ""))
                    {
                        break;
                    }
                    //cleanup associated control points, and associations where underlying points were deleted
                    //m_pQF.WhereClause = (sPref + "pointid" + sSuff).Trim() + " IN (" + sPointOIDList[z] + ")";
                    m_pQF.WhereClause = "POINTID IN (" + sPointOIDList[z] + ")";
                    pSchemaEd.ReleaseReadOnlyFields(pControlTable, esriCadastralFabricTable.esriCFTControl); //release safety-catch
                    if (!FabricUTILS.ResetControlAssociations(pControlTable, m_pQF, bUseNonVersionedDelete))
                    {
                        pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl);//set safety back on
                    }
                }
                pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl);//set safety back on

                if (bUseNonVersionedDelete)
                {
                    FabricUTILS.StopEditing(pWS);
                }

                if (pEd.EditState == esriEditState.esriStateEditing)
                {
                    pEd.StopOperation("Delete parcels");
                }

                //clear selection, to make sure the parcel explorer is updated and refreshed properly
                if (pFeatSel != null && bMoreThan995UnjoinedParcels)
                {
                    pFeatSel.Clear();
                }
            }

            catch (Exception ex)
            {
                if (bUseNonVersionedDelete)
                {
                    FabricUTILS.AbortEditing(pWS);
                }

                if (pEd != null)
                {
                    if (pEd.EditState == esriEditState.esriStateEditing)
                    {
                        pEd.AbortOperation();
                    }
                }

                MessageBox.Show(ex.Message);
                return;
            }
            finally
            {
                RefreshMap(pActiveView, CFParcelLayers, CFPointLayer, CFLineLayer, CFControlLayer, CFLinePointLayer);
                //update the TOC
                IMxDocument mxDocument = (ESRI.ArcGIS.ArcMapUI.IMxDocument)(ArcMap.Application.Document);
                for (int i = 0; i < mxDocument.ContentsViewCount; i++)
                {
                    IContentsView pCV = (IContentsView)mxDocument.get_ContentsView(i);
                    pCV.Refresh(null);
                }

                if (pMouseCursor != null)
                {
                    pMouseCursor.SetCursor(0);
                }

                m_pStepProgressor = null;
                if (!(pProgressorDialog == null))
                {
                    pProgressorDialog.HideDialog();
                }
                pProgressorDialog = null;

                if (bUseNonVersionedDelete)
                {
                    pCadEd.CadastralFabricLayer = null;
                    CFParcelLayers   = null;
                    CFPointLayer     = null;
                    CFLineLayer      = null;
                    CFControlLayer   = null;
                    CFLinePointLayer = null;
                }
            }
        }
        protected override void OnClick()
        {
            bool            bShowProgressor = false;
            IStepProgressor pStepProgressor = null;
            //Create a CancelTracker.
            ITrackCancel           pTrackCancel = null;
            IProgressDialogFactory pProgressorDialogFact;

            IMouseCursor pMouseCursor = new MouseCursorClass();

            pMouseCursor.SetCursor(2);

            //first get the selected parcel features
            UID pUID = new UIDClass();

            pUID.Value = "{114D685F-99B7-4B63-B09F-6D1A41A4DDC1}";
            ICadastralExtensionManager2 pCadExtMan = (ICadastralExtensionManager2)ArcMap.Application.FindExtensionByCLSID(pUID);
            ICadastralEditor            pCadEd     = (ICadastralEditor)ArcMap.Application.FindExtensionByCLSID(pUID);

            //check if there is a Manual Mode "modify" job active ===========
            ICadastralPacketManager pCadPacMan = (ICadastralPacketManager)pCadExtMan;

            if (pCadPacMan.PacketOpen)
            {
                MessageBox.Show("The Delete linepoint command cannot be used when there is an open job.\r\nPlease finish or discard the open job, and try again.",
                                "Delete Selected LinePoints");
                return;
            }

            IEditor pEd = (IEditor)ArcMap.Application.FindExtensionByName("esri object editor");

            IActiveView      pActiveView       = ArcMap.Document.ActiveView;
            IMap             pMap              = pActiveView.FocusMap;
            ICadastralFabric pCadFabric        = null;
            clsFabricUtils   FabricUTILS       = new clsFabricUtils();
            IProgressDialog2 pProgressorDialog = null;

            //if we're in an edit session then grab the target fabric
            if (pEd.EditState == esriEditState.esriStateEditing)
            {
                pCadFabric = pCadEd.CadastralFabric;
            }

            if (pCadFabric == null)
            {//find the first fabric in the map
                if (!FabricUTILS.GetFabricFromMap(pMap, out pCadFabric))
                {
                    MessageBox.Show
                        ("No Parcel Fabric found in the map.\r\nPlease add a single fabric to the map, and try again.");
                    return;
                }
            }

            IArray CFLinePointLayers = new ArrayClass();

            if (!(FabricUTILS.GetLinePointLayersFromFabric(pMap, pCadFabric, out CFLinePointLayers)))
            {
                return; //no fabric sublayers available for the targeted fabric
            }
            bool       bIsFileBasedGDB = false; bool bIsUnVersioned = false; bool bUseNonVersionedDelete = false;
            IWorkspace pWS             = null;
            ITable     pLinePointTable = null;

            try
            {
                if (pEd.EditState == esriEditState.esriStateEditing)
                {
                    try
                    {
                        pEd.StartOperation();
                    }
                    catch
                    {
                        pEd.AbortOperation();//abort any open edit operations and try again
                        pEd.StartOperation();
                    }
                }

                IFeatureLayer pFL = (IFeatureLayer)CFLinePointLayers.get_Element(0);
                IDataset      pDS = (IDataset)pFL.FeatureClass;
                pWS = pDS.Workspace;

                if (!FabricUTILS.SetupEditEnvironment(pWS, pCadFabric, pEd, out bIsFileBasedGDB,
                                                      out bIsUnVersioned, out bUseNonVersionedDelete))
                {
                    return;
                }

                //loop through each linepoint layer and
                //Get the selection of linepoints
                int iCnt = 0;
                int iTotalSelectionCount = 0;
                for (; iCnt < CFLinePointLayers.Count; iCnt++)
                {
                    pFL = (IFeatureLayer)CFLinePointLayers.get_Element(iCnt);
                    IFeatureSelection pFeatSel = (IFeatureSelection)pFL;
                    ISelectionSet2    pSelSet  = (ISelectionSet2)pFeatSel.SelectionSet;
                    iTotalSelectionCount += pSelSet.Count;
                }

                if (iTotalSelectionCount == 0)
                {
                    MessageBox.Show("Please select some line points and try again.", "No Selection",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    if (bUseNonVersionedDelete)
                    {
                        pCadEd.CadastralFabricLayer = null;
                        CFLinePointLayers           = null;
                    }
                    return;
                }

                bShowProgressor = (iTotalSelectionCount > 10);

                if (bShowProgressor)
                {
                    pProgressorDialogFact       = new ProgressDialogFactoryClass();
                    pTrackCancel                = new CancelTrackerClass();
                    pStepProgressor             = pProgressorDialogFact.Create(pTrackCancel, ArcMap.Application.hWnd);
                    pProgressorDialog           = (IProgressDialog2)pStepProgressor;
                    pStepProgressor.MinRange    = 1;
                    pStepProgressor.MaxRange    = iTotalSelectionCount;
                    pStepProgressor.StepValue   = 1;
                    pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral;
                }

                //loop through each linepoint layer and
                //delete from its selection
                m_pQF = new QueryFilterClass();
                iCnt  = 0;
                for (; iCnt < CFLinePointLayers.Count; iCnt++)
                {
                    pFL = (IFeatureLayer)CFLinePointLayers.get_Element(iCnt);
                    IFeatureSelection pFeatSel = (IFeatureSelection)pFL;
                    ISelectionSet2    pSelSet  = (ISelectionSet2)pFeatSel.SelectionSet;

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

                    if (bShowProgressor)
                    {
                        pProgressorDialog.ShowDialog();
                        pStepProgressor.Message = "Collecting line point data...";
                    }

                    //Add the OIDs of all the selected linepoints into a new feature IDSet
                    bool bCont = true;
                    m_pFIDSetLinePoints = new FIDSetClass();

                    ICursor pCursor = null;
                    pSelSet.Search(null, false, out pCursor);//code deletes all selected line points
                    IFeatureCursor pLinePointFeatCurs = (IFeatureCursor)pCursor;
                    IFeature       pLinePointFeat     = pLinePointFeatCurs.NextFeature();

                    while (pLinePointFeat != null)
                    {
                        //Check if the cancel button was pressed. If so, stop process
                        if (bShowProgressor)
                        {
                            bCont = pTrackCancel.Continue();
                            if (!bCont)
                            {
                                break;
                            }
                        }
                        bool bExists = false;
                        m_pFIDSetLinePoints.Find(pLinePointFeat.OID, out bExists);
                        if (!bExists)
                        {
                            m_pFIDSetLinePoints.Add(pLinePointFeat.OID);
                        }

                        Marshal.ReleaseComObject(pLinePointFeat); //garbage collection
                        pLinePointFeat = pLinePointFeatCurs.NextFeature();

                        if (bShowProgressor)
                        {
                            if (pStepProgressor.Position < pStepProgressor.MaxRange)
                            {
                                pStepProgressor.Step();
                            }
                        }
                    }
                    Marshal.ReleaseComObject(pCursor); //garbage collection

                    if (!bCont)
                    {
                        AbortEdits(bUseNonVersionedDelete, pEd, pWS);
                        return;
                    }

                    if (bUseNonVersionedDelete)
                    {
                        if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned))
                        {
                            if (bUseNonVersionedDelete)
                            {
                                pCadEd.CadastralFabricLayer = null;
                            }
                            return;
                        }
                    }

                    //delete all the line point records
                    if (bShowProgressor)
                    {
                        pStepProgressor.Message = "Deleting selected line points...";
                    }

                    bool bSuccess = true;
                    pLinePointTable = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTLinePoints);

                    if (!bUseNonVersionedDelete)
                    {
                        bSuccess = FabricUTILS.DeleteRowsByFIDSet(pLinePointTable, m_pFIDSetLinePoints, pStepProgressor, pTrackCancel);
                    }
                    if (bUseNonVersionedDelete)
                    {
                        bSuccess = FabricUTILS.DeleteRowsUnversioned(pWS, pLinePointTable,
                                                                     m_pFIDSetLinePoints, pStepProgressor, pTrackCancel);
                    }
                    if (!bSuccess)
                    {
                        AbortEdits(bUseNonVersionedDelete, pEd, pWS);
                        return;
                    }
                }

                if (bUseNonVersionedDelete)
                {
                    FabricUTILS.StopEditing(pWS);
                }

                if (pEd.EditState == esriEditState.esriStateEditing)
                {
                    pEd.StopOperation("Delete Line Points");
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            finally
            {
                RefreshMap(pActiveView, CFLinePointLayers);

                //update the TOC
                IMxDocument mxDocument = (ESRI.ArcGIS.ArcMapUI.IMxDocument)(ArcMap.Application.Document);
                for (int i = 0; i < mxDocument.ContentsViewCount; i++)
                {
                    IContentsView pCV = (IContentsView)mxDocument.get_ContentsView(i);
                    pCV.Refresh(null);
                }

                if (pProgressorDialog != null)
                {
                    pProgressorDialog.HideDialog();
                }

                if (bUseNonVersionedDelete)
                {
                    pCadEd.CadastralFabricLayer = null;
                    CFLinePointLayers           = null;
                }

                if (pMouseCursor != null)
                {
                    pMouseCursor.SetCursor(0);
                }
            }
        }
        protected override void OnClick()
        {
            IEditor          m_pEd  = (IEditor)ArcMap.Application.FindExtensionByName("esri object editor");
            ICadastralEditor pCadEd = (ICadastralEditor)ArcMap.Application.FindExtensionByName("esriCadastralUI.CadastralEditorExtension");

            if (m_pEd.EditState == esriEditState.esriStateNotEditing)
            {
                MessageBox.Show("Please start editing first, and try again.", "Start Editing", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            IArray           PolygonLyrArr;
            IMap             pMap       = m_pEd.Map;
            ICadastralFabric pCadFabric = null;

            //if we're in an edit session then grab the target fabric
            if (m_pEd.EditState == esriEditState.esriStateEditing)
            {
                pCadFabric = pCadEd.CadastralFabric;
            }

            if (pCadFabric == null)
            {//find the first fabric in the map
                MessageBox.Show
                    ("No Parcel Fabric found in the workspace you're editing.\r\nPlease re-start editing on a workspace with a fabric, and try again.",
                    "No Fabric found", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            Utilities Utils = new Utilities();

            if (!Utils.GetFabricSubLayers(pMap, esriCadastralFabricTable.esriCFTParcels, out PolygonLyrArr))
            {
                return;
            }
            //check if there is a Manual Mode "modify" job active ===========
            ICadastralPacketManager pCadPacMan = (ICadastralPacketManager)pCadEd;

            if (pCadPacMan.PacketOpen)
            {
                MessageBox.Show("The Area Calculation does not work when the parcel is open.\r\nPlease close the parcel and try again.",
                                "Calculate Stated Area", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            IActiveView pActiveView = ArcMap.Document.ActiveView;

            CalcStatedAreaDLG CalcStatedArea = new CalcStatedAreaDLG();
            bool             bIsFileBasedGDB = false; bool bIsUnVersioned = false; bool bUseNonVersionedEdit = false;
            IWorkspace       pWS               = null;
            ITable           pParcelsTable     = null;
            IProgressDialog2 pProgressorDialog = null;
            IMouseCursor     pMouseCursor      = new MouseCursorClass();

            pMouseCursor.SetCursor(2);
            var pTool = ArcMap.Application.CurrentTool;

            try
            {
                IFeatureLayer pFL = (IFeatureLayer)PolygonLyrArr.get_Element(0);
                IDataset      pDS = (IDataset)pFL.FeatureClass;
                pWS = pDS.Workspace;

                if (!Utils.SetupEditEnvironment(pWS, pCadFabric, m_pEd, out bIsFileBasedGDB,
                                                out bIsUnVersioned, out bUseNonVersionedEdit))
                {
                    return;
                }

                ICadastralSelection pCadaSel       = (ICadastralSelection)pCadEd;
                IEnumGSParcels      pEnumGSParcels = pCadaSel.SelectedParcels;// need to get the parcels before trying to get the parcel count: BUG workaround
                IFeatureSelection   pFeatSel       = (IFeatureSelection)pFL;
                ISelectionSet2      pSelSet        = (ISelectionSet2)pFeatSel.SelectionSet;

                if (pCadaSel.SelectedParcelCount == 0 && pSelSet.Count == 0)
                {
                    MessageBox.Show("Please select some fabric parcels and try again.", "No Selection",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                ArcMap.Application.CurrentTool = null;

                //Display the dialog
                DialogResult pDialogResult = CalcStatedArea.ShowDialog();
                if (pDialogResult != DialogResult.OK)
                {
                    return;
                }

                m_bShowProgressor = (pSelSet.Count > 10) || pCadaSel.SelectedParcelCount > 10;
                if (m_bShowProgressor)
                {
                    m_pProgressorDialogFact     = new ProgressDialogFactoryClass();
                    m_pTrackCancel              = new CancelTrackerClass();
                    m_pStepProgressor           = m_pProgressorDialogFact.Create(m_pTrackCancel, ArcMap.Application.hWnd);
                    pProgressorDialog           = (IProgressDialog2)m_pStepProgressor;
                    m_pStepProgressor.MinRange  = 1;
                    m_pStepProgressor.MaxRange  = pCadaSel.SelectedParcelCount * 3; //(3 runs through the selection)
                    m_pStepProgressor.StepValue = 1;
                    pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral;
                }

                m_pQF = new QueryFilterClass();
                string sPref; string sSuff;

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

                //====== need to do this for all the parcel sublayers in the map that are part of the target fabric
                //pEnumGSParcels should take care of this automatically
                //but need to do this for line sublayer

                if (m_bShowProgressor)
                {
                    pProgressorDialog.ShowDialog();
                    m_pStepProgressor.Message = "Collecting parcel data...";
                }

                //Add the OIDs of all the selected parcels into a new feature IDSet
                int        tokenLimit = 995;
                List <int> oidList    = new List <int>();
                Dictionary <int, string> dict_ParcelSelection2CalculatedArea = new Dictionary <int, string>();

                pParcelsTable = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels);

                pEnumGSParcels.Reset();
                IGSParcel pGSParcel = pEnumGSParcels.Next();
                while (pGSParcel != null)
                {
                    //Check if the cancel button was pressed. If so, stop process
                    if (m_bShowProgressor)
                    {
                        if (!m_pTrackCancel.Continue())
                        {
                            break;
                        }
                    }
                    int iDBId = pGSParcel.DatabaseId;
                    if (!oidList.Contains(iDBId))
                    {
                        oidList.Add(iDBId);
                    }

                    Marshal.ReleaseComObject(pGSParcel); //garbage collection
                    pGSParcel = pEnumGSParcels.Next();
                    if (m_bShowProgressor)
                    {
                        if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange)
                        {
                            m_pStepProgressor.Step();
                        }
                    }
                }
                Marshal.ReleaseComObject(pEnumGSParcels); //garbage collection

                if (m_bShowProgressor)
                {
                    if (!m_pTrackCancel.Continue())
                    {
                        return;
                    }
                }


                string sSuffixUnit = CalcStatedArea.txtSuffix.Text;
                int    iAreaPrec   = (int)CalcStatedArea.numDecPlaces.Value;

                double dSqMPerUnit = 1;
                if (CalcStatedArea.cboAreaUnit.FindStringExact("Acres") == CalcStatedArea.cboAreaUnit.SelectedIndex)
                {
                    dSqMPerUnit = 4046.86;
                }

                if (CalcStatedArea.cboAreaUnit.FindStringExact("Hectares") == CalcStatedArea.cboAreaUnit.SelectedIndex)
                {
                    dSqMPerUnit = 10000;
                }

                if (CalcStatedArea.cboAreaUnit.FindStringExact("Square Feet") == CalcStatedArea.cboAreaUnit.SelectedIndex)
                {
                    dSqMPerUnit = 0.09290304;
                }

                if (CalcStatedArea.cboAreaUnit.FindStringExact("Square Feet US") == CalcStatedArea.cboAreaUnit.SelectedIndex)
                {
                    dSqMPerUnit = 0.09290341;
                }

                if (m_bShowProgressor)
                {
                    pProgressorDialog.ShowDialog();
                    m_pStepProgressor.Message = "Computing areas...";
                }
                List <string> sInClauseList0 = null;
                m_pQF = new QueryFilterClass();
                if (oidList.Count() > 0)
                {
                    sInClauseList0 = Utils.InClauseFromOIDsList(oidList, tokenLimit);
                    foreach (string sInClause in sInClauseList0)
                    {
                        m_pQF.WhereClause = pParcelsTable.OIDFieldName + " IN (" + sInClause + ")";
                        CalculateStatedArea(m_pQF, pParcelsTable, pCadEd, m_pEd.Map.SpatialReference, dSqMPerUnit, sSuffixUnit,
                                            iAreaPrec, ref dict_ParcelSelection2CalculatedArea, m_pTrackCancel);

                        if (m_bShowProgressor)
                        {
                            if (!m_pTrackCancel.Continue())
                            {
                                return;
                            }
                        }
                    }
                }
                else
                {
                    return;
                }


                if (m_bShowProgressor)
                {
                    if (!m_pTrackCancel.Continue())
                    {
                        return;
                    }
                }
                #region Create Cadastral Job
                //string sTime = "";
                //if (!bIsUnVersioned && !bIsFileBasedGDB)
                //{
                //  //see if parcel locks can be obtained on the selected parcels. First create a job.
                //  DateTime localNow = DateTime.Now;
                //  sTime = Convert.ToString(localNow);
                //  ICadastralJob pJob = new CadastralJobClass();
                //  pJob.Name = sTime;
                //  pJob.Owner = System.Windows.Forms.SystemInformation.UserName;
                //  pJob.Description = "Interpolate Z values on selected features";
                //  try
                //  {
                //    Int32 jobId = pCadFabric.CreateJob(pJob);
                //  }
                //  catch (COMException ex)
                //  {
                //    if (ex.ErrorCode == (int)fdoError.FDO_E_CADASTRAL_FABRIC_JOB_ALREADY_EXISTS)
                //    {
                //      MessageBox.Show("Job named: '" + pJob.Name + "', already exists");
                //    }
                //    else
                //    {
                //      MessageBox.Show(ex.Message);
                //    }
                //    return;
                //  }
                //}
                #endregion

                //ILongArray pTempParcelsLongArray = new LongArrayClass();
                //List<int> lstParcelChanges = Utils.FIDsetToLongArray(m_pFIDSetParcels, ref pTempParcelsLongArray, ref pParcelIds, m_pStepProgressor);

                if (m_pEd.EditState == esriEditState.esriStateEditing)
                {
                    try
                    {
                        m_pEd.StartOperation();
                    }
                    catch
                    {
                        m_pEd.AbortOperation();//abort any open edit operations and try again
                        m_pEd.StartOperation();
                    }
                }
                if (bUseNonVersionedEdit)
                {
                    if (!Utils.StartEditing(pWS, bIsUnVersioned))
                    {
                        return;
                    }
                }

                //ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)pCadFabric;
                //pSchemaEd.ReleaseReadOnlyFields(pParcelsTable, esriCadastralFabricTable.esriCFTParcels);
                int    idxParcelStatedArea       = pParcelsTable.FindField("STATEDAREA");
                string ParcelStatedAreaFieldName = pParcelsTable.Fields.get_Field(idxParcelStatedArea).Name;
                if (m_bShowProgressor)
                {
                    //  pProgressorDialog.ShowDialog();
                    m_pStepProgressor.Message = "Updating parcel areas...";
                }

                IRow    pTheFeatRow   = null;
                ICursor pUpdateCursor = null;
                foreach (string sInClause in sInClauseList0)
                {
                    m_pQF.WhereClause = pParcelsTable.OIDFieldName + " IN (" + sInClause + ")";

                    if (bUseNonVersionedEdit)
                    {
                        ITableWrite pTableWr = (ITableWrite)pParcelsTable; //used for unversioned table
                        pUpdateCursor = pTableWr.UpdateRows(m_pQF, false);
                    }
                    else
                    {
                        pUpdateCursor = pParcelsTable.Update(m_pQF, false);
                    }

                    pTheFeatRow = pUpdateCursor.NextRow();
                    while (pTheFeatRow != null)
                    {
                        string sAreaString = dict_ParcelSelection2CalculatedArea[pTheFeatRow.OID];
                        pTheFeatRow.set_Value(idxParcelStatedArea, sAreaString);
                        pTheFeatRow.Store();
                        Marshal.ReleaseComObject(pTheFeatRow); //garbage collection
                        if (m_bShowProgressor)
                        {
                            if (!m_pTrackCancel.Continue())
                            {
                                break;
                            }
                        }
                        pTheFeatRow = pUpdateCursor.NextRow();
                    }
                    Marshal.ReleaseComObject(pUpdateCursor); //garbage collection
                    if (m_bShowProgressor)
                    {
                        if (!m_pTrackCancel.Continue())
                        {
                            break;
                        }
                    }
                }
                m_pEd.StopOperation("Calculate Stated Area");
                //pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTParcels);//set fields back to read-only
            }
            catch (Exception ex)
            {
                if (m_pEd != null)
                {
                    AbortEdits(bIsUnVersioned, m_pEd, pWS);
                }
                MessageBox.Show(ex.Message);
            }
            finally
            {
                ArcMap.Application.CurrentTool = pTool;
                m_pStepProgressor = null;
                m_pTrackCancel    = null;
                if (pProgressorDialog != null)
                {
                    pProgressorDialog.HideDialog();
                }

                RefreshMap(pActiveView, PolygonLyrArr);
                ICadastralExtensionManager pCExMan = (ICadastralExtensionManager)pCadEd;
                IParcelPropertiesWindow2   pPropW  = (IParcelPropertiesWindow2)pCExMan.ParcelPropertiesWindow;
                pPropW.RefreshAll();
                //update the TOC
                IMxDocument mxDocument = (ESRI.ArcGIS.ArcMapUI.IMxDocument)(ArcMap.Application.Document);
                for (int i = 0; i < mxDocument.ContentsViewCount; i++)
                {
                    IContentsView pCV = (IContentsView)mxDocument.get_ContentsView(i);
                    pCV.Refresh(null);
                }

                // refresh the attributes dialog
                ISelectionEvents pSelEvents = (ISelectionEvents)m_pEd.Map;
                pSelEvents.SelectionChanged();

                if (bUseNonVersionedEdit)
                {
                    pCadEd.CadastralFabricLayer = null;
                    PolygonLyrArr = null;
                }

                if (pMouseCursor != null)
                {
                    pMouseCursor.SetCursor(0);
                }
            }
        }