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
            }
        }
Ejemplo n.º 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 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;
        }
Ejemplo n.º 4
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);

            Marshal.ReleaseComObject(pUID);

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

            IFeatureLayer CFPointLayer = null; IFeatureLayer CFLineLayer = null;
            IFeatureLayer CFControlLayer   = null;
            IFeatureLayer CFLinePointLayer = null;

            IActiveView      pActiveView       = ArcMap.Document.ActiveView;
            IMap             pMap              = pActiveView.FocusMap;
            ICadastralFabric pCadFabric        = null;
            IProgressDialog2 pProgressorDialog = null;

            clsFabricUtils UTILS = new clsFabricUtils();

            //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 (!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;
                }
            }

            IArray CFParcelLayers = new ArrayClass();

            if (!(UTILS.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 bUseNonVersioned = false;
            IWorkspace pWS = null;

            try
            {
                //Get the selection of parcels
                IFeatureLayer pFL = (IFeatureLayer)CFParcelLayers.get_Element(0);
                IDataset      pDS = (IDataset)pFL.FeatureClass;
                pWS = pDS.Workspace;

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

                if (bUseNonVersioned)
                {
                    ICadastralFabricLayer pCFLayer = new CadastralFabricLayerClass();
                    pCFLayer.CadastralFabric    = pCadFabric;
                    pCadEd.CadastralFabricLayer = pCFLayer;//NOTE: Need to set this back to NULL when done.
                }

                Hashtable   FabLyrToFieldMap   = new Hashtable();
                DateChanger pDateChangerDialog = new DateChanger();
                pDateChangerDialog.cboBoxFabricClasses.Items.Clear();
                string[] FieldStrArr = new string[CFParcelLayers.Count];
                for (int i = 0; i < CFParcelLayers.Count; i++)
                {
                    FieldStrArr[i] = "";
                    IFeatureLayer lyr = (IFeatureLayer)CFParcelLayers.get_Element(i);
                    //   ICadastralFabricLayer cflyr = CFParcelLayers.get_Element(i);

                    pDateChangerDialog.cboBoxFabricClasses.Items.Add(lyr.Name);
                    IFields pFlds = lyr.FeatureClass.Fields;
                    for (int j = 0; j < lyr.FeatureClass.Fields.FieldCount; j++)
                    {
                        IField pFld = lyr.FeatureClass.Fields.get_Field(j);
                        if (pFld.Type == esriFieldType.esriFieldTypeDate)
                        {
                            if (FieldStrArr[i].Trim() == "")
                            {
                                FieldStrArr[i] = pFld.Name;
                            }
                            else
                            {
                                FieldStrArr[i] += "," + pFld.Name;
                            }
                        }
                    }
                    FabLyrToFieldMap.Add(i, FieldStrArr[i]);
                }
                pDateChangerDialog.FieldMap = FabLyrToFieldMap;
                pDateChangerDialog.cboBoxFabricClasses.SelectedIndex = 0;



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

                //*** get the choices from the dialog
                IFeatureLayer flyr     = (IFeatureLayer)CFParcelLayers.get_Element(pDateChangerDialog.cboBoxFabricClasses.SelectedIndex);
                int           iDateFld = flyr.FeatureClass.Fields.FindField(pDateChangerDialog.cboBoxFields.Text);

                if (pDateChangerDialog.radioButton2.Checked)
                {
                    IField pFld = flyr.FeatureClass.Fields.get_Field(iDateFld);
                    if (!pFld.IsNullable)
                    {
                        MessageBox.Show("The field you selected does not allow NULL values, and must have a date." + Environment.NewLine +
                                        "Please try again using the date option, or using a different date field.", "Field does not Allow Null", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }

                ICadastralFabricSubLayer pSubLyr = (ICadastralFabricSubLayer)flyr;
                bool bLines   = false;
                bool bParcels = false;
                if (pSubLyr.CadastralTableType == esriCadastralFabricTable.esriCFTLines)
                {
                    bLines = true;
                }
                if (pSubLyr.CadastralTableType == esriCadastralFabricTable.esriCFTParcels)
                {
                    bParcels = true;
                }

                //find out if there is a selection for the chosen layer
                bool ChosenLayerHasSelection = false;

                IFeatureSelection   pFeatSel       = null;
                ISelectionSet2      pSelSet        = null;
                ICadastralSelection pCadaSel       = null;
                IEnumGSParcels      pEnumGSParcels = null;

                int iFeatureCnt = 0;
                pFeatSel = (IFeatureSelection)flyr;
                if (pFeatSel != null)
                {
                    pSelSet = (ISelectionSet2)pFeatSel.SelectionSet;
                    ChosenLayerHasSelection = (pSelSet.Count > 0);
                    iFeatureCnt             = pSelSet.Count;
                }
                //****

                if (iFeatureCnt == 0)
                {
                    if (MessageBox.Show("There are no features selected in the " + flyr.Name + " layer." + Environment.NewLine + "Click OK to Change dates for ALL features in the layer.", "No Selection",
                                        MessageBoxButtons.OKCancel) != DialogResult.OK)
                    {
                        return;
                    }
                }
                else
                {
                    pCadaSel = (ICadastralSelection)pCadEd;
                    //** TODO: this enum should be based on the selected points, lines, or line-points
                    pEnumGSParcels = pCadaSel.SelectedParcels;// need to get the parcels before trying to get the parcel count: BUG workaround
                    //***
                }

                if (iFeatureCnt == 0)
                {
                    m_pCursor = (ICursor)flyr.FeatureClass.Search(null, false);
                    ITable pTable = (ITable)flyr.FeatureClass;
                    iFeatureCnt = pTable.RowCount(null);
                }

                m_bShowProgressor = (iFeatureCnt > 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  = iFeatureCnt;
                    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 data...";
                }

                bool bCont = true;
                m_pFIDSetParcels = new FIDSetClass();

                if (ChosenLayerHasSelection && bParcels && !bIsUnVersioned)
                {
                    //if there is a selection add the OIDs of all the selected parcels into a new feature IDSet
                    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);
                        Marshal.ReleaseComObject(pGSParcel); //garbage collection
                        pGSParcel = pEnumGSParcels.Next();
                        //}
                        if (m_bShowProgressor)
                        {
                            if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange)
                            {
                                m_pStepProgressor.Step();
                            }
                        }
                    }
                }

                if ((!ChosenLayerHasSelection && bParcels && !bIsUnVersioned) ||
                    (!ChosenLayerHasSelection && bLines && !bIsUnVersioned))
                {
                    IRow pRow = m_pCursor.NextRow();
                    while (pRow != null)
                    {
                        m_pFIDSetParcels.Add(pRow.OID);
                        Marshal.ReleaseComObject(pRow);
                        pRow = m_pCursor.NextRow();
                    }
                    Marshal.ReleaseComObject(m_pCursor);
                }

                if (bLines && ChosenLayerHasSelection && !bIsUnVersioned)
                {
                    pSelSet.Search(null, false, out m_pCursor);
                    IRow pRow = m_pCursor.NextRow();
                    int  iFld = m_pCursor.FindField("PARCELID");
                    while (pRow != null)
                    {
                        m_pFIDSetParcels.Add((int)pRow.get_Value(iFld));
                        Marshal.ReleaseComObject(pRow);
                        pRow = m_pCursor.NextRow();
                    }
                    Marshal.ReleaseComObject(m_pCursor);
                }

                //=========================================================
                if (!bCont)
                {
                    //Since I'm using update cursor need to clear the cadastral selection
                    pCadaSel.SelectedParcels = null;
                    //clear selection, to make sure the parcel explorer is updated and refreshed properly
                    return;
                }

                string sTime = "";
                if (!bIsUnVersioned)
                {
                    //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 = "Change Date on 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;
                        if (bUseNonVersioned)
                        {
                            pCadEd.CadastralFabricLayer = null;
                        }
                        return;
                    }
                }

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

                    ILongArray pParcelsToLock = new LongArrayClass();

                    UTILS.FIDsetToLongArray(m_pFIDSetParcels, ref pParcelsToLock, m_pStepProgressor);
                    if (m_pStepProgressor != null && !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)
                        {
                            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();
                            //clear selection, to make sure the parcel explorer is updated and refreshed properly
                            RefreshMap(pActiveView, CFParcelLayers, CFPointLayer, CFLineLayer, CFControlLayer, CFLinePointLayer);
                        }
                        else
                        {
                            MessageBox.Show(Convert.ToString(pCOMEx.ErrorCode));
                        }

                        if (bUseNonVersioned)
                        {
                            pCadEd.CadastralFabricLayer = null;
                        }
                        return;
                    }
                }

                //Now... start the edit. Start an edit operation.
                if (pEd.EditState == esriEditState.esriStateEditing)
                {
                    pEd.StartOperation();
                }

                if (bUseNonVersioned)
                {
                    if (!UTILS.StartEditing(pWS, bUseNonVersioned))
                    {
                        if (bUseNonVersioned)
                        {
                            pCadEd.CadastralFabricLayer = null;
                        }
                        return;
                    }
                }

                //Change all the date records
                if (m_pStepProgressor != null)
                {
                    m_pStepProgressor.Message = "Changing dates...";
                }

                bool bSuccess = true;

                ITable      Table2Edit = (ITable)flyr.FeatureClass;
                ITableWrite pTableWr   = (ITableWrite)Table2Edit;

                if (ChosenLayerHasSelection)
                {
                    //TODO: Selection based update does not work on unversioned tables
                    //need to change this code to create an update cursor from the selection,
                    //including code for tokens > 995
                    pSelSet.Update(null, false, out m_pCursor);
                }
                else
                {
                    if (bUseNonVersioned)
                    {
                        m_pCursor = pTableWr.UpdateRows(null, false);
                    }
                    else
                    {
                        m_pCursor = Table2Edit.Update(null, false);
                    }
                }
                ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)pCadFabric;
                if (bLines)
                {
                    pSchemaEd.ReleaseReadOnlyFields(Table2Edit,
                                                    esriCadastralFabricTable.esriCFTLines); //release safety-catch
                }
                else if (bParcels)
                {
                    pSchemaEd.ReleaseReadOnlyFields(Table2Edit,
                                                    esriCadastralFabricTable.esriCFTParcels); //release safety-catch
                }
                else
                {
                    pSchemaEd.ReleaseReadOnlyFields(Table2Edit,
                                                    esriCadastralFabricTable.esriCFTPoints);     //release safety-catch
                    pSchemaEd.ReleaseReadOnlyFields(Table2Edit,
                                                    esriCadastralFabricTable.esriCFTControl);    //release safety-catch
                    pSchemaEd.ReleaseReadOnlyFields(Table2Edit,
                                                    esriCadastralFabricTable.esriCFTLinePoints); //release safety-catch
                }

                if (pDateChangerDialog.radioButton2.Checked)
                {
                    bSuccess = UTILS.ChangeDatesOnTable(m_pCursor, pDateChangerDialog.cboBoxFields.Text, "",
                                                        bUseNonVersioned, m_pStepProgressor, m_pTrackCancel);
                }
                else
                {
                    bSuccess = UTILS.ChangeDatesOnTable(m_pCursor, pDateChangerDialog.cboBoxFields.Text,
                                                        pDateChangerDialog.dateTimePicker1.Text, bUseNonVersioned, m_pStepProgressor, m_pTrackCancel);
                }

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

                    return;
                }

                if (pEd.EditState == esriEditState.esriStateEditing)
                {
                    pEd.StopOperation("Change Date");
                }

                if (bUseNonVersioned)
                {
                    UTILS.StopEditing(pWS);
                }

                if (bParcels)
                {
                    pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTParcels);
                }
                else if (bLines)
                {
                    pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTLines);
                }
                else
                {
                    pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints);     //release safety-catch
                    pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl);    //release safety-catch
                    pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTLinePoints); //release safety-catch
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error:" + ex.Message);
                if (bUseNonVersioned)
                {
                    UTILS.AbortEditing(pWS);
                }
                else
                {
                    pEd.AbortOperation();
                }
            }
            finally
            {
                RefreshMap(pActiveView, CFParcelLayers, CFPointLayer, CFLineLayer, CFControlLayer, CFLinePointLayer);

                if (bUseNonVersioned)
                {
                    pCadEd.CadastralFabricLayer = null;
                    CFParcelLayers   = null;
                    CFPointLayer     = null;
                    CFLineLayer      = null;
                    CFControlLayer   = null;
                    CFLinePointLayer = null;
                }

                m_pStepProgressor = null;
                if (!(pProgressorDialog == null))
                {
                    pProgressorDialog.HideDialog();
                }
                pProgressorDialog = null;
            }
        }
Ejemplo n.º 5
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()
        {
            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);
                }
            }
        }
        private void CalculateStatedArea(IQueryFilter m_pQF, ITable pParcelsTable, ICadastralEditor pCadEd, ISpatialReference pMapSR,
                                         double SquareMetersPerUnitFactor, string Suffix, int DecimalPlaces, ref Dictionary <int, string> dict_ParcelSelection2CalculatedArea, ITrackCancel pTrackCancel)
        {
            bool bTrackCancel = (pTrackCancel != null);
            //ILine pLine = new LineClass();

            ICursor   pCursor       = pParcelsTable.Search(m_pQF, false);
            IRow      pParcelRecord = pCursor.NextRow();
            Utilities Utils         = new Utilities();

            IArray                     pParcelFeatArr = new ArrayClass();
            IGeoDataset                pGeoDS         = (IGeoDataset)((IFeatureClass)pParcelsTable).FeatureDataset;
            ISpatialReference          pFabricSR      = pGeoDS.SpatialReference;
            IProjectedCoordinateSystem pPCS           = null;
            double                     dMetersPerUnit = 1;
            bool bFabricIsInGCS = !(pFabricSR is IProjectedCoordinateSystem);

            if (!bFabricIsInGCS)
            {
                pPCS           = (IProjectedCoordinateSystem)pFabricSR;
                dMetersPerUnit = pPCS.CoordinateUnit.MetersPerUnit;
            }
            else
            {
                pPCS           = (IProjectedCoordinateSystem)pMapSR;
                dMetersPerUnit = pPCS.CoordinateUnit.MetersPerUnit;
            }

            //for each parcel record
            while (pParcelRecord != null)
            {
                IFeature pFeat = (IFeature)pParcelRecord;
                //IGeometry pGeom = pFeat.Shape;
                pParcelFeatArr.Add(pFeat);

                Marshal.ReleaseComObject(pParcelRecord);
                if (bTrackCancel)
                {
                    if (!pTrackCancel.Continue())
                    {
                        break;
                    }
                }

                pParcelRecord = pCursor.NextRow();
            }
            Marshal.ReleaseComObject(pCursor);

            ICadastralFeatureGenerator pFeatureGenerator = new CadastralFeatureGeneratorClass();
            IEnumGSParcels             pEnumGSParcels    = pFeatureGenerator.CreateParcelsFromFeatures(pCadEd, pParcelFeatArr, true);

            pEnumGSParcels.Reset();
            Dictionary <int, int>    dict_ParcelAndStartPt = new Dictionary <int, int>();
            Dictionary <int, IPoint> dict_PointID2Point    = new Dictionary <int, IPoint>();

            //dict_PointID2Point -->> this lookup makes an assumption that the fabric TO point geometry is at the same location as the line *geometry* endpoint
            IParcelLineFunctions3 ParcelLineFx = new ParcelFunctionsClass();

            IGSParcel pGSParcel      = pEnumGSParcels.Next();
            int       iFromPtIDX     = -1;
            int       iToPtIDX       = -1;
            int       iParcelIDX     = -1;
            int       iIsMajorFldIdx = -1;

            while (pGSParcel != null)
            {
                IEnumCELines pCELines     = new EnumCELinesClass();
                IEnumGSLines pEnumGSLines = (IEnumGSLines)pCELines;

                IEnumGSLines pGSLinesInner = pGSParcel.GetParcelLines(null, false);
                pGSLinesInner.Reset();
                IGSParcel         pTemp   = null;
                IGSLine           pGSLine = null;
                ICadastralFeature pCF     = (ICadastralFeature)pGSParcel;
                int iParcID = pCF.Row.OID;
                pGSLinesInner.Next(ref pTemp, ref pGSLine);
                bool bStartPointAdded = false;
                int  iFromPtID        = -1;
                while (pGSLine != null)
                {
                    if (pGSLine.Category == esriCadastralLineCategory.esriCadastralLineBoundary ||
                        pGSLine.Category == esriCadastralLineCategory.esriCadastralLineRoad ||
                        pGSLine.Category == esriCadastralLineCategory.esriCadastralLinePartConnection)
                    {
                        pCELines.Add(pGSLine);
                        ICadastralFeature pCadastralLineFeature = (ICadastralFeature)pGSLine;
                        IFeature          pLineFeat             = (IFeature)pCadastralLineFeature.Row;
                        if (iFromPtIDX == -1)
                        {
                            iFromPtIDX = pLineFeat.Fields.FindField("FROMPOINTID");
                        }
                        if (iToPtIDX == -1)
                        {
                            iToPtIDX = pLineFeat.Fields.FindField("TOPOINTID");
                        }
                        if (iParcelIDX == -1)
                        {
                            iParcelIDX = pLineFeat.Fields.FindField("PARCELID");
                        }
                        if (iIsMajorFldIdx == -1)
                        {
                            iIsMajorFldIdx = pLineFeat.Fields.FindField("ISMAJOR");
                        }

                        if (!bStartPointAdded)
                        {
                            iFromPtID        = (int)pLineFeat.get_Value(iFromPtIDX);
                            bStartPointAdded = true;
                        }
                        IPolyline pPolyline = (IPolyline)pLineFeat.ShapeCopy;
                        //if (bFabricIsInGCS)
                        pPolyline.Project(pPCS);
                        //dict_PointID2Point -->> this lookup makes an assumption that the fabric TO point geometry is at the same location as the line *geometry* endpoint
                        int iToPtID = (int)pLineFeat.get_Value(iToPtIDX);
                        //first make sure the point is not already added
                        if (!dict_PointID2Point.ContainsKey(iToPtID))
                        {
                            dict_PointID2Point.Add(iToPtID, pPolyline.ToPoint);
                        }
                    }
                    pGSLinesInner.Next(ref pTemp, ref pGSLine);
                }

                if (pGSParcel.Unclosed)
                {//skip unclosed parcels
                    pGSParcel = pEnumGSParcels.Next();
                    continue;
                }

                ICadastralFeature pCadastralPolygonFeature = (ICadastralFeature)pGSParcel;
                IFeature          pPolygonFeat             = (IFeature)pCadastralPolygonFeature.Row;
                IPolygon          pParcelPolygon           = (IPolygon)pPolygonFeat.ShapeCopy;

                IGSForwardStar pFwdStar = ParcelLineFx.CreateForwardStar(pEnumGSLines);
                //forward star is created for this parcel, now ready to find misclose for the parcel
                List <int>       LineIdsList               = new List <int>();
                List <IVector3D> TraverseCourses           = new List <IVector3D>();
                List <int>       FabricPointIDList         = new List <int>();
                List <double>    RadiusList                = new List <double>();
                List <bool>      IsMajorList               = new List <bool>();
                List <bool>      IsRunningCounterClockwise = new List <bool>();

                bool bPass = false;
                if (!bFabricIsInGCS)
                {
                    bPass = Utils.GetParcelTraverseEx(ref pFwdStar, iIsMajorFldIdx, iFromPtID, dMetersPerUnit,
                                                      ref LineIdsList, ref TraverseCourses, ref FabricPointIDList, ref RadiusList, ref IsMajorList, ref IsRunningCounterClockwise,
                                                      pParcelPolygon, 0, -1, -1, false);
                }
                else
                {
                    bPass = Utils.GetParcelTraverseEx(ref pFwdStar, iIsMajorFldIdx, iFromPtID, dMetersPerUnit * dMetersPerUnit,
                                                      ref LineIdsList, ref TraverseCourses, ref FabricPointIDList, ref RadiusList, ref IsMajorList, ref IsRunningCounterClockwise,
                                                      pParcelPolygon, 0, -1, -1, false);
                }
                //List<double> SysValList = new List<double>();
                IVector3D MiscloseVector = null;
                IPoint[]  FabricPoints   = new IPoint[FabricPointIDList.Count];//from control

                int f = 0;
                foreach (int j in FabricPointIDList)
                {
                    FabricPoints[f++] = dict_PointID2Point[j];
                }

                double dRatio = 10000;
                double dArea  = 0;
                double dGroundToGridFactor = pGSParcel.Scale;
                bool   bHasCircularArcs    = false;
                f = FabricPointIDList.Count - 1;
                IPoint[] AdjustedTraversePoints = Utils.BowditchAdjustEx(TraverseCourses, FabricPoints[f], FabricPoints[f],
                                                                         RadiusList, IsMajorList, IsRunningCounterClockwise, out MiscloseVector, out dRatio, out dArea,
                                                                         out bHasCircularArcs);

                if (MiscloseVector == null)
                {//skip if vector closure failed
                    pGSParcel = pEnumGSParcels.Next();
                    continue;
                }
                //now compare the Geometry polygon area with the computed area to see if we need to use parametric computed area
                // there needs to be at least one circular arc to warrant using this approach.
                IArea  pGeomArea           = pPolygonFeat.ShapeCopy as IArea;
                double dGroundArea         = pGeomArea.Area / (dGroundToGridFactor * dGroundToGridFactor);
                double dAreaPercentageDiff = Math.Abs(dGroundArea - Math.Abs(dArea)) / dGroundArea;

                if (dAreaPercentageDiff > 0.075 && bHasCircularArcs && dRatio > 250)
                {
                    dArea = dGroundArea;
                }
                else if (bHasCircularArcs && dArea < 0 && dRatio > 7500) //if dArea is negative then lines are running counter-clockwise
                {
                    dArea = Math.Abs(dArea);
                }
                else if (bHasCircularArcs && dArea < 0 && pParcelPolygon.ExteriorRingCount > 1)
                {
                    dArea = pGeomArea.Area;
                }

                dArea *= (dMetersPerUnit * dMetersPerUnit); //convert to square meters first
                dArea /= SquareMetersPerUnitFactor;         //convert to the given unit equivalent

                string sFormattedArea = Math.Round(dArea, DecimalPlaces).ToString() + Suffix;
                dict_ParcelSelection2CalculatedArea.Add(pGSParcel.DatabaseId, sFormattedArea);

                pGSParcel = pEnumGSParcels.Next();

                //if (bShowProgressor)
                //{
                //  if (pStepProgressor.Position < pStepProgressor.MaxRange)
                //    pStepProgressor.Step();
                //}
            }
        }