Пример #1
0
 public void end()
 {
     IStepProgressor step = (IStepProgressor)dialog;
     step.StepValue = max;
     dialog.HideDialog();
     dialog = null;
 }
Пример #2
0
        public ProgressDialog(bool a_EnableCancel, int a_MinValue, int a_MaxValue, string a_Title,
                              string a_Description)
        {
            var a_ProgressDialogFactory = new ProgressDialogFactoryClass();

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

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

            m_ProgressDialog.CancelEnabled = a_EnableCancel;
            m_ProgressDialog.Title         = a_Title;
            m_ProgressDialog.Description   = a_Description;
            m_ProgressDialog.Animation     = esriProgressAnimationTypes.esriProgressSpiral;
        }
Пример #3
0
        private void btnProcesar_Click_1(object sender, EventArgs e)
        {
            statusLblProcesando.Text = "Procesando datos...";

            IProgressDialogFactory pProDiaFac = new ProgressDialogFactoryClass();
            IStepProgressor        pStepPro   = pProDiaFac.Create(null, 0);

            pStepPro.MinRange  = 1;
            pStepPro.MaxRange  = 5;
            pStepPro.StepValue = 1;
            IProgressDialog2 pProDia = (IProgressDialog2)pStepPro;

            pProDia.Animation = esriProgressAnimationTypes.esriProgressGlobe;

            pProDia.Title = "Incorporando Lecturas";
            pProDia.ShowDialog();
            pStepPro.Step();
            pStepPro.Message = "Procesando precipitacion...";


            ProcesarLecturas procesarLecturas = new ProcesarLecturas();

            try
            {
                procesarLecturas.CalcularResultadosPrecipitacion(_sigpiDao, "DEFI_PRECI", "LECTUS_PRECI", dtPickerFechaAProcesar.Value, 10);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error procesando las lecturas:\n" + ex.Message);
            }

            pStepPro.Step();
            pStepPro.Message = "Procesando Temperatura...";
            try
            {
                procesarLecturas.CalcularResultadosTemperatura(_sigpiDao, "DEFI_TEMPE", "LECTUS_TEMPE", dtPickerFechaAProcesar.Value, "T5", 10);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error procesando las lecturas:\n" + ex.Message);
            }

            string sSQL = "UPDATE FECHAS_PROCESO SET FEC_PROCE = #" + dtPickerFechaAProcesar.Value.ToString("MM/dd/yyyy") + "#";

            try
            {
                _sigpiDao.EjecutarSentenciaSinQuery(sSQL);
            }
            catch (Exception ex)
            {
                MessageBox.Show("No se pudo actualizar la fecha de incorporacion.\n" + ex.Message);
            }
            _sigpi.FechaProcesamiento  = dtPickerFechaAProcesar.Value;
            txtUltimaFechaProceso.Text = dtPickerFechaAProcesar.Value.ToLongDateString();

            pProDia.HideDialog();
            MessageBox.Show("Datos Procesados");
        }
Пример #4
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="ProgressBarAnimation" /> class.
        /// </summary>
        /// <param name="animationType">Type of the animation.</param>
        /// <param name="application">The application.</param>
        /// <param name="trackCancel">The track cancel.</param>
        public ProgressDialogAnimation(IApplication application, esriProgressAnimationTypes animationType, ITrackCancel trackCancel)
            : base(application)
        {
            _Dialog      = (IProgressDialog2)(new ProgressDialogFactoryClass()).Create(trackCancel, application.hWnd);
            _TrackCancel = trackCancel;

            this.AnimationType = animationType;
            this.ProgressBar   = (IStepProgressor)_Dialog;
        }
Пример #5
0
        private void button4_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            DateTime fechaProcesamiento = sigpi.FechaProcesamiento;

            IWorkspaceFactory pWF        = new RasterWorkspaceFactoryClass();
            IWorkspace        pWorkspace = pWF.OpenFromFile(sigpi.Parametros.RutaSIGPI + "\\" + sigpi.Parametros.Raster, 0);

            IEnumDataset  pEnumDS = pWorkspace.get_Datasets(esriDatasetType.esriDTRasterDataset);
            IDataset      pDS     = pEnumDS.Next();
            List <string> capas   = new List <string>();

            while (pDS != null)
            {
                if (!pDS.Name.ToUpper().Contains("RASTER"))
                {
                    capas.Add(pDS.Name.ToUpper());
                }
                pDS = pEnumDS.Next();
            }

            FrmProbabilidadCalculada frmProbabilidad = new FrmProbabilidadCalculada(capas.ToArray());

            this.Cursor = Cursors.Default;
            if (frmProbabilidad.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            int iNumDias = frmProbabilidad.NumeroDeDias;

            IProgressDialogFactory pProDiaFac = new ProgressDialogFactoryClass();
            IStepProgressor        pStepPro   = pProDiaFac.Create(null, 0);

            pStepPro.MinRange  = 1;
            pStepPro.MaxRange  = 2;
            pStepPro.StepValue = 1;
            IProgressDialog2 pProDia = (IProgressDialog2)pStepPro;

            pProDia.Animation = esriProgressAnimationTypes.esriProgressGlobe;

            pProDia.Title = "Calcular Probabilidad";
            pProDia.ShowDialog();
            pStepPro.Step();
            pStepPro.Message = "Calculando Probabilidad...";
            try
            {
                procesamiento.ProbabilidadCalculada(frmProbabilidad.ModeloBase, iNumDias, sigpi, frmProbabilidad.OpcionDeGuardar);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            pProDia.HideDialog();
            MessageBox.Show("Se ha calculado el modelo y la probabilidad para el dia:\n" + sigpi.FechaProcesamiento);
            txtFechaUltimoModelo.Text = sigpi.FechaProcesamiento.ToLongDateString();
        }
Пример #6
0
        private void CloneFileList()
        {
            bool itWorked = false;



            int                    cloneCount            = 1; // labeling the processor bar
            ITrackCancel           trackcancel           = new CancelTracker();
            IProgressDialogFactory progressdialogfactory = new ProgressDialogFactoryClass();
            IStepProgressor        stepprogressor        = progressdialogfactory.Create(trackcancel, _application.hWnd);

            stepprogressor.MinRange  = 0;
            stepprogressor.MaxRange  = _fileList.Count;
            stepprogressor.StepValue = 1;
            stepprogressor.Message   = "Copying...";
            IProgressDialog2 progressdialog = (IProgressDialog2)stepprogressor; // Creates and displays

            progressdialog.CancelEnabled = false;
            progressdialog.Description   = "Copying {_fileList.Count} files...";
            progressdialog.Title         = MB_TITLE;
            progressdialog.Animation     = esriProgressAnimationTypes.esriProgressSpiral;


            foreach (KeyValuePair <String, Boolean> file in _fileList)
            {
                if (file.Value)
                {
                    progressdialog.Description = string.Format("Copying File {0} of {1}...", cloneCount, _fileList.Count);
                    if (!itWorked)
                    {
                        SaveFileTypeList(GetExtension());
                    }
                    itWorked = true;

                    try
                    {
                        var sourceFile      = txb_FileWorkspaceSrc.Text + @"\" + Utilities_General.AddPrefixAndSuffixToFileName(file.Key, txb_Prefix.Text, txb_Suffix.Text) + GetExtension();
                        var destinationFile = txb_FileWorkspaceDst.Text + @"\" + Utilities_General.AddPrefixAndSuffixToFileName(file.Key, txb_Prefix.Text, txb_Suffix.Text) + GetExtension();

                        System.IO.File.Copy(sourceFile, destinationFile);
                    }
                    catch (Exception yourBest) // but you don't succeed
                    {
                        yourBest.ToString();
                        // Just So We Get No Crashes ;)
                    }
                    stepprogressor.Step();
                    cloneCount++;
                }
            }
            trackcancel    = null;
            stepprogressor = null;
            progressdialog.HideDialog();
            progressdialog = null;
            //_activeView.Refresh();
        }
        private void Cleanup(IProgressDialog2 ProgressorDialog, IMouseCursor MouseCursor)
        {
            MouseCursor.SetCursor(0);

            if (!(ProgressorDialog == null))
            {
                ProgressorDialog.HideDialog();
            }
            ProgressorDialog  = null;
            m_pStepProgressor = null;
        }
Пример #8
0
        /// <summary>Exports all bookmarks to PDF files.</summary>
        /// <param name="directory">The directory that the exported files will be written to.</param>
        /// <param name="dpi">The resolution of the output files.</param>
        /// <param name="exportFormat">The format of the exported files.</param>
        public void ExportBookmarksToFiles(string directory, long dpi, ExportFormat exportFormat)
        {
            if (!Directory.Exists(directory))
            {
                throw new DirectoryNotFoundException("Directory not found: " + directory);
            }
            IMouseCursor mc        = new MouseCursorClass();
            const int    hourglass = 2;

            mc.SetCursor(hourglass);

            IMxDocument   mxDoc     = _app.Document as IMxDocument;
            IMapBookmarks bookmarks = (IMapBookmarks)mxDoc.FocusMap;

            IEnumSpatialBookmark enumBM = bookmarks.Bookmarks;

            enumBM.Reset();
            ISpatialBookmark sbm = enumBM.Next();


            ProgressDialogFactoryClass dialogFactory = new ProgressDialogFactoryClass();
            var              cancelTracker           = new CancelTrackerClass();
            IStepProgressor  stepProgressor          = dialogFactory.Create(cancelTracker, _app.hWnd);
            IProgressDialog2 progDialog = stepProgressor as IProgressDialog2;

            progDialog.CancelEnabled = true;

            progDialog.ShowDialog();
            stepProgressor.Hide();
            stepProgressor.Message = "Exporting...";

            // Create a formatting string with the proper extension.  (E.g., "{0}.pdf" for PDF files".)
            string fnFmt = string.Format("{{0}}.{0}", Enum.GetName(typeof(ExportFormat), exportFormat));

            try
            {
                while (sbm != null)
                {
                    sbm.ZoomTo(mxDoc.FocusMap);
                    string filename = System.IO.Path.Combine(directory, string.Format(fnFmt, sbm.Name));
                    ExportPageLayoutToFile(mxDoc.PageLayout, filename, dpi, exportFormat);
                    sbm = enumBM.Next();
                }
            }
            finally
            {
                if (progDialog != null)
                {
                    progDialog.HideDialog();
                    ComReleaser.ReleaseCOMObject(progDialog);
                }
            }
        }
Пример #9
0
        private void AutoSave_Save()
        {
            if (!CheckRequirements())
            {
                return;
            }
            if (!IsSaveable())
            {
                return;
            }

            ITrackCancel           trackcancel           = new CancelTrackerClass();
            IProgressDialogFactory progressdialogfactory = new ProgressDialogFactoryClass();
            IStepProgressor        stepprogressor        = progressdialogfactory.Create(trackcancel, _application.hWnd);

            stepprogressor.MinRange  = 0;
            stepprogressor.MaxRange  = 1;
            stepprogressor.StepValue = 1;
            stepprogressor.Message   = "Saving...";
            IProgressDialog2 progressdialog = (IProgressDialog2)stepprogressor; // Creates and displays

            progressdialog.CancelEnabled = true;
            progressdialog.Description   = "Saving...";
            progressdialog.Title         = "Saving...";
            progressdialog.Animation     = esriProgressAnimationTypes.esriDownloadFile;
            try
            {
                ILayer        layer        = _utilitiesArcmap.Layer(this.cboTargetLayer.Text);
                IFeatureLayer featurelayer = layer as IFeatureLayer;

                if (!(featurelayer == null))
                {
                    IFeatureClass   featureclass  = featurelayer.FeatureClass;
                    IWorkspace2     workspace     = ((IDataset)featureclass).Workspace as IWorkspace2;
                    IWorkspaceEdit2 workspaceedit = (IWorkspaceEdit2)workspace;
                    workspaceedit.StopEditing(true);
                    workspaceedit.StartEditing(true);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ABE Calculators", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            finally
            {
                trackcancel    = null;
                stepprogressor = null;
                progressdialog.HideDialog();
                progressdialog        = null;
                this.btnClose.Enabled = true;
            }
        }
Пример #10
0
        public IFIDSet AppendCadastralXML(ICadastralFabric Fabric, ICadastralJob CadastralJob, IProjectedCoordinateSystem TargetProjectedCoordinateSystem, string CadastralXMLPath)
        {
            try
            {
                string sTempPath = System.IO.Path.GetTempPath();
                string sCopiedCadastralXMLFile = System.IO.Path.Combine(sTempPath, CadastralJob.Name.Replace('/', '_').Replace(':', '_') + ".xml");

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

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

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

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



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

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

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

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

                return(pFIDSet);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(null);
            }
        }
Пример #11
0
        /// <summary>
        /// Occurs when this command is clicked
        /// </summary>
        public override void OnClick()
        {
            MgSettings MS = new MgSettings();

            if (!Directory.Exists(MS.RootDir))
            {
                MS.RootDir = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            }
            if (!Directory.Exists(MS.OutDir))
            {
                MS.OutDir = MS.RootDir;
            }
            MS.Save();

            MainForm M = new MainForm();

            if (M.ShowDialog() == DialogResult.OK)
            {
                MergeFunc MF = new MergeFunc(M.RootDir, M.Filename, M.OutDir);
                TM = new System.Windows.Forms.Timer();
                SW.Reset();

                Geoprocessor GP = new Geoprocessor()
                {
                    AddOutputsToMap = M.AddOutputsToMap,
                    OverwriteOutput = M.OverwriteOutput
                };

                GP.ToolExecuting += GP_ToolExecuting;
                GP.ToolExecuted  += GP_ToolExecuted;
                TM.Tick          += TM_Tick;

                ITrackCancel           pTrackCancel    = new CancelTrackerClass();
                IProgressDialogFactory pProgDlgFactory = new ProgressDialogFactoryClass();
                pProDlg = pProgDlgFactory.Create(pTrackCancel, m_application.hWnd) as IProgressDialog2;
                pProDlg.CancelEnabled = true;
                pProDlg.Title         = "Merge in progress...";
                pProDlg.Description   = "Please wait patiently...";
                pProDlg.Animation     = esriProgressAnimationTypes.esriProgressSpiral;

                pStepPro           = pProDlg as IStepProgressor;
                pStepPro.MinRange  = 0;
                pStepPro.MaxRange  = 100;
                pStepPro.StepValue = 1;
                pStepPro.Message   = "Initiating...";

                GP.Execute(MF.GetMerge(), pTrackCancel);
            }
            M.Dispose();
        }
Пример #12
0
        public void start(string title)
        {
            IProgressDialogFactory fact = new ProgressDialogFactory();
            dialog = (IProgressDialog2)fact.Create(new CancelTracker(),this.app.hWnd);

            dialog.Animation = esriProgressAnimationTypes.esriProgressGlobe;
            dialog.CancelEnabled = false;
            dialog.Title = title;

            IStepProgressor step = (IStepProgressor)dialog;
            step.MinRange = 1;
            step.MaxRange = max;
            step.StepValue = 1;
        }
Пример #13
0
        private void ValidateFileList()
        {
            int                    cloneCount            = 1; // labeling the processor bar
            ITrackCancel           trackcancel           = new CancelTracker();
            IProgressDialogFactory progressdialogfactory = new ProgressDialogFactoryClass();
            IStepProgressor        stepprogressor        = progressdialogfactory.Create(trackcancel, _application.hWnd);

            stepprogressor.MinRange  = 0;
            stepprogressor.MaxRange  = _fileList.Count;
            stepprogressor.StepValue = 1;
            stepprogressor.Message   = "Validating...";
            IProgressDialog2 progressdialog = (IProgressDialog2)stepprogressor; // Creates and displays

            progressdialog.CancelEnabled = false;
            progressdialog.Description   = "Validating {_fileList.Count} files...";
            progressdialog.Title         = MB_TITLE;
            progressdialog.Animation     = esriProgressAnimationTypes.esriProgressSpiral;



            IDictionary <String, Boolean> newList = new Dictionary <String, Boolean>();

            foreach (KeyValuePair <String, Boolean> file in _fileList)
            {
                progressdialog.Description = string.Format("Validating {0} of {1}...", cloneCount, _fileList.Count);
                string filePath = txb_FileWorkspaceSrc.Text + "\\" + Utilities_General.AddPrefixAndSuffixToFileName(file.Key, txb_Prefix.Text, txb_Suffix.Text) + GetExtension();
                if (!File.Exists(filePath))
                {
                    newList.Add(file.Key, false);
                }
                else
                {
                    newList.Add(file.Key, file.Value);
                }
                stepprogressor.Step();
                cloneCount++;
            }
            _fileList = newList;



            trackcancel    = null;
            stepprogressor = null;
            progressdialog.HideDialog();
            progressdialog = null;
            //_activeView.Refresh();
        }
Пример #14
0
        static void Main(string[] args)
        {
            //arg 0 = source layer string file gdb string with feature class name
            //arg 1 = target layer path for fabric layer
            //arg 2 = control point tolerance (in projection units) to match with existing fabric points, -1 means don't do it
            //arg 3 = merge tolerance. Merge with existing control points if within tolerance, -1 means turn off merging
            //arg 4 = control merging choices for attributes [KeepExistingAttributes | UpdateExistingAttributes]
            //arg 5 = must have same name to merge if within the tolerance? [NamesMustMatchToMerge | IgnoreNames]
            //arg 6 = if control is merged keep existing names or update with incoming names? [KeepExistingNames | UpdateExistingNames]
            //.....(arg 6 is ignored if arg 5 = NamesMustMatchToMerge)
            //arg 7 = control merging choices for coordinates [UpdateXY | UpdateXYZ | UpdateZ | KeepExistingXYZ]
            //arg 8 = create a log file at the same location as the executable? [LoggingOn | LoggingOff]
            //.....(a log file is always generated unless LoggingOff is explcitly used)

            //ESRI License Initializer generated code.
            m_AOLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeStandard, esriLicenseProductCode.esriLicenseProductCodeAdvanced },
                                                         new esriLicenseExtensionCode[] { });
            //ESRI License Initializer generated code.
            //Do not make any call to ArcObjects after ShutDownApplication()
            int iLen = args.Length;

            if (iLen < 2)
            {
                UsageMessage();
                m_AOLicenseInitializer.ShutdownApplication();
                return;
            }

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

            try
            {
                ICadastralControlImporter pControlPointCadastralImp = new CadastralControlImporterClass();

                // args[0] ============================================
                string PathToFileGDBandFeatureClass = args[0];

                if (args[0].Contains(":") && args[0].Contains("\\"))
                {
                    PathToFileGDBandFeatureClass = args[0];
                }
                else
                {
                    string[] sExecPathArr = System.Reflection.Assembly.GetEntryAssembly().Location.Split('\\');
                    string   x            = "";
                    for (int i = 0; i < (sExecPathArr.Length - 1); i++)
                    {
                        x += sExecPathArr[i] + "\\";
                    }

                    PathToFileGDBandFeatureClass = x + PathToFileGDBandFeatureClass;
                }

                string[] PathToFileGDBArray       = PathToFileGDBandFeatureClass.Split('\\');
                string   NameOfSourceFeatureClass = PathToFileGDBArray[PathToFileGDBArray.Length - 1];
                string   PathToFileGDB            = "";

                for (int i = 0; i < (PathToFileGDBArray.Length - 1); i++)
                {
                    PathToFileGDB += PathToFileGDBArray[i] + "\\";
                }

                PathToFileGDB = PathToFileGDB.TrimEnd('\\');

                if (!System.IO.Directory.Exists(PathToFileGDB))
                {
                    throw new Exception("File does not exist. [" + PathToFileGDB + "]");
                }


                // args[1] ============================================

                string layerFilePathToFabric = args[1];

                if (!(layerFilePathToFabric.Contains(":") && layerFilePathToFabric.Contains("\\")))
                {
                    string[] sExecPathArr = System.Reflection.Assembly.GetEntryAssembly().Location.Split('\\');
                    string   x            = "";
                    for (int i = 0; i < (sExecPathArr.Length - 1); i++)
                    {
                        x += sExecPathArr[i] + "\\";
                    }

                    layerFilePathToFabric = x + layerFilePathToFabric;
                }

                if (!System.IO.File.Exists(layerFilePathToFabric))
                {
                    throw new Exception("File does not exist. [" + layerFilePathToFabric + "]");
                }

                ILayerFile layerFileToTargetFabric = new LayerFileClass();
                layerFileToTargetFabric.Open(layerFilePathToFabric);
                ILayer pLayer = layerFileToTargetFabric.Layer;
                ICadastralFabricLayer pParcelFabLyr       = pLayer as ICadastralFabricLayer;
                ICadastralFabric      pParcelFabric       = pParcelFabLyr.CadastralFabric;
                IDataset             pDS                  = pParcelFabric as IDataset;
                IName                pDSName              = pDS.FullName;
                ICadastralFabricName pCadastralFabricName = pDSName as ICadastralFabricName;

                IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory();
                IFeatureWorkspace pFWS             = (IFeatureWorkspace)workspaceFactory.OpenFromFile(PathToFileGDB, 0);
                pDS = (IDataset)pFWS.OpenFeatureClass(NameOfSourceFeatureClass);
                IName pSourceFeatClassName = pDS.FullName;

                //  args[2] ============================================
                bool   bHasControlTolerance = iLen > 2;
                double dControlToFabricPointMatchTolerance = -1;
                if (bHasControlTolerance)
                {
                    if (!Double.TryParse(args[2], out dControlToFabricPointMatchTolerance))
                    {
                        throw new Exception("The third parameter should be a numeric value. [" + args[2] + "]");
                    }
                }
                pControlPointCadastralImp.ControlPointTolerance = dControlToFabricPointMatchTolerance;
                //'***** performance, -1 means that matching to existing fabric points is turned off
                pControlPointCadastralImp.UseShapeField = true;

                //============= Arguments for merging control points ===============
                // args[3] [4] [5] [6] [7] ============================================
                bool bIsMergingControlPoints = (iLen == 7);
                if (bIsMergingControlPoints)
                {
                    //arg 3 = merge tolerance. Merge with existing control points if within tolerance, -1 means turn off merging
                    //arg 4 = control merging choices for attributes [KeepExistingAttributes | UpdateExistingAttributes]
                    //arg 5 = must have same name to merge if within the tolerance? [NamesMustMatchToMerge | IgnoreNames]
                    //arg 6 = if control is merged keep existing names or update with incoming names? [KeepExistingNames | UpdateExistingNames]
                    //.....(arg 6 is ignored if arg 5 = NamesMustMatchToMerge)
                    //arg 7 = control merging choices for coordinates [UpdateXY | UpdateXYZ | UpdateZ | KeepExistingXYZ]

                    double dControlPointMergingTolerance = -1;
                    if (!Double.TryParse(args[3], out dControlPointMergingTolerance))
                    {
                        { throw new Exception("The fourth parameter should be a numeric value. [" + args[3] + "]"); }
                    }
                    ICadastralControlImporterMerging pImpMerge = pControlPointCadastralImp as ICadastralControlImporterMerging;
                    pImpMerge.MergeCloseControl     = dControlPointMergingTolerance > 0;
                    pImpMerge.CloseControlTolerance = dControlPointMergingTolerance;
                    if (args[4].ToLower().Contains("updateexistingattributes"))
                    {
                        pImpMerge.MergeAttributesOption = esriCFControlMergingAttributes.esriCFControlMergingUpdateAttributes;
                    }
                    else
                    {
                        pImpMerge.MergeAttributesOption = esriCFControlMergingAttributes.esriCFControlMergingKeepAttributes;
                    }

                    pImpMerge.MergeControlNameCaseSensitive = false;

                    pImpMerge.MergeControlSameName = args[5].ToLower().Contains("namesmustmatchtomerge");

                    if (args[6].ToLower().Contains("updateexistingnames") && !args[5].ToLower().Contains("namesmustmatchtomerge"))
                    {
                        pImpMerge.MergeNameOption = esriCFControlMergingName.esriCFControlMergingUpdateExistingNames;
                    }
                    else
                    {
                        pImpMerge.MergeNameOption = esriCFControlMergingName.esriCFControlMergingKeepExistingNames;
                    }

                    if (args[7].ToLower() == "updatexy")
                    {
                        pImpMerge.MergeCoordinateOption = esriCFControlMergingCoordinate.esriCFControlMergingUpdateXY;
                    }
                    else if (args[7].ToLower() == "updatexyz")
                    {
                        pImpMerge.MergeCoordinateOption = esriCFControlMergingCoordinate.esriCFControlMergingUpdateXYZ;
                    }
                    else if (args[7].ToLower() == "updatez")
                    {
                        pImpMerge.MergeCoordinateOption = esriCFControlMergingCoordinate.esriCFControlMergingUpdateZ;
                    }
                    else if (args[7].ToLower() == "keepexistingxyz")
                    {
                        pImpMerge.MergeCoordinateOption = esriCFControlMergingCoordinate.esriCFControlMergingKeepExistingCoordinates;
                    }
                }

                ICadastralImporter pControlImporter = (ICadastralImporter)pControlPointCadastralImp;

                bool bHasExplicitLogFileParameter = (iLen > 8);
                bool bExplicitTurnLoggingOff      = false;
                /// Argument for logging importer results
                //arg 8 = create a log file at the same location as the executable? [LoggingOn | LoggingOff | <path to logfile>]
                //.....(a log file is always generated unless LoggingOff is explcitly used)

                string sLogFilePath = "LogControlImport";
                if (bHasExplicitLogFileParameter)
                {
                    if (args[8].ToLower() == "loggingoff")
                    {
                        bExplicitTurnLoggingOff = true;
                    }
                    if (args[8].ToLower() != "loggingon" && !bExplicitTurnLoggingOff)
                    {
                        if (args[8].Contains(":") && args[8].Contains("\\")) //if (args[8].ToLower() != "loggingon")
                        {
                            sLogFilePath = args[8];
                        }
                        else
                        {
                            string[] sExecPathArr = System.Reflection.Assembly.GetEntryAssembly().Location.Split('\\');
                            string   x            = "";
                            for (int i = 0; i < (sExecPathArr.Length - 1); i++)
                            {
                                x += sExecPathArr[i] + "\\";
                            }
                            sLogFilePath = x + args[8];
                        }
                    }
                }
                else
                {
                    string[] sExecPathArr = System.Reflection.Assembly.GetEntryAssembly().Location.Split('\\');
                    string   x            = "";
                    for (int i = 0; i < (sExecPathArr.Length - 1); i++)
                    {
                        x += sExecPathArr[i] + "\\";
                    }
                    sLogFilePath = x + sLogFilePath;
                }
                sLogFilePath += ".log";

                if (!bExplicitTurnLoggingOff)
                {
                    pControlImporter.OutputLogfile = sLogFilePath; //default location is same as executable
                }
                //Set the properties of the Progress Dialog
                pProDlg.CancelEnabled = false;
                pProDlg.Description   = "Importing Control Point data ...";
                pProDlg.Title         = "Importing Control Points";
                pProDlg.Animation     = esriProgressAnimationTypes.esriProgressGlobe;

                Console.WriteLine("Starting data load...");
                pControlImporter.Import(pSourceFeatClassName, pCadastralFabricName, pTrkCan); //BUG fails if the TrackCancel is null
                Console.WriteLine("Finished data load...");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                //UsageMessage();
            }
            finally
            {
                if (pProDlg != null)
                {
                    pProDlg.HideDialog();
                }
                m_AOLicenseInitializer.ShutdownApplication();
            }
        }
Пример #15
0
        public void Calculate(string sShorelineLayer, string sDepthPointsLayer, double dblInterval, string strShoreDepthField, string strDepthPointDepthField)
        {
            try
            {
                IMxDocument pmxdoc = ArcMap.Document as IMxDocument;
                IMap        pmap   = pmxdoc.FocusMap;

                IFeatureLayer pDepthSoundings = FindLayer(pmap, sDepthPointsLayer) as IFeatureLayer;
                IFeatureLayer pShorelineLayer = FindLayer(pmap, sShorelineLayer) as IFeatureLayer;

                //IFeatureLayer pOutpoints = FindLayer(pmap, sOutpoints) as IFeatureLayer;
                IFeatureLayer pOutpoints = new FeatureLayerClass();
                pOutpoints.FeatureClass = MakePointFC();
                pOutpoints.Name         = "Output Points";
                ArcMap.Document.ActiveView.FocusMap.AddLayer(pOutpoints);

                IFeatureLayer pConnectingLines = FindLayer(pmap, "ConnectingLines") as IFeatureLayer;
                IFeatureLayer pShorePoints     = FindLayer(pmap, "ShorePoints") as IFeatureLayer;



                ////Add fields if necessary
                //AddField(pOutpoints, "Distance");
                //AddField(pOutpoints, "Elevation");


                //Set up the Outpoints cursor
                IFeatureCursor pFCurOutPoints = pOutpoints.Search(null, false);
                pFCurOutPoints = pOutpoints.FeatureClass.Insert(true);
                IFeatureBuffer pFOutPointsBuffer = pOutpoints.FeatureClass.CreateFeatureBuffer();


                //Set up the LineLayer Cursor (now using selected lines)
                IFeatureSelection pShoreLineSelection = pShorelineLayer as IFeatureSelection;

                if (pShoreLineSelection.SelectionSet.Count == 0)
                {
                    MessageBox.Show("You must have at least one shoreline feature selected");
                    return;
                }
                ICursor        pShorelineCursor;
                IFeatureCursor pSelShoreFeatCur;
                pShoreLineSelection.SelectionSet.Search(null, false, out pShorelineCursor);
                pSelShoreFeatCur = pShorelineCursor as IFeatureCursor;
                IFeature pShoreLineFeature = pSelShoreFeatCur.NextFeature();
                //IFeatureCursor pFCur = pShorelineLayer.Search(null, false);
                //IFeature pShoreLineFeature = pFCur.NextFeature();

                //Set up the pConnectingLines cursor
                IFeatureCursor pFCurOutLines = pConnectingLines.Search(null, false);
                pFCurOutLines = pConnectingLines.FeatureClass.Insert(true);
                IFeatureBuffer pFBuffer = pConnectingLines.FeatureClass.CreateFeatureBuffer();

                //Set up the pShorePoints cursor
                IFeatureCursor pShorePointsCursor = pShorePoints.Search(null, false);
                IFeature       pShorePointFeature = pShorePointsCursor.NextFeature();



                IFeature         pNewLineFeature   = null;
                IPointCollection pNewLinePointColl = null;


                double dblDistance = 0;
                double dblTotalDistanceCalculated = 0;
                int    iNumIntervals        = 0;
                double dblElevationDiff     = 0;
                double dblElevationInterval = 0;
                double dblElevation         = 0;
                double dlbStartElevation    = 0;
                double dblEndElevation      = 0;

                int iLineProgressCount           = 0;
                IProgressDialog2 pProgressDialog = ShowProgressIndicator("Calculating points for shoreline vertex: ", 0, 1);
                pProgressDialog.ShowDialog();



                IEnvelope pCombinedEnvelope = CombineExtents(pDepthSoundings.FeatureClass, pShorelineLayer.FeatureClass);
                while (pShoreLineFeature != null)
                {
                    //IPointCollection4 pPointColl = pShoreLineFeature.Shape as IPointCollection4;

                    IPoint ppoint = new PointClass();



                    //for (int i = 0; i <= pPointColl.PointCount - 1; i++)
                    while (pShorePointFeature != null)
                    {
                        ppoint = pShorePointFeature.ShapeCopy as IPoint;
                        System.Diagnostics.Debug.WriteLine("ppoint: " + ppoint.X.ToString());
                        System.Diagnostics.Debug.WriteLine("shorepoint: " + pShorePointFeature.OID.ToString());

                        ////try walking line at set intervals instead of just at vertices
                        //IPoint pLineVertex = new PointClass();
                        //pLineVertex = pPointColl.get_Point(i);

                        IFeatureCursor pDepthCursor = pDepthSoundings.Search(null, false);
                        IFeatureIndex2 pFtrInd      = new FeatureIndexClass();
                        pFtrInd.FeatureClass  = pDepthSoundings.FeatureClass;
                        pFtrInd.FeatureCursor = pDepthCursor;
                        pFtrInd.Index(null, pCombinedEnvelope);
                        IIndexQuery2 pIndQry = pFtrInd as IIndexQuery2;

                        int    FtdID     = 0;
                        double dDist2Ftr = 0;
                        pIndQry.NearestFeature(ppoint, out FtdID, out dDist2Ftr);

                        IFeature pCloseFeature = pDepthSoundings.FeatureClass.GetFeature(FtdID);

                        IPoint pEndPoint = new PointClass();
                        pEndPoint = pCloseFeature.Shape as IPoint;


                        //Make the line here
                        pNewLineFeature   = pConnectingLines.FeatureClass.CreateFeature();
                        pNewLinePointColl = new PolylineClass();

                        object missing = Type.Missing;
                        pNewLinePointColl.AddPoint(pEndPoint, ref missing, ref missing);
                        pNewLinePointColl.AddPoint(ppoint, ref missing, ref missing);
                        pNewLineFeature.Shape = pNewLinePointColl as PolylineClass;

                        //Check to see if new line crosses land, if not, process it.
                        //bool bLineIntersectsShore = FeatureIntersects(pShorelineLayer, pConnectingLines, pNewLineFeature);
                        bool bLineIntersectsShore = false;
                        if (bLineIntersectsShore == false)
                        {
                            pNewLineFeature.Store();



                            ICurve pCurve = pNewLineFeature.Shape as ICurve;
                            pCurve.Project(pmap.SpatialReference);

                            //Get the Starting Elevation from the closest depth point
                            dlbStartElevation = GetStartElevation(pDepthSoundings, pConnectingLines, pNewLineFeature, strDepthPointDepthField);
                            //The Elevation for the first run IS the start elevation
                            dblElevation = dlbStartElevation;
                            //////Get the ending elevation from the shoreline
                            dblEndElevation = GetEndElevation(pShorelineLayer, pConnectingLines, pNewLineFeature, strShoreDepthField);

                            //number of line segments based on the user's interval
                            iNumIntervals    = Convert.ToInt32(pCurve.Length / dblInterval);
                            dblElevationDiff = Math.Abs(dblEndElevation - dlbStartElevation);
                            //The calculated elevation interval to step up each time
                            dblElevationInterval = dblElevationDiff / iNumIntervals;


                            ppoint = new PointClass();

                            while (dblTotalDistanceCalculated <= pCurve.Length)
                            {
                                pFOutPointsBuffer.set_Value(pFOutPointsBuffer.Fields.FindField("LineOID"), pNewLineFeature.OID);
                                pFOutPointsBuffer.set_Value(pFOutPointsBuffer.Fields.FindField("Distance"), dblDistance);
                                pFOutPointsBuffer.set_Value(pFOutPointsBuffer.Fields.FindField("Elevation"), dblElevation);


                                //this code set the point on the line at a distance
                                pCurve.QueryPoint(0, dblDistance, false, ppoint);

                                pFOutPointsBuffer.set_Value(pFOutPointsBuffer.Fields.FindField("X"), ppoint.X);
                                pFOutPointsBuffer.set_Value(pFOutPointsBuffer.Fields.FindField("Y"), ppoint.Y);


                                //reCalc the new distance and elevation values for the next iteration
                                dblDistance = dblDistance + dblInterval;

                                //add or subtract elevation depending on whether dblElevationDiff is positve or negative
                                if (dblElevationDiff > 0)
                                {
                                    dblElevation = dblElevation - dblElevationInterval;
                                }
                                else
                                {
                                    dblElevation = dblElevation + dblElevationInterval;
                                }
                                dblTotalDistanceCalculated = dblTotalDistanceCalculated + dblInterval;



                                //Insert the feature into the featureclass
                                pFOutPointsBuffer.Shape = ppoint;
                                pFCurOutPoints.InsertFeature(pFOutPointsBuffer);
                            }



                            //Reset the distance values back to 0 for the next feature
                            dblDistance = 0;
                            dblTotalDistanceCalculated = 0;
                            pFCurOutPoints.Flush();


                            pStepProgressor.Step();
                            pProgressDialog.Description = "Calculating points for shoreline vertex: " + pShorePointFeature.OID.ToString();
                            iLineProgressCount++;
                        }

                        pShorePointFeature = pShorePointsCursor.NextFeature();
                    }

                    pShoreLineFeature = pSelShoreFeatCur.NextFeature();
                }
                //cleanup
                pFCurOutLines.Flush();
                pSelShoreFeatCur.Flush();
                pProgressDialog.HideDialog();
                pmxdoc.ActiveView.Refresh();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show(ex.StackTrace);
            }
        }
        /// <summary>
        /// Occurs when this command is clicked
        /// </summary>
        public override void OnClick()
        {
            try
            {
                if (m_application == null)
                {
                    return;
                }
                IDocument   document   = m_application.Document;
                ISxDocument sxDocument = (ISxDocument)(document);
                if (sxDocument != null)
                {
                    m_scene = sxDocument.Scene;
                }
                if (m_scene == null)
                {
                    return;
                }
                activeView = m_scene as IActiveView;

                //有图层选图层
                if (m_scene.LayerCount == 0)
                {
                    return;
                }

                //选择基准面
                if (Common.SelectLayer(m_scene.Layers, out SelectedLyrIndex, true, "选择自定义表面") == false)
                {
                    return;
                }

                //QI
                IRasterLayer baseRasterLayer = m_scene.Layer[SelectedLyrIndex[0]] as IRasterLayer;  //不管选多少个只选第一个
                if (baseRasterLayer == null)
                {
                    throw new ArgumentNullException("自定义表面RasterLayer转换失败,为空。");
                }
                IRaster raster = baseRasterLayer.Raster;
                if (raster == null)
                {
                    throw new ArgumentNullException("自定义表面Raster转换失败,为空。");
                }
                IRasterSurface rasterSurface = new RasterSurfaceClass();
                rasterSurface.PutRaster(raster, 0);
                ISurface surface = rasterSurface as ISurface;

                //选择图层
                if (Common.SelectLayer(m_scene.Layers, out SelectedLyrIndex, false, "选择要进行偏移的图层") == false)
                {
                    return;
                }

                //选择倍数
                NumSelect MultiNS = new NumSelect("输入夸大倍数", true);
                if (MultiNS.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                double Multiplier = MultiNS.Result;

                //选择偏移量
                NumSelect NS = new NumSelect();
                if (NS.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                double Offset       = NS.Result;
                bool   DisableCache = NS.DisableCache;

                //Create a CancelTracker.
                ITrackCancel pTrackCancel = new CancelTrackerClass();

                //Create the ProgressDialog. This automatically displays the dialog
                IProgressDialogFactory pProgDlgFactory = new ProgressDialogFactoryClass();
                IProgressDialog2       pProDlg         = pProgDlgFactory.Create(pTrackCancel, m_application.hWnd) as IProgressDialog2;
                pProDlg.CancelEnabled = true;
                pProDlg.Title         = "正在进行自定义表面设置及偏移调整";
                pProDlg.Description   = "设置中,请稍候...";

                pProDlg.Animation = esriProgressAnimationTypes.esriProgressSpiral;

                IStepProgressor pStepPro = pProDlg as IStepProgressor;
                pStepPro.MinRange  = 0;
                pStepPro.MaxRange  = SelectedLyrIndex.Count;
                pStepPro.StepValue = 1;
                pStepPro.Message   = "初始化中...";

                bool bCont = true;

                //对每一个选中的图层进行操作
                for (int i = 0; i < SelectedLyrIndex.Count; i++)
                {
                    //m_application.StatusBar.set_Message(0, i.ToString());
                    pStepPro.Message = "已完成(" + i.ToString() + "/" + SelectedLyrIndex.Count.ToString() + ")";
                    bCont            = pTrackCancel.Continue();
                    if (!bCont)
                    {
                        break;
                    }

                    //选中一个栅格图层
                    IRasterLayer rasterLayer = m_scene.Layer[SelectedLyrIndex[i]] as IRasterLayer;
                    if (rasterLayer == null)
                    {
                        pStepPro.Message = "选中的图层非栅格图层...";
                        continue;
                    }

                    I3DProperties    p3DProperties   = null;
                    ILayerExtensions layerExtensions = rasterLayer as ILayerExtensions;

                    //遍历LayerExtensions找到I3DProperties
                    for (int j = 0; j < layerExtensions.ExtensionCount; j++)
                    {
                        if (layerExtensions.get_Extension(j) is I3DProperties)
                        {
                            p3DProperties = layerExtensions.get_Extension(j) as I3DProperties;
                        }
                    }

                    //设置I3DProperties
                    p3DProperties.ZFactor                = Multiplier;                     //系数
                    p3DProperties.BaseOption             = esriBaseOption.esriBaseSurface; //基准面浮动
                    p3DProperties.BaseSurface            = surface;                        //基准面
                    p3DProperties.OffsetExpressionString = Offset.ToString();              //偏移常量
                    if (DisableCache)
                    {
                        p3DProperties.RenderMode       = esriRenderMode.esriRenderImmediate;         //直接从文件渲染
                        p3DProperties.RenderVisibility = esriRenderVisibility.esriRenderWhenStopped; //停止导航时渲染
                    }
                    p3DProperties.Apply3DProperties(rasterLayer);
                }
                pProDlg.HideDialog();

                //==========================================
                //刷新,不起作用
                if (activeView == null)
                {
                    throw new Exception("活动视图为空! ");
                }
                if (m_sceneHookHelper.ActiveViewer == null)
                {
                    throw new Exception("无活动视图!");
                }
                activeView.Refresh();
                m_sceneHookHelper.ActiveViewer.Redraw(true);
                //==========================================
            }
            catch (Exception err)
            {
                MessageBox.Show(err.ToString());
            }
        }
        private void Cleanup(IProgressDialog2 ProgressorDialog, IMouseCursor MouseCursor)
        {
            MouseCursor.SetCursor(0);

              if (!(ProgressorDialog == null))
              {
            ProgressorDialog.HideDialog();
              }
              ProgressorDialog = null;
              m_pStepProgressor = null;
        }
Пример #18
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);
                }
            }
        }
Пример #19
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
            {
            }
        }
        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
            }
        }
        private void Cleanup(IMouseCursor MouseCursor, IFIDSet PlansFIDSet, ITable pTable,
      ITable PlansTable,  IWorkspace Workspace, IProgressDialog2 pProgressorDialog, bool CleanFabricVar)
        {
            if (pProgressorDialog != null)
            pProgressorDialog.HideDialog();

              if (MouseCursor != null)
            MouseCursor.SetCursor(0);
              if (m_pStepProgressor != null)
            m_pStepProgressor.Hide();

              m_pStepProgressor = null;

              if (PlansFIDSet != null)
              {
            do { }
            while (Marshal.ReleaseComObject(PlansFIDSet) > 0);
              }
              if (m_pProgressorDialogFact != null)
              {
            do { }
            while (Marshal.ReleaseComObject(m_pProgressorDialogFact) > 0);
              }
              if (m_pTrackCancel != null)
              {
            do { }
            while (Marshal.ReleaseComObject(m_pTrackCancel) > 0);
              }

              if (PlansTable != null)
              {
            do { }
            while (Marshal.ReleaseComObject(PlansTable) > 0);
              }

              if (m_pCadaFab != null && CleanFabricVar)
              {
            do { }
            while (Marshal.ReleaseComObject(m_pCadaFab) > 0);
              }

              if (pTable != null)
              {
            do { }
            while (Marshal.ReleaseComObject(pTable) > 0);
              }

              if (Workspace != null)
              {
            do { }
            while (Marshal.ReleaseComObject(Workspace) > 0);
              }
        }
Пример #22
0
        private void MakeAreaVolumeTable(double dStartingElev, double dEndingElev, double dGraduationValue)
        {
            SaveFileDialog dlgSaveFile = new SaveFileDialog();

            dlgSaveFile.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*";

            if (dlgSaveFile.ShowDialog() == DialogResult.OK)
            {
                Toggle3DExtension("ON");
                StreamWriter sw = new StreamWriter(dlgSaveFile.FileName);
                sw.WriteLine("Elevation,Area_acres,Volume");


                IMxDocument pmxdoc = ArcMap.Document as IMxDocument;
                IMap        pmap   = pmxdoc.FocusMap;



                ILayer player = FindLayer(pmap, cboRasterLayers.Text);

                //bool bFeetCorrect = chkFeetCorrect.Checked;
                esriPlaneReferenceType eRef;

                double           dlbRange        = Math.Abs(dStartingElev - dEndingElev);
                IProgressDialog2 pProgressDialog = ShowProgressIndicator("Calculating...", Convert.ToInt32(dlbRange / dGraduationValue), 1);
                pProgressDialog.ShowDialog();



                eRef = esriPlaneReferenceType.esriPlaneReferenceBelow;
                ////if (radAbove.Checked)
                ////{
                ////     eRef = esriPlaneReferenceType.esriPlaneReferenceAbove;

                ////}
                ////else
                ////{
                ////    eRef = esriPlaneReferenceType.esriPlaneReferenceBelow;
                ////}

                ISurface pSurface = GetSurfaceFromLayer(player);

                while (dEndingElev > dStartingElev)
                {
                    pStepProgressor.Step();

                    //Check difference between these two calculations
                    double dArea = pSurface.GetProjectedArea(dStartingElev, eRef);
                    //double dArea = pSurface.GetSurfaceArea(dStartingElev, eRef);

                    //Convert square meters to acres
                    dArea = dArea * 0.000247;

                    double dVolume = pSurface.GetVolume(dStartingElev, eRef);

                    //Convert cubic meter to acre-foot
                    dVolume = dVolume * 0.000811;


                    //Meters to feet.  Probably not needed
                    if (chkVertUnitCorrect.Checked)
                    {
                        dVolume = dVolume / 3.28084;
                    }


                    sw.WriteLine(dStartingElev + "," + dArea + "," + dVolume);
                    dStartingElev = dStartingElev + dGraduationValue;
                }


                sw.Close();
                pProgressDialog.HideDialog();
            }

            AddTable(Path.GetDirectoryName(dlgSaveFile.FileName), Path.GetFileName(dlgSaveFile.FileName));
            Toggle3DExtension("OFF");
        }
        private void Cleanup(IMouseCursor MouseCursor, IFIDSet PlansFIDSet, ITable pTable, 
      ITable PlansTable, IWorkspace Workspace,IProgressDialog2 pProgressorDialog)
        {
            if (pProgressorDialog!=null)
            pProgressorDialog.HideDialog();

              if (MouseCursor!=null)
            MouseCursor.SetCursor(0);
              if (m_pStepProgressor!=null)
            m_pStepProgressor.Hide();

              m_pStepProgressor = null;

              try
              {
            Marshal.ReleaseComObject(PlansFIDSet); //garbage collection
              }
              catch { }

              try
              {
            Marshal.ReleaseComObject(m_pProgressorDialogFact); //garbage collection
              }
              catch { }

              try
              {
            Marshal.ReleaseComObject(m_pTrackCancel); //garbage collection
              }
              catch { }

              if (PlansTable!= null)
            Marshal.ReleaseComObject(PlansTable);
              if (m_pCadaFab != null)
            Marshal.ReleaseComObject(m_pCadaFab);
              if (pTable != null)
            Marshal.ReleaseComObject(pTable);
              if (Workspace!= null)
            Marshal.ReleaseComObject(Workspace);
              if (m_pStartTime != null)
            Marshal.ReleaseComObject(m_pStartTime);
              if (m_pEndTime != null)
            Marshal.ReleaseComObject(m_pEndTime);
        }
Пример #24
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;
            }
        }
Пример #25
0
        private bool ExportLayer(Excel.Workbook ExcelWbk, IMxDocument MxDoc, IFeatureLayer FLayer, ref IProgressDialog2 progressDialog, ref IStepProgressor stepProgressor, ref ITrackCancel trackCancel)
        {
            IFeatureClass FC       = null;
            ISubtypes     Subtypes = null;

            ITableProperties      TableProperties      = null;
            IEnumTableProperties  EnumTableProperties  = null;
            ITableProperty3       TableProperty        = null;
            ITableCharacteristics TableCharacteristics = null;
            IFeatureSelection     FeatSel      = null;
            IDisplayTable         DisplayTable = null;
            ITable       Table       = null;
            ILayerFields LayerFields = null;
            ITableFields TableFields = null;
            ILayer       LayerTest   = null;

            ICursor           Cursor           = null;
            IFeatureCursor    FCursor          = null;
            IField            CurField         = null;
            IDomain           Domain           = null;
            ICodedValueDomain CodedValueDomain = null;
            IFeature          Feat             = null;
            List <IPoint>     pGeo             = null;

            object missing = null;
            object sheet   = null;

            Excel.Worksheet ExcelSheet = null;
            Excel.Range     ExcelRange = null;
            Microsoft.Office.Interop.Excel.Style style = null;

            try
            {
                int    Col = 0;
                int    Row = 0;
                int    i;
                int    j;
                bool   UseDescriptions;
                int    subtype;
                string SheetName;

                missing = System.Reflection.Missing.Value;
                sheet   = ExcelWbk.Sheets[ExcelWbk.Sheets.Count];

                //Add new Excel worksheet
                ExcelSheet = (Excel.Worksheet)ExcelWbk.Sheets.Add(missing, sheet, missing, missing);
                SheetName  = FLayer.Name;
                if (SheetName.Length > 30)
                {
                    SheetName = SheetName.Substring(0, 30);
                }
                ExcelSheet.Name = SheetName;

                //style = ExcelWbk.Styles.Add("Style1");
                //style.NumberFormat = "@";

                LayerTest = (ILayer)FLayer;

                //Get Subtype info
                FC       = FLayer.FeatureClass;
                Subtypes = FC as ISubtypes;
                //Determine whether to use descriptions or codes for domains and subtypes
                UseDescriptions     = true;
                TableProperties     = MxDoc.TableProperties;
                EnumTableProperties = (IEnumTableProperties)TableProperties;
                EnumTableProperties.Reset();
                TableProperty = (ITableProperty3)EnumTableProperties.Next();
                while (TableProperty != null && TableProperty.Layer != null)  //Fixed
                {
                    if (TableProperty.Layer.Equals(LayerTest))
                    {
                        TableCharacteristics = (ITableCharacteristics)TableProperty;
                        UseDescriptions      = TableCharacteristics.ShowCodedValueDomainDescriptions;
                    }
                    TableProperty = (ITableProperty3)EnumTableProperties.Next();
                }
                FeatSel = (IFeatureSelection)FLayer;

                DisplayTable = (IDisplayTable)FLayer;
                Table        = (ITable)DisplayTable.DisplayTable;

                //Get TableFields so later we can determine whether that field is visible
                LayerFields = (ILayerFields)FLayer;
                TableFields = (ITableFields)FLayer;

                //loop through each field and write column headings
                Row = 1;
                for (j = 0; j < TableFields.FieldCount; j++)
                {
                    CurField = TableFields.get_Field(j);

                    //skip blob and geometry fields
                    if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry))
                    {
                        Col += 1;
                        //Write field alias name as Excel column header
                        ExcelSheet.Cells[Row, Col] = TableFields.get_FieldInfo(j).Alias;
                        if (CurField.Type == esriFieldType.esriFieldTypeString)
                        {
                            ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[65535, Col]).EntireColumn.NumberFormat = "@";
                        }
                    }
                }
                Col += 1;
                ExcelSheet.Cells[Row, Col] = "X_COORD";
                Col += 1;
                ExcelSheet.Cells[Row, Col] = "Y_COORD";
                Col += 1;
                ExcelSheet.Cells[Row, Col] = "Lat";
                Col += 1;
                ExcelSheet.Cells[Row, Col] = "Long";
                IField       pFieldTest       = FLayer.FeatureClass.Fields.get_Field(FLayer.FeatureClass.Fields.FindField(FLayer.FeatureClass.ShapeFieldName));
                IGeometryDef pGeometryDefTest = null;
                pGeometryDefTest = pFieldTest.GeometryDef;
                bool bZAware = false;
                bool bMAware = false;
                //Determine if M or Z aware
                if (pGeometryDefTest.GeometryType == esriGeometryType.esriGeometryPoint)
                {
                    bZAware = pGeometryDefTest.HasZ;
                    bMAware = pGeometryDefTest.HasM;
                }
                if (bZAware)
                {
                    Col += 1;
                    ExcelSheet.Cells[Row, Col] = "Z_COORD";
                }
                pFieldTest       = null;
                pGeometryDefTest = null;
                //Get all selected records for this table (use IDisplayTable to get any joined data)
                DisplayTable.DisplaySelectionSet.Search(null, true, out Cursor);
                FCursor = (IFeatureCursor)Cursor;

                //subtype = Subtypes.DefaultSubtypeCode;

                //For each selected record

                Feat = FCursor.NextFeature();
                //  stepProgressor.Step();
                // progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("ExportAsset") + stepProgressor.Position + A4LGSharedFunctions.Localizer.GetString("Of") + MxDoc.FocusMap.SelectionCount.ToString() + ".";

                while (Feat != null)
                {
                    Row += 1;

                    if (Subtypes != null && Subtypes.HasSubtype == true &&
                        (Feat.get_Value(Subtypes.SubtypeFieldIndex) != null))
                    {
                        subtype = Convert.ToInt32(Feat.get_Value(Subtypes.SubtypeFieldIndex));
                    }
                    else
                    {
                        subtype = -99999;
                    }


                    //For each column
                    Col = 0;
                    for (j = 0; j < TableFields.FieldCount; j++)
                    {
                        CurField = TableFields.get_Field(j);

                        //skip blob and geometry fields in data also
                        if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry))
                        {
                            Col += 1;
                            ExcelSheet.Cells[Row, Col] = Feat.get_Value(j);

                            if (UseDescriptions == true && subtype == -99999)
                            {
                                Domain = CurField.Domain;
                                if (Domain != null)
                                {
                                    if (Domain.Type == esriDomainType.esriDTCodedValue)
                                    {
                                        CodedValueDomain = (ICodedValueDomain)CurField.Domain;
                                        for (i = 0; i < CodedValueDomain.CodeCount; i++)
                                        {
                                            if ((CodedValueDomain.get_Value(i)).ToString() == (Feat.get_Value(j)).ToString())
                                            {
                                                //System.Diagnostics.Debug.Print(CodedValueDomain.get_Name(0).ToString());
                                                ExcelSheet.Cells[Row, Col] = CodedValueDomain.get_Name(i);
                                                i = CodedValueDomain.CodeCount;
                                            }
                                        }
                                    }
                                }
                            }
                            else if (UseDescriptions == true && subtype != -99999)
                            {
                                if (Subtypes.SubtypeFieldIndex == j)
                                {
                                    ExcelSheet.Cells[Row, Col] = Subtypes.get_SubtypeName(subtype);
                                }
                                else
                                {
                                    Domain = Subtypes.get_Domain(subtype, CurField.Name);
                                    if ((Domain != null) && (Domain.Type == esriDomainType.esriDTCodedValue))
                                    {
                                        CodedValueDomain = (ICodedValueDomain)Domain;
                                        for (i = 0; i < CodedValueDomain.CodeCount; i++)
                                        {
                                            if ((CodedValueDomain.get_Value(i)).ToString() == (Feat.get_Value(j)).ToString())
                                            {
                                                //System.Diagnostics.Debug.Print(CodedValueDomain.get_Name(0).ToString());
                                                ExcelSheet.Cells[Row, Col] = CodedValueDomain.get_Name(i);
                                                i = CodedValueDomain.CodeCount;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (Feat.Shape != null)
                    {
                        if (Feat.Shape.IsEmpty == false)
                        {
                            pGeo = Globals.GetGeomCenter(Feat.Shape);
                            if (pGeo != null)
                            {
                                if (pGeo.Count > 0)
                                {
                                    if (pGeo[0].X != null)
                                    {
                                        ExcelSheet.Cells[Row, Col + 1] = pGeo[0].X;
                                    }
                                    if (pGeo[0].Y != null)
                                    {
                                        ExcelSheet.Cells[Row, Col + 2] = pGeo[0].Y;
                                    }
                                    if (pGeo[0] != null)
                                    {
                                        pGeo[0].Project(srWGS84);

                                        ExcelSheet.Cells[Row, Col + 3] = pGeo[0].Y;
                                        ExcelSheet.Cells[Row, Col + 4] = pGeo[0].X;
                                    }
                                    if (bZAware)
                                    {
                                        ExcelSheet.Cells[Row, Col + 5] = pGeo[0].Z;
                                    }
                                }
                            }
                        }
                    }

                    stepProgressor.Step();
                    progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("ExportAsset") + stepProgressor.Position + A4LGSharedFunctions.Localizer.GetString("Of") + MxDoc.FocusMap.SelectionCount.ToString() + ".";
                    if (!trackCancel.Continue())
                    {
                        return(false);
                    }


                    Feat = FCursor.NextFeature();
                }

                //Hide Columns
                Col = 0;
                for (j = 0; j < TableFields.FieldCount; j++)
                {
                    CurField = TableFields.get_Field(j);

                    //skip blob and geometry fields in data also
                    if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry))
                    {
                        Col += 1;
                        //Autofit
                        ExcelRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[Row, Col]);
                        ExcelRange.EntireColumn.AutoFit();

                        //Hide column if invisible in ArcMap
                        if (TableFields.get_FieldInfo(j).Visible == false)
                        {
                            ExcelRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[Row, Col]);
                            ExcelRange.EntireColumn.Hidden = true;
                        }
                    }
                }
                return(true);
            }
            catch
            {
                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ExportXLError"));
                return(true);
            }
            finally
            {
                FC       = null;
                Subtypes = null;

                TableProperties = null;
                if (EnumTableProperties != null)
                {
                    Marshal.ReleaseComObject(EnumTableProperties);
                }

                EnumTableProperties  = null;
                TableProperty        = null;
                TableCharacteristics = null;
                FeatSel      = null;
                DisplayTable = null;
                Table        = null;
                LayerFields  = null;
                TableFields  = null;
                LayerTest    = null;
                if (Cursor != null)
                {
                    Marshal.ReleaseComObject(Cursor);
                }
                Cursor = null;

                if (FCursor != null)
                {
                    Marshal.ReleaseComObject(FCursor);
                }
                FCursor          = null;
                CurField         = null;
                Domain           = null;
                CodedValueDomain = null;
                Feat             = null;
                pGeo             = null;

                missing    = null;
                sheet      = null;
                ExcelSheet = null;
                ExcelRange = null;
                style      = null;
            }
        }
Пример #26
0
        private bool ExportTable(Excel.Workbook ExcelWbk, IMxDocument MxDoc, IStandaloneTable StandTable, ref IProgressDialog2 progressDialog, ref IStepProgressor stepProgressor, ref ITrackCancel trackCancel)
        {
            ITableProperties      TableProperties      = null;
            IEnumTableProperties  EnumTableProperties  = null;
            ITableProperty3       TableProperty        = null;
            ITableCharacteristics TableCharacteristics = null;
            ITableSelection       TabSel       = null;
            IDisplayTable         DisplayTable = null;
            ITable       Table       = null;
            IRow         TabRow      = null;
            IObjectClass ObjectClass = null;
            ISubtypes    Subtypes    = null;
            ITableFields TableFields = null;

            ICursor           Cursor           = null;
            IField            CurField         = null;
            IDomain           Domain           = null;
            ICodedValueDomain CodedValueDomain = null;

            object missing = null;
            object sheet   = null;

            Microsoft.Office.Interop.Excel.Style style = null;


            try
            {
                bool   UseDescriptions;
                int    subtype;
                string SheetName;



                int Col = 0;
                int Row = 0;
                int i;
                int j;



                missing = System.Reflection.Missing.Value;

                sheet = ExcelWbk.Sheets[ExcelWbk.Sheets.Count];
                Excel.Worksheet ExcelSheet;
                Excel.Range     ExcelRange;

                //Add new Excel worksheet
                ExcelSheet = (Excel.Worksheet)ExcelWbk.Sheets.Add(missing, sheet, missing, missing);
                //style = ExcelWbk.Styles.Add("Style1");
                //style.NumberFormat = "@";
                //style.Font.Name = "Arial";
                //style.Font.Bold = True
                //style.Font.Size = 12;
                //style.Interior.Pattern = Microsoft.Office.Interop.Excel.XlPattern.xlPattern Solid
                //style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlighLe ft



                SheetName = StandTable.Name;
                if (SheetName.Length > 30)
                {
                    SheetName = SheetName.Substring(0, 30);
                }
                ExcelSheet.Name = SheetName;


                //Determine whether to use descriptions or codes for domains
                UseDescriptions     = true;
                TableProperties     = MxDoc.TableProperties;
                EnumTableProperties = (IEnumTableProperties)TableProperties;
                EnumTableProperties.Reset();
                TableProperty = (ITableProperty3)EnumTableProperties.Next();

                while (TableProperty != null)
                {
                    if (TableProperty.StandaloneTable != null)
                    {
                        if (TableProperty.StandaloneTable.Equals(StandTable))
                        {
                            TableCharacteristics = (ITableCharacteristics)TableProperty;
                            UseDescriptions      = TableCharacteristics.ShowCodedValueDomainDescriptions;
                            break;
                        }
                    }
                    TableProperty = (ITableProperty3)EnumTableProperties.Next();
                }
                TabSel = (ITableSelection)StandTable;

                DisplayTable = (IDisplayTable)StandTable;
                Table        = (ITable)DisplayTable.DisplayTable;

                //Get subtype info
                ObjectClass = Table as IObjectClass;
                Subtypes    = ObjectClass as ISubtypes;

                //Get TableFields so later we can determine whether that field is visible
                TableFields = (ITableFields)StandTable;


                //loop through each field and write column headings
                Row = 1;
                for (j = 0; j < TableFields.FieldCount; j++)
                {
                    CurField = TableFields.get_Field(j);

                    //skip blob and geometry fields
                    if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry))
                    {
                        Col += 1;
                        //Write field alias name as Excel column header
                        ExcelSheet.Cells[Row, Col] = TableFields.get_FieldInfo(j).Alias;
                        if (CurField.Type == esriFieldType.esriFieldTypeString)
                        {
                            ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[65535, Col]).EntireColumn.NumberFormat = "@";
                        }
                    }
                }

                //Get all selected records for this table (use IDisplayTable to get any joined data)
                DisplayTable.DisplaySelectionSet.Search(null, true, out Cursor);

                //subtype = Subtypes.DefaultSubtypeCode;

                //For each selected record

                TabRow = Cursor.NextRow();
                //stepProgressor.Step();
                //     progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("ExportAsset") + stepProgressor.Position + A4LGSharedFunctions.Localizer.GetString("Of") + MxDoc.FocusMap.SelectionCount.ToString() + ".";

                while (TabRow != null)
                {
                    Row += 1;

                    if (Subtypes != null && Subtypes.HasSubtype == true &&
                        (TabRow.get_Value(Subtypes.SubtypeFieldIndex) != null))
                    {
                        subtype = Convert.ToInt32(TabRow.get_Value(Subtypes.SubtypeFieldIndex));
                    }
                    else
                    {
                        subtype = -99999;
                    }


                    //For each column
                    Col = 0;
                    for (j = 0; j < TableFields.FieldCount; j++)
                    {
                        CurField = TableFields.get_Field(j);

                        //skip blob and geometry fields in data also
                        if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry))
                        {
                            Col += 1;
                            ExcelSheet.Cells[Row, Col] = TabRow.get_Value(j);

                            if (UseDescriptions == true && subtype == -99999)
                            {
                                Domain = CurField.Domain;
                                if (Domain != null)
                                {
                                    if (Domain.Type == esriDomainType.esriDTCodedValue)
                                    {
                                        CodedValueDomain = (ICodedValueDomain)CurField.Domain;
                                        for (i = 0; i < CodedValueDomain.CodeCount; i++)
                                        {
                                            if ((CodedValueDomain.get_Value(i)).ToString() == (TabRow.get_Value(j)).ToString())
                                            {
                                                //System.Diagnostics.Debug.Print(CodedValueDomain.get_Name(0).ToString());
                                                ExcelSheet.Cells[Row, Col] = CodedValueDomain.get_Name(i);
                                                i = CodedValueDomain.CodeCount;
                                            }
                                        }
                                    }
                                }
                            }
                            else if (UseDescriptions == true && subtype != -99999)
                            {
                                if (Subtypes.SubtypeFieldIndex == j)
                                {
                                    ExcelSheet.Cells[Row, Col] = Subtypes.get_SubtypeName(subtype);
                                }
                                else
                                {
                                    Domain = Subtypes.get_Domain(subtype, CurField.Name);
                                    if ((Domain != null) && (Domain.Type == esriDomainType.esriDTCodedValue))
                                    {
                                        CodedValueDomain = (ICodedValueDomain)Domain;
                                        for (i = 0; i < CodedValueDomain.CodeCount; i++)
                                        {
                                            if ((CodedValueDomain.get_Value(i)).ToString() == (TabRow.get_Value(j)).ToString())
                                            {
                                                //System.Diagnostics.Debug.Print(CodedValueDomain.get_Name(0).ToString());
                                                ExcelSheet.Cells[Row, Col] = CodedValueDomain.get_Name(i);
                                                i = CodedValueDomain.CodeCount;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    stepProgressor.Step();
                    progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("ExportAsset") + stepProgressor.Position + A4LGSharedFunctions.Localizer.GetString("Of") + MxDoc.FocusMap.SelectionCount.ToString() + ".";
                    if (!trackCancel.Continue())
                    {
                        return(false);
                    }
                    TabRow = Cursor.NextRow();
                }

                //Hide Columns
                Col = 0;
                for (j = 0; j < TableFields.FieldCount; j++)
                {
                    CurField = TableFields.get_Field(j);

                    //skip blob and geometry fields in data also
                    if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry))
                    {
                        Col += 1;
                        //Autofit
                        ExcelRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[Row, Col]);
                        ExcelRange.EntireColumn.AutoFit();

                        //Hide column if invisible in ArcMap
                        if (TableFields.get_FieldInfo(j).Visible == false)
                        {
                            ExcelRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[Row, Col]);
                            ExcelRange.EntireColumn.Hidden = true;
                        }
                    }
                }
                return(true);
            }
            catch
            {
                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ExportXLError"));
                return(true);
            }
            finally
            {
                TableProperties      = null;
                EnumTableProperties  = null;
                TableProperty        = null;
                TableCharacteristics = null;
                TabSel       = null;
                DisplayTable = null;
                Table        = null;
                TabRow       = null;
                ObjectClass  = null;
                Subtypes     = null;
                TableFields  = null;


                if (Cursor != null)
                {
                    Marshal.ReleaseComObject(Cursor);
                }
                Cursor           = null;
                CurField         = null;
                Domain           = null;
                CodedValueDomain = null;

                missing = null;
                sheet   = null;
                style   = null;
            }
        }
Пример #27
0
        private void btnIncorporar_Click_1(object sender, EventArgs e)
        {
            //IncorporarLecturas2();
            //return;

            statusLblProcesando.Text = "Incorporando Lecturas...";

            IProgressDialogFactory pProDiaFac = new ProgressDialogFactoryClass();
            IStepProgressor        pStepPro   = pProDiaFac.Create(null, 0);

            pStepPro.MinRange  = 1;
            pStepPro.MaxRange  = 5;
            pStepPro.StepValue = 1;
            IProgressDialog2 pProDia = (IProgressDialog2)pStepPro;

            pProDia.Animation = esriProgressAnimationTypes.esriProgressGlobe;

            pProDia.Title = "Incorporando Lecturas";
            pProDia.ShowDialog();
            pStepPro.Step();
            pStepPro.Message = "Incorporando temperatura...";

            SIGPIParametros parametros = _parametros;

            PrepararInformacion preparar = new PrepararInformacion();
            string mesTemperatura, mesPrecipitacion;
            string sRuta    = parametros.RutaSIGPI + "\\" + parametros.Lecturas + "\\" + LECTURAS_TEMPERATURA;

            Microsoft.Office.Interop.Excel.Application _excelApp = null;
            Workbook  workBook = null;
            Worksheet sheet = null;
            string    sColumnaDia;
            DateTime  dFechaIncorporacionActual;
            int       iDay;
            bool      bIncorporarTemperatura;

            try
            {
                _excelApp = new Microsoft.Office.Interop.Excel.Application();
                workBook  = _excelApp.Workbooks.Open(sRuta, Type.Missing, Type.Missing, Type.Missing,
                                                     Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                                     Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                sheet          = (Worksheet)workBook.Worksheets.get_Item(1); //.Sheets["max"];
                mesTemperatura = "";
                try
                {
                    mesTemperatura = preparar.VerificarFechasLecturas(sheet, SIGPI_CELDA_MES_TEMPERATURA);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    pProDia.HideDialog();
                    _excelApp.Workbooks.Close();
                    return;
                }
                DateTime dFechaAIncorporar = dtPickerFechaAIncorporar.Value;
                iDay = dFechaAIncorporar.Day;
                if (dFechaAIncorporar.Month != ConversionMes.MesNumero(mesTemperatura.ToUpper()))
                {
                    if (dFechaAIncorporar.Month != ConversionMes.MesNumero(mesTemperatura.ToUpper()) + 1)
                    {
                        MessageBox.Show("La fecha seleccionada no se encuentra en el archivo de lecturas. Periodo correspondiente al mes de: " + mesTemperatura);
                        pProDia.HideDialog();
                        _excelApp.Workbooks.Close();
                        return;
                    }
                }

                int iTotalEstaciones = preparar.TotalEstaciones(sheet, SIGPI_COLUMNA_CODIGO_TEMPERATURA);
                sColumnaDia = preparar.ColumnaLecturaDia(sheet, SIGPI_COLUMNA_INICIO_DIA_TEMPERATURA, iDay.ToString(), SIGPI_FILA_DIA_TEMPERATURA);
                if (sColumnaDia == "-99")
                {
                    MessageBox.Show("No se encontro el dia de lectura en el archivo de Excel de temperaturas. Dia: " + iDay.ToString());
                    pProDia.HideDialog();
                    _excelApp.Workbooks.Close();
                    return;
                }

                List <Lectura> listaTemperatura = preparar.ObtenerLecturas(sheet, _sigpiDao, SIGPI_COLUMNA_CODIGO_TEMPERATURA,
                                                                           sColumnaDia, SIGPI_TEMPERATURA_MIN_VAL, SIGPI_TEMPERATURA_MAX_VAL);
                pStepPro.Step();
                dFechaIncorporacionActual = dtPickerFechaAIncorporar.Value; //_sigpi.FechaIncorporacion.AddDays(1);
                //MessageBox.Show("lecturas a incorporar Temp. : " + listaTemperatura.Count.ToString());
                bIncorporarTemperatura = preparar.IncorporarLecturas(_sigpiDao, SIGPI_TABLA_LECTURAS_TEMPERATURA, dFechaIncorporacionActual, listaTemperatura);

                pStepPro.Message = "Incorporando Precipitacion...";
                pStepPro.Step();
                pStepPro.StepValue = 3;
            }
            finally
            {
                _excelApp.Workbooks.Close();
                GC.Collect();
                GC.WaitForPendingFinalizers();

                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workBook);
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_excelApp);
            }

            sRuta = parametros.RutaSIGPI + "\\" + parametros.Lecturas + "\\" + LECTURAS_PRECIPITACION;


            try
            {
                _excelApp = new Microsoft.Office.Interop.Excel.Application();
                workBook  = _excelApp.Workbooks.Open(sRuta, Type.Missing, Type.Missing, Type.Missing,
                                                     Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                                     Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                sheet = (Worksheet)workBook.Worksheets.get_Item(1); //Sheets["precipitacion"];

                try
                {
                    mesPrecipitacion = preparar.VerificarFechasLecturas(sheet, SIGPI_CELDA_MES_PRECIPITACION);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    pProDia.HideDialog();
                    _excelApp.Workbooks.Close();
                    return;
                }

                sColumnaDia = preparar.ColumnaLecturaDia(sheet, SIGPI_COLUMNA_INICIO_DIA_PRECIPITACION, iDay.ToString(), SIGPI_FILA_DIA_PRECIPITACION);
                if (sColumnaDia == "-99")
                {
                    MessageBox.Show("No se encontro el dia de lectura en el archivo de Excel de precipitacion. Dia: " + iDay.ToString());
                    pProDia.HideDialog();
                    _excelApp.Workbooks.Close();
                    return;
                }

                List <Lectura> listaPrecipitacion = preparar.ObtenerLecturas(sheet, _sigpiDao, SIGPI_COLUMNA_CODIGO_PRECIPITACION,
                                                                             sColumnaDia, SIGPI_PRECIPITACION_MIN_VAL, SIGPI_PRECIPITACION_MAX_VAL);
                //MessageBox.Show("lecturas a incorporar Prec. : " + listaPrecipitacion.Count.ToString());
                bool bIncorporarPrecip = preparar.IncorporarLecturas(_sigpiDao, SIGPI_TABLA_LECTURAS_PRECIPITACION,
                                                                     dFechaIncorporacionActual, listaPrecipitacion);

                pStepPro.StepValue = 4;
                pProDia.HideDialog();

                if (bIncorporarTemperatura && bIncorporarPrecip)
                {
                    txtUltimoDiaIncorporacion.Text = dtPickerFechaAIncorporar.Value.ToLongDateString();
                    preparar.ActualizarFechaIncorporacion(dtPickerFechaAIncorporar.Value, _sigpiDao);
                    _sigpi.FechaIncorporacion      = dtPickerFechaAIncorporar.Value;
                    dtPickerFechaAProcesar.Value   = dtPickerFechaAIncorporar.Value;
                    dtPickerFechaAIncorporar.Value = dtPickerFechaAIncorporar.Value.AddDays(1);
                    MessageBox.Show("Incorporacion de lecturas terminada!");
                }
            }
            finally
            {
                _excelApp.Workbooks.Close();
            }
        }
Пример #28
0
        /// <summary>
        /// Incorpora lecturas desde los archivos descargados desde la intranet
        /// </summary>
        private void IncorporarLecturas2()
        {
            statusLblProcesando.Text = "Incorporando Lecturas...";

            IProgressDialogFactory pProDiaFac = new ProgressDialogFactoryClass();
            IStepProgressor        pStepPro   = pProDiaFac.Create(null, 0);

            pStepPro.MinRange  = 1;
            pStepPro.MaxRange  = 5;
            pStepPro.StepValue = 1;
            IProgressDialog2 pProDia = (IProgressDialog2)pStepPro;

            pProDia.Animation = esriProgressAnimationTypes.esriProgressGlobe;

            pProDia.Title = "Incorporando Lecturas";
            pProDia.ShowDialog();
            pStepPro.Step();
            pStepPro.Message = "Incorporando temperatura...";

            SIGPIParametros parametros = _parametros;

            PrepararInformacion preparar = new PrepararInformacion();
            string mesTemperatura, mesPrecipitacion;
            string sRuta = parametros.RutaSIGPI + "\\" + parametros.Lecturas + "\\" + LECTURAS_TEMPERATURA;

            if (!System.IO.File.Exists(sRuta))
            {
                MessageBox.Show("No existe el Archivo '" + sRuta + "' Verifique la ruta");
                return;
            }
            Microsoft.Office.Interop.Excel.Application _excelApp = new Microsoft.Office.Interop.Excel.Application();
            Workbook workBook = _excelApp.Workbooks.Open(sRuta, Type.Missing, Type.Missing, Type.Missing,
                                                         Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                                         Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            Worksheet sheet;

            try
            {
                sheet = (Worksheet)workBook.Sheets[1];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                _excelApp.Workbooks.Close();
                pProDia.HideDialog();
                return;
            }
            mesTemperatura = "";
            try
            {
                mesTemperatura = preparar.VerificarFechasLecturas(sheet, SIGPI_CELDA_MES_TEMPERATURA);
            }
            catch (Exception ex)
            {
                _excelApp.Workbooks.Close();
                pProDia.HideDialog();
                MessageBox.Show(ex.Message);
                return;
            }
            DateTime dFechaAIncorporar = dtPickerFechaAIncorporar.Value;
            int      iDay = dFechaAIncorporar.Day;

            if (dFechaAIncorporar.Month != ConversionMes.MesNumero(mesTemperatura.ToUpper()))
            {
                if (dFechaAIncorporar.Month != ConversionMes.MesNumero(mesTemperatura.ToUpper()) + 1)
                {
                    MessageBox.Show("La fecha seleccionada no se encuentra en el archivo de lecturas. Periodo correspondiente al mes de: " + mesTemperatura);
                    _excelApp.Workbooks.Close();
                    pProDia.HideDialog();
                    return;
                }
            }

            int    iTotalEstaciones = preparar.TotalEstaciones(sheet, SIGPI_COLUMNA_ESTACIONES);
            string sColumnaDia      = preparar.ColumnaLecturaDia(sheet, 8, iDay.ToString(), "3");

            if (sColumnaDia == "-99")
            {
                MessageBox.Show("No se encontro el dia de lectura en el archivo de Excel de temperaturas. Dia: " + iDay.ToString());
                _excelApp.Workbooks.Close();
                pProDia.HideDialog();
                return;
            }

            List <Lectura> listaTemperatura = preparar.ObtenerLecturas(sheet, _sigpiDao, SIGPI_COLUMNA_CODIGO_TEMPERATURA, sColumnaDia,
                                                                       SIGPI_TEMPERATURA_MIN_VAL, SIGPI_TEMPERATURA_MAX_VAL);
            //pStepPro.Step();
            DateTime dFechaIncorporacionActual = dtPickerFechaAIncorporar.Value; //_sigpi.FechaIncorporacion.AddDays(1);
            //string sFechaIncorporacionActual = dFechaIncorporacionActual.ToString("dd/MM/yyyy");

            bool bIncorporarTemperatura = preparar.IncorporarLecturas(_sigpiDao, SIGPI_TABLA_LECTURAS_TEMPERATURA, dFechaIncorporacionActual, listaTemperatura);

            pStepPro.Message = "Incorporando Precipitacion...";
            pStepPro.Step();
            pStepPro.StepValue = 3;

            sRuta = parametros.RutaSIGPI + "\\" + parametros.Lecturas + "\\" + LECTURAS_PRECIPITACION;

            _excelApp.Workbooks.Close();

            _excelApp = new Microsoft.Office.Interop.Excel.Application();
            workBook  = _excelApp.Workbooks.Open(sRuta, Type.Missing, Type.Missing, Type.Missing,
                                                 Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                                 Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            sheet = (Worksheet)workBook.Sheets[1];

            try
            {
                mesPrecipitacion = preparar.VerificarFechasLecturas(sheet, SIGPI_CELDA_MES_PRECIPITACION);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                _excelApp.Workbooks.Close();
                pProDia.HideDialog();
                return;
            }

            sColumnaDia = preparar.ColumnaLecturaDia(sheet, 8, iDay.ToString(), "2");
            if (sColumnaDia == "-99")
            {
                MessageBox.Show("No se encontro el dia de lectura en el archivo de Excel de precipitacion. Dia: " + iDay.ToString());
                _excelApp.Workbooks.Close();
                pProDia.HideDialog();
                return;
            }

            List <Lectura> listaPrecipitacion = preparar.ObtenerLecturas(sheet, _sigpiDao, SIGPI_COLUMNA_CODIGO_PRECIPITACION, sColumnaDia,
                                                                         SIGPI_PRECIPITACION_MIN_VAL, SIGPI_PRECIPITACION_MAX_VAL);

            bool bIncorporarPrecip = preparar.IncorporarLecturas(_sigpiDao, SIGPI_TABLA_LECTURAS_PRECIPITACION, dFechaIncorporacionActual, listaPrecipitacion);

            pStepPro.StepValue = 4;
            pProDia.HideDialog();

            if (bIncorporarTemperatura && bIncorporarPrecip)
            {
                txtUltimoDiaIncorporacion.Text = dtPickerFechaAIncorporar.Value.ToLongDateString();
                preparar.ActualizarFechaIncorporacion(dtPickerFechaAIncorporar.Value, _sigpiDao);
                _sigpi.FechaIncorporacion      = dtPickerFechaAIncorporar.Value;
                dtPickerFechaAProcesar.Value   = dtPickerFechaAIncorporar.Value;
                dtPickerFechaAIncorporar.Value = dtPickerFechaAIncorporar.Value.AddDays(1);
                MessageBox.Show("Incorporacion de lecturas terminada!");
            }
            _excelApp.Workbooks.Close();
        }
Пример #29
0
        /// <summary>
        /// Occurs when this command is clicked
        /// </summary>
        public override void OnClick()
        {
            try
            {
                if (m_application == null)
                {
                    return;
                }
                IDocument document = m_application.Document;

                //根据应用类型初始化
                switch (applicationType)
                {
                case ApplicationType.ArcMap:
                {
                    IMxDocument mxDocument = (IMxDocument)(document);
                    if (mxDocument != null)
                    {
                        m_map = mxDocument.FocusMap;
                    }
                    if (m_map == null)
                    {
                        return;
                    }
                    activeView = m_map as IActiveView;

                    //有图层则选颜色
                    if (m_map.LayerCount == 0)
                    {
                        return;
                    }
                    if (Common.SelectColor(out FromIC, out ToIC) == false)
                    {
                        return;
                    }

                    //选图层
                    if (Common.SelectLayer(m_map.Layers, out SelectedLyrIndex) == false)
                    {
                        return;
                    }
                    break;
                }

                case ApplicationType.ArcScene:
                {
                    ISxDocument sxDocument = (ISxDocument)(document);
                    if (sxDocument != null)
                    {
                        m_scene = sxDocument.Scene;
                    }
                    if (m_scene == null)
                    {
                        return;
                    }
                    activeView = m_scene as IActiveView;

                    //有图层则选颜色
                    if (m_scene.LayerCount == 0)
                    {
                        return;
                    }
                    if (Common.SelectColor(out FromIC, out ToIC) == false)
                    {
                        return;
                    }

                    //选图层
                    if (Common.SelectLayer(m_scene.Layers, out SelectedLyrIndex) == false)
                    {
                        return;
                    }
                    break;
                }

                default:
                {
                    throw new ArgumentException("未指定应用类型。");
                }
                }

                //Create a CancelTracker.
                ITrackCancel pTrackCancel = new CancelTrackerClass();

                //Create the ProgressDialog. This automatically displays the dialog
                IProgressDialogFactory pProgDlgFactory = new ProgressDialogFactoryClass();
                IProgressDialog2       pProDlg         = pProgDlgFactory.Create(pTrackCancel, m_application.hWnd) as IProgressDialog2;
                pProDlg.CancelEnabled = true;
                pProDlg.Title         = "正在进行唯一值计算";
                pProDlg.Description   = "唯一值计算中,请稍候...";

                pProDlg.Animation = esriProgressAnimationTypes.esriProgressSpiral;

                IStepProgressor pStepPro = pProDlg as IStepProgressor;
                pStepPro.MinRange  = 0;
                pStepPro.MaxRange  = SelectedLyrIndex.Count;
                pStepPro.StepValue = 1;
                pStepPro.Message   = "初始化中...";


                bool bCont = true;

                //对每一个选中的图层进行唯一值化
                for (int i = 0; i < SelectedLyrIndex.Count; i++)
                {
                    //m_application.StatusBar.set_Message(0, i.ToString());
                    pStepPro.Message = "已完成(" + i.ToString() + "/" + SelectedLyrIndex.Count.ToString() + ")";
                    bCont            = pTrackCancel.Continue();
                    if (!bCont)
                    {
                        break;
                    }

                    IRasterLayer rasterLayer = null;
                    switch (applicationType)
                    {
                    case ApplicationType.ArcMap:
                    {
                        rasterLayer = m_map.Layer[SelectedLyrIndex[i]] as IRasterLayer;
                        break;
                    }

                    case ApplicationType.ArcScene:
                    {
                        rasterLayer = m_scene.Layer[SelectedLyrIndex[i]] as IRasterLayer;
                        break;
                    }

                    default:
                    {
                        throw new ArgumentException("未指定应用类型。");
                    }
                    }
                    if (rasterLayer == null)
                    {
                        pStepPro.Message = "选中的图层非栅格图层...";
                        continue;
                    }

                    //设置图层渲染器并更新
                    IRasterRenderer pRasterRenderer = UniqueValueRender(rasterLayer); //渲染唯一值
                    rasterLayer.Renderer = pRasterRenderer;
                    rasterLayer.Renderer.Update();

                    //==========================================
                    //刷新看起来不起作用
                    if (applicationType == ApplicationType.ArcScene)
                    {
                        m_scene.SceneGraph.Invalidate(rasterLayer, true, false);
                        m_sceneHookHelper.ActiveViewer.Redraw(true);

                        m_scene.SceneGraph.RefreshViewers();
                        //pRasterRenderer.Draw(rasterLayer.Raster,esriDrawPhase.esriDPGeography,display,null);
                    }
                    //==========================================
                }
                pProDlg.HideDialog();
                //刷新
                if (activeView == null)
                {
                    throw new Exception("活动视图为空! ");
                }
                switch (applicationType)
                {
                case ApplicationType.ArcMap:
                {
                    activeView.Refresh();
                    break;
                }

                case ApplicationType.ArcScene:
                {
                    //==========================================
                    //刷新看起来不起作用

                    //if (m_sceneHookHelper.ActiveViewer == null)
                    //    throw new Exception("无活动视图。");
                    activeView.Refresh();
                    //m_sceneHookHelper.ActiveViewer.Redraw(true);

                    //IDisplay display = m_scene.SceneGraph as IDisplay;
                    //if (display == null)
                    //    throw new ArgumentNullException("显示对象为空。");
                    //for (int i = 0; i < SelectedLyrIndex.Count; i++)
                    //{
                    //    IRasterLayer rasterLayer = m_scene.Layer[SelectedLyrIndex[i]] as IRasterLayer;
                    //    rasterLayer.Draw(esriDrawPhase.esriDPGeography, display, null);
                    //}

                    //IViewers3D viewers3D = m_scene.SceneGraph as IViewers3D;
                    //if (viewers3D == null)
                    //    throw new ArgumentNullException("3D显示对象为空。");
                    //viewers3D.RefreshViewers();
                    break;
                    //==========================================
                }

                default:
                {
                    throw new ArgumentException("未指定应用类型。");
                }
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.ToString());
            }
        }
Пример #30
0
        public void ExtractPointData(string sLineLayer, string sRasterLayer, double dblInterval, string strFileName)
        {
            try
            {
                strSaveFile = strFileName;

                IMxDocument pmxdoc = ArcMap.Document as IMxDocument;
                IMap        pmap   = pmxdoc.FocusMap;


                IFeatureLayer pLineLayer   = FindLayer(sLineLayer) as IFeatureLayer;
                IRasterLayer  pRasterLayer = FindLayer(sRasterLayer) as IRasterLayer;
                //IFeatureLayer pPointLayer = FindLayer(sPointLayer) as IFeatureLayer;
                IFeatureLayer pPointLayer = new FeatureLayerClass();
                pPointLayer.FeatureClass = MakePointFC();
                //pPointLayer.Name = "Points";
                // ArcMap.Document.ActiveView.FocusMap.AddLayer(pPointLayer);


                //get the Workspace from the IDataset interface on the feature class
                IDataset   dataset   = (IDataset)pLineLayer.FeatureClass;
                IWorkspace workspace = dataset.Workspace;
                //Cast for an IWorkspaceEdit
                IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;

                //Start an edit session and operation
                workspaceEdit.StartEditing(true);
                workspaceEdit.StartEditOperation();

                IProgressDialog2 pProgressDialog = ShowProgressIndicator("Calculating...", pLineLayer.FeatureClass.FeatureCount(null), 1);
                pProgressDialog.ShowDialog();


                //Set up the Outpoints cursor
                IFeatureCursor pFCurOutPoints = pPointLayer.Search(null, false);
                pFCurOutPoints = pPointLayer.FeatureClass.Insert(true);

                //Set up the LineLayer Cursor
                IFeatureCursor pFCur        = pLineLayer.Search(null, false);
                IFeature       pLineFeature = pFCur.NextFeature();

                IFeatureBuffer pFBuffer = pPointLayer.FeatureClass.CreateFeatureBuffer();



                ICurve pCurve;


                double dlbProcessedLength = 0;
                double dblFCTotalLength   = 0;
                int    p = 0;

                while (pLineFeature != null)
                {
                    pProgressDialog.Description = "Calculating line segment " + p.ToString() + " of: " + pLineLayer.FeatureClass.FeatureCount(null).ToString();

                    //create startpoint
                    pCurve         = pLineFeature.Shape as ICurve;
                    pFBuffer.Shape = pCurve.FromPoint;


                    pFBuffer.set_Value(pFBuffer.Fields.FindField("Distance"), 0);
                    pFBuffer.set_Value(pFBuffer.Fields.FindField("LineOID"), pLineFeature.OID);
                    pFBuffer.set_Value(pFBuffer.Fields.FindField("X"), pCurve.FromPoint.X);
                    pFBuffer.set_Value(pFBuffer.Fields.FindField("Y"), pCurve.FromPoint.Y);

                    pFCurOutPoints.InsertFeature(pFBuffer);

                    double dblTotalDistance = pCurve.Length;
                    dlbProcessedLength = dblInterval;


                    IConstructPoint contructionPoint;
                    IPoint          ppoint;
                    while (dlbProcessedLength <= dblTotalDistance)
                    {
                        contructionPoint = new PointClass();
                        contructionPoint.ConstructAlong(pCurve, esriSegmentExtension.esriNoExtension, dlbProcessedLength, false);
                        ppoint = new PointClass();
                        ppoint = contructionPoint as IPoint;

                        pFBuffer.Shape = ppoint;



                        //dblFCTotalLength += dblInterval;

                        pFBuffer.set_Value(pFBuffer.Fields.FindField("Distance"), Math.Round(dlbProcessedLength, 4));
                        pFBuffer.set_Value(pFBuffer.Fields.FindField("LineOID"), pLineFeature.OID);
                        pFBuffer.set_Value(pFBuffer.Fields.FindField("X"), ppoint.X);
                        pFBuffer.set_Value(pFBuffer.Fields.FindField("Y"), ppoint.Y);

                        pFCurOutPoints.InsertFeature(pFBuffer);
                        dlbProcessedLength += dblInterval;

                        pStepProgressor.Step();
                    }

                    dblFCTotalLength += dblInterval;
                    p++;
                    pLineFeature = pFCur.NextFeature();
                }

                //cleanup
                pFCurOutPoints.Flush();
                pFCur.Flush();

                //Stop editing
                workspaceEdit.StopEditOperation();
                workspaceEdit.StopEditing(true);

                Extract(pRasterLayer, pPointLayer);

                pProgressDialog.HideDialog();
                pmxdoc.ActiveView.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show(ex.StackTrace);
            }
        }
Пример #31
0
        private void CreateBatchFile()
        {
            string path             = "";
            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (fbd.ShowDialog() == DialogResult.OK)
            {
                path = fbd.SelectedPath;
            }

            if (!Directory.Exists(path))
            {
                Utilities_MessageBox.ErrorBox("Path Does Not Exist", MB_TITLE);
                return;
            }

            int    versionCount = 1; // This is used to make mutiple files so the batch file don't overwrite on another.
            string filePath     = path + string.Format(@"\{0}_{1}_{2}.bat", cbo_TileIndex.Text, "CopyFiles", versionCount);

            while (File.Exists(filePath))
            {
                versionCount++;
                filePath = path + string.Format(@"\{0}_{1}_{2}.bat", cbo_TileIndex.Text, "CopyFiles", versionCount);
            }



            bool itWorked = false;



            int                    cloneCount            = 1; // labeling the processor bar
            ITrackCancel           trackcancel           = new CancelTracker();
            IProgressDialogFactory progressdialogfactory = new ProgressDialogFactoryClass();
            IStepProgressor        stepprogressor        = progressdialogfactory.Create(trackcancel, _application.hWnd);

            stepprogressor.MinRange  = 0;
            stepprogressor.MaxRange  = _fileList.Count;
            stepprogressor.StepValue = 1;
            stepprogressor.Message   = "Generating...";
            IProgressDialog2 progressdialog = (IProgressDialog2)stepprogressor; // Creates and displays

            progressdialog.CancelEnabled = false;
            progressdialog.Description   = "Prepping {_fileList.Count} files...";
            progressdialog.Title         = MB_TITLE;
            progressdialog.Animation     = esriProgressAnimationTypes.esriProgressSpiral;


            foreach (KeyValuePair <String, Boolean> file in _fileList)
            {
                if (file.Value)
                {
                    progressdialog.Description = string.Format("Adding File {0} of {1}...", cloneCount, _fileList.Count);
                    if (!itWorked)
                    {
                        SaveFileTypeList(GetExtension());
                    }
                    itWorked = true;

                    try
                    {
                        var sourceFile      = txb_FileWorkspaceSrc.Text + @"\" + Utilities_General.AddPrefixAndSuffixToFileName(file.Key, txb_Prefix.Text, txb_Suffix.Text) + GetExtension();
                        var destinationFile = txb_FileWorkspaceDst.Text + @"\" + Utilities_General.AddPrefixAndSuffixToFileName(file.Key, txb_Prefix.Text, txb_Suffix.Text) + GetExtension();

                        using (System.IO.StreamWriter sw = File.AppendText(filePath))
                        {
                            sw.WriteLine(String.Format("copy {0} {1}", sourceFile, destinationFile));
                        }
                    }
                    catch (Exception yourBest) // but you don't succeed
                    {
                        yourBest.ToString();
                        // Just So We Get No Crashes ;)
                    }
                    stepprogressor.Step();
                    cloneCount++;
                }
            }
            trackcancel    = null;
            stepprogressor = null;
            progressdialog.HideDialog();
            progressdialog = null;
            //_activeView.Refresh();
        }
Пример #32
0
        protected override void OnClick()
        {
            //go get a traverse file
            // Display .Net dialog for File selection.
            OpenFileDialog openFileDialog = new OpenFileDialog();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                #endregion

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

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

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

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

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

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

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

                    pProDlg.Description = "File: " + System.IO.Path.GetFileName(CadastralXMLPath) + " (" + iFileCount.ToString() + " of " + iTotalFiles.ToString() + ")";
                    //(pCadFabric as ICadastralFabric3).PostCadastralPacket(pStream, pTrkCan, esriCadastralPacketSetting.esriCadastralPacketNoSetting, ref pFIDSet);
                    (pCadFabric as ICadastralFabric3).InsertCadastralPacket(CadaJob, pStream, pTrkCan, esriCadastralPacketSetting.esriCadastralPacketNoSetting, ref pFIDSet);
                    //int setCnt = pFIDSet.Count();
                }
                RefreshFabricLayers(ArcMap.Document.ActiveView.FocusMap, pCadFabric);
                pEd.StopOperation("Append " + iFileCount.ToString() + " cadastral XML files");
            }
            catch (Exception ex)
            {
                pEd.AbortOperation();
                COMException c_Ex;
                int          errorCode = 0;
                if (ex is COMException)
                {
                    c_Ex      = (COMException)ex;
                    errorCode = c_Ex.ErrorCode;
                }
                if (errorCodeDict.ContainsKey(errorCode))
                {
                    MessageBox.Show(errorCodeDict[errorCode], "Append files");
                }
                else
                {
                    MessageBox.Show("Error: " + ex.Message + Environment.NewLine + ex.HResult.ToString(), "Append files");
                }
            }
            finally
            {
                if (sCopiedCadastralXMLFile != string.Empty)
                {
                    File.Delete(sCopiedCadastralXMLFile);
                }
                if (pProDlg != null)
                {
                    pProDlg.HideDialog();
                }
            }
        }
        public void GeneratePoints2(string sLineLayer, string sDepthPointsLayer, double dblInterval, string strDepthField)
        {
            try
            {
                IMxDocument pmxdoc = ArcMap.Document as IMxDocument;
                IMap        pmap   = pmxdoc.FocusMap;

                IFeatureLayer pDepthSoundings = FindLayer(pmap, sDepthPointsLayer) as IFeatureLayer;
                IFeatureLayer pLineLayer      = FindLayer(pmap, sLineLayer) as IFeatureLayer;
                IFeatureLayer pOutpoints      = new FeatureLayerClass();
                pOutpoints.FeatureClass = MakePointFC();
                pOutpoints.Name         = "Output Points";
                ArcMap.Document.ActiveView.FocusMap.AddLayer(pOutpoints);

                IProgressDialog2 pProgressDialog = ShowProgressIndicator("Calculating...", pLineLayer.FeatureClass.FeatureCount(null), 1);
                pProgressDialog.ShowDialog();

                //Set up the Outpoints cursor
                IFeatureCursor pFCurOutPoints = pOutpoints.Search(null, false);
                pFCurOutPoints = pOutpoints.FeatureClass.Insert(true);

                //Set up the LineLayer Cursor
                IFeatureCursor pFCur        = pLineLayer.Search(null, false);
                IFeature       pLineFeature = pFCur.NextFeature();

                IFeatureBuffer pFBuffer = pOutpoints.FeatureClass.CreateFeatureBuffer();

                ICurve pCurve;
                IPoint ppoint;

                int    iLineProgressCount         = 1;
                double dblDistance                = 0;
                double dblTotalDistanceCalculated = 0;
                double iNumIntervals              = 0;
                double dblElevationDiff           = 0;
                double dblElevationInterval       = 0;
                double dblElevation               = 0;
                double dlbStartElevation          = 0;
                double dblEndElevation            = 0;

                pProgressDialog.Description = "Generating points for Line: " + iLineProgressCount + " of " + pLineLayer.FeatureClass.FeatureCount(null).ToString();

                while (pLineFeature != null)
                {
                    int iStartVertex = 0;
                    int iEndVertex   = 1;
                    //Get the vertices of the line feature
                    IPointCollection4 pPointColl = pLineFeature.Shape as IPointCollection4;


                    //loop thru the vertices
                    for (int i = 0; i <= pPointColl.PointCount - 1; i++)
                    {
                        IPoint pStartPoint = pPointColl.get_Point(iStartVertex);
                        IPoint pEndPoint   = pPointColl.get_Point(iEndVertex);
                        //Make an intermediate line segment between each set of vertices
                        IPath pPath = MakePath(pStartPoint, pEndPoint);

                        //Get the starting elevation from the depth point layer
                        dlbStartElevation = GetPointElevation(pDepthSoundings, pLineLayer, pStartPoint, strDepthField);
                        dblElevation      = dlbStartElevation;
                        IPointCollection pPointForPath = null;
                        //Get the ending elevation from the next vertex
                        pEndPoint       = pPointColl.get_Point(iEndVertex);
                        dblEndElevation = GetPointElevation(pDepthSoundings, pLineLayer, pEndPoint, strDepthField);
                        //If the returned elevation is 0, then there is no coincident depth point, move to the next vertex for your endpoint
                        if (dblEndElevation == 0)
                        {
                            //IPointCollection reshapePath = new PathClass();
                            object missing = Type.Missing;
                            pPointForPath = new PathClass();
                            pPointForPath.AddPoint(pStartPoint, ref missing, ref missing);
                            while (dblEndElevation == 0)
                            {
                                pEndPoint       = pPointColl.get_Point(iEndVertex);
                                dblEndElevation = GetPointElevation(pDepthSoundings, pLineLayer, pEndPoint, strDepthField);


                                pPointForPath.AddPoint(pEndPoint, ref missing, ref missing);
                                //pLineSegment.Reshape(reshapePath as IPath);

                                if (dblEndElevation != 0)
                                {
                                    break;
                                }
                                iEndVertex++;
                            }
                        }

                        if (pPointForPath != null)
                        {
                            pPath = pPointForPath as IPath;
                        }



                        //number of line segments based on the user's interval
                        iNumIntervals    = Convert.ToDouble(pPath.Length / dblInterval);
                        dblElevationDiff = dblEndElevation - dlbStartElevation;

                        //The calculated elevation interval to step up each time
                        dblElevationInterval = dblElevationDiff / iNumIntervals;


                        ppoint = new PointClass();

                        while (dblTotalDistanceCalculated <= pPath.Length)
                        {
                            pFBuffer.set_Value(pFBuffer.Fields.FindField("LineOID"), pLineFeature.OID);
                            pFBuffer.set_Value(pFBuffer.Fields.FindField("Distance"), Math.Round(dblDistance, 4));
                            pFBuffer.set_Value(pFBuffer.Fields.FindField("Elevation"), Math.Round(dblElevation, 4));


                            //this code set the point on the line at a distance
                            pPath.QueryPoint(0, dblDistance, false, ppoint);



                            pFBuffer.set_Value(pFBuffer.Fields.FindField("X"), ppoint.X);
                            pFBuffer.set_Value(pFBuffer.Fields.FindField("Y"), ppoint.Y);

                            //reCalc the new distance and elevation values for the next iteration
                            dblDistance = dblDistance + dblInterval;
                            dblTotalDistanceCalculated = dblTotalDistanceCalculated + dblInterval;

                            //Insert the feature into the featureclass
                            pFBuffer.Shape = ppoint;

                            if (!IsPointCoincident(ppoint, pOutpoints))
                            {
                                pFCurOutPoints.InsertFeature(pFBuffer);
                            }


                            if (dblTotalDistanceCalculated >= pPath.Length)
                            {
                                break;
                            }

                            dblElevation = dblElevation + dblElevationInterval;
                        }



                        //start the next line segment at the end of last one
                        iStartVertex = iEndVertex;
                        //look to the next vertex for the new ending point
                        iEndVertex++;


                        if (iEndVertex == pPointColl.PointCount)
                        {
                            ////if its the last vertex of the last line, add a point
                            //pFBuffer.Shape = pPath.ToPoint;
                            //pFBuffer.set_Value(pFBuffer.Fields.FindField("LineOID"), pLineFeature.OID);
                            //pFBuffer.set_Value(pFBuffer.Fields.FindField("Distance"), Math.Round(dblDistance, 4));
                            //pFBuffer.set_Value(pFBuffer.Fields.FindField("Elevation"), Math.Round(dblElevation, 4));
                            //pFBuffer.set_Value(pFBuffer.Fields.FindField("X"), pPath.ToPoint.X);
                            //pFBuffer.set_Value(pFBuffer.Fields.FindField("Y"), pPath.ToPoint.Y);
                            //pFCurOutPoints.InsertFeature(pFBuffer);

                            //Reset the distance values back to 0 for the next feature
                            dblDistance = 0;
                            dblTotalDistanceCalculated = 0;
                            pStepProgressor.Step();
                            iLineProgressCount++;
                            pPath.SetEmpty();
                            break;
                        }


                        //Reset the distance values back to 0 for the next feature
                        dblDistance = 0;
                        dblTotalDistanceCalculated = 0;
                        //pLineFeature = pFCur.NextFeature();
                        pStepProgressor.Step();
                        //pProgressDialog.Description = "Generating points for Line: " + iLineProgressCount + " of " + pLineLayer.FeatureClass.FeatureCount(null).ToString();
                        iLineProgressCount++;
                        pPath.SetEmpty();
                    }
                    pLineFeature = pFCur.NextFeature();
                }



                //cleanup
                pFCurOutPoints.Flush();
                pFCur.Flush();
                pProgressDialog.HideDialog();
                pmxdoc.ActiveView.Refresh();
            }
            catch (Exception ex)
            {
            }
        }
Пример #34
0
        protected override void OnClick()
        {
            bool            bShowProgressor = false;
            IStepProgressor pStepProgressor = null;
            //Create a CancelTracker.
            ITrackCancel           pTrackCancel = null;
            IProgressDialogFactory pProgressorDialogFact;

            IMouseCursor pMouseCursor = new MouseCursorClass();

            pMouseCursor.SetCursor(2);

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

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

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

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

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

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

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

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

            IArray CFControlLayers = new ArrayClass();

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

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

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

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

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

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

                bShowProgressor = (iTotalSelectionCount > 10);

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

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

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

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

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

                    m_pFIDSetControl = new FIDSetClass();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (pMouseCursor != null)
                {
                    pMouseCursor.SetCursor(0);
                }
            }
        }
        private void ExportLayer(Excel.Workbook ExcelWbk, IMxDocument MxDoc, IFeatureLayer FLayer, ref IProgressDialog2 progressDialog, ref IStepProgressor stepProgressor)
        {
            IFeatureClass FC = null;
            ISubtypes Subtypes = null;

            ITableProperties TableProperties = null;
            IEnumTableProperties EnumTableProperties = null;
            ITableProperty3 TableProperty = null;
            ITableCharacteristics TableCharacteristics = null;
            IFeatureSelection FeatSel = null;
            IDisplayTable DisplayTable = null;
            ITable Table = null;
            ILayerFields LayerFields = null;
            ITableFields TableFields = null;
            ILayer LayerTest = null;

            ICursor Cursor = null;
            IFeatureCursor FCursor = null;
            IField CurField = null;
            IDomain Domain = null;
            ICodedValueDomain CodedValueDomain = null;
            IFeature Feat = null;
            List<IPoint> pGeo = null;

            object missing = null;
            object sheet = null;
            Excel.Worksheet ExcelSheet = null;
            Excel.Range ExcelRange = null;
            Microsoft.Office.Interop.Excel.Style style = null;

            try
            {

                int Col = 0;
                int Row = 0;
                int i;
                int j;
                bool UseDescriptions;
                int subtype;
                string SheetName;

                missing = System.Reflection.Missing.Value;
                sheet = ExcelWbk.Sheets[ExcelWbk.Sheets.Count];

                //Add new Excel worksheet
                ExcelSheet = (Excel.Worksheet)ExcelWbk.Sheets.Add(missing, sheet, missing, missing);
                SheetName = FLayer.Name;
                if (SheetName.Length > 30)
                {
                    SheetName = SheetName.Substring(0, 30);
                }
                ExcelSheet.Name = SheetName;

                //style = ExcelWbk.Styles.Add("Style1");
                //style.NumberFormat = "@";

                LayerTest = (ILayer)FLayer;

                //Get Subtype info
                FC = FLayer.FeatureClass;
                Subtypes = FC as ISubtypes;
                //Determine whether to use descriptions or codes for domains and subtypes
                UseDescriptions = true;
                TableProperties = MxDoc.TableProperties;
                EnumTableProperties = (IEnumTableProperties)TableProperties;
                EnumTableProperties.Reset();
                TableProperty = (ITableProperty3)EnumTableProperties.Next();
                while (TableProperty != null && TableProperty.Layer != null)  //Fixed
                {
                    if (TableProperty.Layer.Equals(LayerTest))
                    {
                        TableCharacteristics = (ITableCharacteristics)TableProperty;
                        UseDescriptions = TableCharacteristics.ShowCodedValueDomainDescriptions;
                    }
                    TableProperty = (ITableProperty3)EnumTableProperties.Next();
                }
                FeatSel = (IFeatureSelection)FLayer;

                DisplayTable = (IDisplayTable)FLayer;
                Table = (ITable)DisplayTable.DisplayTable;

                //Get TableFields so later we can determine whether that field is visible
                LayerFields = (ILayerFields)FLayer;
                TableFields = (ITableFields)FLayer;

                //loop through each field and write column headings
                Row = 1;
                for (j = 0; j < TableFields.FieldCount; j++)
                {
                    CurField = TableFields.get_Field(j);

                    //skip blob and geometry fields
                    if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry))
                    {
                        Col += 1;
                        //Write field alias name as Excel column header
                        ExcelSheet.Cells[Row, Col] = TableFields.get_FieldInfo(j).Alias;
                        if (CurField.Type == esriFieldType.esriFieldTypeString)
                            ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[65535, Col]).EntireColumn.NumberFormat = "@";

                    }
                }
                Col += 1;
                ExcelSheet.Cells[Row, Col] = "X_COORD";
                Col += 1;
                ExcelSheet.Cells[Row, Col] = "Y_COORD";
                Col += 1;
                ExcelSheet.Cells[Row, Col] = "Lat";
                Col += 1;
                ExcelSheet.Cells[Row, Col] = "Long";
                IField pFieldTest = FLayer.FeatureClass.Fields.get_Field(FLayer.FeatureClass.Fields.FindField(FLayer.FeatureClass.ShapeFieldName));
                IGeometryDef pGeometryDefTest = null;
                pGeometryDefTest = pFieldTest.GeometryDef;
                bool bZAware = false;
                bool bMAware = false;
                //Determine if M or Z aware
                if (pGeometryDefTest.GeometryType == esriGeometryType.esriGeometryPoint)
                {
                    bZAware = pGeometryDefTest.HasZ;
                    bMAware = pGeometryDefTest.HasM;
                }
                if (bZAware)
                {
                    Col += 1;
                    ExcelSheet.Cells[Row, Col] = "Z_COORD";
                }
                pFieldTest = null;
                pGeometryDefTest = null;
                //Get all selected records for this table (use IDisplayTable to get any joined data)
                DisplayTable.DisplaySelectionSet.Search(null, true, out Cursor);
                FCursor = (IFeatureCursor)Cursor;

                //subtype = Subtypes.DefaultSubtypeCode;

                //For each selected record

                Feat = FCursor.NextFeature();
                //  stepProgressor.Step();
                // progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("ExportAsset") + stepProgressor.Position + A4LGSharedFunctions.Localizer.GetString("Of") + MxDoc.FocusMap.SelectionCount.ToString() + ".";

                while (Feat != null)
                {
                    Row += 1;

                    if (Subtypes != null && Subtypes.HasSubtype == true &&
                       (Feat.get_Value(Subtypes.SubtypeFieldIndex) != null))
                    {
                        subtype = Convert.ToInt32(Feat.get_Value(Subtypes.SubtypeFieldIndex));
                    }
                    else
                    {
                        subtype = -99999;
                    }

                    //For each column
                    Col = 0;
                    for (j = 0; j < TableFields.FieldCount; j++)
                    {
                        CurField = TableFields.get_Field(j);

                        //skip blob and geometry fields in data also
                        if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry))
                        {
                            Col += 1;
                            ExcelSheet.Cells[Row, Col] = Feat.get_Value(j);

                            if (UseDescriptions == true && subtype == -99999)
                            {
                                Domain = CurField.Domain;
                                if (Domain != null)
                                {
                                    if (Domain.Type == esriDomainType.esriDTCodedValue)
                                    {
                                        CodedValueDomain = (ICodedValueDomain)CurField.Domain;
                                        for (i = 0; i < CodedValueDomain.CodeCount; i++)
                                        {
                                            if ((CodedValueDomain.get_Value(i)).ToString() == (Feat.get_Value(j)).ToString())
                                            {
                                                //System.Diagnostics.Debug.Print(CodedValueDomain.get_Name(0).ToString());
                                                ExcelSheet.Cells[Row, Col] = CodedValueDomain.get_Name(i);
                                                i = CodedValueDomain.CodeCount;
                                            }
                                        }
                                    }
                                }
                            }
                            else if (UseDescriptions == true && subtype != -99999)
                            {
                                if (Subtypes.SubtypeFieldIndex == j)
                                {
                                    ExcelSheet.Cells[Row, Col] = Subtypes.get_SubtypeName(subtype);
                                }
                                else
                                {
                                    Domain = Subtypes.get_Domain(subtype, CurField.Name);
                                    if ((Domain != null) && (Domain.Type == esriDomainType.esriDTCodedValue))
                                    {
                                        CodedValueDomain = (ICodedValueDomain)Domain;
                                        for (i = 0; i < CodedValueDomain.CodeCount; i++)
                                        {
                                            if ((CodedValueDomain.get_Value(i)).ToString() == (Feat.get_Value(j)).ToString())
                                            {
                                                //System.Diagnostics.Debug.Print(CodedValueDomain.get_Name(0).ToString());
                                                ExcelSheet.Cells[Row, Col] = CodedValueDomain.get_Name(i);
                                                i = CodedValueDomain.CodeCount;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (Feat.Shape != null)
                    {
                        if (Feat.Shape.IsEmpty == false)
                        {
                            pGeo = Globals.GetGeomCenter(Feat.Shape);
                            if (pGeo != null)
                            {

                                if (pGeo.Count > 0)
                                {
                                    if (pGeo[0].X != null)
                                        ExcelSheet.Cells[Row, Col + 1] = pGeo[0].X;
                                    if (pGeo[0].Y != null)
                                        ExcelSheet.Cells[Row, Col + 2] = pGeo[0].Y;
                                    if (pGeo[0] != null)
                                    {
                                        pGeo[0].Project(srWGS84);

                                        ExcelSheet.Cells[Row, Col + 3] = pGeo[0].Y;
                                        ExcelSheet.Cells[Row, Col + 4] = pGeo[0].X;
                                    }
                                    if (bZAware)
                                    {

                                        ExcelSheet.Cells[Row, Col + 5] = pGeo[0].Z;
                                    }
                                }
                            }
                        }
                    }

                    stepProgressor.Step();
                    progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("ExportAsset") + stepProgressor.Position + A4LGSharedFunctions.Localizer.GetString("Of") + MxDoc.FocusMap.SelectionCount.ToString() + ".";

                    Feat = FCursor.NextFeature();
                }

                //Hide Columns
                Col = 0;
                for (j = 0; j < TableFields.FieldCount; j++)
                {
                    CurField = TableFields.get_Field(j);

                    //skip blob and geometry fields in data also
                    if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry))
                    {
                        Col += 1;
                        //Autofit
                        ExcelRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[Row, Col]);
                        ExcelRange.EntireColumn.AutoFit();

                        //Hide column if invisible in ArcMap
                        if (TableFields.get_FieldInfo(j).Visible == false)
                        {
                            ExcelRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[Row, Col]);
                            ExcelRange.EntireColumn.Hidden = true;
                        }
                    }
                }
            }
            catch
            {
                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ExportXLError"));

            }
            finally
            {
                FC = null;
                Subtypes = null;

                TableProperties = null;
                if (EnumTableProperties != null)
                    Marshal.ReleaseComObject(EnumTableProperties);

                EnumTableProperties = null;
                TableProperty = null;
                TableCharacteristics = null;
                FeatSel = null;
                DisplayTable = null;
                Table = null;
                LayerFields = null;
                TableFields = null;
                LayerTest = null;
                if (Cursor != null)
                    Marshal.ReleaseComObject(Cursor);
                Cursor = null;

                if (FCursor != null)
                    Marshal.ReleaseComObject(FCursor);
                FCursor = null;
                CurField = null;
                Domain = null;
                CodedValueDomain = null;
                Feat = null;
                pGeo = null;

                missing = null;
                sheet = null;
                ExcelSheet = null;
                ExcelRange = null;
                style = null;

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

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

            IGxApplication pGXApp = (IGxApplication)m_pApp;

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

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

            IMouseCursor pMouseCursor = new MouseCursorClass();

            pMouseCursor.SetCursor(2);

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

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

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

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


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

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

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

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

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

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

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

            bool bDeleteTablesByRowInsteadOfTruncate = false;

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

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

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

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

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

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

                                ICursor pCur = pTableWr.InsertRows(false);

                                IRowBuffer pRowBuff = pTable.CreateRowBuffer();

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

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

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

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

                                pCur.InsertRow(pRowBuff);

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

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

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

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

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

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

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



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

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

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

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

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

                    pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints);
                }

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

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

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

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

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

                    IRowBuffer pRowBuff = pAccTable.CreateRowBuffer();

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

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

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

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

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

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

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

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

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

                Cleanup(pProgressorDialog, pMouseCursor);

                if (TableArray != null)
                {
                    TableArray.RemoveAll();
                }
                FabricUTILS.StopEditing(pWS);
            }
            catch (Exception ex)
            {
                FabricUTILS.AbortEditing(pWS);
                Cleanup(pProgressorDialog, pMouseCursor);
                MessageBox.Show(Convert.ToString(ex.Message));
            }
        }
        private void ExportTable(Excel.Workbook ExcelWbk, IMxDocument MxDoc, IStandaloneTable StandTable, ref IProgressDialog2 progressDialog, ref IStepProgressor stepProgressor)
        {
            ITableProperties TableProperties = null;
            IEnumTableProperties EnumTableProperties = null;
            ITableProperty3 TableProperty = null;
            ITableCharacteristics TableCharacteristics = null;
            ITableSelection TabSel = null;
            IDisplayTable DisplayTable = null;
            ITable Table = null;
            IRow TabRow = null;
            IObjectClass ObjectClass = null;
            ISubtypes Subtypes = null;
            ITableFields TableFields = null;

            ICursor Cursor = null;
            IField CurField = null;
            IDomain Domain = null;
            ICodedValueDomain CodedValueDomain = null;

            object missing = null;
            object sheet = null;
            Microsoft.Office.Interop.Excel.Style style = null;

            try
            {
                bool UseDescriptions;
                int subtype;
                string SheetName;

                int Col = 0;
                int Row = 0;
                int i;
                int j;

                missing = System.Reflection.Missing.Value;

                sheet = ExcelWbk.Sheets[ExcelWbk.Sheets.Count];
                Excel.Worksheet ExcelSheet;
                Excel.Range ExcelRange;

                //Add new Excel worksheet
                ExcelSheet = (Excel.Worksheet)ExcelWbk.Sheets.Add(missing, sheet, missing, missing);
                //style = ExcelWbk.Styles.Add("Style1");
                //style.NumberFormat = "@";
                //style.Font.Name = "Arial";
                //style.Font.Bold = True
                //style.Font.Size = 12;
                //style.Interior.Pattern = Microsoft.Office.Interop.Excel.XlPattern.xlPattern Solid
                //style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlighLe ft

                SheetName = StandTable.Name;
                if (SheetName.Length > 30)
                {
                    SheetName = SheetName.Substring(0, 30);
                }
                ExcelSheet.Name = SheetName;

                //Determine whether to use descriptions or codes for domains
                UseDescriptions = true;
                TableProperties = MxDoc.TableProperties;
                EnumTableProperties = (IEnumTableProperties)TableProperties;
                EnumTableProperties.Reset();
                TableProperty = (ITableProperty3)EnumTableProperties.Next();

                while (TableProperty != null)
                {
                    if (TableProperty.StandaloneTable != null)
                    {
                        if (TableProperty.StandaloneTable.Equals(StandTable))
                        {
                            TableCharacteristics = (ITableCharacteristics)TableProperty;
                            UseDescriptions = TableCharacteristics.ShowCodedValueDomainDescriptions;
                            break;
                        }
                    }
                    TableProperty = (ITableProperty3)EnumTableProperties.Next();
                }
                TabSel = (ITableSelection)StandTable;

                DisplayTable = (IDisplayTable)StandTable;
                Table = (ITable)DisplayTable.DisplayTable;

                //Get subtype info
                ObjectClass = Table as IObjectClass;
                Subtypes = ObjectClass as ISubtypes;

                //Get TableFields so later we can determine whether that field is visible
                TableFields = (ITableFields)StandTable;

                //loop through each field and write column headings
                Row = 1;
                for (j = 0; j < TableFields.FieldCount; j++)
                {
                    CurField = TableFields.get_Field(j);

                    //skip blob and geometry fields
                    if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry))
                    {
                        Col += 1;
                        //Write field alias name as Excel column header
                        ExcelSheet.Cells[Row, Col] = TableFields.get_FieldInfo(j).Alias;
                        if (CurField.Type == esriFieldType.esriFieldTypeString)
                            ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[65535, Col]).EntireColumn.NumberFormat = "@";

                    }
                }

                //Get all selected records for this table (use IDisplayTable to get any joined data)
                DisplayTable.DisplaySelectionSet.Search(null, true, out Cursor);

                //subtype = Subtypes.DefaultSubtypeCode;

                //For each selected record

                TabRow = Cursor.NextRow();
                //stepProgressor.Step();
                //     progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("ExportAsset") + stepProgressor.Position + A4LGSharedFunctions.Localizer.GetString("Of") + MxDoc.FocusMap.SelectionCount.ToString() + ".";

                while (TabRow != null)
                {
                    Row += 1;

                    if (Subtypes != null && Subtypes.HasSubtype == true &&
                       (TabRow.get_Value(Subtypes.SubtypeFieldIndex) != null))
                    {
                        subtype = Convert.ToInt32(TabRow.get_Value(Subtypes.SubtypeFieldIndex));
                    }
                    else
                    {
                        subtype = -99999;
                    }

                    //For each column
                    Col = 0;
                    for (j = 0; j < TableFields.FieldCount; j++)
                    {
                        CurField = TableFields.get_Field(j);

                        //skip blob and geometry fields in data also
                        if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry))
                        {
                            Col += 1;
                            ExcelSheet.Cells[Row, Col] = TabRow.get_Value(j);

                            if (UseDescriptions == true && subtype == -99999)
                            {
                                Domain = CurField.Domain;
                                if (Domain != null)
                                {
                                    if (Domain.Type == esriDomainType.esriDTCodedValue)
                                    {
                                        CodedValueDomain = (ICodedValueDomain)CurField.Domain;
                                        for (i = 0; i < CodedValueDomain.CodeCount; i++)
                                        {
                                            if ((CodedValueDomain.get_Value(i)).ToString() == (TabRow.get_Value(j)).ToString())
                                            {
                                                //System.Diagnostics.Debug.Print(CodedValueDomain.get_Name(0).ToString());
                                                ExcelSheet.Cells[Row, Col] = CodedValueDomain.get_Name(i);
                                                i = CodedValueDomain.CodeCount;
                                            }
                                        }
                                    }
                                }
                            }
                            else if (UseDescriptions == true && subtype != -99999)
                            {
                                if (Subtypes.SubtypeFieldIndex == j)
                                {
                                    ExcelSheet.Cells[Row, Col] = Subtypes.get_SubtypeName(subtype);
                                }
                                else
                                {
                                    Domain = Subtypes.get_Domain(subtype, CurField.Name);
                                    if ((Domain != null) && (Domain.Type == esriDomainType.esriDTCodedValue))
                                    {
                                        CodedValueDomain = (ICodedValueDomain)Domain;
                                        for (i = 0; i < CodedValueDomain.CodeCount; i++)
                                        {
                                            if ((CodedValueDomain.get_Value(i)).ToString() == (TabRow.get_Value(j)).ToString())
                                            {
                                                //System.Diagnostics.Debug.Print(CodedValueDomain.get_Name(0).ToString());
                                                ExcelSheet.Cells[Row, Col] = CodedValueDomain.get_Name(i);
                                                i = CodedValueDomain.CodeCount;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    stepProgressor.Step();
                    progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("ExportAsset") + stepProgressor.Position + A4LGSharedFunctions.Localizer.GetString("Of") + MxDoc.FocusMap.SelectionCount.ToString() + ".";

                    TabRow = Cursor.NextRow();
                }

                //Hide Columns
                Col = 0;
                for (j = 0; j < TableFields.FieldCount; j++)
                {
                    CurField = TableFields.get_Field(j);

                    //skip blob and geometry fields in data also
                    if ((CurField.Type != esriFieldType.esriFieldTypeBlob) && (CurField.Type != esriFieldType.esriFieldTypeGeometry))
                    {
                        Col += 1;
                        //Autofit
                        ExcelRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[Row, Col]);
                        ExcelRange.EntireColumn.AutoFit();

                        //Hide column if invisible in ArcMap
                        if (TableFields.get_FieldInfo(j).Visible == false)
                        {
                            ExcelRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, Col], ExcelSheet.Cells[Row, Col]);
                            ExcelRange.EntireColumn.Hidden = true;
                        }
                    }
                }
            }
            catch
            {
                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ExportXLError"));

            }
            finally
            {
                TableProperties = null;
                EnumTableProperties = null;
                TableProperty = null;
                TableCharacteristics = null;
                TabSel = null;
                DisplayTable = null;
                Table = null;
                TabRow = null;
                ObjectClass = null;
                Subtypes = null;
                TableFields = null;

                if (Cursor != null)
                    Marshal.ReleaseComObject(Cursor);
                Cursor = null;
                CurField = null;
                Domain = null;
                CodedValueDomain = null;

                missing = null;
                sheet = null;
                style = null;

            }
        }