protected override void OnActivate()
        {
            //get the cadastral editor and target fabric
            m_pCadEd  = (ICadastralEditor)ArcMap.Application.FindExtensionByName("esriCadastralUI.CadastralEditorExtension");
            m_pCadFab = m_pCadEd.CadastralFabric;

            if (m_pCadFab == null)
            {
                MessageBox.Show("No target fabric found. Please add a fabric to the map start editing, and try again.");
                return;
            }

            m_pFabricLines = (IFeatureClass)m_pCadFab.get_CadastralTable(esriCadastralFabricTable.esriCFTLines);

            m_editor.CurrentTask    = null;
            m_edSketch              = m_editor as IEditSketch3;
            m_edSketch.GeometryType = esriGeometryType.esriGeometryPolyline;
            m_csc = new TraceConstructorClass();
            m_csc.Initialize(m_editor);
            m_edSketch.ShapeConstructor = m_csc;
            m_csc.Activate();

            // Setup events
            m_editEvents.OnSketchModified           += OnSketchModified;
            m_editEvents5.OnShapeConstructorChanged += OnShapeConstructorChanged;
            m_editEvents.OnSketchFinished           += OnSketchFinished;
        }
Beispiel #2
0
        public bool IsUnVersionedFabric(ICadastralFabric TheFabric)
        {
            bool IsFileBasedGDB = false;
            bool IsUnVersioned  = false;

            ITable     pTable = TheFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels);
            IDataset   pDS    = (IDataset)TheFabric;
            IWorkspace pWS    = pDS.Workspace;

            IsFileBasedGDB = (!(pWS.WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace));

            if (!(IsFileBasedGDB))
            {
                IVersionedObject pVersObj = (IVersionedObject)pTable;
                IsUnVersioned = (!(pVersObj.IsRegisteredAsVersioned));
                pTable        = null;
                pVersObj      = null;
            }
            if (IsUnVersioned && !IsFileBasedGDB)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #3
0
        private bool TestForEditLocks(ICadastralFabric Fabric, string NewJobName, ILongArray ParcelsToLock)
        {
            ICadastralFabricLocks pFabLocks = (ICadastralFabricLocks)Fabric;

            pFabLocks.LockingJob = NewJobName;

            ILongArray pLocksInConflict    = null;
            ILongArray pSoftLcksInConflict = null;

            try
            {
                pFabLocks.AcquireLocks(ParcelsToLock, true, ref pLocksInConflict, ref pSoftLcksInConflict);
                return(true);
            }
            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 parcels of selected lines.");
                    // 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(false);
            }
        }
        protected override void OnActivate()
        {
            //get the cadastral editor and target fabric
              m_pCadEd = (ICadastralEditor)ArcMap.Application.FindExtensionByName("esriCadastralUI.CadastralEditorExtension");
              m_pCadFab = m_pCadEd.CadastralFabric;

              if (m_pCadFab == null)
              {
            MessageBox.Show("No target fabric found. Please add a fabric to the map start editing, and try again.");
            return;
              }

              m_pFabricLines = (IFeatureClass)m_pCadFab.get_CadastralTable(esriCadastralFabricTable.esriCFTLines);

              m_editor.CurrentTask = null;
              m_edSketch = m_editor as IEditSketch3;
              m_edSketch.GeometryType = esriGeometryType.esriGeometryPolyline;
              m_csc = new TraceConstructorClass();
              m_csc.Initialize(m_editor);
              m_edSketch.ShapeConstructor = m_csc;
              m_csc.Activate();

              // Setup events
              m_editEvents.OnSketchModified += OnSketchModified;
              m_editEvents5.OnShapeConstructorChanged += OnShapeConstructorChanged;
              m_editEvents.OnSketchFinished += OnSketchFinished;
        }
Beispiel #5
0
        private bool CreateJob(ICadastralFabric Fabric, string JobDescription, out string NewJobName)
        {
            DateTime      localNow = DateTime.Now;
            string        sTime    = Convert.ToString(localNow);
            ICadastralJob pJob     = new CadastralJob();

            pJob.Name        = NewJobName = sTime;
            pJob.Owner       = System.Windows.Forms.SystemInformation.UserName;
            pJob.Description = JobDescription;
            try
            {
                Int32 jobId = Fabric.CreateJob(pJob);
                return(true);
            }
            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(false);
            }
        }
Beispiel #6
0
        protected override void OnClick()
        {
            ICadastralFabric pCadaFab = null;
            IApplication     pApp     = (IApplication)ArcMap.Application;

            if (pApp == null)
            {
                pApp = (IApplication)ArcCatalog.Application; //if the app is null then try ArcCatalog
            }
            if (pApp == null)
            {
                MessageBox.Show("Could not access the application.", "No Application found");
                return;
            }
            stdole.IUnknown pUnk = null;
            try
            {
                IGxApplication pGXApp = (IGxApplication)pApp;
                pUnk = (stdole.IUnknown)pGXApp.SelectedObject.InternalObjectName.Open();
                if (!(pUnk is ICadastralFabric))
                {
                    MessageBox.Show("Please select a parcel fabric in the Catalog window and try again.", "Not a parcel fabric");
                    return;
                }
                pCadaFab = pUnk as ICadastralFabric;
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was a problem opening this fabric." + Environment.NewLine +
                                ex.Message);
                return;
            }

            int  iV     = GetFabricVersion(pCadaFab);
            bool bCanDo = (iV >= 3);

            if (!bCanDo)
            {
                MessageBox.Show("This extended property is not available with this version of the fabric's schema." +
                                Environment.NewLine + "Please upgrade the fabric and try again.", "Extended Properties");
                return;
            }

            bool   bIsReducedRegenerateTolerance = GetReducedRegenerateTolerance(pCadaFab);
            string sCurrentState_ON_or_OFF       = bIsReducedRegenerateTolerance ? "REDUCED":"NORMAL";
            string sProposedtState_ON_or_OFF     = bIsReducedRegenerateTolerance ? "NORMAL": "REDUCED";

            if (MessageBox.Show("The regenerate tolerance is currently set to "
                                + sCurrentState_ON_or_OFF + Environment.NewLine
                                + "Would you like to set it to " + sProposedtState_ON_or_OFF + " ?" + Environment.NewLine + Environment.NewLine
                                + "Set the REDUCED property to regenerate the fabric with a tolerance 100 times smaller than the "
                                + "default XY tolerance of the dataset." + Environment.NewLine
                                + "Use this REDUCED tolerance for the first regenerate after a data load or after an append to the fabric."
                                + "Then reset it back to NORMAL for subsequent standard editing workflows."
                                , "Regenerate Tolerance"
                                , MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                SetReducedRegenerateTolerance(pCadaFab, !bIsReducedRegenerateTolerance);
            }
        }
Beispiel #7
0
        double GetMinScaleTolerance(ICadastralFabric pFab)
        {
            IDatasetComponent   pDSComponent = (IDatasetComponent)pFab;
            IDEDataset          pDEDS        = pDSComponent.DataElement;
            IDECadastralFabric3 pDECadaFab   = (IDECadastralFabric3)pDEDS;

            IPropertySet pPropSetTol = null;

            pDECadaFab.GetPropertySet(esriCadastralPropertySetType.esriCadastralPropSetEditSettings, out pPropSetTol);

            object retVal = null;

            try
            {
                retVal = pPropSetTol.GetProperty("esriMinScaleTolerance");
            }
            catch
            {
                Marshal.ReleaseComObject(pDEDS);
                Marshal.ReleaseComObject(pPropSetTol);
                return(1.2); //default value
            }
            double d_retVal = Convert.ToDouble(retVal);

            return(d_retVal);
        }
        void OnStartEditing()
        {
            ICadastralEditor pCadEd = m_pParcEditorMan as ICadastralEditor;

            m_TargetFabric = pCadEd.CadastralFabric;

            InitFabricState();
        }
Beispiel #9
0
        public static bool CreateCadastralJob(ICadastralFabric Fabric, string JobName, out ICadastralJob NewCadastralJob, bool WriteToFabric, ref bool JobExists)
        {
            try
            {
                JobExists = false; //first assume it does not exist
                //Create a job.
                ICadastralJob pJob = new CadastralJobClass();
                pJob.Name        = JobName;
                pJob.Owner       = System.Windows.Forms.SystemInformation.UserName;
                pJob.Description = "Append Cadastral XML";
                int jobId;
                NewCadastralJob = null;

                if (WriteToFabric)
                {
                    try
                    {
                        jobId           = Fabric.CreateJob(pJob);
                        NewCadastralJob = pJob;
                    }
                    catch (COMException ex)
                    {
                        if (ex.ErrorCode == (int)fdoError.FDO_E_CADASTRAL_FABRIC_JOB_ALREADY_EXISTS)
                        {
                            //now set the job variable to existing job
                            NewCadastralJob = Fabric.GetJob(JobName);
                            JobExists       = true;
                        }
                        return(false);
                    }
                }
                else
                {
                    NewCadastralJob = pJob;
                }

                return(true);
            }
            catch (Exception ex)
            {
                //create a dictionary of error codes for cadastral job related activities.
                Dictionary <int, String> errorCodeDict = new Dictionary <int, String>();
                errorCodeDict.Add(-2147212278, "Job has already been committed.");
                errorCodeDict.Add(-2147212277, "Job not found.");
                errorCodeDict.Add(-2147212269, "Parcel feature is part of a job that is currently being edited.");
                errorCodeDict.Add(-2147212268, "Source datum does not match the fabric datum.");
                errorCodeDict.Add(-2147212271, "The version of XML cannot be loaded.");
                errorCodeDict.Add(-2147212274, "The specified cadastral job does not belong to the current fabric.");
                errorCodeDict.Add(-2147212284, "A job with the specified name already exists.");
                errorCodeDict.Add(-2147212283, "The status of the job is invalid for this procedure.");
                errorCodeDict.Add(-2147212282, "Schema error. Required fields are missing.");
                errorCodeDict.Add(-2147212281, "Lock already exists for cadastral feature.");
                COMException c_Ex = (COMException)ex;
                NewCadastralJob = null;
                MessageBox.Show(ex.Message + Environment.NewLine + errorCodeDict[c_Ex.ErrorCode]);
                return(false);
            }
        }
Beispiel #10
0
        private int GetFabricVersion(ICadastralFabric pFab)
        {
            IDatasetComponent   pDSComponent = (IDatasetComponent)pFab;
            IDEDataset          pDEDS        = pDSComponent.DataElement;
            IDECadastralFabric2 pDECadaFab2  = (IDECadastralFabric2)pDEDS;
            int x = pDECadaFab2.Version;

            return(x);
        }
Beispiel #11
0
        private int CountPropertySetItems(ICadastralFabric pFab, esriCadastralPropertySetType PropertySetType)
        {
            IDatasetComponent   pDSComponent       = (IDatasetComponent)pFab;
            IDEDataset          pDEDS              = pDSComponent.DataElement;
            IDECadastralFabric3 pDECadaFab3        = (IDECadastralFabric3)pDEDS;
            IPropertySet        pPropSetEdSettings = null;

            pDECadaFab3.GetPropertySet(PropertySetType, out pPropSetEdSettings);
            return(pPropSetEdSettings.Count);
        }
Beispiel #12
0
        public IFIDSet AppendCadastralXML(ICadastralFabric Fabric, ICadastralJob CadastralJob, IProjectedCoordinateSystem TargetProjectedCoordinateSystem, string CadastralXMLPath)
        {
            try
            {
                string sTempPath = System.IO.Path.GetTempPath();
                string sCopiedCadastralXMLFile = System.IO.Path.Combine(sTempPath, CadastralJob.Name.Replace('/', '_').Replace(':', '_') + ".xml");

                //rename ALL oID tags so that they're ignored
                ReplaceInFile(CadastralXMLPath, sCopiedCadastralXMLFile, "oID>", "old_xxX>");

                //Possible TODO for merge-point workaround: analyze coordinates of incoming file and if any are identical to existing fabric coordinates, then make the oID tag match
                //the oID of the existing point in the target fabric. This will trigger point merging of identical points

                ITrackCancel pTrkCan = new CancelTracker();
                // Create and display the Progress Dialog
                IProgressDialogFactory pProDlgFact = new ProgressDialogFactory();
                IProgressDialog2       pProDlg     = pProDlgFact.Create(pTrkCan, 0) as IProgressDialog2;
                //Set the properties of the Progress Dialog
                pProDlg.CancelEnabled = false;
                pProDlg.Description   = "    ";
                pProDlg.Title         = "Append";
                pProDlg.Animation     = esriProgressAnimationTypes.esriProgressGlobe;

                //        do an extract to set the spatial reference
                ((ICadastralFabric3)Fabric).ExtractCadastralPacket(CadastralJob.Name, TargetProjectedCoordinateSystem, null, true);



                IXMLStream pStream = new XMLStream();
                pStream.LoadFromFile(sCopiedCadastralXMLFile);
                IFIDSet pFIDSet = null;//new FIDSet();

                (Fabric as ICadastralFabric3).PostCadastralPacket(pStream, pTrkCan, esriCadastralPacketSetting.esriCadastralPacketNoSetting, ref pFIDSet);
                //(Fabric as ICadastralFabric3).InsertCadastralPacket(CadastralJob, pStream, pTrkCan, esriCadastralPacketSetting.esriCadastralPacketNoSetting, ref pFIDSet);
                int setCnt = pFIDSet.Count();

                RefreshFabricLayers(ArcMap.Document.ActiveView.FocusMap, Fabric);
                File.Delete(sCopiedCadastralXMLFile);

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

                return(pFIDSet);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(null);
            }
        }
        private ICadastralFabric GetFabricFromLayer(ILayer Layer)
        { //interogates a layer and returns it's source fabric if it is a fabric layer
            ICadastralFabric         Fabric    = null;
            ICompositeLayer          pCompLyr  = null;
            ICadastralFabricSubLayer pCFSubLyr = null;
            ICadastralFabricLayer    pCFLayer  = null;
            bool bIsComposite = false;

            if (Layer is ICompositeLayer)
            {
                pCompLyr     = (ICompositeLayer)Layer;
                bIsComposite = true;
            }

            int iCount = 1;

            if (bIsComposite)
            {
                iCount = pCompLyr.Count;
            }

            for (int i = 0; i <= (iCount - 1); i++)
            {
                if (bIsComposite)
                {
                    Layer = pCompLyr.get_Layer(i);
                }
                try
                {
                    pCFLayer = (ICadastralFabricLayer)Layer;
                    Fabric   = pCFLayer.CadastralFabric;
                    return(Fabric);
                }
                catch
                {
                    //if it failed then try it as a fabric sublayer
                    try
                    {
                        pCFSubLyr = (ICadastralFabricSubLayer)Layer;
                        Fabric    = pCFSubLyr.CadastralFabric;
                        return(Fabric);
                    }
                    catch
                    {
                        continue;//cast failed...not a fabric sublayer
                    }
                }
            }
            return(Fabric);
        }
 public bool GetFabricFromMap(IMap InMap, out ICadastralFabric Fabric)
 {//this code assumes only one fabric in the map, and will get the first that it finds.
     //Used when not in an edit session. TODO: THis could return an array of fabrics
     Fabric = null;
     for (int idx = 0; idx <= (InMap.LayerCount - 1); idx++)
     {
         ILayer pLayer = InMap.get_Layer(idx);
         Fabric = GetFabricFromLayer(pLayer);
         if (Fabric != null)
         {
             return(true);
         }
     }
     return(false);
 }
        public bool CadastralTableAddField(ICadastralFabric pCadaFab, esriCadastralFabricTable eTable, esriFieldType FieldType,
                                           string FieldName, string FieldAlias, int FieldLength)
        {
            ITable pTable = pCadaFab.get_CadastralTable(eTable);

            // First check to see if a field with this name already exists
            if (pTable.FindField(FieldName) > -1)
            {
                if (pTable != null)
                {
                    Marshal.ReleaseComObject(pTable);
                }
                return(false);
            }

            IField2 pField = null;

            try
            {
                //Create a new Field
                pField = new FieldClass();
                //QI for IFieldEdit
                IFieldEdit2 pFieldEdit = (IFieldEdit2)pField;
                pFieldEdit.Type_2       = FieldType;
                pFieldEdit.Editable_2   = true;
                pFieldEdit.IsNullable_2 = true;
                pFieldEdit.Name_2       = FieldName;
                pFieldEdit.AliasName_2  = FieldAlias;
                pFieldEdit.Length_2     = FieldLength;
                //'.RasterDef_2 = pRasterDef
                pTable.AddField(pField);

                if (pField != null)
                {
                    Marshal.ReleaseComObject(pField);
                }
            }
            catch (COMException ex)
            {
                if (pField != null)
                {
                    Marshal.ReleaseComObject(pField);
                }
                MessageBox.Show(ex.Message);
                return(false);
            }
            return(true);
        }
Beispiel #16
0
        void SetMinScaleTolerance(ICadastralFabric pFab, double ScaleTolerance)
        {
            IDatasetComponent   pDSComponent       = (IDatasetComponent)pFab;
            IDEDataset          pDEDS              = pDSComponent.DataElement;
            IDECadastralFabric3 pDECadaFab3        = (IDECadastralFabric3)pDEDS;
            IPropertySet        pPropSetEdSettings = null;

            pDECadaFab3.GetPropertySet(esriCadastralPropertySetType.esriCadastralPropSetEditSettings, out pPropSetEdSettings);
            pPropSetEdSettings.SetProperty("esriMinScaleTolerance", ScaleTolerance);
            pDECadaFab3.SetPropertySet(esriCadastralPropertySetType.esriCadastralPropSetEditSettings, pPropSetEdSettings);

            //Update the schema
            ICadastralFabricSchemaEdit pSchemaEd  = (ICadastralFabricSchemaEdit)pFab;
            IDECadastralFabric         pDECadaFab = (IDECadastralFabric)pDECadaFab3;

            pSchemaEd.UpdateSchema(pDECadaFab);
        }
Beispiel #17
0
        public bool TestForEditLocks(ICadastralFabric Fabric, string NewJobName, List <int> ParcelsToLock)
        {
            ICadastralFabricLocks pFabLocks = (ICadastralFabricLocks)Fabric;

            pFabLocks.LockingJob = NewJobName;
            ILongArray pLocksInConflict    = null;
            ILongArray pSoftLcksInConflict = null;

            ILongArray TheParcelsToLock = new LongArrayClass();

            foreach (int i in ParcelsToLock)
            {
                TheParcelsToLock.Add(i);
            }

            try
            {
                pFabLocks.AcquireLocks(TheParcelsToLock, true, ref pLocksInConflict, ref pSoftLcksInConflict);
                return(true);
            }
            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)
                {
                    string sListOfFirst10 = "";
                    for (int i = 0; i < pLocksInConflict.Count; i++)
                    {
                        if (i == 10)
                        {
                            break;
                        }
                        sListOfFirst10 += pLocksInConflict.get_Element(i).ToString() + ", ";
                    }
                    MessageBox.Show("Edit Locks could not be acquired on all parcels." + Environment.NewLine +
                                    "Parcel ids: " + sListOfFirst10.Trim().TrimEnd(','), "Move Fabric Points");
                    // 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(false);
            }
        }
Beispiel #18
0
        public void RefreshFabricLayers(IMap Map, ICadastralFabric Fabric)
        {
            IArray        CFParcelLyrs;
            IFeatureLayer CFPtLyr;
            IFeatureLayer CFLineLyr;
            IFeatureLayer CFCtrlLyr;
            IFeatureLayer CFLinePtLyr;

            if (!GetFabricSubLayersFromFabric(Map, Fabric, out CFPtLyr, out CFLineLyr,
                                              out CFParcelLyrs, out CFCtrlLyr, out CFLinePtLyr))
            {
                return;
            }
            else
            {
                RefreshMap(ArcMap.Document.ActiveView, CFParcelLyrs, CFPtLyr, CFLineLyr, CFCtrlLyr, CFLinePtLyr);
            }
        }
        public bool SetupEditEnvironment(IWorkspace TheWorkspace, ICadastralFabric TheFabric, IEditor TheEditor,
                                         out bool IsFileBasedGDB, out bool IsUnVersioned, out bool UseNonVersionedEdit)
        {
            IsFileBasedGDB      = false;
            IsUnVersioned       = false;
            UseNonVersionedEdit = false;

            ITable pTable = TheFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels);

            IsFileBasedGDB = (!(TheWorkspace.WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace));

            if (!(IsFileBasedGDB))
            {
                IVersionedObject pVersObj = (IVersionedObject)pTable;
                IsUnVersioned = (!(pVersObj.IsRegisteredAsVersioned));
                pTable        = null;
                pVersObj      = null;
            }
            if (IsUnVersioned && !IsFileBasedGDB)
            {//
                DialogResult dlgRes = MessageBox.Show("Fabric is not registered as versioned." +
                                                      "\r\n You will not be able to undo." +
                                                      "\r\n Click 'OK' to delete permanently.",
                                                      "Continue with delete?", MessageBoxButtons.OKCancel);
                if (dlgRes == DialogResult.OK)
                {
                    UseNonVersionedEdit = true;
                }
                else if (dlgRes == DialogResult.Cancel)
                {
                    return(false);
                }
                //MessageBox.Show("The fabric tables are non-versioned." +
                //   "\r\n Please register as versioned, and try again.");
                //return false;
            }
            else if ((TheEditor.EditState == esriEditState.esriStateNotEditing))
            {
                MessageBox.Show("Please start editing first and try again.", "Delete",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                return(false);
            }
            return(true);
        }
Beispiel #20
0
        private bool GetFabricSubLayers(IMap Map, esriCadastralFabricTable FabricSubClass, bool ExcludeNonTargetFabrics,
                                        ICadastralFabric TargetFabric, out IArray CFParcelFabSubLayers)
        {
            ICadastralFabricSubLayer pCFSubLyr     = null;
            IArray        CFParcelFabricSubLayers2 = new ArrayClass();
            IFeatureLayer pParcelFabricSubLayer    = null;
            UID           pId = new UIDClass();

            pId.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}";
            IEnumLayer pEnumLayer = Map.get_Layers(pId, true);

            pEnumLayer.Reset();
            ILayer pLayer = pEnumLayer.Next();

            while (pLayer != null)
            {
                if (pLayer is ICadastralFabricSubLayer)
                {
                    pCFSubLyr = (ICadastralFabricSubLayer)pLayer;
                    if (pCFSubLyr.CadastralTableType == FabricSubClass)
                    {
                        pParcelFabricSubLayer = (IFeatureLayer)pCFSubLyr;
                        ICadastralFabric ThisLayersFabric     = pCFSubLyr.CadastralFabric;
                        bool             bIsTargetFabricLayer = ThisLayersFabric.Equals(TargetFabric);
                        if (!ExcludeNonTargetFabrics || (ExcludeNonTargetFabrics && bIsTargetFabricLayer))
                        {
                            CFParcelFabricSubLayers2.Add(pParcelFabricSubLayer);
                        }
                    }
                }
                pLayer = pEnumLayer.Next();
            }
            CFParcelFabSubLayers = CFParcelFabricSubLayers2;
            if (CFParcelFabricSubLayers2.Count > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        public void GetFabricPlatform(IWorkspace TheWorkspace, ICadastralFabric TheFabric,
                                      out bool IsFileBasedGDB, out bool IsUnVersioned)
        {
            IsFileBasedGDB = false;
            IsUnVersioned  = false;

            ITable pTable = TheFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels);

            IsFileBasedGDB = (!(TheWorkspace.WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace));

            if (!(IsFileBasedGDB))
            {
                IVersionedObject pVersObj = (IVersionedObject)pTable;
                IsUnVersioned = (!(pVersObj.IsRegisteredAsVersioned));
                pVersObj      = null;
            }
            if (pTable != null)
            {
                Marshal.ReleaseComObject(pTable);
            }
        }
        private IGSPlan FindFabricPlanByName(string PlanName, ICadastralEditor CadastralEditor)
        {
            ICursor pCur = null;

            try
            {
                ICadastralFabric pCadaFab   = CadastralEditor.CadastralFabric;
                ITable           pPlanTable = pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTPlans);
                int          iPlanNameFldID = pPlanTable.FindField("NAME");
                string       PlanNameFld    = pPlanTable.Fields.get_Field(iPlanNameFldID).Name;
                IQueryFilter pQF            = new QueryFilter();
                pQF.WhereClause = PlanNameFld + "= '" + PlanName + "'";
                pQF.SubFields   = pPlanTable.OIDFieldName + PlanNameFld;
                pCur            = pPlanTable.Search(pQF, false);
                IRow    pPlanRow = pCur.NextRow();
                IGSPlan pGSPlan  = null;
                if (pPlanRow != null)
                {
                    //Since plan was found, generate plan object from database:
                    ICadastralFeatureGenerator pFeatureGenerator = new CadastralFeatureGenerator();
                    pGSPlan = pFeatureGenerator.CreatePlanFromRow(CadastralEditor, pPlanRow);
                    Marshal.ReleaseComObject(pPlanRow);
                }
                return(pGSPlan);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(null);
            }
            finally
            {
                if (pCur != null)
                {
                    Marshal.ReleaseComObject(pCur);
                }
            }
        }
Beispiel #23
0
        private IGSPlan FindFabricPlanByName(string PlanName, ICadastralEditor CadastralEditor)
        {
            ICursor pCur = null;

            try
            {
                ICadastralFabric pCadaFab   = CadastralEditor.CadastralFabric;
                ITable           pPlanTable = pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTPlans);
                int          iPlanNameFldID = pPlanTable.FindField("NAME");
                string       PlanNameFld    = pPlanTable.Fields.get_Field(iPlanNameFldID).Name;
                IQueryFilter pQF            = new QueryFilterClass();
                pQF.WhereClause = PlanNameFld + "= '" + PlanName + "'";
                pQF.SubFields   = pPlanTable.OIDFieldName + PlanNameFld;
                pCur            = pPlanTable.Search(pQF, false);
                IRow    pPlanRow  = pCur.NextRow();
                IGSPlan pGSPlanDB = null;
                IGSPlan pGSPlan   = null;
                if (pPlanRow != null)
                {
                    //Since plan was found, generate plan object from database:
                    ICadastralFeatureGenerator pFeatureGenerator = new CadastralFeatureGeneratorClass();
                    pGSPlanDB = pFeatureGenerator.CreatePlanFromRow(CadastralEditor, pPlanRow);
                    //Hydrate the database plan as a new GSPlan in GeoSurvey Engine packet
                    pGSPlan = new GSPlanClass();
                    AssignGSPlan(pGSPlanDB, pGSPlan, true);
                }
                return(pGSPlan);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(null);
            }
            finally
            {
            }
        }
        void m_editEvents_OnStartEditing()
        {
            AdjustmentDockWindow.SetEnabled(true);
            ICadastralEditor pCadEd = (ICadastralEditor)ArcMap.Application.FindExtensionByName("esriCadastralUI.CadastralEditorExtension");

            string m_sFieldName = "";

            m_sFieldName = s_extension.FieldName;

            ICadastralFabric pFabric = pCadEd.CadastralFabric;

            if (pFabric == null)
            {
                return;
            }

            IFeatureClass pLinesFC = (IFeatureClass)pFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTLines);

            if (pLinesFC.FindField(m_sFieldName) == -1)
            {
                m_RecordToField = false;
                return;
            }
        }
Beispiel #25
0
        void AddEmptyPlansToList(ICadastralFabric Fabric, IFIDSet EmptyPlansFIDSet, dlgEmptyPlansList EmptyPlansList)
        {
            ITable         pPlansTable = Fabric.get_CadastralTable(esriCadastralFabricTable.esriCFTPlans);
            CheckedListBox list        = EmptyPlansList.checkedListBox1;
            IArray         array       = new ArrayClass();

            for (int idx = 0; idx <= (EmptyPlansFIDSet.Count() - 1); idx++)
            {
                // Add the name of the plan to the list
                Int32 i_x;
                Int32 iPlanName;
                iPlanName = pPlansTable.FindField("NAME");
                EmptyPlansFIDSet.Next(out i_x);
                array.Add(i_x);
                string sPlanName = (string)pPlansTable.GetRow(i_x).get_Value(iPlanName);
                list.Items.Add(sPlanName, true);
            }
            // Bind array of plan ids with the list
            list.Tag = (object)array;
            if (list.Items.Count > 0)
            {
                EmptyPlansList.checkedListBox1_SelectedValueChanged(null, null);
            }
        }
Beispiel #26
0
        bool GetReducedRegenerateTolerance(ICadastralFabric pFab)
        {
            IDatasetComponent   pDSComponent = (IDatasetComponent)pFab;
            IDEDataset          pDEDS        = pDSComponent.DataElement;
            IDECadastralFabric3 pDECadaFab   = (IDECadastralFabric3)pDEDS;

            IPropertySet pPropSetTol = null;

            pDECadaFab.GetPropertySet(esriCadastralPropertySetType.esriCadastralPropSetEditSettings, out pPropSetTol);

            object retVal = null;

            try
            {
                retVal = pPropSetTol.GetProperty("esriReduceRegenerateTolerance");
            }
            catch
            {
                return(false); //default value
            }
            bool b_retVal = Convert.ToBoolean(retVal);

            return(b_retVal);
        }
        protected override void OnClick()
        {
            m_pApp = (IApplication)ArcMap.Application;
              if (m_pApp == null)
            //if the app is null then could be running from ArcCatalog
            m_pApp = (IApplication)ArcCatalog.Application;

              if (m_pApp == null)
              {
            MessageBox.Show("Could not access the application.", "No Application found");
            return;
              }
              IGxApplication pGXApp = (IGxApplication)m_pApp;
              stdole.IUnknown pUnk = null;
              try
              {
            pUnk = (stdole.IUnknown)pGXApp.SelectedObject.InternalObjectName.Open();
              }
              catch (COMException ex)
              {
            if (ex.ErrorCode == (int)fdoError.FDO_E_DATASET_TYPE_NOT_SUPPORTED_IN_RELEASE ||
            ex.ErrorCode == -2147220944)
              MessageBox.Show("The dataset is not supported in this release.", "Could not open the dataset");
            else
              MessageBox.Show(ex.ErrorCode.ToString(), "Could not open the dataset");
            return;
              }

              if (pUnk is ICadastralFabric)
            m_pCadaFab = (ICadastralFabric)pUnk;
              else
              {
            MessageBox.Show("Please select a parcel fabric and try again.", "Not a parcel fabric");
            return;
              }

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

              Utils FabricUTILS = new Utils();

              ITable pTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels);
              IDataset pDS = (IDataset)pTable;
              IWorkspace pWS = pDS.Workspace;
              bool bIsFileBasedGDB = true;
              bool bIsUnVersioned = true;

              FabricUTILS.GetFabricPlatform(pWS, m_pCadaFab, out bIsFileBasedGDB,
            out bIsUnVersioned);

              //Do a Start and Stop editing to make sure we're not running in an edit session
              if (!FabricUTILS.StartEditing(pWS, true))
              {//if start editing fails then bail
            if (pUnk != null)
              Marshal.ReleaseComObject(pUnk);
            Cleanup(pMouseCursor, null, pTable, null, pWS, null);
            FabricUTILS = null;
            return;
              }
              FabricUTILS.StopEditing(pWS);
              IFIDSet pPlansToDelete = null;

              try
              {
            string[] SummaryNames = new string[0]; //define as dynamic array
            string[] RepeatPlans = new string[0]; //define as dynamic array
            ITable pPlansTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTPlans);
            //load all the plan names into a string array
            m_pProgressorDialogFact = new ProgressDialogFactoryClass();
            m_pTrackCancel = new CancelTrackerClass();
            m_pStepProgressor = m_pProgressorDialogFact.Create(m_pTrackCancel, m_pApp.hWnd);
            IProgressDialog2 pProgressorDialog = (IProgressDialog2)m_pStepProgressor;
            int iRowCount = pPlansTable.RowCount(null);
            m_pStepProgressor.MinRange = 1;
            m_pStepProgressor.MaxRange = iRowCount * 2;
            m_pStepProgressor.StepValue = 1;
            pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral;
            pProgressorDialog.ShowDialog();
            m_pStepProgressor.Message = "Finding same-name plans to merge...";

            int iRepeatCnt = 0;

            if (!FindRepeatPlans(pPlansTable, out RepeatPlans, out SummaryNames, out iRepeatCnt))
            {
              pProgressorDialog.HideDialog();
              if (iRepeatCnt == 0)
              {
            MessageBox.Show("All plans in the fabric have unique names." +
               Environment.NewLine + "There are no plans to merge.", "Merge plans by name");
              }
              else
              {
            MessageBox.Show("There was a problem searching for repeat plans.", "Merge plans by name");
              }
              SummaryNames = null;
              RepeatPlans = null;
              Cleanup(pMouseCursor, null, pTable, pPlansTable, pWS, pProgressorDialog);
              return;
            }

            dlgMergeSameNamePlans TheSummaryDialog = new dlgMergeSameNamePlans();

            FillTheSummaryList(TheSummaryDialog, SummaryNames);

            DialogResult dResult = TheSummaryDialog.ShowDialog();

            if (dResult == DialogResult.Cancel)
            {
              pProgressorDialog.HideDialog();
              SummaryNames = null;
              RepeatPlans = null;
              Cleanup(pMouseCursor, null,pTable, pPlansTable, pWS, pProgressorDialog);
              pPlansTable = null;
              return;
            }

            //get the time now
            m_pStartTime = new TimeClass();
            m_pStartTime.SetFromCurrentLocalTime();

            Dictionary<int, int> Lookup = new Dictionary<int, int>();
            string[] InClause = new string[0]; //define as dynamic array

            m_pStepProgressor.Message = "Creating the merge query...";
            FabricUTILS.BuildSearchMapAndQuery(RepeatPlans, out Lookup, out InClause, out pPlansToDelete);

            ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)m_pCadaFab;
            ITable ParcelTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels);
            pSchemaEd.ReleaseReadOnlyFields(ParcelTable, esriCadastralFabricTable.esriCFTParcels); //release safety-catch

            if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned))
            {
              Cleanup(pMouseCursor, pPlansToDelete,pTable, pPlansTable, pWS, pProgressorDialog);
              InClause = null;
              Lookup.Clear();
              Lookup = null;
              return;
            }

            //setup progressor dialog for merge
            m_pStepProgressor.Message = "Moving parcels from source to target plans...";

            if (!FabricUTILS.MergePlans(ParcelTable, Lookup, InClause, bIsUnVersioned,m_pStepProgressor,m_pTrackCancel))
            {
              FabricUTILS.AbortEditing(pWS);
              pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTParcels);
              Cleanup(pMouseCursor, pPlansToDelete,pTable,pPlansTable, pWS,pProgressorDialog);
              InClause = null;
              Lookup.Clear();
              Lookup = null;
              return;
            }

            if (TheSummaryDialog.checkBox1.Checked)
            {
              //setup progressor dialog for Delete
              m_pStepProgressor.MaxRange = pPlansToDelete.Count();
              m_pStepProgressor.Message = "Deleting source plans...";

              if (bIsUnVersioned)
              {
            if (!FabricUTILS.DeleteRowsUnversioned(pWS, pPlansTable, pPlansToDelete, m_pStepProgressor, m_pTrackCancel))
              Cleanup(pMouseCursor, pPlansToDelete,pTable,pPlansTable,pWS,pProgressorDialog);
              }
              else
              {
            if (!FabricUTILS.DeleteRowsByFIDSet(pPlansTable, pPlansToDelete, m_pStepProgressor, m_pTrackCancel))
              Cleanup(pMouseCursor, pPlansToDelete,pTable,pPlansTable, pWS,pProgressorDialog);
              }
            }

            pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTParcels);

            m_pEndTime = new TimeClass();
            m_pEndTime.SetFromCurrentLocalTime();
            ITimeDuration HowLong = m_pEndTime.SubtractTime(m_pStartTime);

            m_pStepProgressor.Message = "["
              + HowLong.Hours.ToString("00") + "h "
              + HowLong.Minutes.ToString("00") + "m "
              + HowLong.Seconds.ToString("00") + "s]" + "  Saving changes...please wait.";

            FabricUTILS.StopEditing(pWS);
            Cleanup(pMouseCursor, pPlansToDelete,pTable,pPlansTable, pWS,pProgressorDialog);

              }
              catch (COMException ex)
              {
            MessageBox.Show(Convert.ToString(ex.ErrorCode));
            Cleanup(pMouseCursor, pPlansToDelete,pTable,null,pWS,null);
              }
        }
        protected override void OnClick()
        {
            m_pApp = (IApplication)ArcMap.Application;
              if (m_pApp == null)
            //if the app is null then could be running from ArcCatalog
            m_pApp = (IApplication)ArcCatalog.Application;

              if (m_pApp == null)
              {
            MessageBox.Show("Could not access the application.", "No Application found");
            return;
              }
              IGxApplication pGXApp = (IGxApplication)m_pApp;
              stdole.IUnknown pUnk = null;
              try
              {
            pUnk = (stdole.IUnknown)pGXApp.SelectedObject.InternalObjectName.Open();
              }
              catch (COMException ex)
              {
            if (ex.ErrorCode == (int)fdoError.FDO_E_DATASET_TYPE_NOT_SUPPORTED_IN_RELEASE ||
            ex.ErrorCode == -2147220944)
              MessageBox.Show("The dataset is not supported in this release.", "Could not open the dataset");
            else
              MessageBox.Show(ex.ErrorCode.ToString(), "Could not open the dataset");
            return;
              }

              if (pUnk is ICadastralFabric)
            m_pCadaFab = (ICadastralFabric)pUnk;
              else
              {
            MessageBox.Show("Please select a parcel fabric and try again.", "Not a parcel fabric");
            return;
              }

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

              Utils FabricUTILS = new Utils();

              ITable pTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels);
              IDataset pDS = (IDataset)pTable;
              IWorkspace pWS = pDS.Workspace;
              bool bIsFileBasedGDB = true;
              bool bIsUnVersioned = true;

              FabricUTILS.GetFabricPlatform(pWS, m_pCadaFab, out bIsFileBasedGDB,
            out bIsUnVersioned);

              //Do a Start and Stop editing to make sure we're not running in an edit session
              if (!FabricUTILS.StartEditing(pWS, true))
              {//if start editing fails then bail
            if (pUnk != null)
              Marshal.ReleaseComObject(pUnk);
            Cleanup(pMouseCursor, null, pTable, null, pWS, null, true);
            FabricUTILS = null;
            return;
              }
              FabricUTILS.StopEditing(pWS);

              ITable pPlansTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTPlans);
              ITable pParcelsTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels);

              m_pProgressorDialogFact = new ProgressDialogFactoryClass();
              m_pTrackCancel = new CancelTrackerClass();
              m_pStepProgressor = m_pProgressorDialogFact.Create(m_pTrackCancel, m_pApp.hWnd);
              IProgressDialog2 pProgressorDialog = (IProgressDialog2)m_pStepProgressor;
              int iRowCount = pPlansTable.RowCount(null);
              int iRowCount2 = pParcelsTable.RowCount(null);
              m_pStepProgressor.MinRange = 1;
              m_pStepProgressor.MaxRange =iRowCount  + iRowCount2;
              m_pStepProgressor.StepValue = 1;
              pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral;
              pProgressorDialog.ShowDialog();
              m_pStepProgressor.Message = "Searching " + iRowCount2.ToString() + " parcel records...";

              int iFixCnt = 0;
              //load all the plan names into a string array

              ArrayList NoPlanParcels = new ArrayList();
              ArrayList NoPlanParcelsGrouped = new ArrayList();
              ArrayList PlansList = new ArrayList();
              Dictionary<int, int> ParcelLookup = new Dictionary<int, int>();

              if (!FindNoPlanParcels(pPlansTable, pParcelsTable, ref PlansList, ref NoPlanParcels,
            ref NoPlanParcelsGrouped, ref ParcelLookup, out iFixCnt))
              {
            pProgressorDialog.HideDialog();
            if (iFixCnt > 0)
              MessageBox.Show("Canceled searching for parcels with no plan.", "Fix Parcels With No Name");

            NoPlanParcels = null;

            Cleanup(pMouseCursor, null, pTable, pPlansTable, pWS, pProgressorDialog, true);
            return;
              }

              m_pStepProgressor.Message = "Search complete.";

              NoPlanParcels.Sort();

              dlgFixParcelsWithNoPlan MissingPlansDialog = new dlgFixParcelsWithNoPlan();
              FillTheList(MissingPlansDialog.listView1, NoPlanParcels);
              FillTheList(MissingPlansDialog.listViewByGroup, NoPlanParcelsGrouped);
              FillTheListBox(MissingPlansDialog.listPlans, PlansList);

              MissingPlansDialog.ThePlansList = PlansList;

              MissingPlansDialog.label1.Text = "Found " + iFixCnt.ToString() +
            " parcels that have a missing plan record.";
              MissingPlansDialog.lblSelectionCount.Text = "(" + iFixCnt.ToString() + " of "
            + iFixCnt.ToString() + " selected to fix)";

              //cleanup
              Cleanup(null, null, null, null, null, pProgressorDialog, false);

              DialogResult dResult = MissingPlansDialog.ShowDialog();

              if (dResult == DialogResult.Cancel)
              {
            Cleanup(null, null, pTable, pPlansTable, pWS, pProgressorDialog, true);
            return;
              }

              //re-initilize the progressor
              m_pProgressorDialogFact = new ProgressDialogFactoryClass();
              m_pTrackCancel = new CancelTrackerClass();
              m_pStepProgressor = m_pProgressorDialogFact.Create(m_pTrackCancel, m_pApp.hWnd);
              pProgressorDialog = (IProgressDialog2)m_pStepProgressor;

              m_pStepProgressor.MinRange = 1;
              m_pStepProgressor.MaxRange = MissingPlansDialog.listView1.CheckedItems.Count;
              m_pStepProgressor.StepValue = 1;
              pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral;
              pProgressorDialog.ShowDialog();
              m_pStepProgressor.Message = "Fixing parcels without a plan...";

              if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned))
              {
            pProgressorDialog.HideDialog();
            Cleanup(null, null, pTable, pPlansTable, pWS, pProgressorDialog, true);
            FabricUTILS = null;
            return;
              }
              int iNewPlanID = 0;

              //Need to collect the choices from the UI and write the results to the DB
              ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)m_pCadaFab;

              if (MissingPlansDialog.radioBtnExistingPlan.Checked)
              {//Get the id of the EXISTING Plan
            string sPlanString = MissingPlansDialog.listPlans.SelectedItem.ToString();
            string[] sPlanOID = Regex.Split(sPlanString, "oid:");
            sPlanOID[1].Trim();
            iNewPlanID = Convert.ToInt32(sPlanOID[1].Remove(sPlanOID[1].LastIndexOf(")")));
              }

              Dictionary<string, int> PlanLookUp= new Dictionary<string,int>();
              ArrayList iUnitsAndFormat = new ArrayList();
              iUnitsAndFormat.Add(m_AngleUnits);
              iUnitsAndFormat.Add(m_AreaUnits);
              iUnitsAndFormat.Add(m_DistanceUnits);
              iUnitsAndFormat.Add(m_DirectionFormat);
              iUnitsAndFormat.Add(m_LineParams);

              if (MissingPlansDialog.radioBtnUserDef.Checked)
              { //create a NEW plan named with user's entered text
            ArrayList sPlanInserts = new ArrayList();
            pSchemaEd.ReleaseReadOnlyFields(pPlansTable, esriCadastralFabricTable.esriCFTPlans); //release safety-catch
            sPlanInserts.Add(MissingPlansDialog.txtPlanName.Text);
            FabricUTILS.InsertPlanRecords(pPlansTable, sPlanInserts,iUnitsAndFormat,PlansList, bIsUnVersioned,
              null, null, ref PlanLookUp);
            if (!PlanLookUp.TryGetValue(MissingPlansDialog.txtPlanName.Text, out iNewPlanID))
            {
              Cleanup(null, null, pTable, pPlansTable, pWS, pProgressorDialog, true);
              FabricUTILS = null;
              return;
            }
              }

              if (MissingPlansDialog.radioBtnPlanID.Checked)
              {//create multiple new plans for each PlanID
            ArrayList sPlanInserts = new ArrayList();
            foreach (ListViewItem listItem in MissingPlansDialog.listViewByGroup.CheckedItems)
              sPlanInserts.Add("[" + listItem.SubItems[0].Text + "]");

            pSchemaEd.ReleaseReadOnlyFields(pPlansTable, esriCadastralFabricTable.esriCFTPlans); //release safety-catch
            FabricUTILS.InsertPlanRecords(pPlansTable, sPlanInserts, iUnitsAndFormat, PlansList, bIsUnVersioned,
              null, null, ref PlanLookUp);
              }

              ArrayList sParcelUpdates = new ArrayList();
              sParcelUpdates.Add("");
              int i = 0;
              int iCnt = 0;
              int iTokenLimit = 995;
              foreach (ListViewItem listItem in MissingPlansDialog.listView1.CheckedItems)
              {
            string s = listItem.SubItems[1].Text;
            string[] sItems = Regex.Split(s, "id:");
            if (iCnt >= iTokenLimit)//time to start a new row
            {
              sParcelUpdates.Add("");//add a new item to the arraylist
              iCnt = 0;//reset token counter
              i++;//increment array index
            }
            sItems[1] = sItems[1].Remove(sItems[1].LastIndexOf(")"));

            if (iCnt == 0)
              sParcelUpdates[i] += sItems[1];
            else
              sParcelUpdates[i] += "," + sItems[1];
            iCnt++;
              }

              //============edit block==========
              try
              {
            pSchemaEd.ReleaseReadOnlyFields(pTable, esriCadastralFabricTable.esriCFTParcels); //release safety-catch

            if (MissingPlansDialog.radioBtnUserDef.Checked || MissingPlansDialog.radioBtnExistingPlan.Checked)
            {
              if (!FabricUTILS.UpdateParcelRecords(pTable, sParcelUpdates, iNewPlanID, bIsUnVersioned,
            m_pStepProgressor, m_pTrackCancel))
              {
            pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTParcels);
            pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPlans);
            FabricUTILS.AbortEditing(pWS);
            Cleanup(null, null, pTable, pPlansTable, pWS, pProgressorDialog, true);
            FabricUTILS = null;
            return;
              }
            }
            if (MissingPlansDialog.radioBtnPlanID.Checked)
            {
              if (!FabricUTILS.UpdateParcelRecordsByPlanGroup(pTable, sParcelUpdates, PlanLookUp,
            ParcelLookup, bIsUnVersioned, m_pStepProgressor, m_pTrackCancel))
              {
            pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTParcels);
            pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPlans);
            FabricUTILS.AbortEditing(pWS);
            Cleanup(null, null, pTable, pPlansTable, pWS, pProgressorDialog, true);
            FabricUTILS = null;
            return;
              }
            }

            pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTParcels);
            pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPlans);

            FabricUTILS.StopEditing(pWS);

            //Cleanup(null, null, pTable, pPlansTable, pWS, pProgressorDialog, true);
            //FabricUTILS = null;
              }
              catch (COMException Ex)
              {
            MessageBox.Show(Ex.ErrorCode.ToString() +":" + Ex.Message,"Fix Missing Plans");
              }
              finally
              {
            Cleanup(null, null, pTable, pPlansTable, pWS, pProgressorDialog, true);
            FabricUTILS = null;
              }
        }
        public double ConvertMetersToFabricUnits(double InDistance, ICadastralFabric Fabric)
        {
            IProjectedCoordinateSystem2 pPCS;
              ILinearUnit pMapLU;
              double dMetersPerMapUnit = 1;

              IGeoDataset pGDS = (IGeoDataset)Fabric;

              ISpatialReference2 pSpatRef = (ISpatialReference2)pGDS.SpatialReference;
              if (pSpatRef == null)
            return InDistance;

              if (pSpatRef is IProjectedCoordinateSystem2)
              {
            pPCS = (IProjectedCoordinateSystem2)pSpatRef;
            pMapLU = pPCS.CoordinateUnit;
            dMetersPerMapUnit = pMapLU.MetersPerUnit;
            double dRes = InDistance / dMetersPerMapUnit;
            return dRes;
              }
              return InDistance;
        }
        public bool SetupEditEnvironment(IWorkspace TheWorkspace, ICadastralFabric TheFabric, IEditor TheEditor, out bool IsFileBasedGDB, out bool IsUnVersioned, out bool UseNonVersionedEdit)
        {
            IsFileBasedGDB = false;
            IsUnVersioned = false;
            UseNonVersionedEdit = false;

            ITable pTable = TheFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels);

            IsFileBasedGDB = (!(TheWorkspace.WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace));

            if (!(IsFileBasedGDB))
            {
                IVersionedObject pVersObj = (IVersionedObject)pTable;
                IsUnVersioned = (!(pVersObj.IsRegisteredAsVersioned));
                pTable = null;
                pVersObj = null;
            }
            if (IsUnVersioned && !IsFileBasedGDB)
            {//
                DialogResult dlgRes = messageBox.Show("Fabric is not registered as versioned." +
                  "\r\n You will not be able to undo." +
                  "\r\n Click 'OK' to delete permanently.",
                  "Continue with delete?", MessageBoxButtons.OKCancel);
                if (dlgRes == DialogResult.OK)
                {
                    UseNonVersionedEdit = true;
                }
                else if (dlgRes == DialogResult.Cancel)
                {
                    return false;
                }
                //MessageBox.Show("The fabric tables are non-versioned." +
                //   "\r\n Please register as versioned, and try again.");
                //return false;
            }
            else if (TheEditor != null && TheEditor.EditState == esriEditState.esriStateNotEditing)
            {
                messageBox.Show("Please start editing first and try again.", "Delete", MessageBoxButtons.OK);
                return false;
            }
            return true;
        }
Beispiel #31
0
        protected override void OnClick()
        {
            bool            bShowProgressor = false;
            IStepProgressor pStepProgressor = null;
            //Create a CancelTracker.
            ITrackCancel           pTrackCancel = null;
            IProgressDialogFactory pProgressorDialogFact;

            IMouseCursor pMouseCursor = new MouseCursorClass();

            pMouseCursor.SetCursor(2);

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

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

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

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

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

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

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

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

            IArray CFControlLayers = new ArrayClass();

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

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

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

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

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

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

                bShowProgressor = (iTotalSelectionCount > 10);

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

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

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

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

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

                    m_pFIDSetControl = new FIDSetClass();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (pMouseCursor != null)
                {
                    pMouseCursor.SetCursor(0);
                }
            }
        }
Beispiel #32
0
        private bool GetFabricSubLayersFromFabric(IMap Map, ICadastralFabric Fabric, out IFeatureLayer CFPointLayer, out IFeatureLayer CFLineLayer,
                                                  out IArray CFParcelLayers, out IFeatureLayer CFControlLayer, out IFeatureLayer CFLinePointLayer)
        {
            ICadastralFabricLayer    pCFLayer  = null;
            ICadastralFabricSubLayer pCFSubLyr = null;
            ICompositeLayer          pCompLyr  = null;
            IArray CFParcelLayers2             = new ArrayClass();

            IDataset pDS              = (IDataset)Fabric;
            IName    pDSName          = pDS.FullName;
            string   FabricNameString = pDSName.NameString;

            long layerCount = Map.LayerCount;

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

            for (int idx = 0; idx <= (layerCount - 1); idx++)
            {
                ILayer pLayer       = Map.get_Layer(idx);
                bool   bIsComposite = false;
                if (pLayer is ICompositeLayer)
                {
                    pCompLyr     = (ICompositeLayer)pLayer;
                    bIsComposite = true;
                }

                int iCompositeLyrCnt = 1;
                if (bIsComposite)
                {
                    iCompositeLyrCnt = pCompLyr.Count;
                }

                for (int i = 0; i <= (iCompositeLyrCnt - 1); i++)
                {
                    if (bIsComposite)
                    {
                        pLayer = pCompLyr.get_Layer(i);
                    }
                    if (pLayer is ICadastralFabricLayer)
                    {
                        pCFLayer = (ICadastralFabricLayer)pLayer;
                        break;
                    }
                    if (pLayer is ICadastralFabricSubLayer)
                    {
                        pCFSubLyr = (ICadastralFabricSubLayer)pLayer;
                        IDataset pDS2     = (IDataset)pCFSubLyr.CadastralFabric;
                        IName    pDSName2 = pDS2.FullName;
                        if (pDSName.NameString.ToLower() == pDSName2.NameString.ToLower() &&
                            pCFSubLyr.CadastralTableType == esriCadastralFabricTable.esriCFTParcels)
                        {
                            pParcelLayer = (IFeatureLayer)pCFSubLyr;
                            CFParcelLayers2.Add(pParcelLayer);
                        }
                        if (CFLineLayer == null && pDSName.NameString.ToLower() == pDSName2.NameString.ToLower() &&
                            pCFSubLyr.CadastralTableType == esriCadastralFabricTable.esriCFTLines)
                        {
                            CFLineLayer = (IFeatureLayer)pCFSubLyr;
                        }
                        if (CFPointLayer == null && pDSName.NameString.ToLower() == pDSName2.NameString.ToLower() &&
                            pCFSubLyr.CadastralTableType == esriCadastralFabricTable.esriCFTPoints)
                        {
                            CFPointLayer = (IFeatureLayer)pCFSubLyr;
                        }
                        if (CFLinePointLayer == null && pDSName.NameString.ToLower() == pDSName2.NameString.ToLower() &&
                            pCFSubLyr.CadastralTableType == esriCadastralFabricTable.esriCFTLinePoints)
                        {
                            CFLinePointLayer = (IFeatureLayer)pCFSubLyr;
                        }
                        if (CFControlLayer == null && pDSName.NameString.ToLower() == pDSName2.NameString.ToLower() &&
                            pCFSubLyr.CadastralTableType == esriCadastralFabricTable.esriCFTControl)
                        {
                            CFControlLayer = (IFeatureLayer)pCFSubLyr;
                        }
                    }
                }

                //Check that the fabric layer belongs to the requested fabric
                if (pCFLayer != null)
                {
                    if (pCFLayer.CadastralFabric.Equals(Fabric))
                    {
                        CFPointLayer = (IFeatureLayer)pCFLayer.get_CadastralSubLayer(esriCadastralFabricRenderer.esriCFRPoints);
                        CFLineLayer  = (IFeatureLayer)pCFLayer.get_CadastralSubLayer(esriCadastralFabricRenderer.esriCFRLines);
                        pParcelLayer = (IFeatureLayer)pCFLayer.get_CadastralSubLayer(esriCadastralFabricRenderer.esriCFRParcels);
                        CFParcelLayers2.Add(pParcelLayer);
                        CFControlLayer   = (IFeatureLayer)pCFLayer.get_CadastralSubLayer(esriCadastralFabricRenderer.esriCFRControlPoints);
                        CFLinePointLayer = (IFeatureLayer)pCFLayer.get_CadastralSubLayer(esriCadastralFabricRenderer.esriCFRLinePoints);
                    }
                    CFParcelLayers = CFParcelLayers2;
                    return(true);
                }
            }
            //at the minimum, just need to make sure we have a parcel sublayer for the requested fabric
            if (pParcelLayer != null)
            {
                CFParcelLayers = CFParcelLayers2;
                return(true);
            }
            else
            {
                CFParcelLayers = null;
                return(false);
            }
        }
 void AddEmptyPlansToList(ICadastralFabric Fabric, IFIDSet EmptyPlansFIDSet, dlgEmptyPlansList EmptyPlansList)
 {
     ITable pPlansTable = Fabric.get_CadastralTable(esriCadastralFabricTable.esriCFTPlans);
       CheckedListBox list = EmptyPlansList.checkedListBox1;
       IArray array = new ArrayClass();
       for (int idx = 0; idx <= (EmptyPlansFIDSet.Count() - 1); idx++)
       {
     // Add the name of the plan to the list
     Int32 i_x;
     Int32 iPlanName;
     iPlanName = pPlansTable.FindField("NAME");
     EmptyPlansFIDSet.Next(out i_x);
     array.Add(i_x);
     string sPlanName = (string)pPlansTable.GetRow(i_x).get_Value(iPlanName);
     list.Items.Add(sPlanName, true);
       }
       // Bind array of plan ids with the list
       list.Tag = (object)array;
       if(list.Items.Count>0)
     EmptyPlansList.checkedListBox1_SelectedValueChanged(null, null);
 }
        public bool UpdateInconsistentHistoryOnParcels(ITable pParcelsTable, int iParcelCount, 
      ICadastralFabric pCadFabric, List<string> sOIDUpdateList, 
      Dictionary<int, string> ParcelToHistory_DICT, 
      IStepProgressor m_pStepProgressor, ITrackCancel m_pTrackCancel)
        {
            bool m_bShowProgressor = (iParcelCount > 10);
              bool bCont = true;
              ICadastralFabricSchemaEdit2 pSchemaEd=null;
              try
              {
              #region update line table history
            //Get the line table history fields
            //SystemStart, SystemEnd, LegalStart, LegalEnd, Historic

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

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

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

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

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

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

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

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

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

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

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

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

            }

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

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

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

            pPlansCur = pPlansTable.Search(null, false);

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

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

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

            if (pParcelCur != null)
            {
              do { }
              while (Marshal.ReleaseComObject(pParcelCur) > 0);
            }
              }
        }
 public bool GetFabricFromMap(IMap InMap, out ICadastralFabric Fabric)
 {
     //this code assumes only one fabric in the map, and will get the first that it finds.
       //Used when not in an edit session. TODO: THis could return an array of fabrics
       Fabric = null;
       for (int idx = 0; idx <= (InMap.LayerCount - 1); idx++)
       {
     ILayer pLayer = InMap.get_Layer(idx);
     Fabric = GetFabricFromLayer(pLayer);
     if (Fabric != null)
       return true;
     else
     {
       if (pLayer != null)
     Marshal.FinalReleaseComObject(pLayer);
     }
       }
       return false;
 }
        public bool UpdateHistoryOnLines(ITable pLinesTable, ITable pPointsTable,
         int iParcelCount, ICadastralFabric pCadFabric, List<string> sOIDList, 
      Dictionary<int, string> ParcelToHistory_DICT, IStepProgressor m_pStepProgressor, ITrackCancel m_pTrackCancel)
        {
            bool m_bShowProgressor = (iParcelCount > 10);
              sOIDList.Add("");
              int tokenLimit = 995;
              bool bCont = true;
              int j = 0;
              int iCounter = 0;
              ICadastralFabricSchemaEdit2 pSchemaEd = null;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

              finally
              {
            pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints);//set safety back on
            pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTLines);//set safety back on
              }
        }
        public bool GetJobAndLocks(ICadastralFabric Fabric, IFIDSet FIDSetParcels, IStepProgressor StepProgressor)
        {
            string sTime = "";
              bool bIsUnVersioned = false;
              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 selected parcels";
            try
            {
              Int32 jobId = Fabric.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);
              }
              Marshal.ReleaseComObject(pJob);
              return false;
            }
            Marshal.ReleaseComObject(pJob);
              }

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

            ILongArray pParcelsToLock = new LongArrayClass();

            FIDsetToLongArray(FIDSetParcels, ref pParcelsToLock, StepProgressor);
            if (StepProgressor != null)
              StepProgressor.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();
              }
              else
              {
            MessageBox.Show(Convert.ToString(pCOMEx.ErrorCode));
              }
              return false;
            }

            Marshal.ReleaseComObject(pSoftLcksInConflict);
            Marshal.ReleaseComObject(pParcelsToLock);
            Marshal.ReleaseComObject(pLocksInConflict);
            return true;
              }
              return false;
        }
Beispiel #39
0
        protected override void OnClick()
        {
            //go get a traverse file
            // Display .Net dialog for File selection.
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // Set File Filter
            openFileDialog.Filter = "Cadastral XML file (*.xml)|*.xml";
            // Enable multi-select
            openFileDialog.Multiselect = true;
            // Don't need to Show Help
            openFileDialog.ShowHelp = false;
            // Set Dialog Title
            openFileDialog.Title       = "Append Cadastral XML files";
            openFileDialog.FilterIndex = 2;
            // Display Open File Dialog
            if (openFileDialog.ShowDialog() != DialogResult.OK)
            {
                openFileDialog = null;
                return;
            }

            //Get the cadastral editor
            ICadastralEditor pCadEd     = (ICadastralEditor)ArcMap.Application.FindExtensionByName("esriCadastralUI.CadastralEditorExtension");
            ICadastralFabric pCadFabric = pCadEd.CadastralFabric;
            IEditor          pEd        = ArcMap.Editor;

            ITrackCancel pTrkCan = new CancelTracker();
            // Create and display the Progress Dialog
            IProgressDialogFactory pProDlgFact = new ProgressDialogFactory();
            IProgressDialog2       pProDlg     = pProDlgFact.Create(pTrkCan, 0) as IProgressDialog2;

            //Set the properties of the Progress Dialog
            pProDlg.CancelEnabled = true;
            pProDlg.Description   = "    ";
            pProDlg.Title         = "Append";
            pProDlg.Animation     = esriProgressAnimationTypes.esriProgressGlobe;
            string sCopiedCadastralXMLFile = "";

            try
            {
                ICadastralJob CadaJob;
                bool          bJobExists = false; //used to trap for the special error message condition of existing job
                pEd.StartOperation();

                #region workaround for setting Projection
                ICadastralJob CadaJobTemp;
                bJobExists = false;
                if (!CreateCadastralJob(pCadFabric, "TEMPJOB", out CadaJobTemp, true, ref bJobExists))
                {
                    if (!bJobExists) // if the create job failed for some other reason than it already exists, then bail out.
                    {
                        MessageBox.Show("Job could not be created.");
                        return;
                    }
                }
                //do an extract to set the spatial reference: bug workaround
                ((ICadastralFabric3)pCadFabric).ExtractCadastralPacket(CadaJobTemp.Name, ArcMap.Document.ActiveView.FocusMap.SpatialReference as IProjectedCoordinateSystem, null, true);
                #endregion

                //make a temporary file for the edited cadastral XML that is used for the fabric update
                string sTempPath = System.IO.Path.GetTempPath();
                sCopiedCadastralXMLFile = System.IO.Path.Combine(sTempPath, "LastUpdatedCadastralXMLAppendedFromBatch.xml");
                int iFileCount  = 0;
                int iTotalFiles = openFileDialog.FileNames.GetLength(0);

                List <string> lstPlans = new List <string>();
                #region get all plan names for all files
                foreach (String CadastralXMLPath in openFileDialog.FileNames)
                {
                    TextReader tr = null;
                    try
                    {
                        tr = new StreamReader(CadastralXMLPath);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        return;
                    }

                    //          string[] sFileLine = new string[0]; //define as dynamic array
                    string sLine       = "";
                    int    iCount      = 0;
                    bool   bInPlanData = false;
                    bool   bInParcel   = false;

                    //fill the array with the lines from the file
                    while (sLine != null)
                    {
                        sLine = tr.ReadLine();
                        try
                        {
                            if (sLine.Trim().Length >= 1) //test for empty lines
                            {
                                if (!bInParcel && !bInPlanData)
                                {
                                    bInPlanData = sLine.Contains("<plan>");
                                }

                                if (bInPlanData && sLine.Contains("<name>") && sLine.Contains("</name>"))
                                {
                                    string sPlanName = sLine.Replace("<name>", "").Replace("</name>", "").Replace("\t", "").Trim();
                                    if (!lstPlans.Contains(sPlanName))
                                    {
                                        lstPlans.Add(sPlanName);
                                    }
                                    bInPlanData = false;
                                }
                            }
                            iCount++;
                        }
                        catch { }
                    }
                    tr.Close(); //close the file and release resources
                }
                string sInClause = "";
                foreach (string sPlan in lstPlans)
                {
                    sInClause += "'" + sPlan + "'" + ",";
                }

                sInClause = sInClause.Remove(sInClause.LastIndexOf(","), 1);

                ITable       pPlansTable = pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTPlans);
                int          iNameFld    = pPlansTable.FindField("Name");
                IQueryFilter pQuFilter   = new QueryFilterClass();
                pQuFilter.WhereClause = "NAME IN (" + sInClause + ")";
                ICursor       pCur           = pPlansTable.Search(pQuFilter, false);
                List <string> lstPlanReplace = new List <string>();

                IRow pPlan = pCur.NextRow();
                while (pPlan != null)
                {
                    lstPlanReplace.Add("<name>" + (string)pPlan.Value[iNameFld] + "</name>\n\t\t<oID>" + pPlan.OID.ToString() + "</oID>");
                    Marshal.ReleaseComObject(pPlan);
                    pPlan = pCur.NextRow();
                }
                Marshal.ReleaseComObject(pCur);

                #endregion

                foreach (String CadastralXMLPath in openFileDialog.FileNames)
                {
                    if (!pTrkCan.Continue())
                    {
                        pEd.AbortOperation();
                        return;
                    }

                    //rename ALL oID tags so that they're ignored. This indicates that these are to be treated as NEW parcels coming in.
                    ReplaceInFile(CadastralXMLPath, sCopiedCadastralXMLFile, "oID>", "old_xxX>");

                    foreach (string sPlanTag in lstPlanReplace)
                    {
                        string sFirstPart = sPlanTag.Substring(0, sPlanTag.IndexOf("\n"));
                        ReplaceInFile(sCopiedCadastralXMLFile, sCopiedCadastralXMLFile, sFirstPart, sPlanTag);
                    }

                    //TEST ONLY
                    //ReplaceInFile(CadastralXMLPath, sCopiedCadastralXMLFile, "oID>", "oID>");

                    //IF using PostCadastralPacket the points are not all merged. If using PostCadastralPacket, then a merge-point workaround would be to analyze coordinates
                    //of incoming file and if any are identical to existing fabric coordinates, then make the oID tag match
                    //the oID of the existing point in the target fabric. This will trigger point merging of identical points when using PostCadastralPacket.
                    //code below uses InsertCadastralPacket and so point merging is handled.

                    IXMLStream pStream = new XMLStream();
                    pStream.LoadFromFile(sCopiedCadastralXMLFile);
                    IFIDSet pFIDSet = null;//new FIDSet();

                    DateTime localNow = DateTime.Now;
                    string   sJobName = Convert.ToString(localNow) + "_" + (iFileCount++).ToString();
                    // note the create option is to NOT write job to fabric and is in-memory only initially, and then the InsertCadastralPacket will create and store the job in the fabric
                    // IF using PostCadastralPacket, then this option should be set to true, so that the job already exists in the fabric.
                    // Also, when using PostCadastralPacket, you can continue to use the same Target job, and a new one is not needed for each iteration.
                    // With InsertCadastralPacket a job is created for each call when new parcels are being created.
                    if (!CreateCadastralJob(pCadFabric, sJobName, out CadaJob, false, ref bJobExists))
                    {
                        pEd.AbortOperation();
                        return;
                    }

                    pProDlg.Description = "File: " + System.IO.Path.GetFileName(CadastralXMLPath) + " (" + iFileCount.ToString() + " of " + iTotalFiles.ToString() + ")";
                    //(pCadFabric as ICadastralFabric3).PostCadastralPacket(pStream, pTrkCan, esriCadastralPacketSetting.esriCadastralPacketNoSetting, ref pFIDSet);
                    (pCadFabric as ICadastralFabric3).InsertCadastralPacket(CadaJob, pStream, pTrkCan, esriCadastralPacketSetting.esriCadastralPacketNoSetting, ref pFIDSet);
                    //int setCnt = pFIDSet.Count();
                }
                RefreshFabricLayers(ArcMap.Document.ActiveView.FocusMap, pCadFabric);
                pEd.StopOperation("Append " + iFileCount.ToString() + " cadastral XML files");
            }
            catch (Exception ex)
            {
                pEd.AbortOperation();
                COMException c_Ex;
                int          errorCode = 0;
                if (ex is COMException)
                {
                    c_Ex      = (COMException)ex;
                    errorCode = c_Ex.ErrorCode;
                }
                if (errorCodeDict.ContainsKey(errorCode))
                {
                    MessageBox.Show(errorCodeDict[errorCode], "Append files");
                }
                else
                {
                    MessageBox.Show("Error: " + ex.Message + Environment.NewLine + ex.HResult.ToString(), "Append files");
                }
            }
            finally
            {
                if (sCopiedCadastralXMLFile != string.Empty)
                {
                    File.Delete(sCopiedCadastralXMLFile);
                }
                if (pProDlg != null)
                {
                    pProDlg.HideDialog();
                }
            }
        }
        protected override void OnClick()
        {
            m_pApp = (IApplication)ArcMap.Application;
              if (m_pApp == null)
            //if the app is null then could be running from ArcCatalog
            m_pApp = (IApplication)ArcCatalog.Application;

              if (m_pApp == null)
              {
            MessageBox.Show("Could not access the application.", "No Application found");
            return;
              }

              IGxApplication pGXApp = (IGxApplication)m_pApp;
              stdole.IUnknown pUnk = null;
              try
              {
            pUnk = (stdole.IUnknown)pGXApp.SelectedObject.InternalObjectName.Open();
              }
              catch (COMException ex)
              {
            if (ex.ErrorCode == (int)fdoError.FDO_E_DATASET_TYPE_NOT_SUPPORTED_IN_RELEASE ||
            ex.ErrorCode == -2147220944)
              MessageBox.Show("The dataset is not supported in this release.", "Could not open the dataset");
            else
              MessageBox.Show(ex.ErrorCode.ToString(), "Could not open the dataset");
            return;
              }

              if (pUnk is ICadastralFabric)
            m_pCadaFab = (ICadastralFabric)pUnk;
              else
              {
            MessageBox.Show("Please select a parcel fabric and try again.", "Not a parcel fabric");
            return;
              }

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

              clsFabricUtils FabricUTILS = new clsFabricUtils();
              IProgressDialog2 pProgressorDialog = null;

              ITable pTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels);
              IDataset pDS = (IDataset)pTable;
              IWorkspace pWS = pDS.Workspace;
              bool bIsFileBasedGDB = true;
              bool bIsUnVersioned = true;

              FabricUTILS.GetFabricPlatform(pWS, m_pCadaFab, out bIsFileBasedGDB,
            out bIsUnVersioned);

              if (!bIsFileBasedGDB && !bIsUnVersioned)
              {
            MessageBox.Show("Truncate operates on non-versioned fabrics."
              + Environment.NewLine +
              "Please unversion the fabric and try again.", "Tables are versioned");
            return;
              }

              //Do a Start and Stop editing to make sure truncate it not running within an edit session
              if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned))
              {//if start editing fails then bail
            Cleanup(pProgressorDialog, pMouseCursor);
            return;
              }
              FabricUTILS.StopEditing(pWS);

              dlgTruncate pTruncateDialog = new dlgTruncate();
              IArray TableArray = new ESRI.ArcGIS.esriSystem.ArrayClass();
              pTruncateDialog.TheFabric = m_pCadaFab;
              pTruncateDialog.TheTableArray = TableArray;

              //Display the dialog
              DialogResult pDialogResult = pTruncateDialog.ShowDialog();

              if (pDialogResult != DialogResult.OK)
              {
            pTruncateDialog = null;
            if (TableArray != null)
            {
              TableArray.RemoveAll();
            }
            return;
              }

              m_pProgressorDialogFact = new ProgressDialogFactoryClass();
              m_pTrackCancel = new CancelTrackerClass();
              m_pStepProgressor = m_pProgressorDialogFact.Create(m_pTrackCancel, m_pApp.hWnd);
              pProgressorDialog = (IProgressDialog2)m_pStepProgressor;
              m_pStepProgressor.MinRange = 0;
              m_pStepProgressor.MaxRange = pTruncateDialog.DropRowCount;
              m_pStepProgressor.StepValue = 1;
              pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral;
              bool bSuccess = false;
              int iControlRowCount=0;
              //look in registry to get flag on whether to run truncate on standard tables, or to delete by row.
              string sDesktopVers = FabricUTILS.GetDesktopVersionFromRegistry();
              if (sDesktopVers.Trim() == "")
            sDesktopVers = "Desktop10.0";
              else
            sDesktopVers = "Desktop" + sDesktopVers;

              bool bDeleteTablesByRowInsteadOfTruncate = false;

              string sValues = FabricUTILS.ReadFromRegistry(RegistryHive.CurrentUser, "Software\\ESRI\\" + sDesktopVers + "\\ArcMap\\Cadastral",
            "AddIn.DeleteFabricRecords_Truncate");

              if (sValues.Trim().ToLower() == "deletebytruncateonstandardtables" || bIsFileBasedGDB)
            bDeleteTablesByRowInsteadOfTruncate = false;

              if (sValues.Trim().ToLower() == "deletebyrowonstandardtables")
            bDeleteTablesByRowInsteadOfTruncate = true;

              if (pTruncateDialog.TruncateControl && !pTruncateDialog.TruncateParcelsLinesPoints)
              { // get the control point count
            ITable pControlTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTControl);
            iControlRowCount = pControlTable.RowCount(null);
              }

              try
              {
            //Work on the table array
            pTable = null;

            m_pFIDSet = new FIDSetClass();
            for (int i = 0; i <= TableArray.Count - 1; i++)
            {
              //if (TableArray.get_Element(i) is ITable) ...redundant
              {
            pTable = (ITable)TableArray.get_Element(i);
            IDataset pDataSet = (IDataset)pTable;
            //Following code uses the truncate method
            //***
            if (pTable is IFeatureClass || !bDeleteTablesByRowInsteadOfTruncate)
            {
              ITableWrite2 pTableWr = (ITableWrite2)pTable;
              m_pStepProgressor.Message = "Deleting all rows in " + pDataSet.Name;
              int RowCnt=pTable.RowCount(null);
              pTableWr.Truncate();
              m_pStepProgressor.MaxRange -= RowCnt;
              //now re-insert the default plan
              string sName = pDataSet.Name.ToUpper().Trim();
              if (sName.EndsWith("_PLANS"))
              {

                int idxPlanName = pTable.FindField("Name");
                int idxPlanDescription = pTable.FindField("Description");
                int idxPlanAngleUnits = pTable.FindField("AngleUnits");
                int idxPlanAreaUnits = pTable.FindField("AreaUnits");
                int idxPlanDistanceUnits = pTable.FindField("DistanceUnits");
                int idxPlanDirectionFormat = pTable.FindField("DirectionFormat");
                int idxPlanLineParameters = pTable.FindField("LineParameters");
                int idxPlanCombinedGridFactor = pTable.FindField("CombinedGridFactor");
                int idxPlanTrueMidBrg = pTable.FindField("TrueMidBrg");
                int idxPlanAccuracy = pTable.FindField("Accuracy");
                int idxPlanInternalAngles = pTable.FindField("InternalAngles");

                ICursor pCur = pTableWr.InsertRows(false);

                IRowBuffer pRowBuff = pTable.CreateRowBuffer();

                double dOneMeterEquals = FabricUTILS.ConvertMetersToFabricUnits(1, m_pCadaFab);
                bool bIsMetric = (dOneMeterEquals==1);

                //write category 1
                pRowBuff.set_Value(idxPlanName, "<map>");
                pRowBuff.set_Value(idxPlanDescription, "System default plan");
                pRowBuff.set_Value(idxPlanAngleUnits, 3);

                //
                if (bIsMetric)
                {
                  pRowBuff.set_Value(idxPlanAreaUnits, 5);
                  pRowBuff.set_Value(idxPlanDistanceUnits, 9001);
                  pRowBuff.set_Value(idxPlanDirectionFormat, 1);
                }
                else
                {
                  pRowBuff.set_Value(idxPlanAreaUnits, 4);
                  pRowBuff.set_Value(idxPlanDistanceUnits, 9003);
                  pRowBuff.set_Value(idxPlanDirectionFormat, 4);
                }

                pRowBuff.set_Value(idxPlanLineParameters, 4);
                pRowBuff.set_Value(idxPlanCombinedGridFactor, 1);
                //pRowBuff.set_Value(idxPlanTrueMidBrg, 1);
                pRowBuff.set_Value(idxPlanAccuracy, 4);
                pRowBuff.set_Value(idxPlanInternalAngles, 0);

                pCur.InsertRow(pRowBuff);

                pCur.Flush();
                if (pRowBuff != null)
                  Marshal.ReleaseComObject(pRowBuff);
                if (pCur != null)
                  Marshal.ReleaseComObject(pCur);

              }

            }
              }
             }
            }
            catch(COMException ex)
            {
              MessageBox.Show(ex.Message + ": " + Convert.ToString(ex.ErrorCode));
              Cleanup(pProgressorDialog, pMouseCursor);
              return;
            }

              //do the loop again, this time within the edit transaction and using the delete function for the chosen tables
              try
              {
            //Start an Edit Transaction
            if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned))
            {//if start editing fails then bail
              Cleanup(pProgressorDialog, pMouseCursor);
              return;
            }
            for (int i = 0; i <= TableArray.Count - 1; i++)
            {
              //if (TableArray.get_Element(i) is ITable)
              {
            pTable = (ITable)TableArray.get_Element(i);
            IDataset pDataSet = (IDataset)pTable;

            if (pTable is IFeatureClass || !bDeleteTablesByRowInsteadOfTruncate)
            {
            }
            else
            {
              //The following code is in place to workaround a limitation of truncate for fabric classes
              //without a shapefield. It uses an alternative method for removing all the rows
              //with the Delete function.
              //General note: This method could be used exclusively, without needing the truncate method.
              //One advantage is that it allows the option to cancel the whole
              //operation using the cancel tracker. Truncate is faster, but is problematic if
              //the truncate fails, and leaves a partially deleted fabric. For example, if the
              //lines table is deleted but the points table truncate fails, the fabric would be in a
              //corrupt state.
              //****

              m_pFIDSet.SetEmpty();
              string sName = pDataSet.Name.ToUpper().Trim();
              m_pStepProgressor.Message = "Loading rows from " + pDataSet.Name;

              if (sName.EndsWith("_PLANS"))
              {//for Plans table make sure the default plan is not deleted
                IQueryFilter pQF = new QueryFilterClass();
                string sPref; string sSuff;
                ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS;
                sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix);
                sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix);
                string sFieldName = "NAME";
                //pQF.WhereClause = sPref + sFieldName + sSuff + " <> '<map>'";
                pQF.WhereClause = sFieldName + " <> '<map>'";
                if (!BuildFIDSetFromTable(pTable, pQF, ref m_pFIDSet))
                {
                  FabricUTILS.AbortEditing(pWS);
                  Cleanup(pProgressorDialog, pMouseCursor);
                  return;
                }

              }
              else
              {
                if (!BuildFIDSetFromTable(pTable, null, ref m_pFIDSet))
                {
                  FabricUTILS.AbortEditing(pWS);
                  Cleanup(pProgressorDialog, pMouseCursor);
                  return;
                }
              }

              if (m_pFIDSet.Count() == 0)
                continue;

              m_pStepProgressor.Message = "Deleting all rows in " + pDataSet.Name;
              bSuccess = FabricUTILS.DeleteRowsUnversioned(pWS, pTable, m_pFIDSet,
                m_pStepProgressor, m_pTrackCancel);
              if (!bSuccess)
              {
                FabricUTILS.AbortEditing(pWS);
                Cleanup(pProgressorDialog, pMouseCursor);
                return;
              }
            }
              }
            }

            //now need to Fix control-to-point associations if one table was truncated
            //and the other was not
            if (pTruncateDialog.TruncateControl && !pTruncateDialog.TruncateParcelsLinesPoints)
            {
              IQueryFilter pQF = new QueryFilterClass();
              string sPref; string sSuff;
              ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS;
              sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix);
              sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix);
              ITable PointTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints);
              m_pStepProgressor.Message = "Resetting control associations on points...please wait.";
              int idxFld = PointTable.FindField("NAME");
              string sFieldName = PointTable.Fields.get_Field(idxFld).Name;

              //NAME IS NOT NULL AND (NAME <>'' OR NAME <>' ')
              //pQF.WhereClause = sPref + sFieldName + sSuff + " IS NOT NULL AND (" +
              //  sPref + sFieldName + sSuff + "<>'' OR " + sPref + sFieldName + sSuff + " <>' ')";
              //pQF.WhereClause = sFieldName + " IS NOT NULL AND (" + sFieldName + "<>'' OR " + sFieldName + " <>' ')";
              pQF.WhereClause = sFieldName + " IS NOT NULL AND " + sFieldName + " > ''"; //changed 1/14/2016

              ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)m_pCadaFab;
              pSchemaEd.ReleaseReadOnlyFields(PointTable, esriCadastralFabricTable.esriCFTPoints);

              m_pStepProgressor.MinRange = 0;
              m_pStepProgressor.MaxRange = iControlRowCount;

              if (!ResetPointAssociations(PointTable, pQF, true, m_pStepProgressor, m_pTrackCancel))
              {
            pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints);
            FabricUTILS.AbortEditing(pWS);
            Cleanup(pProgressorDialog, pMouseCursor);
            return;
              }

              pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints);

            }

            else if (pTruncateDialog.TruncateParcelsLinesPoints && !pTruncateDialog.TruncateControl)
            {
              IQueryFilter pQF = new QueryFilterClass();
              string sPref; string sSuff;
              ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS;
              sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix);
              sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix);
              //POINTID >=0 AND POINTID IS NOT NULL
              m_pStepProgressor.Message = "Resetting associations on control points...please wait.";
              ITable ControlTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTControl);
              int idxFld = ControlTable.FindField("POINTID");
              string sFieldName = ControlTable.Fields.get_Field(idxFld).Name;

              //pQF.WhereClause = sPref + sFieldName + sSuff + " IS NOT NULL AND " +
              //  sPref + sFieldName + sSuff + " >=0";
              pQF.WhereClause = sFieldName + " IS NOT NULL AND " + sFieldName + " >=0";

              ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)m_pCadaFab;
              pSchemaEd.ReleaseReadOnlyFields(ControlTable, esriCadastralFabricTable.esriCFTControl);
              if (!FabricUTILS.ResetControlAssociations(ControlTable, null, true))
              {
            pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl);
            FabricUTILS.AbortEditing(pWS);
            Cleanup(pProgressorDialog, pMouseCursor);
            return;
              }
              pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl);
            }

            //now need to re-assign default accuracy table values, if the option was checked
            if (pTruncateDialog.ResetAccuracyTableDefaults)
            {
              double dCat1 = FabricUTILS.ConvertMetersToFabricUnits(0.001, m_pCadaFab);
              double dCat2 = FabricUTILS.ConvertMetersToFabricUnits(0.01, m_pCadaFab);
              double dCat3 = FabricUTILS.ConvertMetersToFabricUnits(0.02, m_pCadaFab);
              double dCat4 = FabricUTILS.ConvertMetersToFabricUnits(0.05, m_pCadaFab);
              double dCat5 = FabricUTILS.ConvertMetersToFabricUnits(0.2, m_pCadaFab);
              double dCat6 = FabricUTILS.ConvertMetersToFabricUnits(1, m_pCadaFab);
              double dCat7 = FabricUTILS.ConvertMetersToFabricUnits(10, m_pCadaFab);

              ITable pAccTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTAccuracy);
              int idxBrgSD = pAccTable.FindField("BrgSD");
              int idxDistSD = pAccTable.FindField("DistSD");
              int idxPPM = pAccTable.FindField("PPM");
              int idxCategory = pAccTable.FindField("Category");
              int idxDescription = pAccTable.FindField("Description");
              ITableWrite2 pTableWr = (ITableWrite2)pAccTable;
              ICursor pCur = pTableWr.InsertRows(false);

              IRowBuffer pRowBuff = pAccTable.CreateRowBuffer();

              //write category 1
              pRowBuff.set_Value(idxCategory, 1);
              pRowBuff.set_Value(idxBrgSD, 5);
              pRowBuff.set_Value(idxDistSD, dCat1);
              pRowBuff.set_Value(idxPPM, 5);
              pRowBuff.set_Value(idxDescription, "1 - Highest");
              pCur.InsertRow(pRowBuff);

              //write category 2
              pRowBuff.set_Value(idxCategory, 2);
              pRowBuff.set_Value(idxBrgSD, 30);
              pRowBuff.set_Value(idxDistSD, dCat2);
              pRowBuff.set_Value(idxPPM, 25);
              pRowBuff.set_Value(idxDescription, "2 - After 1980");
              pCur.InsertRow(pRowBuff);

              //write category 3
              pRowBuff.set_Value(idxCategory, 3);
              pRowBuff.set_Value(idxBrgSD, 60);
              pRowBuff.set_Value(idxDistSD, dCat3);
              pRowBuff.set_Value(idxPPM, 50);
              pRowBuff.set_Value(idxDescription, "3 - 1908 to 1980");
              pCur.InsertRow(pRowBuff);

              //write category 4
              pRowBuff.set_Value(idxCategory, 4);
              pRowBuff.set_Value(idxBrgSD, 120);
              pRowBuff.set_Value(idxDistSD, dCat4);
              pRowBuff.set_Value(idxPPM, 125);
              pRowBuff.set_Value(idxDescription, "4 - 1881 to 1907");
              pCur.InsertRow(pRowBuff);

              //write category 5
              pRowBuff.set_Value(idxCategory, 5);
              pRowBuff.set_Value(idxBrgSD, 300);
              pRowBuff.set_Value(idxDistSD, dCat5);
              pRowBuff.set_Value(idxPPM, 125);
              pRowBuff.set_Value(idxDescription, "5 - Before 1881");
              pCur.InsertRow(pRowBuff);

              //write category 6
              pRowBuff.set_Value(idxCategory, 6);
              pRowBuff.set_Value(idxBrgSD, 3600);
              pRowBuff.set_Value(idxDistSD, dCat6);
              pRowBuff.set_Value(idxPPM, 1000);
              pRowBuff.set_Value(idxDescription, "6 - 1800");
              pCur.InsertRow(pRowBuff);

              //write category 7
              pRowBuff.set_Value(idxCategory, 7);
              pRowBuff.set_Value(idxBrgSD, 6000);
              pRowBuff.set_Value(idxDistSD, dCat7);
              pRowBuff.set_Value(idxPPM, 5000);
              pRowBuff.set_Value(idxDescription, "7 - Lowest");
              pCur.InsertRow(pRowBuff);

              pCur.Flush();
              if (pRowBuff != null)
            Marshal.ReleaseComObject(pRowBuff);
              if (pCur != null)
            Marshal.ReleaseComObject(pCur);
            }

            //now need to cleanup the IDSequence table if ALL the tables were truncated
            if(pTruncateDialog.TruncateControl&&
               pTruncateDialog.TruncateParcelsLinesPoints &&
               pTruncateDialog.TruncateJobs &&
               pTruncateDialog.TruncateAdjustments)
            {
              IWorkspace2 pWS2=(IWorkspace2)pWS;
              IDataset TheFabricDS=(IDataset)m_pCadaFab;
              string sFabricName=TheFabricDS.Name;
              string sName = sFabricName + "_IDSequencer";
              bool bExists=pWS2.get_NameExists(esriDatasetType.esriDTTable, sName);
              IFeatureWorkspace pFWS=(IFeatureWorkspace)pWS;
              ITable pSequencerTable;
              if (bExists)
              {
            pSequencerTable = pFWS.OpenTable(sName);
            IFIDSet pFIDSet= new FIDSetClass();
            if (BuildFIDSetFromTable(pSequencerTable, null, ref pFIDSet))
              FabricUTILS.DeleteRowsUnversioned(pWS, pSequencerTable, pFIDSet, null, null);
              }
            }

            Cleanup(pProgressorDialog, pMouseCursor);

            if (TableArray != null)
            {
              TableArray.RemoveAll();
            }
            FabricUTILS.StopEditing(pWS);
              }
              catch (Exception ex)
              {
            FabricUTILS.AbortEditing(pWS);
            Cleanup(pProgressorDialog, pMouseCursor);
            MessageBox.Show(Convert.ToString(ex.Message));
              }
        }
        public bool GetControlLayersFromFabric(IMap Map, ICadastralFabric Fabric, out IArray CFControlLayers)
        {
            ICadastralFabricLayer pCFLayer = null;
              ICadastralFabricSubLayer pCFSubLyr = null;
              ICompositeLayer pCompLyr = null;
              IArray CFControlLayers2 = new ArrayClass();

              long layerCount = Map.LayerCount;

              IFeatureLayer pControllLayer = null;
              for (int idx = 0; idx <= (layerCount - 1); idx++)
              {
            ILayer pLayer = Map.get_Layer(idx);
            bool bIsComposite = false;
            if (pLayer is ICompositeLayer)
            {
              pCompLyr = (ICompositeLayer)pLayer;
              bIsComposite = true;
            }

            int iCompositeLyrCnt = 1;
            if (bIsComposite)
              iCompositeLyrCnt = pCompLyr.Count;

            for (int i = 0; i <= (iCompositeLyrCnt - 1); i++)
            {
              if (bIsComposite)
            pLayer = pCompLyr.get_Layer(i);
              if (pLayer is ICadastralFabricLayer)
              {
            pCFLayer = (ICadastralFabricLayer)pLayer;
            break;
              }
              if (pLayer is ICadastralFabricSubLayer)
              {
            pCFSubLyr = (ICadastralFabricSubLayer)pLayer;
            ICadastralFabric pCadFab2 = null;
            try
            {
              pCadFab2 = pCFSubLyr.CadastralFabric; //this fails when the layer is created from a selection
            }
            catch (Exception)
            {
              continue;
            }
            if (Fabric.Equals(pCadFab2) &&
            pCFSubLyr.CadastralTableType == esriCadastralFabricTable.esriCFTControl)
            {
              pControllLayer = (IFeatureLayer)pCFSubLyr;
              CFControlLayers2.Add(pControllLayer);
            }
              }
            }

            //Check that the fabric layer belongs to the requested fabric
            if (pCFLayer != null)
            {
              if (pCFLayer.CadastralFabric.Equals(Fabric))
              {
            pControllLayer = (IFeatureLayer)pCFLayer.get_CadastralSubLayer(esriCadastralFabricRenderer.esriCFRControlPoints);
            CFControlLayers2.Add(pControllLayer);
            Debug.WriteLine(pControllLayer.Name);
              }
              CFControlLayers = CFControlLayers2;
              return true;
            }
              }
              //at the minimum, just need to make sure we have a control sublayer for the requested fabric
              if (pControllLayer != null)
              {
            CFControlLayers = CFControlLayers2;
            return true;
              }
              else
              {
            CFControlLayers = null;
            return false;
              }
        }
        public void RefreshFabricLayers(IMap Map, ICadastralFabric Fabric)
        {
            IArray CFParcelLyrs;
            IFeatureLayer CFPtLyr;
            IFeatureLayer CFLineLyr;
            IFeatureLayer CFCtrlLyr;
            IFeatureLayer CFLinePtLyr;

            if (!GetFabricSubLayersFromFabric(Map,Fabric,out CFPtLyr, out CFLineLyr,
             out CFParcelLyrs, out CFCtrlLyr, out CFLinePtLyr))
              return;
            else
              RefreshMap(ArcMap.Document.ActiveView,CFParcelLyrs,CFPtLyr,CFLineLyr,CFCtrlLyr,CFLinePtLyr);
        }
        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
            }
        }
        public bool IsUnVersionedFabric(ICadastralFabric TheFabric)
        {
            bool IsFileBasedGDB = false;
              bool IsUnVersioned = false;

              ITable pTable = TheFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels);
              IDataset pDS=(IDataset)TheFabric;
              IWorkspace pWS = pDS.Workspace;

              IsFileBasedGDB = (!(pWS.WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace));

              if (!(IsFileBasedGDB))
              {
            IVersionedObject pVersObj = (IVersionedObject)pTable;
            IsUnVersioned = (!(pVersObj.IsRegisteredAsVersioned));
            pTable = null;
            pVersObj = null;
              }
              if (IsUnVersioned && !IsFileBasedGDB)
            return true;
              else
            return false;
        }
        public void UpdateCurves(ICadastralFabric pCadFabric, IFeatureClass pFabricLinesFC, IEnumerable<InferredCurve> curvesToUpdate, myProgessor progressor)
        {
            IEnumerable<InferredCurve> updateCurves = (from InferredCurve c in curvesToUpdate where c.Action == UpdateAction.Update select c);

            bool bIsFileBasedGDB = false;
            bool bIsUnVersioned = false;
            bool bUseNonVersionedDelete = false;
            IWorkspace pWS = m_pEd != null ? m_pEd.EditWorkspace : ((IDataset)pFabricLinesFC).Workspace;

            if (!SetupEditEnvironment(pWS, pCadFabric, m_pEd, out bIsFileBasedGDB, out bIsUnVersioned, out bUseNonVersionedDelete))
            {
                messageBox.Show("The editing environment could not be initialized");
                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 CadastralJob();
                pJob.Name = sTime;
                pJob.Owner = System.Windows.Forms.SystemInformation.UserName;
                pJob.Description = "Convert lines to curves";
                try
                {
                    Int32 jobId = pCadFabric.CreateJob(pJob);
                }
                catch (COMException ex)
                {
                    if (ex.ErrorCode == (int)fdoError.FDO_E_CADASTRAL_FABRIC_JOB_ALREADY_EXISTS)
                    {
                        messageBox.Show("Job named: '" + pJob.Name + "', already exists");
                    }
                    else
                    {
                        messageBox.Show(ex.Message);
                    }
                    return;
                }
            }
            #endregion

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

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

            ILongArray affectedParcels = new LongArrayClass();
            IFIDSet parcelFIDs = new FIDSet();
            foreach (int i in updateCurves.Select(w => w.Parcel).Distinct())
            {
                parcelFIDs.Add(i);
                affectedParcels.Add(i);
            }

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

                if (!bIsFileBasedGDB)
                    progressor.setStepProgressorProperties(0, "Testing for edit locks on parcels...");

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

                    return;
                }
            }
            #endregion

            if (m_pEd != null && m_pEd.EditState == esriEditState.esriStateEditing)
            {
                try
                {
                    m_pEd.StartOperation();
                }
                catch
                {
                    m_pEd.AbortOperation();//abort any open edit operations and try again
                    m_pEd.StartOperation();
                }
            }
            else
            {
                //this code is extecuted by the tests, only executed against a file gdb
                IWorkspaceEdit wsEdit = (IWorkspaceEdit)pWS;
                wsEdit.StartEditing(false);
                wsEdit.StartEditOperation();
            }

            if (bUseNonVersionedDelete)
            {
                if (!StartEditing(pWS, bIsUnVersioned))
                {
                    messageBox.Show("Couldn't start an edit session");
                    return;
                }
            }

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

            // m_pEd.StartOperation();

            updateValues(updateCurves, progressor, pFabricLinesFC, bIsUnVersioned);

            ICadastralFabricRegeneration pRegenFabric = new CadastralFabricRegenerator();
            #region regenerator enum
            // enum esriCadastralRegeneratorSetting
            // esriCadastralRegenRegenerateGeometries         =   1
            // esriCadastralRegenRegenerateMissingRadials     =   2,
            // esriCadastralRegenRegenerateMissingPoints      =   4,
            // esriCadastralRegenRemoveOrphanPoints           =   8,
            // esriCadastralRegenRemoveInvalidLinePoints      =   16,
            // esriCadastralRegenSnapLinePoints               =   32,
            // esriCadastralRegenRepairLineSequencing         =   64,
            // esriCadastralRegenRepairPartConnectors         =   128

            // By default, the bitmask member is 0 which will only regenerate geometries.
            // (equivalent to passing in regeneratorBitmask = 1)
            #endregion

            //pRegenFabric.CadastralFabric = pCadFabric;
            //pRegenFabric.RegeneratorBitmask = 7;
            //pRegenFabric.RegenerateParcels(parcelFIDs, false, progressor.cancelTracker);

            if (m_pEd != null)
            {
                m_pEd.StopOperation("Insert missing circular arc information.");
            }
            else
            {
                //this code is extecuted by the tests, only executed against a file gdb
                IWorkspaceEdit wsEdit = (IWorkspaceEdit)pWS;
                wsEdit.StartEditOperation();
                wsEdit.StopEditing(false);
            }
        }
        public bool TestForEditLocks(ICadastralFabric Fabric, string NewJobName, List<int> ParcelsToLock)
        {
            ICadastralFabricLocks pFabLocks = (ICadastralFabricLocks)Fabric;
              pFabLocks.LockingJob = NewJobName;
              ILongArray pLocksInConflict = null;
              ILongArray pSoftLcksInConflict = null;

              ILongArray TheParcelsToLock = new LongArrayClass();
              foreach (int i in ParcelsToLock)
            TheParcelsToLock.Add(i);

              try
              {
            pFabLocks.AcquireLocks(TheParcelsToLock, true, ref pLocksInConflict, ref pSoftLcksInConflict);
            return true;
              }
              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)
            {
              string sListOfFirst10="";
              for (int i = 0; i < pLocksInConflict.Count; i++)
              {
            if (i == 10) break;
            sListOfFirst10 += pLocksInConflict.get_Element(i).ToString() + ", ";
              }
              MessageBox.Show("Edit Locks could not be acquired on all parcels." + Environment.NewLine +
              "Parcel ids: " + sListOfFirst10.Trim().TrimEnd(','),"Move Fabric Points");
              // 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 false;
              }
        }
        protected override void OnClick()
        {
            m_pApp = (IApplication)ArcMap.Application;
            if (m_pApp == null)
            {
                //if the app is null then could be running from ArcCatalog
                m_pApp = (IApplication)ArcCatalog.Application;
            }

            if (m_pApp == null)
            {
                MessageBox.Show("Could not access the application.", "No Application found");
                return;
            }

            IGxApplication pGXApp = (IGxApplication)m_pApp;

            stdole.IUnknown pUnk = null;
            try
            {
                pUnk = (stdole.IUnknown)pGXApp.SelectedObject.InternalObjectName.Open();
            }
            catch (COMException ex)
            {
                if (ex.ErrorCode == (int)fdoError.FDO_E_DATASET_TYPE_NOT_SUPPORTED_IN_RELEASE ||
                    ex.ErrorCode == -2147220944)
                {
                    MessageBox.Show("The dataset is not supported in this release.", "Could not open the dataset");
                }
                else
                {
                    MessageBox.Show(ex.ErrorCode.ToString(), "Could not open the dataset");
                }
                return;
            }

            if (pUnk is ICadastralFabric)
            {
                m_pCadaFab = (ICadastralFabric)pUnk;
            }
            else
            {
                MessageBox.Show("Please select a parcel fabric and try again.", "Not a parcel fabric");
                return;
            }

            IMouseCursor pMouseCursor = new MouseCursorClass();

            pMouseCursor.SetCursor(2);

            clsFabricUtils   FabricUTILS       = new clsFabricUtils();
            IProgressDialog2 pProgressorDialog = null;

            ITable     pTable          = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels);
            IDataset   pDS             = (IDataset)pTable;
            IWorkspace pWS             = pDS.Workspace;
            bool       bIsFileBasedGDB = true;
            bool       bIsUnVersioned  = true;

            FabricUTILS.GetFabricPlatform(pWS, m_pCadaFab, out bIsFileBasedGDB,
                                          out bIsUnVersioned);

            if (!bIsFileBasedGDB && !bIsUnVersioned)
            {
                MessageBox.Show("Truncate operates on non-versioned fabrics."
                                + Environment.NewLine +
                                "Please unversion the fabric and try again.", "Tables are versioned");
                return;
            }


            //Do a Start and Stop editing to make sure truncate it not running within an edit session
            if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned))
            {//if start editing fails then bail
                Cleanup(pProgressorDialog, pMouseCursor);
                return;
            }
            FabricUTILS.StopEditing(pWS);

            dlgTruncate pTruncateDialog = new dlgTruncate();
            IArray      TableArray      = new ESRI.ArcGIS.esriSystem.ArrayClass();

            pTruncateDialog.TheFabric     = m_pCadaFab;
            pTruncateDialog.TheTableArray = TableArray;

            //Display the dialog
            DialogResult pDialogResult = pTruncateDialog.ShowDialog();

            if (pDialogResult != DialogResult.OK)
            {
                pTruncateDialog = null;
                if (TableArray != null)
                {
                    TableArray.RemoveAll();
                }
                return;
            }

            m_pProgressorDialogFact     = new ProgressDialogFactoryClass();
            m_pTrackCancel              = new CancelTrackerClass();
            m_pStepProgressor           = m_pProgressorDialogFact.Create(m_pTrackCancel, m_pApp.hWnd);
            pProgressorDialog           = (IProgressDialog2)m_pStepProgressor;
            m_pStepProgressor.MinRange  = 0;
            m_pStepProgressor.MaxRange  = pTruncateDialog.DropRowCount;
            m_pStepProgressor.StepValue = 1;
            pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral;
            bool bSuccess         = false;
            int  iControlRowCount = 0;
            //look in registry to get flag on whether to run truncate on standard tables, or to delete by row.
            string sDesktopVers = FabricUTILS.GetDesktopVersionFromRegistry();

            if (sDesktopVers.Trim() == "")
            {
                sDesktopVers = "Desktop10.0";
            }
            else
            {
                sDesktopVers = "Desktop" + sDesktopVers;
            }

            bool bDeleteTablesByRowInsteadOfTruncate = false;

            string sValues = FabricUTILS.ReadFromRegistry(RegistryHive.CurrentUser, "Software\\ESRI\\" + sDesktopVers + "\\ArcMap\\Cadastral",
                                                          "AddIn.DeleteFabricRecords_Truncate");

            if (sValues.Trim().ToLower() == "deletebytruncateonstandardtables" || bIsFileBasedGDB)
            {
                bDeleteTablesByRowInsteadOfTruncate = false;
            }

            if (sValues.Trim().ToLower() == "deletebyrowonstandardtables")
            {
                bDeleteTablesByRowInsteadOfTruncate = true;
            }

            if (pTruncateDialog.TruncateControl && !pTruncateDialog.TruncateParcelsLinesPoints)
            { // get the control point count
                ITable pControlTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTControl);
                iControlRowCount = pControlTable.RowCount(null);
            }

            try
            {
                //Work on the table array
                pTable = null;

                m_pFIDSet = new FIDSetClass();
                for (int i = 0; i <= TableArray.Count - 1; i++)
                {
                    //if (TableArray.get_Element(i) is ITable) ...redundant
                    {
                        pTable = (ITable)TableArray.get_Element(i);
                        IDataset pDataSet = (IDataset)pTable;
                        //Following code uses the truncate method
                        //***
                        if (pTable is IFeatureClass || !bDeleteTablesByRowInsteadOfTruncate)
                        {
                            ITableWrite2 pTableWr = (ITableWrite2)pTable;
                            m_pStepProgressor.Message = "Deleting all rows in " + pDataSet.Name;
                            int RowCnt = pTable.RowCount(null);
                            pTableWr.Truncate();
                            m_pStepProgressor.MaxRange -= RowCnt;
                            //now re-insert the default plan
                            string sName = pDataSet.Name.ToUpper().Trim();
                            if (sName.EndsWith("_PLANS"))
                            {
                                int idxPlanName               = pTable.FindField("Name");
                                int idxPlanDescription        = pTable.FindField("Description");
                                int idxPlanAngleUnits         = pTable.FindField("AngleUnits");
                                int idxPlanAreaUnits          = pTable.FindField("AreaUnits");
                                int idxPlanDistanceUnits      = pTable.FindField("DistanceUnits");
                                int idxPlanDirectionFormat    = pTable.FindField("DirectionFormat");
                                int idxPlanLineParameters     = pTable.FindField("LineParameters");
                                int idxPlanCombinedGridFactor = pTable.FindField("CombinedGridFactor");
                                int idxPlanTrueMidBrg         = pTable.FindField("TrueMidBrg");
                                int idxPlanAccuracy           = pTable.FindField("Accuracy");
                                int idxPlanInternalAngles     = pTable.FindField("InternalAngles");

                                ICursor pCur = pTableWr.InsertRows(false);

                                IRowBuffer pRowBuff = pTable.CreateRowBuffer();

                                double dOneMeterEquals = FabricUTILS.ConvertMetersToFabricUnits(1, m_pCadaFab);
                                bool   bIsMetric       = (dOneMeterEquals == 1);

                                //write category 1
                                pRowBuff.set_Value(idxPlanName, "<map>");
                                pRowBuff.set_Value(idxPlanDescription, "System default plan");
                                pRowBuff.set_Value(idxPlanAngleUnits, 3);

                                //
                                if (bIsMetric)
                                {
                                    pRowBuff.set_Value(idxPlanAreaUnits, 5);
                                    pRowBuff.set_Value(idxPlanDistanceUnits, 9001);
                                    pRowBuff.set_Value(idxPlanDirectionFormat, 1);
                                }
                                else
                                {
                                    pRowBuff.set_Value(idxPlanAreaUnits, 4);
                                    pRowBuff.set_Value(idxPlanDistanceUnits, 9003);
                                    pRowBuff.set_Value(idxPlanDirectionFormat, 4);
                                }

                                pRowBuff.set_Value(idxPlanLineParameters, 4);
                                pRowBuff.set_Value(idxPlanCombinedGridFactor, 1);
                                //pRowBuff.set_Value(idxPlanTrueMidBrg, 1);
                                pRowBuff.set_Value(idxPlanAccuracy, 4);
                                pRowBuff.set_Value(idxPlanInternalAngles, 0);

                                pCur.InsertRow(pRowBuff);

                                pCur.Flush();
                                if (pRowBuff != null)
                                {
                                    Marshal.ReleaseComObject(pRowBuff);
                                }
                                if (pCur != null)
                                {
                                    Marshal.ReleaseComObject(pCur);
                                }
                            }
                        }
                    }
                }
            }
            catch (COMException ex)
            {
                MessageBox.Show(ex.Message + ": " + Convert.ToString(ex.ErrorCode));
                Cleanup(pProgressorDialog, pMouseCursor);
                return;
            }

            //do the loop again, this time within the edit transaction and using the delete function for the chosen tables
            try
            {
                //Start an Edit Transaction
                if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned))
                {//if start editing fails then bail
                    Cleanup(pProgressorDialog, pMouseCursor);
                    return;
                }
                for (int i = 0; i <= TableArray.Count - 1; i++)
                {
                    //if (TableArray.get_Element(i) is ITable)
                    {
                        pTable = (ITable)TableArray.get_Element(i);
                        IDataset pDataSet = (IDataset)pTable;

                        if (pTable is IFeatureClass || !bDeleteTablesByRowInsteadOfTruncate)
                        {
                        }
                        else
                        {
                            //The following code is in place to workaround a limitation of truncate for fabric classes
                            //without a shapefield. It uses an alternative method for removing all the rows
                            //with the Delete function.
                            //General note: This method could be used exclusively, without needing the truncate method.
                            //One advantage is that it allows the option to cancel the whole
                            //operation using the cancel tracker. Truncate is faster, but is problematic if
                            //the truncate fails, and leaves a partially deleted fabric. For example, if the
                            //lines table is deleted but the points table truncate fails, the fabric would be in a
                            //corrupt state.
                            //****

                            m_pFIDSet.SetEmpty();
                            string sName = pDataSet.Name.ToUpper().Trim();
                            m_pStepProgressor.Message = "Loading rows from " + pDataSet.Name;

                            if (sName.EndsWith("_PLANS"))
                            {//for Plans table make sure the default plan is not deleted
                                IQueryFilter pQF = new QueryFilterClass();
                                string       sPref; string sSuff;
                                ISQLSyntax   pSQLSyntax = (ISQLSyntax)pWS;
                                sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix);
                                sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix);
                                string sFieldName = "NAME";
                                //pQF.WhereClause = sPref + sFieldName + sSuff + " <> '<map>'";
                                pQF.WhereClause = sFieldName + " <> '<map>'";
                                if (!BuildFIDSetFromTable(pTable, pQF, ref m_pFIDSet))
                                {
                                    FabricUTILS.AbortEditing(pWS);
                                    Cleanup(pProgressorDialog, pMouseCursor);
                                    return;
                                }
                            }
                            else
                            {
                                if (!BuildFIDSetFromTable(pTable, null, ref m_pFIDSet))
                                {
                                    FabricUTILS.AbortEditing(pWS);
                                    Cleanup(pProgressorDialog, pMouseCursor);
                                    return;
                                }
                            }

                            if (m_pFIDSet.Count() == 0)
                            {
                                continue;
                            }

                            m_pStepProgressor.Message = "Deleting all rows in " + pDataSet.Name;
                            bSuccess = FabricUTILS.DeleteRowsUnversioned(pWS, pTable, m_pFIDSet,
                                                                         m_pStepProgressor, m_pTrackCancel);
                            if (!bSuccess)
                            {
                                FabricUTILS.AbortEditing(pWS);
                                Cleanup(pProgressorDialog, pMouseCursor);
                                return;
                            }
                        }
                    }
                }



                //now need to Fix control-to-point associations if one table was truncated
                //and the other was not
                if (pTruncateDialog.TruncateControl && !pTruncateDialog.TruncateParcelsLinesPoints)
                {
                    IQueryFilter pQF = new QueryFilterClass();
                    string       sPref; string sSuff;
                    ISQLSyntax   pSQLSyntax = (ISQLSyntax)pWS;
                    sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix);
                    sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix);
                    ITable PointTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints);
                    m_pStepProgressor.Message = "Resetting control associations on points...please wait.";
                    int    idxFld     = PointTable.FindField("NAME");
                    string sFieldName = PointTable.Fields.get_Field(idxFld).Name;

                    //NAME IS NOT NULL AND (NAME <>'' OR NAME <>' ')
                    //pQF.WhereClause = sPref + sFieldName + sSuff + " IS NOT NULL AND (" +
                    //  sPref + sFieldName + sSuff + "<>'' OR " + sPref + sFieldName + sSuff + " <>' ')";
                    //pQF.WhereClause = sFieldName + " IS NOT NULL AND (" + sFieldName + "<>'' OR " + sFieldName + " <>' ')";
                    pQF.WhereClause = sFieldName + " IS NOT NULL AND " + sFieldName + " > ''"; //changed 1/14/2016

                    ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)m_pCadaFab;
                    pSchemaEd.ReleaseReadOnlyFields(PointTable, esriCadastralFabricTable.esriCFTPoints);

                    m_pStepProgressor.MinRange = 0;
                    m_pStepProgressor.MaxRange = iControlRowCount;

                    if (!ResetPointAssociations(PointTable, pQF, true, m_pStepProgressor, m_pTrackCancel))
                    {
                        pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints);
                        FabricUTILS.AbortEditing(pWS);
                        Cleanup(pProgressorDialog, pMouseCursor);
                        return;
                    }

                    pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints);
                }

                else if (pTruncateDialog.TruncateParcelsLinesPoints && !pTruncateDialog.TruncateControl)
                {
                    IQueryFilter pQF = new QueryFilterClass();
                    string       sPref; string sSuff;
                    ISQLSyntax   pSQLSyntax = (ISQLSyntax)pWS;
                    sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix);
                    sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix);
                    //POINTID >=0 AND POINTID IS NOT NULL
                    m_pStepProgressor.Message = "Resetting associations on control points...please wait.";
                    ITable ControlTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTControl);
                    int    idxFld       = ControlTable.FindField("POINTID");
                    string sFieldName   = ControlTable.Fields.get_Field(idxFld).Name;

                    //pQF.WhereClause = sPref + sFieldName + sSuff + " IS NOT NULL AND " +
                    //  sPref + sFieldName + sSuff + " >=0";
                    pQF.WhereClause = sFieldName + " IS NOT NULL AND " + sFieldName + " >=0";

                    ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)m_pCadaFab;
                    pSchemaEd.ReleaseReadOnlyFields(ControlTable, esriCadastralFabricTable.esriCFTControl);
                    if (!FabricUTILS.ResetControlAssociations(ControlTable, null, true))
                    {
                        pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl);
                        FabricUTILS.AbortEditing(pWS);
                        Cleanup(pProgressorDialog, pMouseCursor);
                        return;
                    }
                    pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl);
                }

                //now need to re-assign default accuracy table values, if the option was checked
                if (pTruncateDialog.ResetAccuracyTableDefaults)
                {
                    double dCat1 = FabricUTILS.ConvertMetersToFabricUnits(0.001, m_pCadaFab);
                    double dCat2 = FabricUTILS.ConvertMetersToFabricUnits(0.01, m_pCadaFab);
                    double dCat3 = FabricUTILS.ConvertMetersToFabricUnits(0.02, m_pCadaFab);
                    double dCat4 = FabricUTILS.ConvertMetersToFabricUnits(0.05, m_pCadaFab);
                    double dCat5 = FabricUTILS.ConvertMetersToFabricUnits(0.2, m_pCadaFab);
                    double dCat6 = FabricUTILS.ConvertMetersToFabricUnits(1, m_pCadaFab);
                    double dCat7 = FabricUTILS.ConvertMetersToFabricUnits(10, m_pCadaFab);

                    ITable       pAccTable      = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTAccuracy);
                    int          idxBrgSD       = pAccTable.FindField("BrgSD");
                    int          idxDistSD      = pAccTable.FindField("DistSD");
                    int          idxPPM         = pAccTable.FindField("PPM");
                    int          idxCategory    = pAccTable.FindField("Category");
                    int          idxDescription = pAccTable.FindField("Description");
                    ITableWrite2 pTableWr       = (ITableWrite2)pAccTable;
                    ICursor      pCur           = pTableWr.InsertRows(false);

                    IRowBuffer pRowBuff = pAccTable.CreateRowBuffer();

                    //write category 1
                    pRowBuff.set_Value(idxCategory, 1);
                    pRowBuff.set_Value(idxBrgSD, 5);
                    pRowBuff.set_Value(idxDistSD, dCat1);
                    pRowBuff.set_Value(idxPPM, 5);
                    pRowBuff.set_Value(idxDescription, "1 - Highest");
                    pCur.InsertRow(pRowBuff);

                    //write category 2
                    pRowBuff.set_Value(idxCategory, 2);
                    pRowBuff.set_Value(idxBrgSD, 30);
                    pRowBuff.set_Value(idxDistSD, dCat2);
                    pRowBuff.set_Value(idxPPM, 25);
                    pRowBuff.set_Value(idxDescription, "2 - After 1980");
                    pCur.InsertRow(pRowBuff);

                    //write category 3
                    pRowBuff.set_Value(idxCategory, 3);
                    pRowBuff.set_Value(idxBrgSD, 60);
                    pRowBuff.set_Value(idxDistSD, dCat3);
                    pRowBuff.set_Value(idxPPM, 50);
                    pRowBuff.set_Value(idxDescription, "3 - 1908 to 1980");
                    pCur.InsertRow(pRowBuff);

                    //write category 4
                    pRowBuff.set_Value(idxCategory, 4);
                    pRowBuff.set_Value(idxBrgSD, 120);
                    pRowBuff.set_Value(idxDistSD, dCat4);
                    pRowBuff.set_Value(idxPPM, 125);
                    pRowBuff.set_Value(idxDescription, "4 - 1881 to 1907");
                    pCur.InsertRow(pRowBuff);

                    //write category 5
                    pRowBuff.set_Value(idxCategory, 5);
                    pRowBuff.set_Value(idxBrgSD, 300);
                    pRowBuff.set_Value(idxDistSD, dCat5);
                    pRowBuff.set_Value(idxPPM, 125);
                    pRowBuff.set_Value(idxDescription, "5 - Before 1881");
                    pCur.InsertRow(pRowBuff);

                    //write category 6
                    pRowBuff.set_Value(idxCategory, 6);
                    pRowBuff.set_Value(idxBrgSD, 3600);
                    pRowBuff.set_Value(idxDistSD, dCat6);
                    pRowBuff.set_Value(idxPPM, 1000);
                    pRowBuff.set_Value(idxDescription, "6 - 1800");
                    pCur.InsertRow(pRowBuff);

                    //write category 7
                    pRowBuff.set_Value(idxCategory, 7);
                    pRowBuff.set_Value(idxBrgSD, 6000);
                    pRowBuff.set_Value(idxDistSD, dCat7);
                    pRowBuff.set_Value(idxPPM, 5000);
                    pRowBuff.set_Value(idxDescription, "7 - Lowest");
                    pCur.InsertRow(pRowBuff);

                    pCur.Flush();
                    if (pRowBuff != null)
                    {
                        Marshal.ReleaseComObject(pRowBuff);
                    }
                    if (pCur != null)
                    {
                        Marshal.ReleaseComObject(pCur);
                    }
                }

                //now need to cleanup the IDSequence table if ALL the tables were truncated
                if (pTruncateDialog.TruncateControl &&
                    pTruncateDialog.TruncateParcelsLinesPoints &&
                    pTruncateDialog.TruncateJobs &&
                    pTruncateDialog.TruncateAdjustments)
                {
                    IWorkspace2       pWS2        = (IWorkspace2)pWS;
                    IDataset          TheFabricDS = (IDataset)m_pCadaFab;
                    string            sFabricName = TheFabricDS.Name;
                    string            sName       = sFabricName + "_IDSequencer";
                    bool              bExists     = pWS2.get_NameExists(esriDatasetType.esriDTTable, sName);
                    IFeatureWorkspace pFWS        = (IFeatureWorkspace)pWS;
                    ITable            pSequencerTable;
                    if (bExists)
                    {
                        pSequencerTable = pFWS.OpenTable(sName);
                        IFIDSet pFIDSet = new FIDSetClass();
                        if (BuildFIDSetFromTable(pSequencerTable, null, ref pFIDSet))
                        {
                            FabricUTILS.DeleteRowsUnversioned(pWS, pSequencerTable, pFIDSet, null, null);
                        }
                    }
                }

                Cleanup(pProgressorDialog, pMouseCursor);

                if (TableArray != null)
                {
                    TableArray.RemoveAll();
                }
                FabricUTILS.StopEditing(pWS);
            }
            catch (Exception ex)
            {
                FabricUTILS.AbortEditing(pWS);
                Cleanup(pProgressorDialog, pMouseCursor);
                MessageBox.Show(Convert.ToString(ex.Message));
            }
        }
 public bool CreateJob(ICadastralFabric Fabric, string JobDescription, out string NewJobName)
 {
     DateTime localNow = DateTime.Now;
       string sTime = Convert.ToString(localNow);
       ICadastralJob pJob = new CadastralJob();
       pJob.Name = NewJobName = sTime;
       pJob.Owner = System.Windows.Forms.SystemInformation.UserName;
       pJob.Description = JobDescription;
       try { Int32 jobId = Fabric.CreateJob(pJob); return true; }
       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 false; }
 }
        public bool GetFabricSubLayersFromFabric(IMap Map, ICadastralFabric Fabric, out IFeatureLayer CFPointLayer, out IFeatureLayer CFLineLayer,
          out IArray CFParcelLayers, out IFeatureLayer CFControlLayer, out IFeatureLayer CFLinePointLayer)
        {
            ICadastralFabricLayer pCFLayer = null;
              ICadastralFabricSubLayer pCFSubLyr = null;
              ICompositeLayer pCompLyr = null;
              IArray CFParcelLayers2 = new ArrayClass();

              IDataset pDS = (IDataset)Fabric;
              IName pDSName = pDS.FullName;
              string FabricNameString = pDSName.NameString;

              long layerCount = Map.LayerCount;
              CFPointLayer = null; CFLineLayer = null; CFControlLayer = null; CFLinePointLayer = null;
              IFeatureLayer pParcelLayer = null;
              for (int idx = 0; idx <= (layerCount - 1); idx++)
              {
            ILayer pLayer = Map.get_Layer(idx);
            bool bIsComposite = false;
            if (pLayer is ICompositeLayer)
            {
              pCompLyr = (ICompositeLayer)pLayer;
              bIsComposite = true;
            }

            int iCompositeLyrCnt = 1;
            if (bIsComposite)
              iCompositeLyrCnt = pCompLyr.Count;

            for (int i = 0; i <= (iCompositeLyrCnt - 1); i++)
            {
              if (bIsComposite)
            pLayer = pCompLyr.get_Layer(i);
              if (pLayer is ICadastralFabricLayer)
              {
            pCFLayer = (ICadastralFabricLayer)pLayer;
            break;
              }
              if (pLayer is ICadastralFabricSubLayer)
              {
            pCFSubLyr = (ICadastralFabricSubLayer)pLayer;
            IDataset pDS2 = (IDataset)pCFSubLyr.CadastralFabric;
            IName pDSName2 = pDS2.FullName;
            if (pDSName.NameString.ToLower() == pDSName2.NameString.ToLower() &&
            pCFSubLyr.CadastralTableType == esriCadastralFabricTable.esriCFTParcels)
            {
              pParcelLayer = (IFeatureLayer)pCFSubLyr;
              CFParcelLayers2.Add(pParcelLayer);
            }
            if (CFLineLayer == null && pDSName.NameString.ToLower() == pDSName2.NameString.ToLower() &&
            pCFSubLyr.CadastralTableType == esriCadastralFabricTable.esriCFTLines)
              CFLineLayer = (IFeatureLayer)pCFSubLyr;
            if (CFPointLayer == null && pDSName.NameString.ToLower() == pDSName2.NameString.ToLower() &&
            pCFSubLyr.CadastralTableType == esriCadastralFabricTable.esriCFTPoints)
              CFPointLayer = (IFeatureLayer)pCFSubLyr;
            if (CFLinePointLayer == null && pDSName.NameString.ToLower() == pDSName2.NameString.ToLower() &&
            pCFSubLyr.CadastralTableType == esriCadastralFabricTable.esriCFTLinePoints)
              CFLinePointLayer = (IFeatureLayer)pCFSubLyr;
            if (CFControlLayer == null && pDSName.NameString.ToLower() == pDSName2.NameString.ToLower() &&
            pCFSubLyr.CadastralTableType == esriCadastralFabricTable.esriCFTControl)
              CFControlLayer = (IFeatureLayer)pCFSubLyr;
              }
            }

            //Check that the fabric layer belongs to the requested fabric
            if (pCFLayer != null)
            {
              if (pCFLayer.CadastralFabric.Equals(Fabric))
              {
            CFPointLayer = (IFeatureLayer)pCFLayer.get_CadastralSubLayer(esriCadastralFabricRenderer.esriCFRPoints);
            CFLineLayer = (IFeatureLayer)pCFLayer.get_CadastralSubLayer(esriCadastralFabricRenderer.esriCFRLines);
            pParcelLayer = (IFeatureLayer)pCFLayer.get_CadastralSubLayer(esriCadastralFabricRenderer.esriCFRParcels);
            CFParcelLayers2.Add(pParcelLayer);
            Debug.WriteLine(pParcelLayer.Name);
            CFControlLayer = (IFeatureLayer)pCFLayer.get_CadastralSubLayer(esriCadastralFabricRenderer.esriCFRControlPoints);
            CFLinePointLayer = (IFeatureLayer)pCFLayer.get_CadastralSubLayer(esriCadastralFabricRenderer.esriCFRLinePoints);
              }

              if (CFLinePointLayer != null)
            CFParcelLayers2.Add(CFLinePointLayer);

              if (CFControlLayer != null)
            CFParcelLayers2.Add(CFControlLayer);

              if (CFLineLayer != null)
            CFParcelLayers2.Add(CFLineLayer);

              if (CFPointLayer != null)
            CFParcelLayers2.Add(CFPointLayer);

              CFParcelLayers = CFParcelLayers2;
              return true;
            }
              }
              //at the minimum, just need to make sure we have a parcel sublayer for the requested fabric
              if (pParcelLayer != null)
              {
            if (CFLinePointLayer != null)
              CFParcelLayers2.Add(CFLinePointLayer);

            if (CFControlLayer != null)
              CFParcelLayers2.Add(CFControlLayer);

            if (CFLineLayer != null)
              CFParcelLayers2.Add(CFLineLayer);

            if (CFPointLayer != null)
              CFParcelLayers2.Add(CFPointLayer);

            CFParcelLayers = CFParcelLayers2;
            return true;
              }
              else
              {
            CFParcelLayers = null;
            return false;
              }
        }
        public void GetFabricPlatform(IWorkspace TheWorkspace, ICadastralFabric TheFabric,
      out bool IsFileBasedGDB, out bool IsUnVersioned)
        {
            IsFileBasedGDB = false;
              IsUnVersioned = false;

              ITable pTable = TheFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels);

              IsFileBasedGDB = (!(TheWorkspace.WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace));

              if (!(IsFileBasedGDB))
              {
            IVersionedObject pVersObj = (IVersionedObject)pTable;
            IsUnVersioned = (!(pVersObj.IsRegisteredAsVersioned));
            pTable = null;
            pVersObj = null;
              }
        }