コード例 #1
0
        /// <summary>
        /// Gets the index of the display field for the feature's layer, if it is on the map
        /// </summary>
        /// <param name="feature">IFeature to look for</param>
        /// <returns>int</returns>
        //public int GetDisplayIndex(ESRI.ArcGIS.Geodatabase.IFeature feature)
        //{
        //    if (null == feature)
        //    {
        //        throw new ArgumentNullException("feature");
        //    }
        //    else if (null == feature.Class)
        //    {
        //        throw new InvalidOperationException("feature.Class cannot be null");
        //    }

        //    int result = -1;

        //    int key = feature.Class.ObjectClassID;

        //    if (_displayIndices.ContainsKey(key))
        //    {
        //        result = _displayIndices[key];
        //    }
        //    else
        //    {
        //        ESRI.ArcGIS.Geodatabase.IDataset dataset = feature.Class as ESRI.ArcGIS.Geodatabase.IDataset;
        //        if (null != dataset)
        //        {
        //            string className = GdbUtils.ParseTableName(dataset);
        //            ESRI.ArcGIS.Carto.IFeatureLayer ftLayer = this.FindFeatureLayer(className);
        //            if (null != ftLayer)
        //            {
        //                result = feature.Fields.FindField(ftLayer.DisplayField);
        //            }
        //        }

        //        _displayIndices[key] = result;  // Putting it here means that we may store -1 even if the layer was undiscoverable
        //                                        // even one time...we could move it into where result is assigned if we wanted
        //                                        // it to recheck every time this is called
        //    }

        //    return result;
        //}

        /// <summary>
        /// Creates a new Progress Dialog in the hook, with a given ITrackCancel
        /// </summary>
        /// <param name="trackCancel">Tracks cancel</param>
        /// <param name="message">The message</param>
        /// <param name="min">Minimum progress</param>
        /// <param name="max">Maximum progress</param>
        /// <param name="step">Progress per step</param>
        /// <param name="desc">Description</param>
        /// <param name="title">Title</param>
        /// <returns>IProgressDialog2</returns>
        public ESRI.ArcGIS.Framework.IProgressDialog2 CreateProgressDialog(ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel, string message, int min, int max, int step, string desc, string title)
        {
            int?hWnd = this.hWnd;

            if (null == hWnd)
            {
                throw new InvalidOperationException("Unable to determine hWnd of Hook");
            }

            //ProgressBar
            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();

            // Set the properties of the Step Progressor
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = progressDialogFactory.Create(trackCancel, (int)hWnd);
            stepProgressor.MinRange  = min;
            stepProgressor.MaxRange  = max;
            stepProgressor.StepValue = step;
            stepProgressor.Message   = message;

            // Create the ProgressDialog. This automatically displays the dialog
            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast

            // Set the properties of the ProgressDialog
            progressDialog.CancelEnabled = true;
            progressDialog.Description   = desc;
            progressDialog.Title         = title;
            progressDialog.Animation     = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe;

            return(progressDialog);
        }
コード例 #2
0
        public void ExportSelectedRecordsToExcel()
        {
            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;
            ESRI.ArcGIS.esriSystem.IStepProgressor       stepProgressor        = null;
            ESRI.ArcGIS.Framework.IProgressDialog2       progressDialog        = null;
            IMxDocument mxdoc = null;
            IMap        map   = null;
            IStandaloneTableCollection standTabColl = null;
            IStandaloneTable           standTable   = null;
            ITableSelection            tableSel     = null;
            IEnumFeature      enumFeat  = null;
            IFeature          feat      = null;
            IFeatureSelection featSel   = null;
            ITable            openTable = null;
            object            missing   = null;
            //object fileName = null;
            object newTemplate = null;
            object docType     = null;
            object isVisible   = null;


            UID geoFeatureLayerID = null;

            IEnumLayer    enumLayer = null;
            IFeatureLayer featlayer = null;

            try
            {
                mxdoc = (IMxDocument)_app.Document;
                map   = mxdoc.FocusMap;

                long standTableCnt;
                int  i = 0;
                bool selectionInTable = false;


                missing = System.Reflection.Missing.Value;
                // fileName = "normal.dot";
                newTemplate = false;
                docType     = 0;
                isVisible   = true;

                //Get enumeration of feature layers
                geoFeatureLayerID       = new UIDClass();
                geoFeatureLayerID.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}";
                enumLayer = map.get_Layers(geoFeatureLayerID, true);

                enumLayer.Reset();

                standTabColl  = (IStandaloneTableCollection)map;
                standTableCnt = standTabColl.StandaloneTableCount;

                enumFeat = (IEnumFeature)map.FeatureSelection;
                enumFeat.Reset();
                feat = enumFeat.Next();



                if (standTableCnt > 0)
                {
                    for (int j = 0; j < standTableCnt; j++)
                    {
                        standTable = standTabColl.get_StandaloneTable(j);
                        if (standTable.Valid)
                        {
                            openTable = (ITable)standTable;
                            tableSel  = (ITableSelection)openTable;
                            if (tableSel.SelectionSet.Count > 0)
                            {
                                selectionInTable = true;
                                break;
                            }
                        }
                    }
                }

                if ((selectionInTable == false) && (feat == null))
                {
                    MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("DataToolsMess_1") + Environment.NewLine + A4LGSharedFunctions.Localizer.GetString("DataToolsMess_2"), messageBoxHeader);
                    return;
                }
                // Create a CancelTracker
                ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

                // Set the properties of the Step Progressor
                System.Int32 int32_hWnd = _app.hWnd;

                progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();
                stepProgressor        = progressDialogFactory.Create(trackCancel, int32_hWnd);



                stepProgressor.MinRange  = 0;
                stepProgressor.MaxRange  = mxdoc.FocusMap.SelectionCount;
                stepProgressor.StepValue = 1;
                stepProgressor.Message   = A4LGSharedFunctions.Localizer.GetString("ExportXL");
                // Create the ProgressDialog. This automatically displays the dialog
                progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast

                // Set the properties of the ProgressDialog
                progressDialog.CancelEnabled = true;
                progressDialog.Description   = A4LGSharedFunctions.Localizer.GetString("ExportAsset") + "1" + A4LGSharedFunctions.Localizer.GetString("Of") + mxdoc.FocusMap.SelectionCount.ToString() + ".";
                progressDialog.Title         = A4LGSharedFunctions.Localizer.GetString("ExportXL");
                progressDialog.Animation     = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe;
                progressDialog.ShowDialog();

                if ((feat != null) && (selectionInTable == true))
                {
                    ExcelApp = new Excel.ApplicationClass();


                    //Delete default worksheets
                    ExcelApp.DisplayAlerts = false;
                    objBook = ExcelApp.Workbooks.Add(missing);
                    //objBook = ExcelApp.Workbooks.get_Item(1);
                    for (int m = objBook.Sheets.Count; m > 1; m--)
                    {
                        objSheet = (Excel.Worksheet)objBook.Sheets.get_Item(m);
                        objSheet.Delete();
                    }

                    featlayer = (IFeatureLayer)enumLayer.Next();
                    while (featlayer != null)
                    {
                        if ((featlayer.Valid) && (featlayer.Selectable))
                        {
                            featSel = (IFeatureSelection)featlayer;
                            if (featSel.SelectionSet.Count > 0)
                            {
                                if (ExportLayer(objBook, mxdoc, featlayer, ref progressDialog, ref stepProgressor, ref trackCancel) == false)
                                {
                                    return;
                                }
                            }
                        }
                        featlayer = (IFeatureLayer)enumLayer.Next();
                    }

                    for (i = 0; i < standTableCnt; i++)
                    {
                        standTable = standTabColl.get_StandaloneTable(i);
                        if (standTable.Valid)
                        {
                            openTable = (ITable)standTable;
                            tableSel  = (ITableSelection)openTable;
                            if (tableSel.SelectionSet.Count > 0)
                            {
                                if (ExportTable(objBook, mxdoc, standTable, ref progressDialog, ref stepProgressor, ref trackCancel) == false)
                                {
                                    return;
                                }
                            }
                        }
                    }
                }
                else if ((feat != null) && (selectionInTable == false))
                {
                    ExcelApp = new Excel.ApplicationClass();

                    //Delete default worksheets
                    ExcelApp.DisplayAlerts = false;
                    objBook = ExcelApp.Workbooks.Add(missing);
                    //objBook = ExcelApp.Workbooks.get_Item(1);
                    for (int m = objBook.Sheets.Count; m > 1; m--)
                    {
                        objSheet = (Excel.Worksheet)objBook.Sheets.get_Item(m);
                        objSheet.Delete();
                    }


                    ILayer pTLay = enumLayer.Next();
                    while (pTLay != null)
                    {
                        if (pTLay is IFeatureLayer)
                        {
                            featlayer = (IFeatureLayer)pTLay;
                            if ((featlayer.Valid))
                            {
                                featSel = (IFeatureSelection)featlayer;
                                if (featSel.SelectionSet.Count > 0)
                                {
                                    if (ExportLayer(objBook, mxdoc, featlayer, ref progressDialog, ref stepProgressor, ref trackCancel) == false)
                                    {
                                        return;
                                    }
                                }
                            }
                        }
                        pTLay = enumLayer.Next();
                    }
                    pTLay = null;
                }
                else if ((feat == null) && (selectionInTable == true))
                {
                    ExcelApp = new Excel.ApplicationClass();

                    //Delete default worksheets
                    ExcelApp.DisplayAlerts = false;
                    objBook = ExcelApp.Workbooks.Add(missing);
                    //objBook = ExcelApp.Workbooks.get_Item(1);
                    for (int m = objBook.Sheets.Count; m > 1; m--)
                    {
                        objSheet = (Excel.Worksheet)objBook.Sheets.get_Item(m);
                        objSheet.Delete();
                    }
                    for (i = 0; i < standTableCnt; i++)
                    {
                        standTable = standTabColl.get_StandaloneTable(i);
                        if (standTable.Valid)
                        {
                            openTable = (ITable)standTable;
                            tableSel  = (ITableSelection)openTable;
                            if (tableSel.SelectionSet.Count > 0)
                            {
                                if (ExportTable(objBook, mxdoc, standTable, ref progressDialog, ref stepProgressor, ref trackCancel) == false)
                                {
                                    return;
                                }
                            }
                        }
                    }
                }


                if (objBook.Sheets.Count > 1)
                {
                    objSheet = (Excel.Worksheet)objBook.Sheets.get_Item(1);
                    objSheet.Delete();
                }
                //objSheet = (Excel.Worksheet)objBook.Sheets["Sheet2"];
                //objSheet.Delete();
                //objSheet = (Excel.Worksheet)objBook.Sheets["Sheet3"];
                //objSheet.Delete();
                ExcelApp.DisplayAlerts = true;

                //Make the first sheet active
                objSheet = (Excel.Worksheet)objBook.Sheets.get_Item(1) as Excel.Worksheet;
                (objSheet as Microsoft.Office.Interop.Excel._Worksheet).Activate();

                //Make Excel visible
                ExcelApp.Visible = true;
                return;
            }
            catch (Exception ex)
            {
                if (ExcelApp != null)
                {
                    ExcelApp = null;
                }

                //ExcelApp.Visible = true;
                MessageBox.Show("ExportSelectedRecordsToExcel\n" + ex.Message, ex.Source);
                return;
            }
            finally
            {
                if (progressDialog != null)
                {
                    progressDialog.HideDialog();
                }

                progressDialogFactory = null;
                stepProgressor        = null;
                progressDialog        = null;
                mxdoc        = null;
                map          = null;
                standTabColl = null;
                standTable   = null;
                tableSel     = null;
                enumFeat     = null;
                feat         = null;
                featSel      = null;
                openTable    = null;
                missing      = null;
                //fileName = null;
                newTemplate = null;
                docType     = null;
                isVisible   = null;


                geoFeatureLayerID = null;

                enumLayer = null;
                featlayer = null;
            }
        }
コード例 #3
0
        private bool RemoveFiberCableConfigDomains(IWorkspace wksp)
        {
            bool result = true;

            if (wksp == null || ((wksp as IWorkspaceDomains3) == null))
            {
                return(false);
            }

            try
            {
                // get Handles to everything we need first or bail.
                IFeatureClass cableFc = FindFeatureClass(ConfigUtil.FiberCableFtClassName);
                if (cableFc == null)
                {
                    return(false);
                }
                ISubtypes subs = cableFc as ISubtypes;
                if (subs == null)
                {
                    return(false);
                }
                IClassSchemaEdit4 schEdit = cableFc as IClassSchemaEdit4;
                if (schEdit == null)
                {
                    return(false);
                }

                // ----------------------------------------------------
                // First we have to unassign the domains from the FC fields
                // ----------------------------------------------------
                schEdit.AlterDomain(ConfigUtil.NumberOfFibersFieldName, null);
                schEdit.AlterDomain(ConfigUtil.NumberOfBuffersFieldName, null);
                _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Unassigned FiberCable domains", "NumberOfFibers + NumberOfBuffers");

                // ----------------------------------------------------
                // Also have to remove domain from the subtypes (arghh)
                // 1 & 2 are overhead and underground.
                // ----------------------------------------------------
                IEnumSubtype types = subs.Subtypes;
                subs.set_Domain(1, ConfigUtil.NumberOfFibersFieldName, null);
                subs.set_Domain(2, ConfigUtil.NumberOfFibersFieldName, null);
                subs.set_Domain(1, ConfigUtil.NumberOfBuffersFieldName, null);
                subs.set_Domain(2, ConfigUtil.NumberOfBuffersFieldName, null);
                _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Removed FiberCable subtype domains", "NumberOfFibers + NumberOfBuffers");

                // ----------------------------------------------------
                // Now we can remove the domains
                // ----------------------------------------------------
                IWorkspaceDomains3 wkspDomains = wksp as IWorkspaceDomains3;
                if (wkspDomains.get_CanDeleteDomain("NumberOfFibers") &&
                    wkspDomains.get_CanDeleteDomain("NumberOfBuffers"))
                {
                    wkspDomains.DeleteDomain("NumberOfFibers");
                    wkspDomains.DeleteDomain("NumberOfBuffers");
                    MessageBox.Show("Domains successfully deleted");
                    _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Domains successfully deleted", "NumberOfFibers + NumberOfBuffers");
                }
                else
                {
                    MessageBox.Show("Upgrade failed. \nCould not get exclusive access to this database. \nPLEASE RESTORE FROM YOUR BACKUP");
                    _logHelper.addLogEntry(DateTime.Now.ToString(), "ERROR", "Cannot delete domains.", "Non-Exclusive access?");
                    return(false);
                }

                // ----------------------------------------------------
                // Recalculate the fields based on the count of actual
                // related objects found. We'll use this code later
                // for integrity checking.
                // ----------------------------------------------------
                IRelationshipClass bufferRelationship = GdbUtils.GetRelationshipClass(cableFc, ConfigUtil.FiberCableToBufferRelClassName);
                IRelationshipClass strandRelationship = GdbUtils.GetRelationshipClass(cableFc, ConfigUtil.FiberCableToFiberRelClassName);
                IFeature           ft;
                int bufferIdx = cableFc.Fields.FindField(ConfigUtil.NumberOfBuffersFieldName);
                int strandIdx = cableFc.Fields.FindField(ConfigUtil.NumberOfFibersFieldName);
                if (bufferIdx == -1 || strandIdx == -1)
                {
                    _logHelper.addLogEntry(DateTime.Now.ToString(), "ERROR", "Cannot find buffer or strand fields.",
                                           ConfigUtil.NumberOfBuffersFieldName + " " + ConfigUtil.NumberOfFibersFieldName);
                    MessageBox.Show("Upgrade failed. \nCould not find appropriate fields based on current config settings. \nPLEASE RESTORE FROM YOUR BACKUP.");
                    return(false);
                }
                _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Recalculating buffer and strand counts...");
                // Start edit session do the updates....
                ArcMap.Editor.StartEditing(wksp);
                IFeatureCursor cables = cableFc.Update(null, false);
                int            count  = cableFc.FeatureCount(null);

                //ProgressBar
                ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();

                ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

                // Set the properties of the Step Progressor
                ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = progressDialogFactory.Create(trackCancel, ArcMap.Application.hWnd);
                stepProgressor.MinRange  = 1;
                stepProgressor.MaxRange  = count;
                stepProgressor.StepValue = 1;
                stepProgressor.Message   = "Updating cable config for " + count + " cables";

                // Create the ProgressDialog. This automatically displays the dialog
                ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast

                // Set the properties of the ProgressDialog
                progressDialog.CancelEnabled = false;
                progressDialog.Description   = "";
                progressDialog.Title         = "Workspace Upgrade";
                progressDialog.Animation     = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe;
                progressDialog.ShowDialog();

                int i = 1;
                while ((ft = cables.NextFeature()) != null)
                {
                    progressDialog.Description = string.Format("Updating cable {0} of {1}", i, count);
                    stepProgressor.Step();

                    ISet buffers = bufferRelationship.GetObjectsRelatedToObject(ft);
                    ft.set_Value(bufferIdx, buffers.Count);
                    ISet strands = strandRelationship.GetObjectsRelatedToObject(ft);
                    ft.set_Value(strandIdx, strands.Count);
                    ft.Store();
                    i++;
                }
                progressDialog.HideDialog();
                ArcMap.Editor.StopEditing(true);
                _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Upgrade Completed Successfully.");
                MessageBox.Show("Upgrade Completed Successfully.");
            }
            catch (Exception e)
            {
                _logHelper.addLogEntry(DateTime.Now.ToString(), "ERROR", "RemoveFiberCableConfigDomains", e.Message);
                result = false;
            }
            return(result);
        }
コード例 #4
0
        private void btnSelect_Click(object sender, EventArgs e)
        {
            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = null;
            ESRI.ArcGIS.esriSystem.IStepProgressor       stepProgressor        = null;
            ESRI.ArcGIS.Framework.IProgressDialog2       progressDialog        = null;
            // Create a CancelTracker
            ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = null;
            ISpatialFilter         pSpatFilt = null;
            IFeatureLayer          pFL       = null;
            IFeatureCursor         pFCurs    = null;
            IFeature               pFeat     = null;
            ISimpleJunctionFeature pSimpFeat = null;

            // Create an edit operation enabling undo/redo
            try
            {
                (_app.Document as IMxDocument).FocusMap.ClearSelection();


                trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();
                // Set the properties of the Step Progressor
                System.Int32 int32_hWnd = _app.hWnd;
                progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();
                stepProgressor        = progressDialogFactory.Create(trackCancel, int32_hWnd);

                stepProgressor.MinRange  = 0;
                stepProgressor.MaxRange  = lstJunctionLayers.Items.Count;
                stepProgressor.StepValue = 1;
                stepProgressor.Message   = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_1");
                // Create the ProgressDialog. This automatically displays the dialog
                progressDialog = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast

                // Set the properties of the ProgressDialog
                progressDialog.CancelEnabled = true;
                progressDialog.Description   = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_1");
                progressDialog.Title         = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_1");
                progressDialog.Animation     = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressGlobe;
                progressDialog.ShowDialog();


                for (int i = 0; i < lstJunctionLayers.Items.Count; i++)
                {
                    bool boolean_Continue = trackCancel.Continue();
                    if (!boolean_Continue)
                    {
                        return;
                    }
                    progressDialog.Description = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_2") + lstJunctionLayers.Items[i].ToString();
                    if (lstJunctionLayers.GetItemCheckState(i) == CheckState.Checked)
                    {
                        bool FCorLayer = true;
                        pFL = (IFeatureLayer)Globals.FindLayer(_app, lstJunctionLayers.Items[i].ToString(), ref FCorLayer);
                        if (pFL != null)
                        {
                            pSpatFilt               = new SpatialFilterClass();
                            pSpatFilt.Geometry      = _env as IGeometry;
                            pSpatFilt.SpatialRel    = esriSpatialRelEnum.esriSpatialRelIntersects;
                            pSpatFilt.GeometryField = pFL.FeatureClass.ShapeFieldName;
                            int featCnt = pFL.FeatureClass.FeatureCount(pSpatFilt);

                            if (featCnt > 0)
                            {
                                pFCurs = pFL.Search(pSpatFilt, true);
                                pFeat  = pFCurs.NextFeature();
                                int loopCnt = 1;

                                while (pFeat != null)
                                {
                                    boolean_Continue = trackCancel.Continue();
                                    if (!boolean_Continue)
                                    {
                                        return;
                                    }
                                    stepProgressor.Message = A4LGSharedFunctions.Localizer.GetString("SltByJctCountProc_3") + loopCnt + A4LGSharedFunctions.Localizer.GetString("Of") + featCnt;

                                    if (pFeat is SimpleJunctionFeature)
                                    {
                                        pSimpFeat = (ISimpleJunctionFeature)pFeat;
                                        if (pSimpFeat.EdgeFeatureCount >= numMinEdge.Value && pSimpFeat.EdgeFeatureCount <= numMaxEdge.Value)
                                        {
                                            (_app.Document as IMxDocument).FocusMap.SelectFeature(pFL as ILayer, pFeat);
                                        }
                                    }
                                    loopCnt++;
                                    pFeat = pFCurs.NextFeature();
                                }
                            }
                        }
                    }
                    stepProgressor.Step();
                }
            }
            catch (Exception Ex)

            {
                MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorInThe") + A4LGSharedFunctions.Localizer.GetString("SltByJctCountLbl_22") + "\r\n" + Ex.Message);
            }
            finally
            {
                if (progressDialog != null)
                {
                    progressDialog.HideDialog();
                }

                progressDialogFactory = null;
                stepProgressor        = null;
                progressDialog        = null;
                trackCancel           = null;
                pSpatFilt             = null;
                pFL = null;
                if (pFCurs != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pFCurs);
                }
                pFCurs    = null;
                pFeat     = null;
                pSimpFeat = null;
                this.Hide();
                (_app.Document as IMxDocument).ActiveView.Refresh();

                MessageBox.Show((_app.Document as IMxDocument).FocusMap.SelectionCount + A4LGSharedFunctions.Localizer.GetString("SltByJctCountMess_1"));
            }
        }
コード例 #5
0
        protected override void OnClick()
        {
            // Get the min/max zoom from user input
            int minzoom = 0;
            int maxzoom = 6;

            Ecotrust.Form1 form1 = new Ecotrust.Form1();
            if (form1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                minzoom = (int)form1.numericUpDown1.Value;
                maxzoom = (int)form1.numericUpDown2.Value;
            }
            else
            {
                return; //TODO
            }

            // Use the FolderBrowserDialog Class to choose export folder
            System.Windows.Forms.FolderBrowserDialog folderDialog = new System.Windows.Forms.FolderBrowserDialog();
            folderDialog.Description = "Select output folder for map tiles...";
            string exportDir = "";

            if (folderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // The returned string will be the full path, filename and file-extension for the chosen shapefile. Example: "C:\test\cities.shp"
                exportDir = folderDialog.SelectedPath;
                if (exportDir == "")
                {
                    return;  // TODO raise error
                }
            }
            else
            {
                return; //TODO
            }

            ESRI.ArcGIS.ArcMapUI.IMxDocument mxDocument = ArcMap.Application.Document as ESRI.ArcGIS.ArcMapUI.IMxDocument; // Dynamic Cast
            ESRI.ArcGIS.Carto.IActiveView    activeView = mxDocument.ActiveView;
            ESRI.ArcGIS.Carto.IMap           map        = activeView.FocusMap;

            ESRI.ArcGIS.Geometry.IEnvelope mapaoi = activeView.Extent;

            // Set up export object and tile pixel coordinates
            int tileSizeX = 256;
            int tileSizeY = 256;

            // set up exporter with transparent background
            ESRI.ArcGIS.Output.IExportPNG pngexport = new ESRI.ArcGIS.Output.ExportPNGClass();
            ESRI.ArcGIS.Display.IColor    tcolor    = new ESRI.ArcGIS.Display.RgbColorClass();
            // Warning: 254,254,254 will be set to transparent; don't use in any of map styling
            ((IRgbColor)tcolor).Red   = 254;
            ((IRgbColor)tcolor).Green = 254;
            ((IRgbColor)tcolor).Blue  = 254;
            ((ExportPNG)pngexport).BackgroundColor = tcolor;
            pngexport.TransparentColor             = tcolor;
            ESRI.ArcGIS.Output.IExport export = (ESRI.ArcGIS.Output.IExport)pngexport;

            ESRI.ArcGIS.esriSystem.tagRECT exportRECT;
            exportRECT.left   = 0;
            exportRECT.top    = 0;
            exportRECT.right  = tileSizeX;
            exportRECT.bottom = tileSizeY;
            ESRI.ArcGIS.Geometry.IEnvelope envelope = new ESRI.ArcGIS.Geometry.EnvelopeClass();
            envelope.PutCoords(exportRECT.left, exportRECT.top, exportRECT.right, exportRECT.bottom);
            export.PixelBounds = envelope;

            map.DelayDrawing(true);

            // Turn off all layers
            for (int i = 0; i < map.LayerCount; i++)
            {
                map.get_Layer(i).Visible = false;
            }

            // Calculate total number of tiles needed
            GlobalMercator mercator = new GlobalMercator();

            GlobalMercator.Coords tempmins;
            GlobalMercator.Coords tempmaxs;
            Double numTiles = 0;

            for (int tz = minzoom; tz <= maxzoom; tz++)
            {
                tempmins  = mercator.MetersToTile(mapaoi.XMin, mapaoi.YMin, tz);
                tempmaxs  = mercator.MetersToTile(mapaoi.XMax, mapaoi.YMax, tz);
                numTiles += ((tempmaxs.y - tempmins.y) + 1) * ((tempmaxs.x - tempmins.x) + 1);
            }
            numTiles *= map.LayerCount;

            ESRI.ArcGIS.esriSystem.IStatusBar statusBar = ArcMap.Application.StatusBar;
            statusBar.set_Message(0, "Rendering " + numTiles.ToString() + " tiles");

            // Create a CancelTracker
            ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel = new ESRI.ArcGIS.Display.CancelTrackerClass();

            ESRI.ArcGIS.Framework.IProgressDialogFactory progressDialogFactory = new ESRI.ArcGIS.Framework.ProgressDialogFactoryClass();

            // Set the properties of the Step Progressor
            System.Int32 int32_hWnd = ArcMap.Application.hWnd;
            ESRI.ArcGIS.esriSystem.IStepProgressor stepProgressor = progressDialogFactory.Create(trackCancel, int32_hWnd);
            stepProgressor.MinRange  = 0;
            stepProgressor.MaxRange  = (int)numTiles;
            stepProgressor.StepValue = 1;
            stepProgressor.Message   = "Calculating " + numTiles.ToString() + " tiles";

            // Create the ProgressDialog. This automatically displays the dialog
            ESRI.ArcGIS.Framework.IProgressDialog2 progressDialog2 = (ESRI.ArcGIS.Framework.IProgressDialog2)stepProgressor; // Explict Cast

            // Set the properties of the ProgressDialog
            progressDialog2.CancelEnabled = true;
            progressDialog2.Description   = "Rendering " + numTiles.ToString() + " map tiles";
            progressDialog2.Title         = "Creating map tiles...";
            progressDialog2.Animation     = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriDownloadFile;
            System.Boolean boolean_Continue = true;

            int tileCount = 0;

            for (int lyrnum = 0; lyrnum < map.LayerCount; lyrnum++)
            {
                // Turn on the layer of interest
                ESRI.ArcGIS.Carto.ILayer layer = map.get_Layer(lyrnum);
                layer.Visible = true;

                // Set extents
                //ESRI.ArcGIS.Geometry.IEnvelope layeraoi = layer.AreaOfInterest;
                ESRI.ArcGIS.Geometry.IEnvelope aoi = new ESRI.ArcGIS.Geometry.EnvelopeClass();

                // Create layer directory if it doesn't exist
                DirectoryInfo dir = new DirectoryInfo(exportDir + "\\" + layer.Name);
                if (!dir.Exists)
                {
                    dir.Create();
                }

                DateTime startTime = DateTime.Now;

                // Loop through zoom levels, rows, cols
                for (int tz = minzoom; tz <= maxzoom; tz++)
                {
                    GlobalMercator.Coords mins = mercator.MetersToTile(mapaoi.XMin, mapaoi.YMin, tz);
                    GlobalMercator.Coords maxs = mercator.MetersToTile(mapaoi.XMax, mapaoi.YMax, tz);

                    // Create zoom directory if it doesn't exist
                    DirectoryInfo dir2 = new DirectoryInfo(dir.FullName + "\\" + tz);
                    if (!dir2.Exists)
                    {
                        dir2.Create();
                    }

                    for (int tx = (int)mins.x; tx <= (int)maxs.x; tx++)
                    {
                        // Create X directory if it doesn't exist
                        DirectoryInfo dir3 = new DirectoryInfo(dir2.FullName + "\\" + tx);
                        if (!dir3.Exists)
                        {
                            dir3.Create();
                        }

                        for (int ty = (int)mins.y; ty <= (int)maxs.y; ty++)
                        {
                            // Flip y-axis for output tile name
                            int invertTy = (int)((Math.Pow(2, tz) - 1) - ty);

                            tileCount += 1;

                            // TODO Calculate time and set new message
                            // TimeSpan timeElapsed = TimeSpan.FromTicks(DateTime.Now.Subtract(startTime).Ticks); // * ((double)tileCount - (numTiles + 1)) / (numTiles + 1));
                            // double timeRemaining = (timeElapsed.TotalSeconds / (tileCount / numTiles)) - timeElapsed.TotalSeconds;
                            //(" + ((int)timeRemaining).ToString() +" remaining)";

                            stepProgressor.Message = layer.Name + "\\" + tz + "\\" + tx + "\\" + invertTy +
                                                     ".png (" + tileCount + " of " + numTiles + ")";


                            export.ExportFileName = dir3.FullName + "\\" + invertTy + ".png";

                            GlobalMercator.Bounds bnd = mercator.TileBounds(tx, ty, tz);
                            aoi.PutCoords(bnd.minx, bnd.miny, bnd.maxx, bnd.maxy);
                            aoi.SpatialReference = map.SpatialReference; // TODO aoi spatial reference == mercator?
                            // Use FullExtent instead of Extent to make the extent independent of the activeView ratio
                            activeView.FullExtent = aoi;

                            // Export
                            System.Int32 hDC = export.StartExporting();
                            activeView.Output(hDC, (System.Int16)export.Resolution, ref exportRECT, null, null); // Explicit Cast and 'ref' keyword needed
                            export.FinishExporting();
                            export.Cleanup();

                            stepProgressor.Position = tileCount;

                            //Check if the cancel button was pressed. If so, break out of row
                            boolean_Continue = trackCancel.Continue();
                            if (!boolean_Continue)
                            {
                                break;
                            }
                        }
                        //Check if the cancel button was pressed. If so, break out of col
                        boolean_Continue = trackCancel.Continue();
                        if (!boolean_Continue)
                        {
                            break;
                        }
                    }
                    //Check if the cancel button was pressed. If so, break out of layers
                    boolean_Continue = trackCancel.Continue();
                    if (!boolean_Continue)
                    {
                        break;
                    }

                    // Write log
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(exportDir + "\\log.txt", true))
                    {
                        file.WriteLine(layer.Name + ", zoom " + tz + ", numtiles " + tileCount + ":" +
                                       mins.x + " " + mins.y + " " + maxs.x + " " + maxs.y);
                    }
                }
                // Turn it off
                layer.Visible = false;
            }

            map.DelayDrawing(false);

            // Turn ON all layers
            for (int i = 0; i < map.LayerCount; i++)
            {
                map.get_Layer(i).Visible = true;
            }

            // restore extent
            activeView.FullExtent = mapaoi;
            activeView.Refresh();

            // Done
            trackCancel    = null;
            stepProgressor = null;
            progressDialog2.HideDialog();
            progressDialog2 = null;
        }