Exemple #1
0
        private List <IAttachment> method_4(IObject iobject_0)
        {
            List <IAttachment> list   = new List <IAttachment>();
            IClass             class2 = iobject_0.Class;

            if (class2 is ITableAttachments)
            {
                ITableAttachments attachments = (ITableAttachments)class2;
                if (!attachments.HasAttachments)
                {
                    return(list);
                }
                IAttachmentManager attachmentManager = attachments.AttachmentManager;
                ILongArray         oids = new LongArrayClass();
                oids.Add(iobject_0.OID);
                IEnumAttachment attachmentsByParentIDs = attachmentManager.GetAttachmentsByParentIDs(oids, false);
                attachmentsByParentIDs.Reset();
                IAttachment item = null;
                while ((item = attachmentsByParentIDs.Next()) != null)
                {
                    list.Add(item);
                }
            }
            return(list);
        }
Exemple #2
0
 private void InitAttachment()
 {
     this.toolStripDropDownButton1.DropDownItems.Clear();
     if (this.m_pObject.Class is ITableAttachments)
     {
         ITableAttachments attachments = (ITableAttachments)this.m_pObject.Class;
         if (attachments.HasAttachments)
         {
             ToolStripItem      item;
             IAttachmentManager attachmentManager = attachments.AttachmentManager;
             ILongArray         oids = new LongArrayClass();
             oids.Add(this.m_pObject.OID);
             IEnumAttachment attachmentsByParentIDs = attachmentManager.GetAttachmentsByParentIDs(oids, false);
             attachmentsByParentIDs.Reset();
             IAttachment attachment2 = null;
             string[]    strArray    = new string[2];
             int         num         = 0;
             while ((attachment2 = attachmentsByParentIDs.Next()) != null)
             {
                 item = new ToolStripButton(attachment2.Name)
                 {
                     Tag = attachment2
                 };
                 this.toolStripDropDownButton1.DropDownItems.Add(item);
                 num++;
             }
             item = new ToolStripButton("打开附件管理器");
             this.toolStripDropDownButton1.DropDownItems.Add(item);
             this.toolAttachmentLabel.Text = string.Format("附件({0})", num);
         }
     }
 }
Exemple #3
0
        private void frmAttachment_Load(object sender, EventArgs e)
        {
            ListViewItem item;

            string[] strArray;
            if (this.Attachments != null)
            {
                this.btnAdd.Visible    = false;
                this.btnDelete.Visible = false;
                item     = null;
                strArray = new string[2];
                foreach (IAttachment attachment in this.Attachments)
                {
                    strArray[0] = attachment.Name;
                    strArray[1] = attachment.Size.ToString();
                    item        = new ListViewItem(strArray)
                    {
                        Tag = attachment
                    };
                    this.listView1.Items.Add(item);
                }
                this.btnAllSaveAs.Enabled = this.listView1.Items.Count > 0;
            }
            else
            {
                ITableAttachments  attachments       = (ITableAttachments)this.Object.Class;
                IAttachmentManager attachmentManager = attachments.AttachmentManager;
                ILongArray         oids = new LongArrayClass();
                oids.Add(this.Object.OID);
                IEnumAttachment attachmentsByParentIDs = attachmentManager.GetAttachmentsByParentIDs(oids, true);
                attachmentsByParentIDs.Reset();
                IAttachment attachment = null;
                item     = null;
                strArray = new string[2];
                while ((attachment = attachmentsByParentIDs.Next()) != null)
                {
                    strArray[0] = attachment.Name;
                    strArray[1] = attachment.Size.ToString();
                    item        = new ListViewItem(strArray)
                    {
                        Tag = attachment
                    };
                    this.listView1.Items.Add(item);
                }
                this.btnAllSaveAs.Enabled = this.listView1.Items.Count > 0;
            }
        }
Exemple #4
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);
            }
        }
 private IFunctionRasterDataset createExtractFunction(string[] paramArr)
 {
     IFunctionRasterDataset inRaster = getRaster(paramArr[0]);
     ILongArray lArr = new LongArrayClass();
     foreach (string s in paramArr[1].Split(new char[]{','}))
     {
         int bnd = System.Convert.ToInt32(s.Trim()) - 1;
         lArr.Add(bnd);
     }
     return rsUtil.getBands(inRaster,lArr);
 }
 private void calcExtractBand(string[] prmArr, out string name, out IRaster raster)
 {
     name = prmArr[1].Split(new char[] { '@' })[1];
     string inRaster1 = prmArr[2].Split(new char[] { '@' })[1];
     string bands = prmArr[0].Split(new char[] { '@' })[1];
     IRaster rs = null;
     ILongArray lArr = new LongArrayClass();
     IRasterBandCollection rsBc = new RasterClass();
     if (rstDic.ContainsKey(inRaster1)) rs = rstDic[inRaster1];
     else rs = rsUtil.returnRaster(inRaster1);
     foreach (string s in bands.Split(new char[] { ',' }))
     {
         int bndIndex = System.Convert.ToInt32(s.Split(new char[] { '_' })[1]) - 1;
         lArr.Add(bndIndex);
     }
     raster = rsUtil.createRaster(rsUtil.getBands(rs, lArr));
 }
        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;
              }
        }
        private void btnExecute_Click(object sender, EventArgs e)
        {
            string rstNm = txtOutNm.Text;
            if (rstNm == null || rstNm == "")
            {
                MessageBox.Show("You must specify a output name","No Output",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }
            if (clbBands.CheckedItems.Count < 1)
            {
                MessageBox.Show("You must check at least on Raster Band", "No Bands", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            ILongArray lArr = new LongArrayClass();
            for (int i = 0; i < clbBands.CheckedItems.Count; i++)
            {
                string bandVl = clbBands.CheckedItems[i].ToString();
                int bndIndex = System.Convert.ToInt32(bandVl.Split(new char[] { '_' })[1])-1;
                lArr.Add(bndIndex);
            }
            this.Visible = false;
            esriUtil.Forms.RunningProcess.frmRunningProcessDialog rp = new RunningProcess.frmRunningProcessDialog(false);
            DateTime dt = DateTime.Now;
            rp.addMessage("Extracting Bands From  Raster. This may take a while...");
            rp.stepPGBar(10);
            rp.TopMost = true;
            rp.Show();
            try
            {
                outraster = rsUtil.returnRaster(rsUtil.getBands(rstDic[cmbInRaster1.Text],lArr));
                if (mp != null&&addToMap)
                {
                    rp.addMessage("Calculating Statistics...");

                    rp.Refresh();
                    IRasterLayer rstLyr = new RasterLayerClass();
                    //rsUtil.calcStatsAndHist(((IRaster2)outraster).RasterDataset);
                    rstLyr.CreateFromRaster(outraster);
                    rstLyr.Name = rstNm;
                    rstLyr.Visible = false;
                    mp.AddLayer(rstLyr);
                }
                outrastername = rstNm;
                this.DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                rp.addMessage(ex.ToString());
            }
            finally
            {
                DateTime dt2 = DateTime.Now;
                TimeSpan ts = dt2.Subtract(dt);
                string t = " in " + ts.Days.ToString() + " days " + ts.Hours.ToString() + " hours " + ts.Minutes.ToString() + " minutes and " + ts.Seconds.ToString() + " seconds .";
                rp.stepPGBar(100);
                rp.addMessage("Finished Extacting Bands" + t);
                rp.enableClose();
                this.Close();
            }
        }
        protected override void OnClick()
        {
            #region Prepare for editing
            IMouseCursor pMouseCursor = new MouseCursorClass();
            pMouseCursor.SetCursor(2);

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

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

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

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

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

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

            IArray CFParcelLayers = new ArrayClass();

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

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

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

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

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

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

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

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

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

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

                #endregion

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

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

                m_pFIDSetParcels = new FIDSetClass();

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

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

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

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

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

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

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

                #endregion

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

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

                    ILongArray pParcelsToLock = new LongArrayClass();

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

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

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

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

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

                pEd.StartOperation();

                #region The Edit

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

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

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

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

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

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

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

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

                        return;
                    }
                }

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

                #endregion

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

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

            ICadastralPacketManager pCadPacketMan = (ICadastralPacketManager)pCadEd;

            //bool bStartedWithPacketOpen = pCadPacketMan.PacketOpen;

            if (pParcEditorMan == null)
            {
                return;
            }

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

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

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

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

            if (pConstr == null)
            {
                return;
            }

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

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

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

            ICadastralUndoRedo pCadUndoRedo = pConstr as ICadastralUndoRedo;

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

                ICadastralParcel pCadaParcel = pCadPacketMan.JobPacket as ICadastralParcel;

                IGSParcel pGSParcel = null;

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

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

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

                pPointCalc.Rotation = TheRotation;
                IGSPoint pClosingPoint = null;

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

                    //      pPointCalc.AddLine(pParcelLine);

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

                    //    }
                    //    bLineSelectionSequence = true;

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

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

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

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

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

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

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

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

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

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

                    pCadUndoRedo.StartUndoRedoSession("Adjust Traverse");

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

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

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

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

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

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

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

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

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

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

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

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

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

                    dPreviousPointX = dAdjustedPointX;
                    dPreviousPointY = dAdjustedPointY;

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

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

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

                IEditProperties2 pEdProps = pEd as IEditProperties2;

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

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

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

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

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

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

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

                dlgTraverseResults dlgTraverseResults = new dlgTraverseResults();
                AddTraverseInfoToGrid(pConstr.Parcel.Plan, dlgTraverseResults.dataGridView1, Traverse, AdjustedTraverse, lstCoursesFromTo);
                dlgTraverseResults.txtMiscloseReport.Text = sReport;
                DialogResult dRes = dlgTraverseResults.ShowDialog();
                if (dRes == DialogResult.Cancel)
                {
                    //since we cancelled, set the points back
                    foreach (int i in lstPointIds)
                    {
                        pFixedPoints.SetFixedPoint(i, false);
                    }
                    pCadUndoRedo.WriteUndoRedoSession(false);
                }
                else
                {
                    pCadUndoRedo.WriteUndoRedoSession(true);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + "Line number:" + ex.LineNumber().ToString()
                                + " in " + ex.TargetSite.Name, "Traverse");
                pCadUndoRedo.WriteUndoRedoSession(false);
            }
        }
        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;
        }
        public static Dictionary <string, ILongArray> GetOIDArraysBySourceNameFromMapSelection(IMap map, List <string> sourceNames)
        {
            UIDClass uid = new UIDClass();

            uid.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}";             //IGeoFeatureLayer

            IEnumLayer searchEnumLayer = map.get_Layers(uid, true);

            searchEnumLayer.Reset();

            //create result dictionary from source names with empty oidArrays

            Dictionary <string, ILongArray> oidArraysBySourceName = new Dictionary <string, ILongArray>();
            ILongArray oidArray = null;

            foreach (string sourceName in sourceNames)
            {
                if (!oidArraysBySourceName.TryGetValue(sourceName, out oidArray))
                {
                    oidArray = new LongArrayClass();
                    oidArraysBySourceName.Add(sourceName, oidArray);
                }
            }

            ILayer layer = searchEnumLayer.Next();

            while (layer != null)
            {
                IDisplayTable displayTable = layer as IDisplayTable;
                string        sourceName   = "";
                if (layer.Valid && layer.Visible && displayTable != null)
                {
                    IDataset ds = displayTable.DisplayTable as IDataset;
                    if (ds != null)
                    {
                        sourceName = ds.Name;
                    }
                }

                if (sourceName.Length > 0)
                {
                    if (oidArraysBySourceName.TryGetValue(sourceName, out oidArray))
                    {
                        ISelectionSet selSet   = displayTable.DisplaySelectionSet;
                        IEnumIDs      enumOIDs = null;
                        if (selSet != null)
                        {
                            enumOIDs = selSet.IDs;
                        }

                        if (enumOIDs != null)
                        {
                            enumOIDs.Reset();
                            int oid = enumOIDs.Next();
                            while (oid != -1)
                            {
                                oidArray.Add(oid);
                                oid = enumOIDs.Next();
                            }
                        }
                    }
                }

                layer = searchEnumLayer.Next();
            }

            return(oidArraysBySourceName);
        }
        protected override void OnClick()
        {
            ICadastralEditor pCadEd = (ICadastralEditor)ArcMap.Application.FindExtensionByName("esriCadastralUI.CadastralEditorExtension");
              IParcelEditManager pParcEditorMan = (IParcelEditManager)pCadEd;

              ICadastralPacketManager pCadPacketMan = (ICadastralPacketManager)pCadEd;
              //bool bStartedWithPacketOpen = pCadPacketMan.PacketOpen;

              if (pParcEditorMan == null)
            return;

              IEditor pEd = (IEditor)ArcMap.Application.FindExtensionByName("esri object editor");
              if (pEd.EditState == esriEditState.esriStateNotEditing)
              {
            MessageBox.Show("Please start editing and try again.");
            return;
              }

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

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

              if (pConstr == null)
            return;

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

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

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

              ICadastralUndoRedo pCadUndoRedo = pConstr as ICadastralUndoRedo;
              try
              {
            int iParcelID = -1;
            if (pConstructionParentParcels.ParentParcelCount>0)
              pConstructionParentParcels.GetParentParcel(0, ref iParcelID);

            ICadastralParcel pCadaParcel = pCadPacketMan.JobPacket as ICadastralParcel;

            IGSParcel pGSParcel = null;

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

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

            if (!pCadastralEditorSettings2.MeasurementView)
              TheRotation = pGSParcel.Rotation;//radians

            if (TheRotation == 123456789)
              TheRotation = 0;

            pPointCalc.Rotation = TheRotation;
            IGSPoint pClosingPoint = null;

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

              //      pPointCalc.AddLine(pParcelLine);

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

              //    }
              //    bLineSelectionSequence = true;

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

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

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

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

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

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

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

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

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

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

              pCadUndoRedo.StartUndoRedoSession("Adjust Traverse");

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

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

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

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

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

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

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

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

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

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

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

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

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

              dPreviousPointX = dAdjustedPointX;
              dPreviousPointY = dAdjustedPointY;

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

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

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

            IEditProperties2 pEdProps = pEd as IEditProperties2;

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

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

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

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

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

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

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

            dlgTraverseResults dlgTraverseResults = new dlgTraverseResults();
            AddTraverseInfoToGrid(pConstr.Parcel.Plan, dlgTraverseResults.dataGridView1, Traverse, AdjustedTraverse, lstCoursesFromTo);
            dlgTraverseResults.txtMiscloseReport.Text = sReport;
            DialogResult dRes = dlgTraverseResults.ShowDialog();
            if (dRes == DialogResult.Cancel)
            {
              //since we cancelled, set the points back
              foreach (int i in lstPointIds)
            pFixedPoints.SetFixedPoint(i, false);
              pCadUndoRedo.WriteUndoRedoSession(false);
            }
            else
              pCadUndoRedo.WriteUndoRedoSession(true);
              }
              catch (Exception ex)
              {
            MessageBox.Show(ex.Message + Environment.NewLine + "Line number:" + ex.LineNumber().ToString()
              + " in " + ex.TargetSite.Name, "Traverse");
            pCadUndoRedo.WriteUndoRedoSession(false);
              }
        }
Exemple #14
0
        protected override void OnClick()
        {
            IMouseCursor pMouseCursor = new MouseCursorClass();

            pMouseCursor.SetCursor(2);

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

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

            Marshal.ReleaseComObject(pUID);

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

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

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

            clsFabricUtils UTILS = new clsFabricUtils();

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

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

            IArray CFParcelLayers = new ArrayClass();

            if (!(UTILS.GetFabricSubLayersFromFabric(pMap, pCadFabric, out CFPointLayer, out CFLineLayer,
                                                     out CFParcelLayers, out CFControlLayer, out CFLinePointLayer)))
            {
                return; //no fabric sublayers available for the targeted fabric
            }
            bool       bIsFileBasedGDB = false; bool bIsUnVersioned = false; bool bUseNonVersioned = false;
            IWorkspace pWS = null;

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

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

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

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

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



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

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

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

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

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

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

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

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

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

                m_bShowProgressor = (iFeatureCnt > 10);
                if (m_bShowProgressor)
                {
                    m_pProgressorDialogFact     = new ProgressDialogFactoryClass();
                    m_pTrackCancel              = new CancelTrackerClass();
                    m_pStepProgressor           = m_pProgressorDialogFact.Create(m_pTrackCancel, ArcMap.Application.hWnd);
                    pProgressorDialog           = (IProgressDialog2)m_pStepProgressor;
                    m_pStepProgressor.MinRange  = 1;
                    m_pStepProgressor.MaxRange  = iFeatureCnt;
                    m_pStepProgressor.StepValue = 1;
                    pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral;
                }
                m_pQF = new QueryFilterClass();
                string sPref; string sSuff;

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

                //====== need to do this for all the parcel sublayers in the map that are part of the target fabric
                if (m_bShowProgressor)
                {
                    pProgressorDialog.ShowDialog();
                    m_pStepProgressor.Message = "Collecting data...";
                }

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

                if (ChosenLayerHasSelection && bParcels && !bIsUnVersioned)
                {
                    //if there is a selection add the OIDs of all the selected parcels into a new feature IDSet
                    pEnumGSParcels.Reset();
                    IGSParcel pGSParcel = pEnumGSParcels.Next();

                    while (pGSParcel != null)
                    {
                        //Check if the cancel button was pressed. If so, stop process
                        if (m_bShowProgressor)
                        {
                            bCont = m_pTrackCancel.Continue();
                            if (!bCont)
                            {
                                break;
                            }
                        }
                        m_pFIDSetParcels.Add(pGSParcel.DatabaseId);
                        Marshal.ReleaseComObject(pGSParcel); //garbage collection
                        pGSParcel = pEnumGSParcels.Next();
                        //}
                        if (m_bShowProgressor)
                        {
                            if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange)
                            {
                                m_pStepProgressor.Step();
                            }
                        }
                    }
                }

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

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

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

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

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

                    ILongArray pParcelsToLock = new LongArrayClass();

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

                    try
                    {
                        pFabLocks.AcquireLocks(pParcelsToLock, true, ref pLocksInConflict, ref pSoftLcksInConflict);
                    }
                    catch (COMException pCOMEx)
                    {
                        if (pCOMEx.ErrorCode == (int)fdoError.FDO_E_CADASTRAL_FABRIC_JOB_LOCK_ALREADY_EXISTS)
                        {
                            MessageBox.Show("Edit Locks could not be acquired on all selected parcels.");
                            // since the operation is being aborted, release any locks that were acquired
                            pFabLocks.UndoLastAcquiredLocks();
                            //clear selection, to make sure the parcel explorer is updated and refreshed properly
                            RefreshMap(pActiveView, CFParcelLayers, CFPointLayer, CFLineLayer, CFControlLayer, CFLinePointLayer);
                        }
                        else
                        {
                            MessageBox.Show(Convert.ToString(pCOMEx.ErrorCode));
                        }

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

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

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

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

                bool bSuccess = true;

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

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

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

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

                    return;
                }

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

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

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

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

                m_pStepProgressor = null;
                if (!(pProgressorDialog == null))
                {
                    pProgressorDialog.HideDialog();
                }
                pProgressorDialog = null;
            }
        }
        protected override void OnClick()
        {
            IMouseCursor pMouseCursor = new MouseCursorClass();
              pMouseCursor.SetCursor(2);

              //first get the selected parcel features
              UID pUID = new UIDClass();
              pUID.Value = "{114D685F-99B7-4B63-B09F-6D1A41A4DDC1}";
              ICadastralExtensionManager2 pCadExtMan = (ICadastralExtensionManager2)ArcMap.Application.FindExtensionByCLSID(pUID);
              ICadastralEditor pCadEd = (ICadastralEditor)ArcMap.Application.FindExtensionByCLSID(pUID);
              Marshal.ReleaseComObject(pUID);

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

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

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

              clsFabricUtils UTILS = new clsFabricUtils();

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

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

              IArray CFParcelLayers = new ArrayClass();

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

              bool bIsFileBasedGDB = false; bool bIsUnVersioned = false; bool bUseNonVersioned = false;
              IWorkspace pWS = null;
              try
              {
            //Get the selection of parcels
            IFeatureLayer pFL = (IFeatureLayer)CFParcelLayers.get_Element(0);
            IDataset pDS = (IDataset)pFL.FeatureClass;
            pWS = pDS.Workspace;

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

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

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

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

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

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

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

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

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

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

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

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

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

            m_bShowProgressor = (iFeatureCnt > 10);
            if (m_bShowProgressor)
            {
              m_pProgressorDialogFact = new ProgressDialogFactoryClass();
              m_pTrackCancel = new CancelTrackerClass();
              m_pStepProgressor = m_pProgressorDialogFact.Create(m_pTrackCancel, ArcMap.Application.hWnd);
              pProgressorDialog = (IProgressDialog2)m_pStepProgressor;
              m_pStepProgressor.MinRange = 1;
              m_pStepProgressor.MaxRange = iFeatureCnt;
              m_pStepProgressor.StepValue = 1;
              pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral;
            }
            m_pQF = new QueryFilterClass();
            string sPref; string sSuff;

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

            //====== need to do this for all the parcel sublayers in the map that are part of the target fabric
            if (m_bShowProgressor)
            {
              pProgressorDialog.ShowDialog();
              m_pStepProgressor.Message = "Collecting data...";
            }

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

            if (ChosenLayerHasSelection && bParcels && !bIsUnVersioned)
            {
              //if there is a selection add the OIDs of all the selected parcels into a new feature IDSet
              pEnumGSParcels.Reset();
              IGSParcel pGSParcel = pEnumGSParcels.Next();

              while (pGSParcel != null)
              {
            //Check if the cancel button was pressed. If so, stop process
            if (m_bShowProgressor)
            {
              bCont = m_pTrackCancel.Continue();
              if (!bCont)
                break;
            }
            m_pFIDSetParcels.Add(pGSParcel.DatabaseId);
            Marshal.ReleaseComObject(pGSParcel); //garbage collection
            pGSParcel = pEnumGSParcels.Next();
            //}
            if (m_bShowProgressor)
            {
              if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange)
                m_pStepProgressor.Step();
            }
              }
            }

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

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

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

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

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

              ILongArray pParcelsToLock = new LongArrayClass();

              UTILS.FIDsetToLongArray(m_pFIDSetParcels, ref pParcelsToLock, m_pStepProgressor);
              if (m_pStepProgressor != null && !bIsFileBasedGDB)
            m_pStepProgressor.Message = "Testing for edit locks on parcels...";

              try
              {
            pFabLocks.AcquireLocks(pParcelsToLock, true, ref pLocksInConflict, ref pSoftLcksInConflict);
              }
              catch (COMException pCOMEx)
              {
            if (pCOMEx.ErrorCode == (int)fdoError.FDO_E_CADASTRAL_FABRIC_JOB_LOCK_ALREADY_EXISTS)
            {
              MessageBox.Show("Edit Locks could not be acquired on all selected parcels.");
              // since the operation is being aborted, release any locks that were acquired
              pFabLocks.UndoLastAcquiredLocks();
              //clear selection, to make sure the parcel explorer is updated and refreshed properly
              RefreshMap(pActiveView, CFParcelLayers, CFPointLayer, CFLineLayer, CFControlLayer, CFLinePointLayer);
            }
            else
            {
              MessageBox.Show(Convert.ToString(pCOMEx.ErrorCode));
            }

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

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

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

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

            bool bSuccess = true;

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

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

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

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

              return;
            }

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

            if (bUseNonVersioned)
              UTILS.StopEditing(pWS);

            if (bParcels)
              pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTParcels);
            else if (bLines)
              pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTLines);
            else
            {
              pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints); //release safety-catch
              pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl); //release safety-catch
              pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTLinePoints); //release safety-catch
            }

              }
              catch (Exception ex)
              {
            MessageBox.Show("Error:" + ex.Message);
            if (bUseNonVersioned)
              UTILS.AbortEditing(pWS);
            else
              pEd.AbortOperation();
              }
              finally
              {
            RefreshMap(pActiveView, CFParcelLayers, CFPointLayer, CFLineLayer, CFControlLayer, CFLinePointLayer);

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

            m_pStepProgressor = null;
            if (!(pProgressorDialog == null))
              pProgressorDialog.HideDialog();
            pProgressorDialog = null;
              }
        }
        public void Execute()
        {
            try {
                // Create new spatial reference
                ISpatialReference spatialReference = null;
                if (this.SRef.ToLowerInvariant().Contains("projcs")) {
                    spatialReference = new ProjectedCoordinateSystemClass();
                }
                else {
                    spatialReference = new GeographicCoordinateSystemClass();
                }

                // Import SpatialReference Definition
                int bytes2;
                IESRISpatialReferenceGEN2 gen = (IESRISpatialReferenceGEN2)spatialReference;
                gen.ImportFromESRISpatialReference(this.SRef, out bytes2);

                // Create Search Extent
                IEnvelope extent = new EnvelopeClass();
                extent.PutCoords(this.XMin, this.YMin, this.XMax, this.YMax);
                extent.SpatialReference = spatialReference;

                // Open Saved Layer File
                ILayerFile layerFile = new LayerFileClass();
                layerFile.Open(this.Path);
                ILayer layer = layerFile.Layer;
                layerFile.Close();

                // Where clause and list of selected OIDs
                string where = string.Empty;
                List<int> ids = new List<int>();

                IImageServerLayer imageLayer = null;
                if (layer is IImageServerLayer) {
                    imageLayer = (IImageServerLayer)layer;

                    // Get Selection Set
                    IFeatureLayerDefinition definition = layer as IFeatureLayerDefinition;
                    if (definition != null) {
                        // Find Selected OIDs
                        if (definition.DefinitionSelectionSet != null) {
                            if (definition.DefinitionSelectionSet.Count > 0) {
                                IEnumIDs emumids = definition.DefinitionSelectionSet.IDs;
                                int id = emumids.Next();
                                while (id != -1) {
                                    ids.Add(id);
                                    id = emumids.Next();
                                }
                            }
                        }

                        // Update Where Clause
                        if (!string.IsNullOrEmpty(definition.DefinitionExpression)) {
                            where = definition.DefinitionExpression;
                        }
                    }
                }
                else if (layer is IMosaicLayer) {
                    IMosaicLayer mosaicLayer = (IMosaicLayer)layer;
                    imageLayer = mosaicLayer.PreviewLayer;
                    ITableDefinition tableDefinition = mosaicLayer as ITableDefinition;
                    if (tableDefinition != null) {
                        // Find Selected OIDs
                        if (tableDefinition.DefinitionSelectionSet != null) {
                            if (tableDefinition.DefinitionSelectionSet.Count > 0) {
                                IEnumIDs emumids = tableDefinition.DefinitionSelectionSet.IDs;
                                int id = emumids.Next();
                                while (id != -1) {
                                    ids.Add(id);
                                    id = emumids.Next();
                                }
                            }
                        }

                        // Update Where Clause
                        if (!string.IsNullOrEmpty(tableDefinition.DefinitionExpression)) {
                            where = tableDefinition.DefinitionExpression;
                        }
                    }
                }

                // Use FeatureSelected (if any)
                IFeatureSelection featureSelection = imageLayer as IFeatureSelection;
                if (featureSelection != null) {
                    if (featureSelection.SelectionSet != null) {
                        if (featureSelection.SelectionSet.Count > 0) {
                            IEnumIDs emumids = featureSelection.SelectionSet.IDs;
                            int id = emumids.Next();
                            while (id != -1) {
                                ids.Add(id);
                                id = emumids.Next();
                            }
                        }
                    }
                }

                // Get Bands
                ILongArray bands = new LongArrayClass();
                IRasterRenderer rasterRenderer = imageLayer.Renderer;
                if (rasterRenderer != null) {
                    IRasterRGBRenderer2 rasterRGBRenderer = rasterRenderer as IRasterRGBRenderer2;
                    if (rasterRGBRenderer != null) {
                        bands.Add(rasterRGBRenderer.UseRedBand ? rasterRGBRenderer.RedBandIndex : -1);
                        bands.Add(rasterRGBRenderer.UseGreenBand ? rasterRGBRenderer.GreenBandIndex : -1);
                        bands.Add(rasterRGBRenderer.UseBlueBand ? rasterRGBRenderer.BlueBandIndex : -1);
                        bands.Add(rasterRGBRenderer.UseAlphaBand ? rasterRGBRenderer.AlphaBandIndex : -1);
                    }
                }

                // Create Spatial Filter
                ISpatialFilter spatialFilter = new SpatialFilterClass() {
                    Geometry = extent,
                    SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects,
                    WhereClause = where
                };

                IImageServer imageServer = imageLayer.DataSource as IImageServer;
                if (imageServer == null) { return; }
                IImageServer3 imageServer3 = imageServer as IImageServer3;
                if (imageServer3 == null) { return; }
                IRecordSet recordSet = imageServer3.GetCatalogItems(spatialFilter);
                ICursor cursor = recordSet.get_Cursor(false);
                IFeatureCursor featureCursor = (IFeatureCursor)cursor;
                IFeature feature = featureCursor.NextFeature();
                List<IFeature> list = new List<IFeature>();

                int indexCategory = featureCursor.FindField("Category");

                while (feature != null) {
                    // Exclude non-primary images (no overviews)
                    if (indexCategory != -1) {
                        int cat = (int)feature.get_Value(indexCategory);
                        if (cat != 1) {
                            feature = featureCursor.NextFeature();
                            continue;
                        }
                    }

                    // Exclude unselected features
                    if (ids.Count > 0) {
                        int oid = feature.OID;
                        if (!ids.Contains(oid)) {
                            feature = featureCursor.NextFeature();
                            continue;
                        }
                    }

                    list.Add(feature);
                    feature = featureCursor.NextFeature();
                }

                // If nothing, fire event then exit
                if (list.Count == 0) {
                    this.OnThumbnailSummary(new SummaryEventArgs());
                    return;
                }

                // Get Full Extent of Features
                SummaryEventArgs summary = new SummaryEventArgs() {
                    XMin = list.Min(f => f.Shape.Envelope.CloneProject(spatialReference).XMin),
                    YMin = list.Min(f => f.Shape.Envelope.CloneProject(spatialReference).YMin),
                    XMax = list.Max(f => f.Shape.Envelope.CloneProject(spatialReference).XMax),
                    YMax = list.Max(f => f.Shape.Envelope.CloneProject(spatialReference).YMax),
                    Count = list.Count
                };

                // Add Fields
                IFields fields = featureCursor.Fields;
                for (int i = 0; i < fields.FieldCount; i++) {
                    IField field = fields.get_Field(i);
                    switch (field.Type) {
                        case esriFieldType.esriFieldTypeBlob:
                        case esriFieldType.esriFieldTypeGeometry:
                        case esriFieldType.esriFieldTypeGlobalID:
                        case esriFieldType.esriFieldTypeGUID:
                        case esriFieldType.esriFieldTypeRaster:
                        case esriFieldType.esriFieldTypeXML:
                            break;
                        case esriFieldType.esriFieldTypeOID:
                        case esriFieldType.esriFieldTypeDate:
                        case esriFieldType.esriFieldTypeDouble:
                        case esriFieldType.esriFieldTypeInteger:
                        case esriFieldType.esriFieldTypeSingle:
                        case esriFieldType.esriFieldTypeSmallInteger:
                        case esriFieldType.esriFieldTypeString:
                            summary.Fields.Add(
                                new Field() {
                                    Name = field.Name,
                                    Alias = field.AliasName,
                                    Type = field.Type
                                }
                            );
                            break;
                        default:
                            break;
                    }
                }

                // Raise Summary Event
                this.OnThumbnailSummary(summary);

                // Loop for each feature
                foreach (IFeature feat in list) {
                    // Project Extent to Current Map Spatial Reference
                    IEnvelope extentMap = feat.Shape.Envelope.CloneProject(spatialReference);

                    int width;
                    int height;
                    if (extentMap.Width > extentMap.Height) {
                        width = this.MaxImageSize;
                        height = Convert.ToInt32((double)this.MaxImageSize * (double)extentMap.Height / (double)extentMap.Width);
                    }
                    else {
                        width = Convert.ToInt32((double)this.MaxImageSize * (double)extentMap.Width / (double)extentMap.Height);
                        height = this.MaxImageSize;
                    }

                    IMosaicRule mosaicRule = new MosaicRuleClass() {
                        MosaicMethod = esriMosaicMethod.esriMosaicLockRaster,
                        LockRasterID = feat.OID.ToString()
                    };
                    IGeoImageDescription geoImageDescription = new GeoImageDescriptionClass() {
                        BandSelection = bands.Count > 0 ? bands : null,
                        MosaicRule = mosaicRule,
                        Compression = "PNG",
                        Width = width,
                        Height = height,
                        SpatialReference = spatialReference,
                        Extent = extentMap,
                        Interpolation = rstResamplingTypes.RSP_BilinearInterpolation,
                    };

                    // Assembly MosaicRequest (will be executed in background thread)
                    MosaicRequest mosaicRequest = new MosaicRequest() {
                        MosaicExtractor = this,
                        ImageServer = imageServer3,
                        GeoImageDescription = geoImageDescription,
                        XMin = extentMap.XMin,
                        YMin = extentMap.YMin,
                        XMax = extentMap.XMax,
                        YMax = extentMap.YMax,
                    };

                    // Add Attributes Names and Values
                    foreach (Field field in summary.Fields) {
                        int index = feat.Fields.FindField(field.Name);
                        if (index < 0) { continue; }
                        mosaicRequest.Attributes.Add(field.Name, feat.get_Value(index));
                    }

                    // Start Mosaic Request in Background Thread
                    Thread thread = new Thread(new ThreadStart(mosaicRequest.Execute));
                    MosaicEnvironment.Default.Threads.Add(thread);
                    thread.Start();
                }
            }
            catch { }
        }
Exemple #17
0
        protected override void OnClick()
        {
            m_bNoUpdates = false;
            m_sReport    = "Direction Inverse Report:";
            IEditor m_pEd = (IEditor)ArcMap.Application.FindExtensionByName("esri object editor");

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

            UID pUID = new UIDClass();

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

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

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

            try
            {
                IEditProperties2 pEditorProps2 = (IEditProperties2)m_pEd;

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

                //double dMetersPerUnit = 1;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                RefineToBestRadiusAndCenterPoint(dictLineToCurveNeighbourData);

                #endregion

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

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


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

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

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


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

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

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

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

                        return;
                    }
                }
                #endregion

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

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

                m_pQF = new QueryFilter();

                // m_pEd.StartOperation();

                List <string> sInClauseList = Utils.InClauseFromOIDsList(lstLineIds, 995);
                foreach (string InClause in sInClauseList)
                {
                    m_pQF.WhereClause = pFabricLinesFC.OIDFieldName + " IN (" + InClause + ")";
                    if (!UpdateCircularArcValues((ITable)pFabricLinesFC, m_pQF, bIsUnVersioned, dictLineToCurveNeighbourData))
                    {
                        ;
                    }
                }
                m_pEd.StopOperation("Insert missing circular arc information.");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                m_pEd.AbortOperation();
            }
            finally
            {
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="inRequest"></param>
        /// <param name="mode"></param>
        /// <param name="authorizedLayerSet"></param>
        /// <returns></returns>
        private IMessage FilterLayerIds ( IMessage inRequest, SoapRequestType mode, HashSet<String> authorizedLayerSet )
        {
            // 1. Find the index of the layers parameter
            // 2. Get the value for the interested parameter
            // 3. Manipulate it
            // 4. Put it back into IMessage

            int idx = -1;
            IXMLSerializeData inRequestData = inRequest.Parameters;
            try
            {
                idx = inRequestData.Find("LayerIDs");
            }
            catch (Exception ignore)
            {
            }

            LongArray layerIdInLA = null;
            if (idx >= 0)
            {
                // Get all the requested layers
                layerIdInLA = (LongArray)inRequestData.GetObject(idx, inRequest.NamespaceURI, "ArrayOfInt");

                // Perform filtering based on access to different layers. 
                // Remove restricted ids in-place
                for (int i = layerIdInLA.Count - 1; i >= 0; i--)
                {

                    if (!authorizedLayerSet.Contains(layerIdInLA.Element[i].ToString()))
                    {
                        layerIdInLA.Remove(i);
                    }
                }
            }
            else //no LayerIDs specified, attaching authorized layer list instead
            {
                layerIdInLA = new LongArrayClass();
                foreach (var goodLayerId in authorizedLayerSet)
                {
                    layerIdInLA.Add(Int32.Parse(goodLayerId));
                }
                inRequestData.AddObject("LayerIDs", layerIdInLA);
            }

            // If binary request we dont have to create and copy in a new Message object
            if (mode == SoapRequestType.Binary)
            {
                return inRequest;
            }

            // Create new request message
            IMessage modifiedInRequest = _SoapSOIHelper.CreateNewIMessage(inRequest);
            IXMLSerializeData modifiedInRequestData = modifiedInRequest.Parameters;

            // Put all parameters back in IMessage
            for (int i = 0; i < inRequestData.Count; i++)
            {
                if (_SoapSOIHelper.GetSoapOperationParameterName(inRequest.Name, i).Equals("LayerIDs", StringComparison.CurrentCultureIgnoreCase))
                {
                    // Add the modified MapDescription
                    _SoapSOIHelper.AddObjectToXMLSerializeData(_SoapSOIHelper.GetSoapOperationParameterName(inRequest.Name, i),
                      layerIdInLA, _SoapSOIHelper.GetSoapOperationParameterTypeName(inRequest.Name, i), modifiedInRequestData);
                }
                else
                {
                    /*
                     * Add other parameters as is. Here we are using the SOI helper to add and get parameters
                     * because we don't care about the type we just want to copy from one IMessage object to
                     * another.
                     */
                    _SoapSOIHelper.AddObjectToXMLSerializeData(
                      _SoapSOIHelper.GetSoapOperationParameterName(inRequest.Name, i),
                      _SoapSOIHelper.GetObjectFromXMLSerializeData(i, inRequest.NamespaceURI,
                          _SoapSOIHelper.GetSoapOperationParameterTypeName(inRequest.Name, i), inRequestData),
                      _SoapSOIHelper.GetSoapOperationParameterTypeName(inRequest.Name, i), modifiedInRequestData);
                }
            }

            return modifiedInRequest;
        }
        static void Main(string[] args)
        {
            ESRI.ArcGIS.esriSystem.AoInitialize aoInit;

            #region Initialize License
            try
            {
                Console.WriteLine("Obtaining license");
                ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);
                aoInit = new AoInitializeClass();
                esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeBasic);
                Console.WriteLine("Ready with license.");
            }
            catch (Exception exc)
            {
                // If it fails at this point, shutdown the test and ignore any subsequent errors.
                Console.WriteLine(exc.Message);
                return;
            }
            #endregion

            try
            {
                #region Specify input directory and dataset name
                // The directory which contains the Panchromatic Image.
                string panDir = @"C:\Data\QB\Pan";
                // The directory which contains the Multispectral Image.
                string rgbDir = @"C:\Data\QB\MS";

                string panImageName = "05JAN27104436-P1BS-005533787010_01_P002.TIF";
                string rgbImageName = "05JAN27104436-M1BS-005533787010_01_P002.TIF";

                // Output filename.
                string outputDataset = @"c:\Temp\QBTemplateCS.afr";
                #endregion

                #region Initialize
                // Setup Workspaces.
                Type factoryType = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory");
                IWorkspaceFactory workspaceFactory   = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
                IRasterWorkspace  panRasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(panDir, 0);
                IRasterWorkspace  rgbRasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(rgbDir, 0);

                // Open Datasets
                IRasterDataset panDataset = panRasterWorkspace.OpenRasterDataset(panImageName);
                IRasterDataset rgbDataset = rgbRasterWorkspace.OpenRasterDataset(rgbImageName);
                #endregion

                #region Create Variables
                // Create one variable of type IRasterFunctionVariable for each
                // Raster Dataset opened above

                // Create a new Raster Function Variable
                IRasterFunctionVariable panVar = new RasterFunctionVariableClass();
                // Set the name of the variable
                panVar.Name = "panImage";
                // Describe the variable
                panVar.Description = "Panchromatic Image to be used for pansharpening";
                // Specify whether it represents a dataset
                panVar.IsDataset = true;

                // Create a new Raster Function Variable
                IRasterFunctionVariable rgbVar = new RasterFunctionVariableClass();
                // Set the name of the variable
                rgbVar.Name = "rgbImage";
                // Describe the variable
                rgbVar.Description = "Multispectral Image to be used for pansharpening";
                // Specify whether it represents a dataset
                rgbVar.IsDataset = true;
                #endregion

                #region Prepare the Pan Image
                // Setup statistics for each band
                IArray            statsArrayPan = new ArrayClass();
                IRasterStatistics statsPanBand  = new RasterStatisticsClass();
                statsPanBand.Minimum = 1;
                statsPanBand.Maximum = 2047;
                statsArrayPan.Add(statsPanBand);
                // Create the arguments object for the stretching function
                IStretchFunctionArguments stretchingPanFunctionArguements = new StretchFunctionArgumentsClass();
                // Set the stretching type
                stretchingPanFunctionArguements.StretchType =
                    esriRasterStretchType.esriRasterStretchMinimumMaximum;
                // Set the statistics created above
                stretchingPanFunctionArguements.Statistics = statsArrayPan;
                // Set the input raster, in this case, the variable for the Pan Image
                stretchingPanFunctionArguements.Raster = panVar;

                // Create the function object to stretch the Pan Image.
                IRasterFunction stretchingPanFunction = new StretchFunction();

                // Create a Raster Function Template object for the stretch function
                IRasterFunctionTemplate stretchingPanFunctionT = new RasterFunctionTemplateClass();
                // Set the function on the template
                stretchingPanFunctionT.Function = (IRasterFunction)stretchingPanFunction;
                // Set the arguments for the function
                stretchingPanFunctionT.Arguments = stretchingPanFunctionArguements;
                #endregion

                #region Prepare the Multispectral (RGB) Image
                // Create an array which defines the order of bands
                ILongArray bandIDs = new LongArrayClass();
                bandIDs.Add(2);
                bandIDs.Add(1);
                bandIDs.Add(0);
                // Create an Extract Band Function Arguments object
                IExtractBandFunctionArguments extractRgbBandFunctionArgs = (IExtractBandFunctionArguments)
                                                                           new ExtractBandFunctionArguments();
                // Set the order of bands of the output
                extractRgbBandFunctionArgs.BandIDs = bandIDs;
                // Set the input raster, in this case the variable for the Multispectral Image
                extractRgbBandFunctionArgs.Raster = rgbVar;

                // Create the Extract Band Function object
                IRasterFunction extractRgbBandFunction = new ExtractBandFunction();

                // Create a Raster Function Template object for the function created above
                IRasterFunctionTemplate extractRgbBandFunctionT = new RasterFunctionTemplateClass();
                // Set the function on the template
                extractRgbBandFunctionT.Function = (IRasterFunction)extractRgbBandFunction;
                // Set the arguments for the function
                extractRgbBandFunctionT.Arguments = extractRgbBandFunctionArgs;

                // Setup statistics for each band
                IArray            statsArray    = new ArrayClass();
                IRasterStatistics statsMulBand1 = new RasterStatisticsClass();
                statsMulBand1.Minimum = 100;
                statsMulBand1.Maximum = 1721;
                statsArray.Add(statsMulBand1);
                IRasterStatistics statsMulBand2 = new RasterStatisticsClass();
                statsMulBand2.Minimum = 95;
                statsMulBand2.Maximum = 2047;
                statsArray.Add(statsMulBand2);
                IRasterStatistics statsMulBand3 = new RasterStatisticsClass();
                statsMulBand3.Minimum = 34;
                statsMulBand3.Maximum = 2006;
                statsArray.Add(statsMulBand3);

                // Create a stretching function for the multispectral image
                IRasterFunction stretchingRGBFunction = new StretchFunction();
                // Create an arguments object for the stretch function
                IStretchFunctionArguments stretchingRGBFunctionArguments =
                    new StretchFunctionArgumentsClass();
                // Set the type of stretchings to perform
                stretchingRGBFunctionArguments.StretchType =
                    esriRasterStretchType.esriRasterStretchMinimumMaximum;
                // Set the statistics created above
                stretchingRGBFunctionArguments.Statistics = statsArray;
                // Set the extract band function template created above as the input
                stretchingRGBFunctionArguments.Raster = extractRgbBandFunctionT;

                // Create a Raster Function Template object for the function created above
                IRasterFunctionTemplate stretchingRGBFunctionT = new RasterFunctionTemplateClass();
                // Set the function on the template
                stretchingRGBFunctionT.Function = (IRasterFunction)stretchingRGBFunction;
                // Set the arguments for the function
                stretchingRGBFunctionT.Arguments = stretchingRGBFunctionArguments;
                #endregion

                #region Pansharpen the Pan Image with the Multispectral
                // Create a Raster Function Arguments object for the pansharpen function
                IPansharpeningFunctionArguments pansharpFunctionArguements =
                    new PansharpeningFunctionArgumentsClass();
                // Set the Panchromatic image which has been prepared above
                pansharpFunctionArguements.PanImage = stretchingPanFunctionT;
                // Set the Multispectral image which has been prepared above
                pansharpFunctionArguements.MSImage = stretchingRGBFunctionT;

                // Create a new pansharpen raster function object
                IRasterFunction pansharpenFunction = new PansharpeningFunction();
                // Create a new pansharpen function arguments object
                IPansharpeningFunctionArguments pansharpenFunctionArguements =
                    new PansharpeningFunctionArgumentsClass();
                // Set the pansharpening type
                pansharpenFunctionArguements.PansharpeningType =
                    esriPansharpeningType.esriPansharpeningESRI;
                // Create an array of doubles that sets the weights for each band
                IDoubleArray weightsArray = new DoubleArrayClass();
                weightsArray.Add(0.167);
                weightsArray.Add(0.166);
                weightsArray.Add(0.166);
                // and set it on the arguments object
                pansharpenFunctionArguements.Weights = weightsArray;

                // Create a Raster Function Template object for the pansharpen function
                IRasterFunctionTemplate rasterFunction = new RasterFunctionTemplateClass();
                rasterFunction.Function  = (IRasterFunction)pansharpenFunction;
                rasterFunction.Arguments = pansharpFunctionArguements;
                ((IRasterFunction)rasterFunction).PixelType = rstPixelType.PT_UCHAR;
                #endregion

                #region Resolve variables
                // Create a PropertySet object to set the values for the
                // Raster Function Variables created above
                IPropertySet variables = new PropertySet();
                variables.SetProperty("panImage", panDataset);
                variables.SetProperty("rgbImage", rgbDataset);
                #endregion

                #region Create the Function Raster Dataset
                // Create the Function Raster Dataset Object for the Pansharpened Dataset
                IFunctionRasterDataset functionRasterDataset = new FunctionRasterDataset();
                // Create a name object for the Function Raster Dataset.
                IFunctionRasterDatasetName functionRasterDatasetName =
                    new FunctionRasterDatasetNameClass();
                // Specify the output filename for the new dataset (including
                // the .afr extension at the end).
                functionRasterDatasetName.FullName = outputDataset;
                functionRasterDataset.FullName     = (IName)functionRasterDatasetName;
                // Initialize the new Function Raster Dataset with the Raster Function
                // Template and the property set containing the variables and their values.
                functionRasterDataset.Init((IRasterFunction)rasterFunction, variables);

                ITemporaryDataset myTempDset = (ITemporaryDataset)functionRasterDataset;
                myTempDset.MakePermanent();
                #endregion

                #region Shutdown
                Console.WriteLine("Success.");
                Console.WriteLine("Press any key...");
                Console.ReadKey();

                // Shutdown License
                aoInit.Shutdown();
                #endregion
            }
            catch (Exception exc)
            {
                #region Shutdown
                Console.WriteLine("Exception Caught while creating Function Raster Dataset. " + exc.Message);
                Console.WriteLine("Failed.");
                Console.WriteLine("Press any key...");
                Console.ReadKey();

                // Shutdown License
                aoInit.Shutdown();
                #endregion
            }
        }
        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 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);
            }
        }
Exemple #22
0
        protected override void OnClick()
        {
            //first check that we are currently editing
            if (ArcMap.Editor.EditState != esriEditState.esriStateEditing)
            {
                MessageBox.Show("Please start editing and try again.", "Sample Code");
                return;
            }

            //get the cadastral editor
            ICadastralEditor pCadEd = (ICadastralEditor)ArcMap.Application.FindExtensionByName("esriCadastralUI.CadastralEditorExtension");

            //get the fabric line layers that belong to the target fabric.
            // **SAMPLE CODE NOTE**
            //This next function allows for more than 1 fabric lines sublayer in the map document, and uses a line layer array
            //However, this sample code assumes just one line fabric sub layer, and works with the first found
            //The function is provided for other expanded uses if needed elsewhere.
            IArray LineLayerArray;

            if (!GetFabricSubLayers(ArcMap.Document.ActiveView.FocusMap, esriCadastralFabricTable.esriCFTLines,
                                    true, pCadEd.CadastralFabric, out LineLayerArray))
            {
                return;
            }

            // get the line selection; this code sample uses first line layer for the target fabric (first element)
            ISelectionSet2 LineSelection =
                GetSelectionFromLayer(LineLayerArray.get_Element(0) as ICadastralFabricSubLayer);

            // check to see if there is only one parcel line selected
            // **SAMPLE CODE NOTE**
            //This sample code ensures one line feature, although it can be easily adapted for use on
            //multiple line selection.
            if (LineSelection.Count != 1)
            {
                MessageBox.Show("Please select only one parcel line from the Target fabric.", "Sample Code");
                return;
            }
            //Get a search cursor from the line selection to get the parcel id
            //We need to get an edit lock on the parcel using the parcel id
            //An edit lock will guarantee the edit will persist in a multi-user environment after a reconcile

            ILongArray pParcelsToLock        = new LongArrayClass();
            IFIDSet    pFIDSetForParcelRegen = new FIDSet();
            ICursor    pCur;

            LineSelection.Search(null, false, out pCur);
            //this cursor returns the selected lines
            // **SAMPLE CODE NOTE**
            //setup for potential use for multiple line selection, even though this sample uses a single line selection

            //get the field indices for line attributes needed.
            int idxParcelID    = pCur.FindField("parcelid");
            int idxToPointID   = pCur.FindField("topointid");
            int idxFromPointID = pCur.FindField("frompointid");
            int idxCenterPtId  = pCur.FindField("centerpointid");
            int idxDistance    = pCur.FindField("distance");
            int idxRadius      = pCur.FindField("radius");
            int idxCategory    = pCur.FindField("category");

            //also need the fabric point table and fields
            IFeatureClass pFabricPointsFC = (IFeatureClass)pCadEd.CadastralFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints);
            int           idxPointX       = pFabricPointsFC.FindField("x");
            int           idxPointY       = pFabricPointsFC.FindField("y");
            int           idxPointCtrPt   = pFabricPointsFC.FindField("centerpoint");

            var ListFromToPairsForRadialLines = new List <int[]>();

            // **SAMPLE CODE NOTE**
            //setup for potential use for multiple line selection, even though this sample uses a single line selection
            //the list declared above is here for potential use in Add-ins that make use of multiple circular arc lines

            int[] ParcelIdCtrPtIdFromId1FromId2;
            IRow  pRow = pCur.NextRow();

            while (pRow != null)
            {
                int iParcelID = (int)pRow.get_Value(idxParcelID);
                pParcelsToLock.Add(iParcelID);        //LongArray for the parcel locks
                pFIDSetForParcelRegen.Add(iParcelID); //FIDSet for the parcel regenerate
                //now check for a center point id on the line; this is for the case of changing the radius of an existing curve

                object value = pRow.get_Value(idxCenterPtId);
                if (value != DBNull.Value)
                {                                                  //collecting information to remove radial lines
                    ParcelIdCtrPtIdFromId1FromId2    = new int[4]; // 4-element array
                    ParcelIdCtrPtIdFromId1FromId2[0] = iParcelID;
                    ParcelIdCtrPtIdFromId1FromId2[1] = (int)value; //center point is always the to point of the radial line
                    ParcelIdCtrPtIdFromId1FromId2[2] = (int)pRow.get_Value(idxFromPointID);
                    ParcelIdCtrPtIdFromId1FromId2[3] = (int)pRow.get_Value(idxToPointID);
                    // **SAMPLE CODE NOTE**
                    //now add the array, to the list to accomodate other add-ins that may use
                    //more than one selected circular arc line
                    ListFromToPairsForRadialLines.Add(ParcelIdCtrPtIdFromId1FromId2);
                }
                Marshal.ReleaseComObject(pRow);
                pRow = pCur.NextRow();
            }
            Marshal.ReleaseComObject(pCur);

            bool IsFileBasedGDB = (ArcMap.Editor.EditWorkspace.WorkspaceFactory.WorkspaceType !=
                                   esriWorkspaceType.esriRemoteDatabaseWorkspace);

            if (!IsFileBasedGDB)
            {
                //for file geodatabase creating a job is optional
                //see if parcel locks can be obtained on the selected parcels. First create a job.
                string NewJobName = "";
                if (!CreateJob(pCadEd.CadastralFabric, "Sample Code change line to curve", out NewJobName))
                {
                    return;
                }

                if (!TestForEditLocks(pCadEd.CadastralFabric, NewJobName, pParcelsToLock))
                {
                    return;
                }
            }

            //if we get this far, an edit lock has been acquired, or this is file geodatabase (no lock required)
            //prompt the user for a new radius value

            string sRadius = Interaction.InputBox("Enter a new Radius:", "Radius");
            //**SAMPLE CODE NOTE** :
            // using the Interaction class from the Microsfot Visual Basic library
            // is a quick and easy way to provide an input dialog in a single line of code for sample purposes,
            // without neeing to add a windows form, dockable window, or other UI elements into this project.

            double dRadius = 0;

            if (!Double.TryParse(sRadius, out dRadius))
            {
                return;
            }
            //we have a valid double value, so we can get ready to edit

            IProgressDialogFactory pProgressorDialogFact = new ProgressDialogFactoryClass();
            ITrackCancel           pTrackCancel          = new CancelTracker();
            IStepProgressor        pStepProgressor       = pProgressorDialogFact.Create(pTrackCancel, ArcMap.Application.hWnd);
            IProgressDialog2       pProgressorDialog     = (IProgressDialog2)pStepProgressor;

            ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)pCadEd.CadastralFabric;

            try
            {                                                                                                     //turn off the read-only flag on the lines table and points table
                pSchemaEd.ReleaseReadOnlyFields(LineSelection.Target, esriCadastralFabricTable.esriCFTLines);     //release read-only
                pSchemaEd.ReleaseReadOnlyFields((ITable)pFabricPointsFC, esriCadastralFabricTable.esriCFTPoints); //release read-only

                //start an edit operation
                ArcMap.Editor.StartOperation();

                //get an update cursor to make the edit on the line(s)
                LineSelection.Update(null, false, out pCur);

                pRow = pCur.NextRow();
                int iChangeCount = 0;
                while (pRow != null)
                {
                    double dChord = (double)pRow.get_Value(idxDistance);
                    if (Math.Abs(dRadius) <= dChord / 2 && dRadius != 0) //minimum allowable radius is half the chord
                    {
                        Marshal.ReleaseComObject(pRow);
                        pRow = pCur.NextRow();
                        continue;
                    }

                    //compute a center point location from new radius, unless it's 0
                    int iNewCtrPtId = 0;
                    if (dRadius != 0)
                    {
                        IFeature pFeat         = pRow as IFeature;
                        IPoint   pCtrPt        = ComputeCenterPointFromRadius(pFeat.Shape as IPolyline, dRadius, true);
                        IFeature pNewPointFeat = pFabricPointsFC.CreateFeature();
                        //**SAMPLE CODE NOTE** :
                        //if adding a large number of points (more than 20) then createfeature is not the fastest approach,
                        //Instead you would pre-allocate points using an insert cursor...
                        //At this point in the code, the normal geodatabase performance considerations apply
                        iNewCtrPtId = pNewPointFeat.OID;
                        pNewPointFeat.set_Value(idxPointX, pCtrPt.X);
                        pNewPointFeat.set_Value(idxPointY, pCtrPt.Y);
                        pNewPointFeat.set_Value(idxPointCtrPt, 1); //1 = true boolean
                        pNewPointFeat.Shape = pCtrPt;
                        pNewPointFeat.Store();
                    }
                    //get the initial radius if the line is a curve (radius is being updated)
                    object obj = pRow.get_Value(idxRadius);
                    bool   bIsChangingFromCurve = (obj != DBNull.Value);                  //there is a radius value
                    obj = pRow.get_Value(idxCenterPtId);
                    bIsChangingFromCurve = bIsChangingFromCurve && (obj != DBNull.Value); //radius value and Ctr Pt ID exist
                    int iExistingCtrPtId = 0;
                    if (bIsChangingFromCurve)
                    {
                        iExistingCtrPtId = (int)obj;
                    }
                    if (dRadius == 0) //user entered value is zero meaning convert to straight line
                    {                 //changing to a straight line so set the center point an radius to null
                        pRow.set_Value(idxRadius, DBNull.Value);
                        pRow.set_Value(idxCenterPtId, DBNull.Value);
                    }
                    else if (!bIsChangingFromCurve) //user entered a new radius, and the existing line is not a curve
                    {                               //changing to a circular arc so set the radius, and set the center point id to the new point's OID
                        pRow.set_Value(idxRadius, dRadius);
                        pRow.set_Value(idxCenterPtId, iNewCtrPtId);
                    }
                    else if (bIsChangingFromCurve) //user entered a radius, and the existing line is a curve

                    {
                        pCur.UpdateRow(pRow);
                    }
                    iChangeCount++;
                    Marshal.ReleaseComObject(pRow);
                    pRow = pCur.NextRow();
                }
                Marshal.ReleaseComObject(pCur);

                if (iChangeCount == 0)
                {//if there are no changes then don't add to the edit operation stack
                    ArcMap.Editor.AbortOperation();
                    return;
                }

                if (ListFromToPairsForRadialLines.Count > 0)
                {
                    IQueryFilter pQuFilter          = new QueryFilter();
                    string       sCat               = LineSelection.Target.Fields.get_Field(idxCategory).Name;
                    string       sToPt              = LineSelection.Target.Fields.get_Field(idxToPointID).Name;
                    string       sFromPt            = LineSelection.Target.Fields.get_Field(idxFromPointID).Name;
                    string       sParcelID          = LineSelection.Target.Fields.get_Field(idxParcelID).Name;
                    string       sInClauseToPts     = "(";
                    string       sInClauseFromPts   = "(";
                    string       sInClauseParcelIds = "(";
                    //**SAMPLE CODE NOTE** :
                    //The following In Clause, when contructed for production environments
                    //should take into account the token limit on Oracle database platforms. (<1000)
                    // the processing of the in clause should be broekn into blocks with the in cluase has no more than 1000 elements
                    foreach (int[] iParcelIdCtrPtIdFromId1FromId2 in ListFromToPairsForRadialLines)
                    {
                        if (sInClauseParcelIds.Length == 1)
                        {
                            sInClauseParcelIds += iParcelIdCtrPtIdFromId1FromId2[0].ToString();
                        }
                        else
                        {
                            sInClauseParcelIds += "," + iParcelIdCtrPtIdFromId1FromId2[0].ToString();
                        }

                        if (sInClauseToPts.Length == 1)
                        {
                            sInClauseToPts += iParcelIdCtrPtIdFromId1FromId2[1].ToString();
                        }
                        else
                        {
                            sInClauseToPts += "," + iParcelIdCtrPtIdFromId1FromId2[1].ToString();
                        }

                        if (sInClauseFromPts.Length == 1)
                        {
                            sInClauseFromPts += iParcelIdCtrPtIdFromId1FromId2[2].ToString();
                            sInClauseFromPts += "," + iParcelIdCtrPtIdFromId1FromId2[3].ToString();
                        }
                        else
                        {
                            sInClauseFromPts += "," + iParcelIdCtrPtIdFromId1FromId2[2].ToString();
                            sInClauseFromPts += "," + iParcelIdCtrPtIdFromId1FromId2[2].ToString();
                        }
                    }

                    pQuFilter.WhereClause = sCat + " = 4 AND " + sParcelID + " IN " + sInClauseParcelIds
                                            + ") AND " + sFromPt + " IN " + sInClauseFromPts
                                            + ") AND " + sToPt + " IN " + sInClauseToPts + ")";
                    LineSelection.Target.DeleteSearchedRows(pQuFilter);
                }

                //with the new information added to the line, the rest of the parcel needs to be updated
                //regenerate the parcel using the parcel fidset

                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    = pCadEd.CadastralFabric;
                pRegenFabric.RegeneratorBitmask = 7;
                pRegenFabric.RegenerateParcels(pFIDSetForParcelRegen, false, pTrackCancel);

                //15 (enum values of 8 means remove orphan points; this only works when doing entire fabric)
                //TODO: remove orphaned center points programmatically
                pStepProgressor.MinRange    = 0;
                pStepProgressor.MaxRange    = iChangeCount;
                pStepProgressor.StepValue   = 1;
                pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral;
                pRegenFabric.RegenerateParcels(pFIDSetForParcelRegen, false, pTrackCancel);

                ArcMap.Editor.StopOperation("Change line radius");
            }
            catch (Exception ex)
            {
                ArcMap.Editor.AbortOperation();
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (pSchemaEd != null)
                {
                    pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints);
                    pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTLines);
                }
                pStepProgressor = null;
                if (!(pProgressorDialog == null))
                {
                    pProgressorDialog.HideDialog();
                }
                pProgressorDialog = null;

                RefreshMap(LineLayerArray);
                ICadastralExtensionManager pCExMan = (ICadastralExtensionManager)pCadEd;
                IParcelPropertiesWindow2   pPropW  = (IParcelPropertiesWindow2)pCExMan.ParcelPropertiesWindow;
                pPropW.RefreshAll();
                //update the TOC
                IMxDocument mxDocument = (ESRI.ArcGIS.ArcMapUI.IMxDocument)(ArcMap.Application.Document);
                for (int i = 0; i < mxDocument.ContentsViewCount; i++)
                {
                    IContentsView pCV = (IContentsView)mxDocument.get_ContentsView(i);
                    pCV.Refresh(null);
                }
            }
        }
Exemple #23
0
        protected override void OnClick()
        {
            IMouseCursor pMouseCursor = new MouseCursorClass();

            pMouseCursor.SetCursor(2);

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

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

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

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

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

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

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

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

            IArray CFParcelLayers = new ArrayClass();

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

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

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

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

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

                ICadastralSelection pCadaSel = (ICadastralSelection)pCadEd;

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

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

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

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

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

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

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

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

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

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

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

                m_pFIDSetParcels = new FIDSetClass();

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

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

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

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

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

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

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

                    ILongArray pParcelsToLock = new LongArrayClass();

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

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

                        return;
                    }
                }

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

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

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

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

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

                    AbortEdits(bUseNonVersionedDelete, pEd, pWS);

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

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

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

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

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

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

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

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

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

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

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

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

                        AbortEdits(bUseNonVersionedDelete, pEd, pWS);

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

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

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

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

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

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

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

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

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

                string TheWhereClause = "(FROMPOINTID IN (";

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

                TheWhereClause = "(TOPOINTID IN (";

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

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

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

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

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

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

                //=====

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (bUseNonVersionedDelete)
                {
                    pCadEd.CadastralFabricLayer = null;
                    CFParcelLayers   = null;
                    CFPointLayer     = null;
                    CFLineLayer      = null;
                    CFControlLayer   = null;
                    CFLinePointLayer = null;
                }
            }
        }
Exemple #24
0
        public void Execute()
        {
            try {
                // Create new spatial reference
                ISpatialReference spatialReference = null;
                if (this.SRef.ToLowerInvariant().Contains("projcs"))
                {
                    spatialReference = new ProjectedCoordinateSystemClass();
                }
                else
                {
                    spatialReference = new GeographicCoordinateSystemClass();
                }

                // Import SpatialReference Definition
                int bytes2;
                IESRISpatialReferenceGEN2 gen = (IESRISpatialReferenceGEN2)spatialReference;
                gen.ImportFromESRISpatialReference(this.SRef, out bytes2);

                // Create Search Extent
                IEnvelope extent = new EnvelopeClass();
                extent.PutCoords(this.XMin, this.YMin, this.XMax, this.YMax);
                extent.SpatialReference = spatialReference;

                // Open Saved Layer File
                ILayerFile layerFile = new LayerFileClass();
                layerFile.Open(this.Path);
                ILayer layer = layerFile.Layer;
                layerFile.Close();

                // Where clause and list of selected OIDs
                string where = string.Empty;
                List <int> ids = new List <int>();

                IImageServerLayer imageLayer = null;
                if (layer is IImageServerLayer)
                {
                    imageLayer = (IImageServerLayer)layer;

                    // Get Selection Set
                    IFeatureLayerDefinition definition = layer as IFeatureLayerDefinition;
                    if (definition != null)
                    {
                        // Find Selected OIDs
                        if (definition.DefinitionSelectionSet != null)
                        {
                            if (definition.DefinitionSelectionSet.Count > 0)
                            {
                                IEnumIDs emumids = definition.DefinitionSelectionSet.IDs;
                                int      id      = emumids.Next();
                                while (id != -1)
                                {
                                    ids.Add(id);
                                    id = emumids.Next();
                                }
                            }
                        }

                        // Update Where Clause
                        if (!string.IsNullOrEmpty(definition.DefinitionExpression))
                        {
                            where = definition.DefinitionExpression;
                        }
                    }
                }
                else if (layer is IMosaicLayer)
                {
                    IMosaicLayer mosaicLayer = (IMosaicLayer)layer;
                    imageLayer = mosaicLayer.PreviewLayer;
                    ITableDefinition tableDefinition = mosaicLayer as ITableDefinition;
                    if (tableDefinition != null)
                    {
                        // Find Selected OIDs
                        if (tableDefinition.DefinitionSelectionSet != null)
                        {
                            if (tableDefinition.DefinitionSelectionSet.Count > 0)
                            {
                                IEnumIDs emumids = tableDefinition.DefinitionSelectionSet.IDs;
                                int      id      = emumids.Next();
                                while (id != -1)
                                {
                                    ids.Add(id);
                                    id = emumids.Next();
                                }
                            }
                        }

                        // Update Where Clause
                        if (!string.IsNullOrEmpty(tableDefinition.DefinitionExpression))
                        {
                            where = tableDefinition.DefinitionExpression;
                        }
                    }
                }

                // Use FeatureSelected (if any)
                IFeatureSelection featureSelection = imageLayer as IFeatureSelection;
                if (featureSelection != null)
                {
                    if (featureSelection.SelectionSet != null)
                    {
                        if (featureSelection.SelectionSet.Count > 0)
                        {
                            IEnumIDs emumids = featureSelection.SelectionSet.IDs;
                            int      id      = emumids.Next();
                            while (id != -1)
                            {
                                ids.Add(id);
                                id = emumids.Next();
                            }
                        }
                    }
                }

                // Get Bands
                ILongArray      bands          = new LongArrayClass();
                IRasterRenderer rasterRenderer = imageLayer.Renderer;
                if (rasterRenderer != null)
                {
                    IRasterRGBRenderer2 rasterRGBRenderer = rasterRenderer as IRasterRGBRenderer2;
                    if (rasterRGBRenderer != null)
                    {
                        bands.Add(rasterRGBRenderer.UseRedBand ? rasterRGBRenderer.RedBandIndex : -1);
                        bands.Add(rasterRGBRenderer.UseGreenBand ? rasterRGBRenderer.GreenBandIndex : -1);
                        bands.Add(rasterRGBRenderer.UseBlueBand ? rasterRGBRenderer.BlueBandIndex : -1);
                        bands.Add(rasterRGBRenderer.UseAlphaBand ? rasterRGBRenderer.AlphaBandIndex : -1);
                    }
                }

                // Create Spatial Filter
                ISpatialFilter spatialFilter = new SpatialFilterClass()
                {
                    Geometry    = extent,
                    SpatialRel  = esriSpatialRelEnum.esriSpatialRelIntersects,
                    WhereClause = where
                };

                IImageServer imageServer = imageLayer.DataSource as IImageServer;
                if (imageServer == null)
                {
                    return;
                }
                IImageServer3 imageServer3 = imageServer as IImageServer3;
                if (imageServer3 == null)
                {
                    return;
                }
                IRecordSet      recordSet     = imageServer3.GetCatalogItems(spatialFilter);
                ICursor         cursor        = recordSet.get_Cursor(false);
                IFeatureCursor  featureCursor = (IFeatureCursor)cursor;
                IFeature        feature       = featureCursor.NextFeature();
                List <IFeature> list          = new List <IFeature>();

                int indexCategory = featureCursor.FindField("Category");

                while (feature != null)
                {
                    // Exclude non-primary images (no overviews)
                    if (indexCategory != -1)
                    {
                        int cat = (int)feature.get_Value(indexCategory);
                        if (cat != 1)
                        {
                            feature = featureCursor.NextFeature();
                            continue;
                        }
                    }

                    // Exclude unselected features
                    if (ids.Count > 0)
                    {
                        int oid = feature.OID;
                        if (!ids.Contains(oid))
                        {
                            feature = featureCursor.NextFeature();
                            continue;
                        }
                    }

                    list.Add(feature);
                    feature = featureCursor.NextFeature();
                }

                // If nothing, fire event then exit
                if (list.Count == 0)
                {
                    this.OnThumbnailSummary(new SummaryEventArgs());
                    return;
                }

                // Get Full Extent of Features
                SummaryEventArgs summary = new SummaryEventArgs()
                {
                    XMin  = list.Min(f => f.Shape.Envelope.CloneProject(spatialReference).XMin),
                    YMin  = list.Min(f => f.Shape.Envelope.CloneProject(spatialReference).YMin),
                    XMax  = list.Max(f => f.Shape.Envelope.CloneProject(spatialReference).XMax),
                    YMax  = list.Max(f => f.Shape.Envelope.CloneProject(spatialReference).YMax),
                    Count = list.Count
                };

                // Add Fields
                IFields fields = featureCursor.Fields;
                for (int i = 0; i < fields.FieldCount; i++)
                {
                    IField field = fields.get_Field(i);
                    switch (field.Type)
                    {
                    case esriFieldType.esriFieldTypeBlob:
                    case esriFieldType.esriFieldTypeGeometry:
                    case esriFieldType.esriFieldTypeGlobalID:
                    case esriFieldType.esriFieldTypeGUID:
                    case esriFieldType.esriFieldTypeRaster:
                    case esriFieldType.esriFieldTypeXML:
                        break;

                    case esriFieldType.esriFieldTypeOID:
                    case esriFieldType.esriFieldTypeDate:
                    case esriFieldType.esriFieldTypeDouble:
                    case esriFieldType.esriFieldTypeInteger:
                    case esriFieldType.esriFieldTypeSingle:
                    case esriFieldType.esriFieldTypeSmallInteger:
                    case esriFieldType.esriFieldTypeString:
                        summary.Fields.Add(
                            new Field()
                        {
                            Name  = field.Name,
                            Alias = field.AliasName,
                            Type  = field.Type
                        }
                            );
                        break;

                    default:
                        break;
                    }
                }

                // Raise Summary Event
                this.OnThumbnailSummary(summary);

                // Loop for each feature
                foreach (IFeature feat in list)
                {
                    // Project Extent to Current Map Spatial Reference
                    IEnvelope extentMap = feat.Shape.Envelope.CloneProject(spatialReference);

                    int width;
                    int height;
                    if (extentMap.Width > extentMap.Height)
                    {
                        width  = this.MaxImageSize;
                        height = Convert.ToInt32((double)this.MaxImageSize * (double)extentMap.Height / (double)extentMap.Width);
                    }
                    else
                    {
                        width  = Convert.ToInt32((double)this.MaxImageSize * (double)extentMap.Width / (double)extentMap.Height);
                        height = this.MaxImageSize;
                    }

                    IMosaicRule mosaicRule = new MosaicRuleClass()
                    {
                        MosaicMethod = esriMosaicMethod.esriMosaicLockRaster,
                        LockRasterID = feat.OID.ToString()
                    };
                    IGeoImageDescription geoImageDescription = new GeoImageDescriptionClass()
                    {
                        BandSelection    = bands.Count > 0 ? bands : null,
                        MosaicRule       = mosaicRule,
                        Compression      = "PNG",
                        Width            = width,
                        Height           = height,
                        SpatialReference = spatialReference,
                        Extent           = extentMap,
                        Interpolation    = rstResamplingTypes.RSP_BilinearInterpolation,
                    };

                    // Assembly MosaicRequest (will be executed in background thread)
                    MosaicRequest mosaicRequest = new MosaicRequest()
                    {
                        MosaicExtractor     = this,
                        ImageServer         = imageServer3,
                        GeoImageDescription = geoImageDescription,
                        XMin = extentMap.XMin,
                        YMin = extentMap.YMin,
                        XMax = extentMap.XMax,
                        YMax = extentMap.YMax,
                    };

                    // Add Attributes Names and Values
                    foreach (Field field in summary.Fields)
                    {
                        int index = feat.Fields.FindField(field.Name);
                        if (index < 0)
                        {
                            continue;
                        }
                        mosaicRequest.Attributes.Add(field.Name, feat.get_Value(index));
                    }

                    // Start Mosaic Request in Background Thread
                    Thread thread = new Thread(new ThreadStart(mosaicRequest.Execute));
                    MosaicEnvironment.Default.Threads.Add(thread);
                    thread.Start();
                }
            }
            catch { }
        }
Exemple #25
0
        private void btnExecute_Click(object sender, EventArgs e)
        {
            string rstNm = txtOutNm.Text;

            if (rstNm == null || rstNm == "")
            {
                MessageBox.Show("You must specify a output name", "No Output", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (clbBands.CheckedItems.Count < 1)
            {
                MessageBox.Show("You must check at least on Raster Band", "No Bands", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            ILongArray lArr = new LongArrayClass();

            for (int i = 0; i < clbBands.CheckedItems.Count; i++)
            {
                string bandVl   = clbBands.CheckedItems[i].ToString();
                int    bndIndex = System.Convert.ToInt32(bandVl.Split(new char[] { '_' })[1]) - 1;
                lArr.Add(bndIndex);
            }
            this.Visible = false;
            esriUtil.Forms.RunningProcess.frmRunningProcessDialog rp = new RunningProcess.frmRunningProcessDialog(false);
            DateTime dt = DateTime.Now;

            rp.addMessage("Extracting Bands From  Raster. This may take a while...");
            rp.stepPGBar(10);
            rp.TopMost = true;
            rp.Show();
            try
            {
                outraster = rsUtil.returnRaster(rsUtil.getBands(rstDic[cmbInRaster1.Text], lArr));
                if (mp != null && addToMap)
                {
                    rp.addMessage("Calculating Statistics...");

                    rp.Refresh();
                    IRasterLayer rstLyr = new RasterLayerClass();
                    //rsUtil.calcStatsAndHist(((IRaster2)outraster).RasterDataset);
                    rstLyr.CreateFromRaster(outraster);
                    rstLyr.Name    = rstNm;
                    rstLyr.Visible = false;
                    mp.AddLayer(rstLyr);
                }
                outrastername     = rstNm;
                this.DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                rp.addMessage(ex.ToString());
            }
            finally
            {
                DateTime dt2 = DateTime.Now;
                TimeSpan ts  = dt2.Subtract(dt);
                string   t   = " in " + ts.Days.ToString() + " days " + ts.Hours.ToString() + " hours " + ts.Minutes.ToString() + " minutes and " + ts.Seconds.ToString() + " seconds .";
                rp.stepPGBar(100);
                rp.addMessage("Finished Extacting Bands" + t);
                rp.enableClose();
                this.Close();
            }
        }
		public static Dictionary<string, ILongArray> GetOIDArraysBySourceNameFromMapSelection(IMap map, List<string> sourceNames)
		{
			UIDClass uid = new UIDClass();
			uid.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}"; //IGeoFeatureLayer

			IEnumLayer searchEnumLayer = map.get_Layers(uid, true);
			searchEnumLayer.Reset();

			//create result dictionary from source names with empty oidArrays

			Dictionary<string, ILongArray> oidArraysBySourceName = new Dictionary<string, ILongArray>();
			ILongArray oidArray = null;

			foreach (string sourceName in sourceNames)
			{
				if (!oidArraysBySourceName.TryGetValue(sourceName, out oidArray))
				{
					oidArray = new LongArrayClass();
					oidArraysBySourceName.Add(sourceName, oidArray);
				}
			}

			ILayer layer = searchEnumLayer.Next();
			while (layer != null)
			{
				IDisplayTable displayTable = layer as IDisplayTable;
				string sourceName = "";
				if (layer.Valid && layer.Visible && displayTable != null)
				{
					IDataset ds = displayTable.DisplayTable as IDataset;
					if (ds != null)
						sourceName = ds.Name;
				}

				if (sourceName.Length > 0)
				{
					if (oidArraysBySourceName.TryGetValue(sourceName, out oidArray))
					{
						ISelectionSet selSet = displayTable.DisplaySelectionSet;
						IEnumIDs enumOIDs = null;
						if (selSet != null)
							enumOIDs = selSet.IDs;

						if (enumOIDs != null)
						{
							enumOIDs.Reset();
							int oid = enumOIDs.Next();
							while (oid != -1)
							{
								oidArray.Add(oid);
								oid = enumOIDs.Next();
							}
						}
					}
				}

				layer = searchEnumLayer.Next();
			}

			return oidArraysBySourceName;
		}
        static void Main(string[] args)
        {
            ESRI.ArcGIS.esriSystem.AoInitialize aoInit;

            #region Initialize License
            try
            {
                Console.WriteLine("Obtaining license");
                ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);
                aoInit = new AoInitializeClass();
                esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeBasic);
                Console.WriteLine("Ready with license.");
            }
            catch (Exception exc)
            {
                // If it fails at this point, shutdown the test and ignore any subsequent errors.
                Console.WriteLine(exc.Message);
                return;
            }
            #endregion

            try
            {
                #region Specify input directory and dataset name
                // The directory which contains the Panchromatic Image.
                string panDir = @"C:\Data\QB\Pan";
                // The directory which contains the Multispectral Image.
                string rgbDir = @"C:\Data\QB\MS";
                
                string panImageName = "05JAN27104436-P1BS-005533787010_01_P002.TIF";
                string rgbImageName = "05JAN27104436-M1BS-005533787010_01_P002.TIF";

                // Output filename.
                string outputDataset = @"c:\Temp\QBTemplateCS.afr";
                #endregion

                #region Initialize
                // Setup Workspaces.
                Type factoryType = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory");
                IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
                IRasterWorkspace panRasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(panDir, 0);
                IRasterWorkspace rgbRasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(rgbDir, 0);

                // Open Datasets
                IRasterDataset panDataset = panRasterWorkspace.OpenRasterDataset(panImageName);
                IRasterDataset rgbDataset = rgbRasterWorkspace.OpenRasterDataset(rgbImageName);
                #endregion

                #region Create Variables
                // Create one variable of type IRasterFunctionVariable for each 
                // Raster Dataset opened above
                
                // Create a new Raster Function Variable
                IRasterFunctionVariable panVar = new RasterFunctionVariableClass();
                // Set the name of the variable
                panVar.Name = "panImage";
                // Describe the variable
                panVar.Description = "Panchromatic Image to be used for pansharpening";
                // Specify whether it represents a dataset
                panVar.IsDataset = true;

                // Create a new Raster Function Variable
                IRasterFunctionVariable rgbVar = new RasterFunctionVariableClass();
                // Set the name of the variable
                rgbVar.Name = "rgbImage";
                // Describe the variable
                rgbVar.Description = "Multispectral Image to be used for pansharpening";
                // Specify whether it represents a dataset
                rgbVar.IsDataset = true;
                #endregion

                #region Prepare the Pan Image
                // Setup statistics for each band
                IArray statsArrayPan = new ArrayClass();
                IRasterStatistics statsPanBand = new RasterStatisticsClass();
                statsPanBand.Minimum = 1;
                statsPanBand.Maximum = 2047;
                statsArrayPan.Add(statsPanBand);
                // Create the arguments object for the stretching function
                IStretchFunctionArguments stretchingPanFunctionArguements = new StretchFunctionArgumentsClass();
                // Set the stretching type
                stretchingPanFunctionArguements.StretchType =
                    esriRasterStretchType.esriRasterStretchMinimumMaximum;
                // Set the statistics created above
                stretchingPanFunctionArguements.Statistics = statsArrayPan;
                // Set the input raster, in this case, the variable for the Pan Image
                stretchingPanFunctionArguements.Raster = panVar;

                // Create the function object to stretch the Pan Image.
                IRasterFunction stretchingPanFunction = new StretchFunction();

                // Create a Raster Function Template object for the stretch function
                IRasterFunctionTemplate stretchingPanFunctionT = new RasterFunctionTemplateClass();
                // Set the function on the template
                stretchingPanFunctionT.Function = (IRasterFunction)stretchingPanFunction;
                // Set the arguments for the function
                stretchingPanFunctionT.Arguments = stretchingPanFunctionArguements;
                #endregion

                #region Prepare the Multispectral (RGB) Image
                // Create an array which defines the order of bands
                ILongArray bandIDs = new LongArrayClass();
                bandIDs.Add(2);
                bandIDs.Add(1);
                bandIDs.Add(0);
                // Create an Extract Band Function Arguments object
                IExtractBandFunctionArguments extractRgbBandFunctionArgs = (IExtractBandFunctionArguments)
                    new ExtractBandFunctionArguments();
                // Set the order of bands of the output
                extractRgbBandFunctionArgs.BandIDs = bandIDs;
                // Set the input raster, in this case the variable for the Multispectral Image
                extractRgbBandFunctionArgs.Raster = rgbVar;

                // Create the Extract Band Function object
                IRasterFunction extractRgbBandFunction = new ExtractBandFunction();

                // Create a Raster Function Template object for the function created above
                IRasterFunctionTemplate extractRgbBandFunctionT = new RasterFunctionTemplateClass();
                // Set the function on the template
                extractRgbBandFunctionT.Function = (IRasterFunction)extractRgbBandFunction;
                // Set the arguments for the function
                extractRgbBandFunctionT.Arguments = extractRgbBandFunctionArgs;

                // Setup statistics for each band
                IArray statsArray = new ArrayClass();
                IRasterStatistics statsMulBand1 = new RasterStatisticsClass();
                statsMulBand1.Minimum = 100;
                statsMulBand1.Maximum = 1721;
                statsArray.Add(statsMulBand1);
                IRasterStatistics statsMulBand2 = new RasterStatisticsClass();
                statsMulBand2.Minimum = 95;
                statsMulBand2.Maximum = 2047;
                statsArray.Add(statsMulBand2);
                IRasterStatistics statsMulBand3 = new RasterStatisticsClass();
                statsMulBand3.Minimum = 34;
                statsMulBand3.Maximum = 2006;
                statsArray.Add(statsMulBand3);

                // Create a stretching function for the multispectral image
                IRasterFunction stretchingRGBFunction = new StretchFunction();
                // Create an arguments object for the stretch function
                IStretchFunctionArguments stretchingRGBFunctionArguments = 
                    new StretchFunctionArgumentsClass();
                // Set the type of stretchings to perform
                stretchingRGBFunctionArguments.StretchType =
                    esriRasterStretchType.esriRasterStretchMinimumMaximum;
                // Set the statistics created above
                stretchingRGBFunctionArguments.Statistics = statsArray;
                // Set the extract band function template created above as the input
                stretchingRGBFunctionArguments.Raster = extractRgbBandFunctionT;

                // Create a Raster Function Template object for the function created above
                IRasterFunctionTemplate stretchingRGBFunctionT = new RasterFunctionTemplateClass();
                // Set the function on the template
                stretchingRGBFunctionT.Function = (IRasterFunction)stretchingRGBFunction;
                // Set the arguments for the function
                stretchingRGBFunctionT.Arguments = stretchingRGBFunctionArguments;
                #endregion

                #region Pansharpen the Pan Image with the Multispectral
                // Create a Raster Function Arguments object for the pansharpen function
                IPansharpeningFunctionArguments pansharpFunctionArguements = 
                    new PansharpeningFunctionArgumentsClass();
                // Set the Panchromatic image which has been prepared above
                pansharpFunctionArguements.PanImage = stretchingPanFunctionT;
                // Set the Multispectral image which has been prepared above
                pansharpFunctionArguements.MSImage = stretchingRGBFunctionT;

                // Create a new pansharpen raster function object
                IRasterFunction pansharpenFunction = new PansharpeningFunction();
                // Create a new pansharpen function arguments object
                IPansharpeningFunctionArguments pansharpenFunctionArguements = 
                    new PansharpeningFunctionArgumentsClass();
                // Set the pansharpening type
                pansharpenFunctionArguements.PansharpeningType = 
                    esriPansharpeningType.esriPansharpeningESRI;
                // Create an array of doubles that sets the weights for each band
                IDoubleArray weightsArray = new DoubleArrayClass();
                weightsArray.Add(0.167);
                weightsArray.Add(0.166);
                weightsArray.Add(0.166);
                // and set it on the arguments object
                pansharpenFunctionArguements.Weights = weightsArray;

                // Create a Raster Function Template object for the pansharpen function
                IRasterFunctionTemplate rasterFunction = new RasterFunctionTemplateClass();
                rasterFunction.Function = (IRasterFunction)pansharpenFunction;
                rasterFunction.Arguments = pansharpFunctionArguements;
                ((IRasterFunction)rasterFunction).PixelType = rstPixelType.PT_UCHAR;
                #endregion

                #region Resolve variables
                // Create a PropertySet object to set the values for the 
                // Raster Function Variables created above
                IPropertySet variables = new PropertySet();
                variables.SetProperty("panImage", panDataset);
                variables.SetProperty("rgbImage", rgbDataset);
                #endregion

                #region Create the Function Raster Dataset
                // Create the Function Raster Dataset Object for the Pansharpened Dataset
                IFunctionRasterDataset functionRasterDataset = new FunctionRasterDataset();
                // Create a name object for the Function Raster Dataset.
                IFunctionRasterDatasetName functionRasterDatasetName =
                    new FunctionRasterDatasetNameClass();
                // Specify the output filename for the new dataset (including 
                // the .afr extension at the end).
                functionRasterDatasetName.FullName = outputDataset;
                functionRasterDataset.FullName = (IName)functionRasterDatasetName;
                // Initialize the new Function Raster Dataset with the Raster Function 
                // Template and the property set containing the variables and their values.
                functionRasterDataset.Init((IRasterFunction)rasterFunction, variables);

                ITemporaryDataset myTempDset = (ITemporaryDataset)functionRasterDataset;
                myTempDset.MakePermanent();
                #endregion

                #region Shutdown
                Console.WriteLine("Success.");
                Console.WriteLine("Press any key...");
                Console.ReadKey();

                // Shutdown License
                aoInit.Shutdown();
                #endregion
            }
            catch (Exception exc)
            {
                #region Shutdown
                Console.WriteLine("Exception Caught while creating Function Raster Dataset. " + exc.Message);
                Console.WriteLine("Failed.");
                Console.WriteLine("Press any key...");
                Console.ReadKey();

                // Shutdown License
                aoInit.Shutdown();
                #endregion
            }        
        }
Exemple #28
0
        /*
         * This method executes a utility network trace to find all the low voltage service points
         * serviced by the specified transformer and returns the service points global IDs
         */
        private IStringArray FindLVServicePoints(string xfrGlobalID)
        {
            //Get required Utility Network interfaces
            IBaseNetwork      unBaseNetwork    = (IBaseNetwork)unDataset;
            IDatasetComponent datasetComponent = (IDatasetComponent)unDataset;
            IDEDataset        deDataset        = datasetComponent.DataElement;
            IDEBaseNetwork    deBaseNetwork    = (IDEBaseNetwork)deDataset;
            IDEUtilityNetwork deUtilityNetwork = (IDEUtilityNetwork)deBaseNetwork;
            IDataElement      deElement        = (IDataElement)deDataset;

            //Create and initialize network tracer
            IUtilityNetworkQuery unQry = unBaseNetwork.CreateQuery();
            ITracer unTracer           = unBaseNetwork.CreateTracer();

            unTracer.Initialize(unQry, (IDataElement)deDataset);

            // Add transformer as trace starting point
            IStringArray startGUID = new StrArrayClass();

            startGUID.Add(xfrGlobalID);
            ILongArray startTerm = new LongArrayClass();

            startTerm.Add(MV_XFR_TERMINAL_ID);

            unTracer.AddTraceLocationForJunctionFeatures(esriTraceLocationType.esriTLTStartingPoint, startGUID, startTerm);

            // Configure trace parameters
            UNTraceConfiguration traceConfig = new UNTraceConfiguration();

            traceConfig.IgnoreBarriersAtStartingPoints = true;
            traceConfig.IncludeContainers = false;
            traceConfig.IncludeBarriers   = false;
            traceConfig.IncludeContent    = true;
            traceConfig.IncludeIsolated   = false;
            traceConfig.IncludeStructures = false;
            traceConfig.IncludeUpToFirstSpatialContainer = false;
            traceConfig.DomainNetworkName   = DOMAIN_NETWORK;
            traceConfig.TierName            = MV_TIER_NAME;
            traceConfig.TargetTierName      = MV_TIER_NAME;
            traceConfig.TraversabilityScope = esriTraversabilityScope.esriTSJunctionsAndEdges;
            traceConfig.FilterScope         = esriTraversabilityScope.esriTSJunctionsAndEdges;
            traceConfig.ValidateConsistency = false;

            // Add output filter to only return service points
            IArray outFilters = new ArrayClass();

            for (int i = 0; i < LV_SERVICE_ASSETTYPES.Length; i++)
            {
                UNOutputFilter outFilter = new UNOutputFilter();
                outFilter.NetworkSourceID = DEVICE_SOURCE_ID;
                outFilter.AssetGroupCode  = LV_SERVICE_ASSETGROUP;
                outFilter.AssetTypeCode   = LV_SERVICE_ASSETTYPES[i];
                outFilters.Add(outFilter);
            }
            traceConfig.OutputFilters = outFilters;

            unTracer.TraceConfiguration = (ITraceConfiguration)traceConfig;

            // Execute the trace
            long[] jEid = new long[1];
            long[] eEid = new long[1];

            unTracer.Trace(esriUtilityNetworkTraceType.esriUNTTDownstream, out jEid, out eEid);

            // Get features from returned elements
            IUNTraceResults unTraceResults = (IUNTraceResults)unTracer;

            ILongArray   junctionNetworkSourceIDs = new LongArrayClass();
            IStringArray junctionGlobalIDs        = new StrArrayClass();
            ILongArray   junctionObjectIDs        = new LongArrayClass();
            ILongArray   junctionTerminalIDs      = new LongArrayClass();
            ILongArray   junctionAssetGroupCodes  = new LongArrayClass();
            ILongArray   junctionAssetTypeCodes   = new LongArrayClass();
            ILongArray   edgeNetworkSourceIDs     = new LongArrayClass();
            IStringArray edgeGlobalIDs            = new StrArrayClass();
            ILongArray   edgeObjectIDs            = new LongArrayClass();
            ILongArray   edgeAssetGroupCodes      = new LongArrayClass();
            ILongArray   edgeAssetTypeCodes       = new LongArrayClass();

            unTraceResults.TraceResultFeatures(out junctionNetworkSourceIDs, out junctionGlobalIDs, out junctionObjectIDs, out junctionTerminalIDs, out junctionAssetGroupCodes, out junctionAssetTypeCodes, out edgeNetworkSourceIDs, out edgeGlobalIDs, out edgeObjectIDs, out edgeAssetGroupCodes, out edgeAssetTypeCodes);

            return(junctionGlobalIDs);
        }
 /// <summary>
 /// retrieves a IRaster for a given a raster band
 /// </summary>
 /// <param name="inRaster">template raster</param>
 /// <param name="index">band index zero based</param>
 /// <returns></returns>
 public IFunctionRasterDataset getBand(object inRaster, int index)
 {
     ILongArray lArr = new LongArrayClass();
     lArr.Add(index);
     return getBands(inRaster, lArr);
 }