Example #1
0
        ///<summary> The text fields of a specified layer </summary>
        /// <param name="pLayer"> The layer from which a list of text fields is to be fetched </param>
        ///<returns> Function to retrieve a list of all text fields in a given layer </returns>
        public ArrayList TextFields(ILayer pLayer)
        {
            ArrayList pList = new ArrayList();

            if (pLayer == null)
            {
                return(pList);
            }
            try
            {
                if (pLayer is IGeoFeatureLayer)
                {
                    IFeatureLayer pFlayer       = (IFeatureLayer)pLayer;
                    IDisplayTable pDisplayTable = (IDisplayTable)pFlayer;
                    IFields       pFields       = pDisplayTable.DisplayTable.Fields;
                    for (int i = 0; i < pFields.FieldCount; i++)
                    {
                        IField pField = pFields.get_Field(i);
                        if (pField.Type == esriFieldType.esriFieldTypeString)
                        {
                            pList.Add(pField.AliasName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (SupressMessaging == false)
                {
                    MessageBox.Show(ex.Message, "All Text Fields - By Layer", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            return(pList);
        }
Example #2
0
        /// <summary>
        /// This function will check to make sure that the passed in layer is a valid SDE layer.
        /// It ensures that the layer is not:
        ///      and that it is not
        ///         1). an XY event layer
        ///         2). in a relationship with a RESPONDER layer
        /// </summary>
        /// <param name="pLayer">the layer to validate</param>
        /// <returns>true / false (is valid / not valid)</returns>
        public static bool IsValidGisLayer(ILayer pLayer)
        {
            if (pLayer.Valid && pLayer is IGeoFeatureLayer)
            {
                // Skip the feature if it is an XY Event Source
                IGeoFeatureLayer pGfLayer = pLayer as IGeoFeatureLayer;
                if (pGfLayer.FeatureClass is IXYEventSource)
                {
                    return(false);
                }

                // Skip the feature if it is joined to a Responder table
                IDisplayTable pDispTable = pLayer as IDisplayTable;
                if (pDispTable != null)
                {
                    ITable pTable = pDispTable.DisplayTable;
                    var    table  = pTable as IRelQueryTable;
                    if (table != null)
                    {
                        IRelQueryTable pRelQueryTable = table;
                        IObjectClass   pClass         = pRelQueryTable.DestinationTable as IObjectClass;
                        if (pClass == null)
                        {
                            return(false);
                        }
                    }
                }
                //// See if the feature name is for a Service Location
                //string sName = pGfLayer.FeatureClass.AliasName;
                //if (sName == layerName)
                return(true);
            }
            return(false);
        }
Example #3
0
        /// <summary>
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="objectClass"></param>
        /// <param name="table"></param>
        /// <param name="row"></param>
        private static void ExportRow(XmlWriter writer, ObjectClass objectClass, IDisplayTable table, IRow row)
        {
            writer.WriteStartElement("ObjectClassRow");
            if (row.HasOID)
                writer.WriteAttributeString(row.Table.OIDFieldName, Convert.ToString(row.OID));

            foreach (FieldNameAndAlias alias in GetObjectClassFields(objectClass, table))
            {
                int index = row.Fields.FindField(alias.name);
                if (index == -1)
                    continue;

                writer.WriteStartElement("ObjectClassField");
                writer.WriteAttributeString("name", alias.alias);
                object obj2 = row.get_Value(index);
                if ((obj2 != null) && (obj2 != DBNull.Value))
                {
                    string str = Convert.ToString(obj2).Trim();
                    if (row.Fields.get_Field(index).Type == esriFieldType.esriFieldTypeDate)
                        str = Convert.ToDateTime(str).ToString("MM/dd/yyyy");
                    writer.WriteString(str);
                }
                else
                {
                    writer.WriteString("");
                }

                writer.WriteEndElement();
            }

            writer.WriteEndElement();
        }
Example #4
0
 public static bool TableIsJoinLayer(ITable itable_0, ITable itable_1)
 {
     try
     {
         IDisplayTable table = itable_0 as IDisplayTable;
         if (table != null)
         {
             ITable displayTable = table.DisplayTable;
             string str          = (itable_1 as IDataset).Name.ToLower();
             while (displayTable is IRelQueryTable)
             {
                 IRelQueryTable table3 = displayTable as IRelQueryTable;
                 if ((table3.DestinationTable as IDataset).Name.ToLower() == str)
                 {
                     return(true);
                 }
                 displayTable = table3.SourceTable;
             }
         }
         return(false);
     }
     catch (COMException exception)
     {
         MessageBox.Show(exception.Message, "COM Error: " + exception.ErrorCode.ToString(), MessageBoxButtons.OK,
                         MessageBoxIcon.Exclamation);
     }
     catch (Exception exception2)
     {
         MessageBox.Show(exception2.Message, ".NET Error: ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
     }
     return(false);
 }
Example #5
0
 private void method_1(ITable itable_1)
 {
     try
     {
         IDisplayTable table = itable_1 as IDisplayTable;
         if (table != null)
         {
             IRelQueryTable table3;
             for (ITable table2 = table.DisplayTable; table2 is IRelQueryTable; table2 = table3.SourceTable)
             {
                 table3 = table2 as IRelQueryTable;
                 ITable destinationTable = table3.DestinationTable;
                 this.JoiningDataList.Items.Add(new ObjectWrap(destinationTable));
             }
         }
     }
     catch (COMException exception)
     {
         MessageBox.Show(exception.Message, "COM Error: " + exception.ErrorCode.ToString(), MessageBoxButtons.OK,
                         MessageBoxIcon.Exclamation);
     }
     catch (Exception exception2)
     {
         MessageBox.Show(exception2.Message, ".NET Error: ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
     }
 }
Example #6
0
 private void cboInputData_SelectedIndexChanged(object sender, System.EventArgs e)
 {
     // Set the chkUseSelectedFeatures control based on if anything is selected or not
     if (cboInputData.SelectedIndex >= 0)
     {
         IDisplayTable displayTable = m_listDisplayTable[cboInputData.SelectedIndex] as IDisplayTable;
         chkUseSelection.Checked = (displayTable.DisplaySelectionSet.Count > 0);
         chkUseSelection.Enabled = (displayTable.DisplaySelectionSet.Count > 0);
     }
 }
Example #7
0
        /// <summary>
        ///     Export the object class
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="objectClass"></param>
        /// <param name="cursor"></param>
        /// <param name="table"></param>
        private static void ExportObjectClass(XmlWriter writer, ObjectClass objectClass, ICursor cursor,
            IDisplayTable table)
        {
            StartExportObjectClass(writer, objectClass, table);

            for (IRow row = cursor.NextRow(); row != null; row = cursor.NextRow())
                ExportRow(writer, objectClass, table, row);

            EndExportObjectClass(writer);
        }
Example #8
0
        /// <summary>
        /// </summary>
        /// <param name="objectClass"></param>
        /// <param name="table"></param>
        /// <returns></returns>
        private static string GetDisplayTableName(ObjectClass objectClass, IDisplayTable table)
        {
            if (table is IFeatureLayer)
                return ((IFeatureLayer) table).Name;

            if (table is IStandaloneTable)
                return ((IStandaloneTable) table).Name;

            string name = objectClass.name;
            return name;
        }
Example #9
0
        private void setDataSource(IDisplayTable pDisplayTable)
        {
            DataTable  pTable = new DataTable();
            IField     pField = null;
            DataColumn pColumn;

            for (int i = 0; i < pDisplayTable.DisplayTable.Fields.FieldCount; i++)
            {
                pField = pDisplayTable.DisplayTable.Fields.get_Field(i);
                string name = getRealName(pField);
                pColumn = new DataColumn(name);//delete table name
                //
                MessageBox.Show("Field name:" + name + " " + pField.Name + "; Field aliasName: " + pField.AliasName);
                pColumn.AllowDBNull = pField.IsNullable;
                if (pTable.Columns.Contains(pColumn.ColumnName))
                {
                    pColumn.ColumnName += "1";
                    pTable.Columns.Add(pColumn);
                }
                else
                {
                    pTable.Columns.Add(pColumn);
                }
            }
            ICursor pcusor = pDisplayTable.SearchDisplayTable(null, false);
            IRow    pRow;

            pRow = pcusor.NextRow();
            DataRow pDataRow;

            while (pRow != null)
            {
                pDataRow = pTable.NewRow();
                for (int i = 0; i < pRow.Fields.FieldCount; i++)
                {
                    if (pRow.Fields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        pDataRow[i] = "shapeType";//ensure the type, need to be changed
                    }
                    else if (pRow.Fields.get_Field(i).Type == esriFieldType.esriFieldTypeBlob)
                    {
                        pDataRow[i] = "Element";
                    }
                    else
                    {
                        pDataRow[i] = pRow.get_Value(i);
                    }
                }
                pTable.Rows.Add(pDataRow);
                pRow = pcusor.NextRow();
            }
            DataGrdView.DataSource = pTable;
            DataGrdView.Refresh();
        }
Example #10
0
        /// <summary>
        /// Gets the number of rows of the table, belonging to a given layer.
        /// </summary>
        /// <param name="layer">Esri layer of the TOC</param>
        /// <returns>Number of rows or Null if the layer is invalid.</returns>
        public static int?GetLayerRowCount(IFeatureLayer layer)
        {
            IDisplayTable displayTable = (IDisplayTable)layer;

            if ((layer.Valid) && (displayTable != null))
            {
                IQueryFilter queryFilter = new QueryFilterClass();
                queryFilter.AddField(layer.FeatureClass.OIDFieldName);
                return(displayTable.DisplayTable.RowCount(queryFilter));
            }
            return(null);
        }
Example #11
0
        /// <summary>
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private ITable GetTableFromDatasetName(string name)
        {
            ITable displayTable;

            IDisplayTable displayTableFromDatasetName = GetDisplayTableFromDatasetName(name);

            if (displayTableFromDatasetName != null)
                displayTable = displayTableFromDatasetName.DisplayTable;
            else
                displayTable = GetFeatureClassFromDatasetName(name) as ITable;

            return displayTable;
        }
Example #12
0
        private void btnRemoveJoining_Click(object sender, EventArgs e)
        {
            IDisplayTable table        = this.itable_0 as IDisplayTable;
            ITable        displayTable = table.DisplayTable;

            if (displayTable is IRelQueryTable)
            {
                string str = this.JoiningDataList.SelectedItem.ToString();
                while (displayTable is IRelQueryTable)
                {
                    IRelQueryTable table3 = displayTable as IRelQueryTable;
                    if ((table3.DestinationTable as IDataset).Name == str)
                    {
                        break;
                    }
                    displayTable = table3.SourceTable;
                }
                if (displayTable is IRelQueryTable)
                {
                    IRelQueryTable table5 = displayTable as IRelQueryTable;
                    displayTable = table5.SourceTable;
                    IDisplayRelationshipClass class2 = this.itable_0 as IDisplayRelationshipClass;
                    if (displayTable is IRelQueryTable)
                    {
                        table5 = displayTable as IRelQueryTable;
                        IRelQueryTableInfo info = table5 as IRelQueryTableInfo;
                        class2.DisplayRelationshipClass(table5.RelationshipClass, info.JoinType);
                    }
                    else
                    {
                        class2.DisplayRelationshipClass(null, esriJoinType.esriLeftInnerJoin);
                    }
                    this.JoiningDataList.Items.Clear();
                    if (this.OnJoinAndRelationChange != null)
                    {
                        this.OnJoinAndRelationChange();
                    }
                    this.method_1(this.itable_0);
                    if (this.JoiningDataList.Items.Count > 0)
                    {
                        this.btnRemoveAllJoining.Enabled = true;
                    }
                    else
                    {
                        this.btnRemoveAllJoining.Enabled = false;
                    }
                }
            }
        }
Example #13
0
 private void method_5(IMap imap_0, IFeatureWorkspace ifeatureWorkspace_0, IFeatureWorkspace ifeatureWorkspace_1,
                       ICollectionTableVersionChanges icollectionTableVersionChanges_0)
 {
     try
     {
         IEnumLayer layer = imap_0.get_Layers(null, true);
         if (layer != null)
         {
             for (ILayer layer2 = layer.Next(); layer2 != null; layer2 = layer.Next())
             {
                 if (layer2 is IDisplayTable)
                 {
                     IDisplayTable table = layer2 as IDisplayTable;
                     if (this.method_3(table.DisplayTable as IDataset, ifeatureWorkspace_0, ifeatureWorkspace_1,
                                       icollectionTableVersionChanges_0))
                     {
                         this.method_2(layer2 as IDisplayRelationshipClass, table.DisplayTable as IRelQueryTable);
                     }
                 }
                 if (layer2 is IFeatureLayer)
                 {
                     IFeatureLayer layer3       = layer2 as IFeatureLayer;
                     IDataset      featureClass = layer3.FeatureClass as IDataset;
                     if (featureClass != null)
                     {
                         this.method_3(featureClass, ifeatureWorkspace_0, ifeatureWorkspace_1,
                                       icollectionTableVersionChanges_0);
                         if (featureClass.Workspace == ifeatureWorkspace_0)
                         {
                             IFeatureClass class2 =
                                 this.method_1(ifeatureWorkspace_1, featureClass) as IFeatureClass;
                             if (class2 != null)
                             {
                                 layer3.FeatureClass = class2;
                                 icollectionTableVersionChanges_0.Add(featureClass as ITable, class2 as ITable);
                             }
                         }
                     }
                 }
             }
         }
     }
     catch (Exception exception)
     {
         MessageBox.Show(exception.Message);
     }
 }
Example #14
0
        /// <summary>
        /// Gets the number of rows, belonging to a given layer, filtered by the layer.
        /// </summary>
        /// <param name="layer">Esri layer of the TOC</param>
        /// <returns>Number of rows or Null if the layer is invalid or not filtered.</returns>
        public static int?GetFilteredLayerRowCount(IFeatureLayer layer)
        {
            IDisplayTable displayTable = (IDisplayTable)layer;

            if ((layer.Valid) && (displayTable != null))
            {
                IFeatureLayerDefinition layerDefinition = layer as IFeatureLayerDefinition;
                string filter = layerDefinition?.DefinitionExpression;
                if (!string.IsNullOrEmpty(filter))
                {
                    IQueryFilter queryFilter = new QueryFilterClass();
                    queryFilter.WhereClause = filter;
                    queryFilter.AddField(layer.FeatureClass.OIDFieldName);
                    return(displayTable.DisplayTable.RowCount(queryFilter));
                }
            }
            return(null);
        }
Example #15
0
 public static void JoinTableLayer(ITable itable_0, string string_0, ITable itable_1, string string_1)
 {
     try
     {
         ITable        attributeTable = null;
         ITable        displayTable   = null;
         IDisplayTable table3         = itable_0 as IDisplayTable;
         if (table3 != null)
         {
             displayTable = table3.DisplayTable;
         }
         if (displayTable is IRelQueryTable)
         {
             attributeTable = displayTable;
         }
         else
         {
             IAttributeTable table4 = itable_0 as IAttributeTable;
             if (table4 == null)
             {
                 return;
             }
             attributeTable = table4.AttributeTable;
         }
         if (itable_1 is IStandaloneTable)
         {
             itable_1 = (itable_1 as IStandaloneTable).Table;
         }
         IMemoryRelationshipClassFactory factory = new MemoryRelationshipClassFactoryClass();
         IRelationshipClass relClass             = factory.Open("TabletoLayer", (IObjectClass)itable_1, string_1,
                                                                (IObjectClass)attributeTable, string_0, "forward", "backward",
                                                                esriRelCardinality.esriRelCardinalityOneToMany);
         ((IDisplayRelationshipClass)itable_0).DisplayRelationshipClass(relClass, esriJoinType.esriLeftOuterJoin);
     }
     catch (COMException exception)
     {
         MessageBox.Show(exception.Message, "COM Error: " + exception.ErrorCode.ToString(), MessageBoxButtons.OK,
                         MessageBoxIcon.Exclamation);
     }
     catch (Exception exception2)
     {
         MessageBox.Show(exception2.Message, ".NET Error: ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
     }
 }
Example #16
0
        ///<summary> The number fields of a specified layer </summary>
        /// <param name="LayerName"> The layer from which a list of number fields is to be fetched </param>
        ///<returns> Function to retrieve a list of all number fields in a given layer </returns>
        public ArrayList NumberFields(string LayerName)
        {
            ArrayList pList = new ArrayList();

            if (FocusMap == null)
            {
                return(pList);
            }
            if (FocusMap.LayerCount == 0)
            {
                return(pList);
            }

            try
            {
                ILayer pLayer = Layer(LayerName);
                if (pLayer == null)
                {
                    return(pList);
                }
                if (pLayer is IGeoFeatureLayer)
                {
                    IFeatureLayer pFlayer       = (IFeatureLayer)pLayer;
                    IDisplayTable pDisplayTable = (IDisplayTable)pFlayer;
                    IFields       pFields       = pDisplayTable.DisplayTable.Fields;
                    for (int i = 0; i < pFields.FieldCount; i++)
                    {
                        IField pField = pFields.get_Field(i);
                        if (pField.Type == esriFieldType.esriFieldTypeDouble || pField.Type == esriFieldType.esriFieldTypeInteger || pField.Type == esriFieldType.esriFieldTypeSingle || pField.Type == esriFieldType.esriFieldTypeSmallInteger)
                        {
                            pList.Add(pField.AliasName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (SupressMessaging == false)
                {
                    MessageBox.Show(ex.Message, "All Number Fields - By Layer Name", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            return(pList);
        }
Example #17
0
 private void method_4(IStandaloneTableCollection istandaloneTableCollection_0,
                       IFeatureWorkspace ifeatureWorkspace_0, IFeatureWorkspace ifeatureWorkspace_1,
                       ICollectionTableVersionChanges icollectionTableVersionChanges_0)
 {
     try
     {
         IDisplayTable table = null;
         for (int i = 0; i < istandaloneTableCollection_0.StandaloneTableCount; i++)
         {
             IStandaloneTable table2 = istandaloneTableCollection_0.get_StandaloneTable(i);
             if (table2 is IDisplayTable)
             {
                 table = table2 as IDisplayTable;
                 if (this.method_3(table.DisplayTable as IDataset, ifeatureWorkspace_0, ifeatureWorkspace_1,
                                   icollectionTableVersionChanges_0))
                 {
                     this.method_2(table2 as IDisplayRelationshipClass, table.DisplayTable as IRelQueryTable);
                 }
             }
             IDataset dataset = table2.Table as IDataset;
             if (dataset != null)
             {
                 this.method_3(dataset, ifeatureWorkspace_0, ifeatureWorkspace_1,
                               icollectionTableVersionChanges_0);
                 if (dataset.Workspace == ifeatureWorkspace_0)
                 {
                     ITable newTable = this.method_1(ifeatureWorkspace_1, dataset);
                     if (newTable != null)
                     {
                         table2.Table = newTable;
                         icollectionTableVersionChanges_0.Add(dataset as ITable, newTable);
                     }
                 }
             }
         }
     }
     catch (Exception exception)
     {
         MessageBox.Show(exception.Message);
     }
 }
Example #18
0
        /// <summary>
        /// </summary>
        /// <param name="displayTable"></param>
        /// <param name="fieldName"></param>
        /// <param name="defaultFieldAlias"></param>
        /// <returns></returns>
        private static string GetFieldAliasFromDisplayTable(IDisplayTable displayTable, string fieldName,
            string defaultFieldAlias)
        {
            if (displayTable == null)
                return fieldName;

            var fields = displayTable as ILayerFields;
            if (fields != null)
            {
                int index = fields.FindField(fieldName);
                if (index != -1)
                    return fields.get_FieldInfo(index).Alias;
            }
            else if (defaultFieldAlias == null)
            {
                int num2 = displayTable.DisplayTable.FindField(fieldName);
                if (num2 != -1)
                    return displayTable.DisplayTable.Fields.get_Field(num2).AliasName;
            }

            return defaultFieldAlias;
        }
Example #19
0
        private void processJoins(IFeatureLayer flyr)
        {
            IDisplayTable  dispTbl = flyr as IDisplayTable;
            ITable         tbl     = dispTbl.DisplayTable;
            IRelQueryTable rqt;
            ITable         destTable;
            IDataset       dataset;
            string         destName;
            string         destServer;
            string         destInstance;
            string         destUser;
            string         res = "";
            string         joinType;

            // Holt iterativ alle Joins!
            while (tbl is IRelQueryTable)
            {
                rqt = (IRelQueryTable)tbl;
                IRelQueryTableInfo rqtInfo  = (IRelQueryTableInfo)rqt;
                IRelationshipClass relClass = rqt.RelationshipClass;
                destTable = rqt.DestinationTable;
                if (rqtInfo.JoinType == esriJoinType.esriLeftInnerJoin)
                {
                    joinType = "esriLeftInnerJoin";
                }
                else
                {
                    joinType = "esriLeftOuterJoin";
                }
                dataset      = (IDataset)destTable;
                destName     = dataset.Name;
                destServer   = dataset.Workspace.ConnectionProperties.GetProperty("server").ToString();
                destInstance = dataset.Workspace.ConnectionProperties.GetProperty("instance").ToString();
                destUser     = dataset.Workspace.ConnectionProperties.GetProperty("user").ToString();
                res          = res + "(" + destName + "/" + destServer + "/" + destInstance + "/" + destUser + "/" + relClass.OriginPrimaryKey + "/" + relClass.OriginForeignKey + "/" + joinType + ")";
                tbl          = rqt.SourceTable;
            }
            joininfo = res;
        }
Example #20
0
        /// <summary>
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="objectClass"></param>
        /// <param name="relClasses"></param>
        /// <param name="parentCursor"></param>
        private void ExportRelatedObjects(XmlWriter writer, ObjectClass objectClass, IEnumRelationshipClass relClasses,
            ICursor parentCursor)
        {
            IRelationshipClass class2 = relClasses.Next();
            IDataset originClass = null;
            while (class2 != null)
            {
                originClass = (IDataset) class2.OriginClass;
                if (originClass.Name == objectClass.name)
                    break;

                originClass = (IDataset) class2.DestinationClass;
                if (originClass.Name == objectClass.name)
                    break;

                class2 = relClasses.Next();
            }

            if (class2 == null)
                return;

            IDisplayTable displayTableFromDatasetName = GetDisplayTableFromDatasetName(originClass.Name);
            StartExportObjectClass(writer, objectClass, displayTableFromDatasetName);
            for (IRow row = parentCursor.NextRow(); row != null; row = parentCursor.NextRow())
            {
                ISet objectsRelatedToObject = class2.GetObjectsRelatedToObject(row as IObject);
                for (var row2 = objectsRelatedToObject.Next() as IRow;
                    row2 != null;
                    row2 = objectsRelatedToObject.Next() as IRow)
                {
                    ExportRow(writer, objectClass, displayTableFromDatasetName, row2);
                }
            }

            EndExportObjectClass(writer);
        }
Example #21
0
        public bool ShowModal(IMapControl3 mapControl, IEngineNetworkAnalystEnvironment naEnv)
        {
            // Initialize variables
            m_okClicked        = false;
            m_listDisplayTable = new System.Collections.ArrayList();

            var activeCategory = naEnv.NAWindow.ActiveCategory as IEngineNAWindowCategory2;

            if (activeCategory == null)
            {
                return(false);
            }

            IDataLayer dataLayer = activeCategory.DataLayer;

            if (dataLayer == null)
            {
                return(false);
            }

            // Set up the title of this dialog
            String dataLayerName = GetDataLayerName(dataLayer);

            if (dataLayerName.Length == 0)
            {
                return(false);
            }

            this.Text = "Load Items into " + dataLayerName;

            // Make sure the combo box lists only the appropriate possible input data layers
            PopulateInputDataComboBox(mapControl, dataLayer);

            //Select the first display table from the list
            if (cboInputData.Items.Count > 0)
            {
                cboInputData.SelectedIndex = 0;
            }

            // Show the window
            this.ShowDialog();

            // If we selected a layer and clicked OK, load the locations
            if (m_okClicked && (cboInputData.SelectedIndex >= 0))
            {
                try
                {
                    // Get a cursor on the source display table (either though the selection set or table)
                    // Use IDisplayTable because it accounts for joins, querydefs, etc.
                    // IDisplayTable is implemented by FeatureLayers and StandaloneTables.
                    //
                    IDisplayTable displayTable = m_listDisplayTable[cboInputData.SelectedIndex] as IDisplayTable;
                    ICursor       cursor;
                    if (chkUseSelection.Checked)
                    {
                        ISelectionSet selSet;
                        selSet = displayTable.DisplaySelectionSet;
                        selSet.Search(null, false, out cursor);
                    }
                    else
                    {
                        cursor = displayTable.SearchDisplayTable(null, false);
                    }

                    // Get the NAContext from the active analysis layer
                    INAContext naContext = naEnv.NAWindow.ActiveAnalysis.Context;

                    // Get the dataset for the active NAClass
                    IDataset naDataset = activeCategory.NAClass as IDataset;

                    // Setup NAClassLoader and Load Locations
                    INAClassLoader2 naClassLoader = new NAClassLoader() as INAClassLoader2;
                    naClassLoader.Initialize(naContext, naDataset.Name, cursor);

                    // Avoid loading network locations onto non-traversable portions of elements
                    INALocator3 locator = naContext.Locator as INALocator3;
                    locator.ExcludeRestrictedElements = true;
                    locator.CacheRestrictedElements(naContext);

                    int rowsIn      = 0;
                    int rowsLocated = 0;
                    naClassLoader.Load(cursor, null, ref rowsIn, ref rowsLocated);

                    // Let the user know if some of the rows failed to locate
                    if (rowsIn != rowsLocated)
                    {
                        MessageBox.Show("Out of " + rowsIn + " + rows, " + rowsLocated + " rows were located",
                                        "Loading locations", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, "Loading locations failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                return(true);
            }

            return(false);
        }
Example #22
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                // make sure the user selected a field to edit
                if (cboCheckDecimals.SelectedIndex == -1)
                {
                    MessageBox.Show("Please select a field from the drop-down menu to edit.", "Select Field", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // make sure the user has selected a layer to edit in the choose layer combobox
                if (cboChooseLayer.SelectedIndex == -1)
                {
                    MessageBox.Show("Please choose a layer from the top drop-down list to base edits on.", "Select Layer", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // make sure the user is editing
                //get the editor extension
                UID arcUID = new UID();
                arcUID.Value         = "esriEditor.Editor";
                clsGlobals.arcEditor = clsGlobals.arcApplication.FindExtensionByCLSID(arcUID) as IEditor3;

                // check if editing first
                if (clsGlobals.arcEditor.EditState == ESRI.ArcGIS.Editor.esriEditState.esriStateNotEditing)
                {
                    MessageBox.Show("You must be editing in order to make all selected feature values for the " + cboChooseLayer.Text + " layer on the " + cboCheckDecimals.Text + " field... to empty string.  Please start editing and then try again.", "Must Be Editing", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // show the cursor as busy
                System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;


                // get access to the layer that is specified in the choose layer dropdown box
                clsGlobals.pGFlayer     = null;
                clsGlobals.arcFeatLayer = null;

                // loop through the map's layers and check for the layer with the targeted name (based on the choose layer combobox)
                for (int i = 0; i < clsGlobals.pMap.LayerCount; i++)
                {
                    if (clsGlobals.pMap.Layer[i].Name == cboChooseLayer.Text)
                    {
                        clsGlobals.pGFlayer     = (IGeoFeatureLayer)clsGlobals.pMap.Layer[i];
                        clsGlobals.arcFeatLayer = (IFeatureLayer)clsGlobals.pMap.Layer[i];
                    }
                }

                IDataset       arcDataset       = (IDataset)clsGlobals.arcFeatLayer;
                IWorkspace     arcWorkspace     = arcDataset.Workspace;
                IWorkspaceEdit arcWorkspaceEdit = (IWorkspaceEdit)arcWorkspace;

                // make sure we're editing the correct workspace
                if (!(arcWorkspaceEdit.IsBeingEdited()))
                {
                    MessageBox.Show("You must be editing the " + cboChooseLayer.Text + " layer in order to proceed.", "Must Be Editing", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // get access to the selected features in the user specified layer
                IDisplayTable arcDisplayTable = (IDisplayTable)clsGlobals.arcFeatLayer;
                ISelectionSet arcSelectionSet = arcDisplayTable.DisplaySelectionSet;

                // make sure there's at least one feature selected in the specified layer
                if (arcSelectionSet.Count == 0)
                {
                    MessageBox.Show("You must select at least one feature in the " + cboChooseLayer.Text + " layer to edit values in the " + cboCheckDecimals.Text + " field... making them empty string.", "No Features are Selected.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // confirm the user wants to edit that layer's fields on the selected records
                DialogResult dialogResult = MessageBox.Show("Would you like to proceed with editing " + arcSelectionSet.Count + " features on the " + cboChooseLayer.Text + " Layer, rounding the values in the " + cboCheckDecimals.Text + " Field to the nearest whole number?", "Confirm Edits", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (dialogResult == DialogResult.Yes)
                {
                    // set some variables for editing the selected features
                    IFeature arcFeatureToEdit = null;
                    IEnumIDs arcEnumIDs       = arcSelectionSet.IDs;
                    int      iD;

                    // loop through the selected feature in the user specified layer and make the values in the user specified field empty string
                    while ((iD = arcEnumIDs.Next()) != -1)
                    {
                        arcFeatureToEdit = clsGlobals.arcFeatLayer.FeatureClass.GetFeature(iD);
                        clsGlobals.arcEditor.StartOperation();

                        double d          = (double)arcFeatureToEdit.get_Value(arcFeatureToEdit.Fields.FindField(cboCheckDecimals.Text));
                        int    intRounded = Convert.ToInt32(d);

                        arcFeatureToEdit.set_Value(arcFeatureToEdit.Fields.FindField(cboCheckDecimals.Text), intRounded);

                        arcFeatureToEdit.Store();
                        clsGlobals.arcEditor.StopOperation(cboCheckDecimals.Text.ToString() + " values rounded");
                    }

                    MessageBox.Show("Done rounding decimal places for " + arcSelectionSet.Count + " features on the " + cboChooseLayer.Text + " Layer, rounding the vaules in the " + cboCheckDecimals.Text + " Field to the nearest whole number.  Don't forget to save edits if you want to retain the changes.", "Done!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else if (dialogResult == DialogResult.No)
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Message: " + Environment.NewLine + ex.Message + Environment.NewLine + Environment.NewLine +
                                "Error Source: " + Environment.NewLine + ex.Source + Environment.NewLine + Environment.NewLine +
                                "Error Location:" + Environment.NewLine + ex.StackTrace,
                                "Push Utrans Roads to SGID!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        //---------------------------------------------------------------------
        // CHANGED: CR13 (Export features performance)
        // Enable query filter to be built for specific layer so that
        // subset layers can be exported rather than always the whole
        // feature layer.
        private IQueryFilter ExportQueryFilter(string originPKJoinField, IFeatureLayer featureLayer,
            IFeatureClass featureClass, IDisplayTable hluDisplayTable, IDataset attributeDataset,
            List<IField> featClassFields, List<IField> attributeFields,
            out bool featClassFieldsQualified, out bool attributeFieldsQualified)
        {
            StringBuilder queryFilterSubFields = new StringBuilder();
            string queryFilterWhereClause = String.Empty;

            featClassFieldsQualified = hluDisplayTable.DisplayTable.Fields.get_Field(0)
                .Name.StartsWith(featureLayer.Name + ".");
            attributeFieldsQualified = hluDisplayTable.DisplayTable.Fields.get_Field(
                featureClass.Fields.FieldCount).Name.StartsWith(attributeDataset.Name + ".");

            if (featClassFieldsQualified)
            {
                queryFilterSubFields.Append(String.Join(",", featClassFields
                    .Select(f => featureLayer.Name + "." + f.Name).ToArray()));
            }
            else
            {
                queryFilterSubFields.Append(String.Join(",", featClassFields.Select(f => f.Name).ToArray()));
            }

            if (attributeFieldsQualified)
            {
                queryFilterSubFields.Append(",").Append(String.Join(",",
                    attributeFields.Select(f => attributeDataset.Name + "." + f.Name).ToArray()));
                // Don't set the where clause because all features will always
                // be exported from the specified layer.
                //queryFilterWhereClause = String.Format("{0} IS NOT NULL",
                  //  _hluLayer.Name + "." + originPKJoinField);
            }
            else
            {
                queryFilterSubFields.Append(",").Append(
                    String.Join(",", attributeFields.Select(f => f.Name).ToArray()));
                // Don't set the where clause because all features will always
                // be exported from the specified layer.
                //queryFilterWhereClause = String.Format("{0} IS NOT NULL", originPKJoinField);
            }
            IQueryFilter exportQueryFilter = new QueryFilterClass();
            exportQueryFilter.SubFields = queryFilterSubFields.ToString();
            exportQueryFilter.WhereClause = queryFilterWhereClause;

            return exportQueryFilter;
        }
        private void ExportInsertFeatures(IDisplayTable hluDisplayTable, IQueryFilter exportQueryFilter, 
            int exportRowCount, int[] exportFieldMap, bool isShp, object outWS, IFeatureClass outFeatureClass)
        {
            // Create a Cancel Tracker.
            ITrackCancel trackCancel = new CancelTrackerClass();

            // Create the Progress Dialog. This automatically displays the dialog.
            IProgressDialogFactory progressDlgFactory = new ProgressDialogFactoryClass();
            IProgressDialog2 progressDlg = progressDlgFactory.Create(trackCancel, _application.hWnd) as IProgressDialog2;

            // Set the properties of the Progress Dialog.
            progressDlg.CancelEnabled = true;
            progressDlg.Title = "Export Progress";
            progressDlg.Description = string.Format("Exporting HLU Features and Attributes\n({0} features)", exportRowCount.ToString());
            progressDlg.Animation = esriProgressAnimationTypes.esriNoAnimation;

            // Set the properties of the Step Progressor.
            IStepProgressor stepProgressor = progressDlg as IStepProgressor;
            stepProgressor.MinRange = 0;
            stepProgressor.MaxRange = exportRowCount;
            stepProgressor.StepValue = 1;
            stepProgressor.Message = "";

            // Set the continue progress to true.
            bool contProgress = true;

            IWorkspaceEdit workspaceEdit = null;
            IWorkspace wsOut = outWS as IWorkspace;
            bool restoreEditSession = InEditingSession;
            if (restoreEditSession) CloseEditSession(true);

            // If the workspace is remote then the data is being accessed
            // via ArcSDE.
            if (wsOut.WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace)
            {
                Editor.StartEditing(wsOut);
                Editor.StartOperation();
            }
            // Otherwise, it must be a FileSystem (for shapefiles)
            // or LocalDatabase (for geodatabases) workspace.
            else
            {
                workspaceEdit = (IWorkspaceEdit)outWS;
                workspaceEdit.StartEditing(true);
                workspaceEdit.StartEditOperation();
            }
            
            IFeatureCursor exportFeatureCursor =
                (IFeatureCursor)hluDisplayTable.SearchDisplayTable(exportQueryFilter, true);
            IFeature exportFeature;

            IFeatureCursor insertCursor = outFeatureClass.Insert(true);
            IFeatureBuffer featureBuffer = outFeatureClass.CreateFeatureBuffer();

            bool calcGeometry = _hluFeatureClass.ShapeType == esriGeometryType.esriGeometryPoint || isShp;
            double geom1;
            double geom2;
            // The last two fields are always the geometry fields.
            int ixGeom1 = featureBuffer.Fields.FieldCount - 2;
            int ixGeom2 = featureBuffer.Fields.FieldCount - 1;

            try
            {
                object item;
                while ((exportFeature = exportFeatureCursor.NextFeature()) != null)
                {
                    featureBuffer.Shape = exportFeature.ShapeCopy;

                    for (int i = 2; i < exportFieldMap.Length; i++)
                    {
                        item = exportFeature.get_Value(exportFieldMap[i]);
                        if (item != DBNull.Value)
                            featureBuffer.set_Value(i, item);
                        //---------------------------------------------------------------------
                        // FIX: 036 Clear all missing fields when exporting features from ArcGIS.
                        else
                            featureBuffer.set_Value(i, null);
                        //---------------------------------------------------------------------
                    }

                    if (calcGeometry)
                    {
                        GetGeometryProperties(exportFeature, out geom1, out geom2);
                        if (geom1 != -1)
                            featureBuffer.set_Value(ixGeom1, geom1);
                        if (geom2 != -1)
                            featureBuffer.set_Value(ixGeom2, geom2);
                    }

                    try { insertCursor.InsertFeature(featureBuffer); }
                    catch { }

                    // Check if the cancel button was pressed. If so, stop the process.
                    contProgress = trackCancel.Continue();
                    if (!contProgress)
                        throw new Exception("Export cancelled by user.");
                }
                FlushCursor(false, ref insertCursor);

                if (workspaceEdit == null)
                {
                    Editor.StopOperation(String.Empty);
                    Editor.StopEditing(true);
                }
                else
                {
                    workspaceEdit.StopEditOperation();
                    workspaceEdit.StopEditing(true);
                }
            }
            catch
            {
                if (workspaceEdit == null)
                {
                    Editor.AbortOperation();
                    Editor.StopEditing(false);
                }
                else
                {
                    workspaceEdit.AbortEditOperation();
                    workspaceEdit.StopEditOperation();
                    workspaceEdit.StopEditing(false);
                }
                throw;
            }
            finally
            {
                FlushCursor(true, ref exportFeatureCursor);

                if (restoreEditSession) OpenEditSession();

                // Hide the progress dialog.
                trackCancel = null;
                stepProgressor = null;
                progressDlg.HideDialog();
                progressDlg = null;
                progressDlgFactory = null;
            }
        }
Example #25
0
        private void PopulateInputDataComboBox(IMapControl3 mapControl, IDataLayer dataLayer)
        {
            esriGeometryType targetGeoType = GetDataLayerGeometryType(dataLayer);

            IEnumLayer    sourceLayers       = null;
            ILayer        sourceLayer        = null;
            IDisplayTable sourceDisplayTable = null;
            UID           searchInterfaceUID = new UID();

            if (targetGeoType != esriGeometryType.esriGeometryNull)
            {
                // Only include layers that are of type IFeatureLayer
                searchInterfaceUID.Value = typeof(IFeatureLayer).GUID.ToString("B");
                sourceLayers             = mapControl.Map.get_Layers(searchInterfaceUID, true);

                // iterate over all of the feature layers
                sourceLayer = sourceLayers.Next();
                while (sourceLayer != null)
                {
                    // Verify that the layer is a feature layer and a display table
                    IFeatureLayer sourceFeatureLayer = sourceLayer as IFeatureLayer;
                    sourceDisplayTable = sourceLayer as IDisplayTable;
                    if ((sourceFeatureLayer != null) && (sourceDisplayTable != null))
                    {
                        // Make sure that the geometry of the feature layer matches the geometry
                        //   of the class into which we are loading
                        IFeatureClass    sourceFeatureClass = sourceFeatureLayer.FeatureClass;
                        esriGeometryType sourceGeoType      = sourceFeatureClass.ShapeType;
                        if ((sourceGeoType == targetGeoType) ||
                            (targetGeoType == esriGeometryType.esriGeometryPoint && sourceGeoType == esriGeometryType.esriGeometryMultipoint))
                        {
                            // Add the layer name to the combobox and the layer to the list
                            cboInputData.Items.Add(sourceLayer.Name);
                            m_listDisplayTable.Add(sourceDisplayTable);
                        }
                    }

                    sourceLayer = sourceLayers.Next();
                }
            }
            // The layer being loaded into has no geometry type
            else
            {
                // Find all of the standalone table that are not part of an NALayer
                IStandaloneTableCollection sourceStandaloneTables = mapControl.Map as IStandaloneTableCollection;
                IStandaloneTable           sourceStandaloneTable  = null;
                sourceDisplayTable = null;

                int count = 0;
                if (sourceStandaloneTables != null)
                {
                    count = sourceStandaloneTables.StandaloneTableCount;
                }

                for (int i = 0; i < count; ++i)
                {
                    sourceStandaloneTable = sourceStandaloneTables.get_StandaloneTable(i);
                    sourceDisplayTable    = sourceStandaloneTable as IDisplayTable;

                    if ((sourceStandaloneTable != null) && (sourceDisplayTable != null))
                    {
                        // Add the table name to the combobox and the layer to the list
                        cboInputData.Items.Add(sourceStandaloneTable.Name);
                        m_listDisplayTable.Add(sourceDisplayTable);
                    }
                }

                // Find all of the standalone tables that are part of an NALayer
                searchInterfaceUID.Value = typeof(INALayer).GUID.ToString("B");
                sourceLayers             = mapControl.Map.get_Layers(searchInterfaceUID, true);

                sourceLayer = sourceLayers.Next();
                while (sourceLayer != null)
                {
                    INALayer sourceNALayer = sourceLayer as INALayer;
                    if (sourceNALayer != null)
                    {
                        sourceStandaloneTables = sourceNALayer as IStandaloneTableCollection;
                        sourceStandaloneTable  = null;
                        sourceDisplayTable     = null;

                        count = 0;
                        if (sourceStandaloneTables != null)
                        {
                            count = sourceStandaloneTables.StandaloneTableCount;
                        }

                        for (int i = 0; i < count; ++i)
                        {
                            sourceStandaloneTable = sourceStandaloneTables.get_StandaloneTable(i);
                            sourceDisplayTable    = sourceStandaloneTable as IDisplayTable;

                            if ((sourceStandaloneTable != null) && (sourceDisplayTable != null))
                            {
                                // Add the table name to the combobox and the layer to the list
                                cboInputData.Items.Add(sourceStandaloneTable.Name);
                                m_listDisplayTable.Add(sourceDisplayTable);
                            }
                        }
                    }

                    sourceLayer = sourceLayers.Next();
                }
            }
        }
Example #26
0
        /// <summary>
        ///     return the FieldName and Alias data as an array of data objects
        /// </summary>
        /// <param name="objectClass"></param>
        /// <param name="displayTable"></param>
        /// <returns></returns>
        private static FieldNameAndAlias[] GetObjectClassFields(ObjectClass objectClass, IDisplayTable displayTable)
        {
            // if the fields to return are identified in the config xml file
            if (objectClass.Fields != null)
            {
                var aliasArray = new FieldNameAndAlias[objectClass.Fields.Length];
                for (int j = 0; j < objectClass.Fields.Length; j++)
                {
                    var alias = new FieldNameAndAlias
                    {
                        alias = (objectClass.Fields[j].alias.Length == 0
                            ? GetFieldAliasFromDisplayTable(displayTable, objectClass.Fields[j])
                            : objectClass.Fields[j].alias),
                        name = objectClass.Fields[j].name
                    };

                    // * If alias defined in xml config, use it, otherwise use the display alias..?

                    aliasArray[j] = alias;
                }

                return aliasArray;
            }

            // otherwise return all of the fields in the table as named
            int fieldCount = displayTable.DisplayTable.Fields.FieldCount;
            var aliasArray2 = new FieldNameAndAlias[fieldCount];
            for (int i = 0; i < fieldCount; i++)
            {
                var alias2 = new FieldNameAndAlias();
                IField field = displayTable.DisplayTable.Fields.get_Field(i);
                alias2.alias = GetFieldAliasFromDisplayTable(displayTable, field.Name, field.AliasName);
                alias2.name = displayTable.DisplayTable.Fields.get_Field(i).Name;
                aliasArray2[i] = alias2;
            }

            return aliasArray2;
        }
Example #27
0
        protected override void OnMouseDown(ESRI.ArcGIS.Desktop.AddIns.Tool.MouseEventArgs arg)
        {
            int            X      = arg.X;
            int            Y      = arg.Y;
            IMxApplication pMxApp = null;
            IMxDocument    pMxDoc = null;

            pMxApp = (IMxApplication)ArcMap.Application;
            pMxDoc = (IMxDocument)ArcMap.Application.Document;

            // calculate tolerance rectangle to identify features inside it
            int Tolerance = 0;

            Tolerance = pMxDoc.SearchTolerancePixels;

            IDisplayTransformation pDispTrans = null;

            pDispTrans = pMxApp.Display.DisplayTransformation;
            tagRECT pToleranceRect = new tagRECT();

            pToleranceRect.left   = X - Tolerance;
            pToleranceRect.right  = X + Tolerance;
            pToleranceRect.top    = Y - Tolerance;
            pToleranceRect.bottom = Y + Tolerance;

            IEnvelope pSearchEnvelope = null;

            pSearchEnvelope = new EnvelopeClass();
            pDispTrans.TransformRect(pSearchEnvelope, ref pToleranceRect, (int)(esriDisplayTransformationEnum.esriTransformPosition | esriDisplayTransformationEnum.esriTransformToMap));

            // identify feature points of measurement
            IBasicDocument pBasicDoc = null;

            pBasicDoc = (IBasicDocument)ArcMap.Application.Document;
            pSearchEnvelope.SpatialReference = pMxDoc.ActiveView.FocusMap.SpatialReference;

            IIdentify pIdentify = null;

            pIdentify = (IIdentify)pMxDoc.FocusMap.get_Layer(0);
            if (pIdentify == null)
            {
                MessageBox.Show("No layer");
                return;
            }

            IArray pIDArray = null;

            pIDArray = pIdentify.Identify(pSearchEnvelope);

            // get object from feature point
            IIdentifyObj pIDObj = null;

            if (pIDArray != null)
            {
                pIDObj = (IIdentifyObj)pIDArray.get_Element(0);
            }

            if (pIDObj == null)
            {
                MessageBox.Show("No feature was identified");
                return;
            }

            // get the name of the layer containing feature points
            ILayer pLayer = null;

            pLayer = pMxDoc.FocusMap.get_Layer(0);

            string layerName = null;

            layerName = pLayer.Name;

            // get primary display field for measurement values and set names of a date/time field and gage ID field
            IFeatureLayer pFeatLayer = null;

            pFeatLayer = (IFeatureLayer)pLayer;
            string dataFldName   = null;
            string timefldName   = null;
            string gageIDFldName = null;

            dataFldName   = "TSValue";
            timefldName   = "TSDateTime"; // substitute data/time field name for different dataset
            gageIDFldName = "Name";       // substitute gage ID field name for different dataset

            // get display table from layer
            ITable        pTable        = null;
            IDisplayTable pDisplayTable = null;

            pDisplayTable = (IDisplayTable)pLayer;
            if (pDisplayTable != null)
            {
                pTable = pDisplayTable.DisplayTable;
                if (pTable == null)
                {
                    goto THEEND;
                }
            }

            // get fields from display table
            IFields pFields = null;

            pFields = pTable.Fields;
            long fldCount = 0;

            fldCount = pFields.FieldCount;

            // create WHERE clause from identified objects of measurement points
            int gageIDFldIdx = 0;

            gageIDFldIdx = pFields.FindField(gageIDFldName);

            IRowIdentifyObject pRowIDObj = null;

            pRowIDObj = (IRowIdentifyObject)pIDObj;

            string gageID = null;

            gageID = (string)pRowIDObj.Row.get_Value(gageIDFldIdx);

            IFeatureLayerDefinition pFeatureLayerDef = null;

            pFeatureLayerDef = (IFeatureLayerDefinition)pLayer;
            string definitionExpression = null;

            definitionExpression = pFeatureLayerDef.DefinitionExpression;

            string whereClause = null;

            if (definitionExpression == "")
            {
                whereClause = "[" + gageIDFldName + "] = '" + gageID + "'";
            }
            else
            {
                whereClause = "[" + gageIDFldName + "] = '" + gageID + "' AND " + definitionExpression;
            }

            //find color for the identified object from feature layer's renderer
            IGeoFeatureLayer pGeoFeatureLayer = null;

            pGeoFeatureLayer = (IGeoFeatureLayer)pLayer;

            ILookupSymbol pLookupSymbol = null;

            pLookupSymbol = (ILookupSymbol)pGeoFeatureLayer.Renderer;

            IFeature pFeature = null;

            pFeature = (IFeature)pRowIDObj.Row;

            IMarkerSymbol pSymbol = null;

            pSymbol = (IMarkerSymbol)pLookupSymbol.LookupSymbol(false, pFeature);

            // Find an opened GraphWindow
            IDataGraphBase    pDataGraphBase = null;
            IDataGraphT       pDataGraphT    = null;
            IDataGraphWindow2 pDGWin         = null;

            IDataGraphCollection pDataGraphs = null;

            pDataGraphs = (IDataGraphCollection)pMxDoc;
            int grfCount = 0;

            grfCount = pDataGraphs.DataGraphCount;
            for (int i = 0; i < grfCount; i++)
            {
                pDataGraphBase = pDataGraphs.get_DataGraph(i);
                pDGWin         = FindGraphWindow(ref pDataGraphBase);
                if (pDGWin != null)
                {
                    break;
                }
            }

            // if there is not an opened graph window - create a new graph for
            if (pDGWin == null)
            {
                // create graph
                pDataGraphT    = new DataGraphTClass();
                pDataGraphBase = (IDataGraphBase)pDataGraphT;

                // load template from <ARCGISHOME>\GraphTemplates\
                string strPath = null;
                strPath = Environment.GetEnvironmentVariable("ARCGISHOME");
                try
                {
                    pDataGraphT.LoadTemplate(strPath + @"GraphTemplates\timeseries.tee");
                }
                catch
                { }

                // graph, axis and legend titles. Substitute them for different input layer
                pDataGraphT.GeneralProperties.Title           = "Daily Streamflow for Guadalupe Basin in 1999";
                pDataGraphT.LegendProperties.Title            = "Monitoring Point";
                pDataGraphT.get_AxisProperties(0).Title       = "Streamflow (cfs)";
                pDataGraphT.get_AxisProperties(0).Logarithmic = true;
                pDataGraphT.get_AxisProperties(2).Title       = "Date";
                pDataGraphBase.Name = layerName;
            }
            else // get graph from the opened window
            {
                pDataGraphT = (IDataGraphT)pDataGraphBase;
            }

            // create vertical line series for all measurements for the identified gage
            ISeriesProperties pSP = null;

            pSP             = pDataGraphT.AddSeries("line:vertical");
            pSP.ColorType   = esriGraphColorType.esriGraphColorCustomAll;
            pSP.CustomColor = pSymbol.Color.RGB;
            pSP.WhereClause = whereClause;
            pSP.InLegend    = true;
            pSP.Name        = gageID;

            pSP.SourceData = pLayer;
            pSP.SetField(0, timefldName);
            pSP.SetField(1, dataFldName);
            IDataSortSeriesProperties pSortFlds = null;

            pSortFlds = (IDataSortSeriesProperties)pSP;
            int idx = 0;

            pSortFlds.AddSortingField(timefldName, true, ref idx);


            pDataGraphBase.UseSelectedSet = true;

            ITrackCancel pCancelTracker = null;

            pCancelTracker = new CancelTracker();
            pDataGraphT.Update(pCancelTracker);

            // create data graph window if there is not any opened one
            if (pDGWin == null)
            {
                pDGWin = new DataGraphWindowClass();
                pDGWin.DataGraphBase = pDataGraphBase;
                pDGWin.Application   = ArcMap.Application;
                pDGWin.Show(true);

                pDataGraphs.AddDataGraph(pDataGraphBase);
            }

THEEND:
            return;

            //base.OnMouseDown(arg);
        }
        private void ExportInsertFeatures(IDisplayTable hluDisplayTable, IQueryFilter exportQueryFilter, 
            int exportRowCount, int[] exportFieldMap, bool isShp, object outWS, IFeatureClass outFeatureClass)
        {
            IStatusBar statusBar = _application.StatusBar;
            IStepProgressor progressBar = statusBar.ProgressBar;
            progressBar.Position = 0;
            statusBar.ShowProgressBar("Exporting...", 0, exportRowCount, 1, true);

            IWorkspaceEdit workspaceEdit = null;
            IWorkspace wsOut = outWS as IWorkspace;
            bool restoreEditSession = InEditingSession;
            if (restoreEditSession) CloseEditSession(true);

            if (wsOut.WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace)
            {
                Editor.StartEditing(wsOut);
                Editor.StartOperation();
            }

            else
            {
                workspaceEdit = (IWorkspaceEdit)outWS;
                workspaceEdit.StartEditing(true);
                workspaceEdit.StartEditOperation();
            }
            
            IFeatureCursor exportFeatureCursor =
                (IFeatureCursor)hluDisplayTable.SearchDisplayTable(exportQueryFilter, true);
            IFeature exportFeature;

            IFeatureCursor insertCursor = outFeatureClass.Insert(true);
            IFeatureBuffer featureBuffer = outFeatureClass.CreateFeatureBuffer();

            bool calcGeometry = _hluFeatureClass.ShapeType == esriGeometryType.esriGeometryPoint || isShp;
            double geom1;
            double geom2;
            int ixGeom1 = featureBuffer.Fields.FieldCount - 2;
            int ixGeom2 = featureBuffer.Fields.FieldCount - 1;

            try
            {
                object item;
                while ((exportFeature = exportFeatureCursor.NextFeature()) != null)
                {
                    featureBuffer.Shape = exportFeature.ShapeCopy;

                    for (int i = 2; i < exportFieldMap.Length; i++)
                    {
                        item = exportFeature.get_Value(exportFieldMap[i]);
                        if (item != DBNull.Value) featureBuffer.set_Value(i, item);
                    }

                    if (calcGeometry)
                    {
                        GetGeometryProperties(exportFeature, out geom1, out geom2);
                        if (geom1 != -1)
                            featureBuffer.set_Value(ixGeom1, geom1);
                        if (geom2 != -1)
                            featureBuffer.set_Value(ixGeom2, geom2);
                    }

                    try { insertCursor.InsertFeature(featureBuffer); }
                    catch { }

                    progressBar.Step();
                }
                FlushCursor(false, ref insertCursor);

                if (workspaceEdit == null)
                {
                    Editor.StopOperation(String.Empty);
                    Editor.StopEditing(true);
                }
                else
                {
                    workspaceEdit.StopEditOperation();
                    workspaceEdit.StopEditing(true);
                }
            }
            catch
            {
                if (workspaceEdit == null)
                {
                    Editor.AbortOperation();
                    Editor.StopEditing(false);
                }
                else
                {
                    workspaceEdit.AbortEditOperation();
                    workspaceEdit.StopEditOperation();
                    workspaceEdit.StopEditing(false);
                }
                throw;
            }
            finally
            {
                FlushCursor(true, ref exportFeatureCursor);
                if (restoreEditSession) OpenEditSession();
                statusBar.set_Message((int)esriStatusBarPanes.esriStatusMain, "");
                statusBar.HideProgressBar();
            }
        }
Example #29
0
        /// <summary>
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="objectClass"></param>
        /// <param name="table"></param>
        private static void StartExportObjectClass(XmlWriter writer, ObjectClass objectClass, IDisplayTable table)
        {
            try
            {
                writer.WriteStartElement("ObjectClass");
                writer.WriteAttributeString("name", GetDisplayTableName(objectClass, table));
                writer.WriteStartElement("ObjectClassFieldDefinition");
                FieldNameAndAlias[] objectClassFields = GetObjectClassFields(objectClass, table);
                if (objectClassFields != null)
                {
                    foreach (FieldNameAndAlias alias in objectClassFields)
                    {
                        writer.WriteElementString("FieldDefinition", alias.alias);
                    }
                }

                writer.WriteEndElement();
                writer.WriteStartElement("ObjectClassRows");
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }
Example #30
0
        public bool ShowModal(IMapControl3 mapControl, IEngineNetworkAnalystEnvironment naEnv)
        {
            // Initialize variables
            m_okClicked        = false;
            m_listDisplayTable = new System.Collections.ArrayList();

            // Get the NALayer and NAContext
            INALayer   naLayer   = naEnv.NAWindow.ActiveAnalysis;
            INAContext naContext = naLayer.Context;

            //Get the active category
            IEngineNAWindowCategory2 activeCategory = naEnv.NAWindow.ActiveCategory as IEngineNAWindowCategory2;

            if (activeCategory == null)
            {
                return(false);
            }

            INAClass   naClass    = activeCategory.NAClass;
            IDataset   naDataset  = naClass as IDataset;
            IDataLayer pDataLayer = activeCategory.DataLayer;

            ILayer           pLayer           = pDataLayer as ILayer;
            IFeatureLayer    pFeatureLayer    = pDataLayer as IFeatureLayer;
            IStandaloneTable pStandaloneTable = pDataLayer as IStandaloneTable;

            esriGeometryType targetGeoType = esriGeometryType.esriGeometryNull;

            String dataLayerName = "";

            if (pFeatureLayer != null)
            {
                if (pLayer.Valid)
                {
                    IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
                    if (pFeatureClass != null)
                    {
                        targetGeoType = pFeatureClass.ShapeType;
                        dataLayerName = pLayer.Name;
                    }
                }
            }
            else if (pStandaloneTable != null)
            {
                dataLayerName = pStandaloneTable.Name;
            }

            if (dataLayerName.Length == 0)
            {
                return(false);
            }

            this.Text = "Load Items into " + dataLayerName;

            // Loop through all the sourcedisplayTables having targetGeoType to the combo box and the
            // list of displayTables

            IEnumLayer    sourceLayers       = null;
            ILayer        sourceLayer        = null;
            IDisplayTable sourceDisplayTable = null;
            UID           searchInterfaceUID = new UID();

            if (targetGeoType != esriGeometryType.esriGeometryNull)
            {
                searchInterfaceUID.Value = typeof(IFeatureLayer).GUID.ToString("B");
                sourceLayers             = mapControl.Map.get_Layers(searchInterfaceUID, true);

                sourceLayer = sourceLayers.Next();
                while (sourceLayer != null)
                {
                    IFeatureLayer sourceFeatureLayer = sourceLayer as IFeatureLayer;
                    sourceDisplayTable = sourceLayer as IDisplayTable;

                    if ((sourceFeatureLayer != null) && (sourceDisplayTable != null))
                    {
                        IFeatureClass    sourceFeatureClass = sourceFeatureLayer.FeatureClass;
                        esriGeometryType sourceGeoType      = sourceFeatureClass.ShapeType;
                        if ((sourceGeoType == targetGeoType) ||
                            (targetGeoType == esriGeometryType.esriGeometryPoint && sourceGeoType == esriGeometryType.esriGeometryMultipoint))
                        {
                            // Add the layer name to the combobox and the layer to the list
                            cboInputData.Items.Add(sourceLayer.Name);
                            m_listDisplayTable.Add(sourceDisplayTable);
                        }
                    }

                    sourceLayer = sourceLayers.Next();
                }
            }
            else //if (targetGeoType == esriGeometryType.esriGeometryNull)
            {
                IStandaloneTableCollection sourceStandaloneTables = mapControl.Map as IStandaloneTableCollection;
                IStandaloneTable           sourceStandaloneTable  = null;
                sourceDisplayTable = null;

                int count = 0;
                if (sourceStandaloneTables != null)
                {
                    count = sourceStandaloneTables.StandaloneTableCount;
                }

                for (int i = 0; i < count; ++i)
                {
                    sourceStandaloneTable = sourceStandaloneTables.get_StandaloneTable(i);
                    sourceDisplayTable    = sourceStandaloneTable as IDisplayTable;

                    if ((sourceStandaloneTable != null) && (sourceDisplayTable != null))
                    {
                        // Add the table name to the combobox and the layer to the list
                        cboInputData.Items.Add(sourceStandaloneTable.Name);
                        m_listDisplayTable.Add(sourceDisplayTable);
                    }
                }

                searchInterfaceUID.Value = typeof(INALayer).GUID.ToString("B");
                sourceLayers             = mapControl.Map.get_Layers(searchInterfaceUID, true);

                sourceLayer = sourceLayers.Next();
                while (sourceLayer != null)
                {
                    INALayer sourceNALayer = sourceLayer as INALayer;
                    if (sourceNALayer != null)
                    {
                        sourceStandaloneTables = sourceNALayer as IStandaloneTableCollection;
                        sourceStandaloneTable  = null;
                        sourceDisplayTable     = null;

                        count = 0;
                        if (sourceStandaloneTables != null)
                        {
                            count = sourceStandaloneTables.StandaloneTableCount;
                        }

                        for (int i = 0; i < count; ++i)
                        {
                            sourceStandaloneTable = sourceStandaloneTables.get_StandaloneTable(i);
                            sourceDisplayTable    = sourceStandaloneTable as IDisplayTable;

                            if ((sourceStandaloneTable != null) && (sourceDisplayTable != null))
                            {
                                // Add the table name to the combobox and the layer to the list
                                cboInputData.Items.Add(sourceStandaloneTable.Name);
                                m_listDisplayTable.Add(sourceDisplayTable);
                            }
                        }
                    }

                    sourceLayer = sourceLayers.Next();
                }
            }

            //Select the first display table from the list
            if (cboInputData.Items.Count > 0)
            {
                cboInputData.SelectedIndex = 0;
            }

            // Show the window
            this.ShowDialog();

            // If we selected a layer and clicked OK, load the locations
            if (m_okClicked && (cboInputData.SelectedIndex >= 0))
            {
                // Get a cursor on the source display table (either though the selection set or table)
                // Use IDisplayTable because it accounts for joins, querydefs, etc.
                // IDisplayTable is implemented by FeatureLayers and StandaloneTables.
                //
                IDisplayTable displayTable = m_listDisplayTable[cboInputData.SelectedIndex] as IDisplayTable;
                ICursor       cursor;
                if (chkUseSelection.Checked)
                {
                    ISelectionSet selSet;
                    selSet = displayTable.DisplaySelectionSet;
                    selSet.Search(null, false, out cursor);
                }
                else
                {
                    cursor = displayTable.SearchDisplayTable(null, false);
                }

                // Setup NAClassLoader and Load Locations
                INAClassLoader2 naClassLoader = new NAClassLoader() as INAClassLoader2;
                naClassLoader.Initialize(naContext, naDataset.Name, cursor);

                // Avoid loading network locations onto non-traversable portions of elements
                INALocator3 locator = naContext.Locator as INALocator3;
                locator.ExcludeRestrictedElements = true;
                locator.CacheRestrictedElements(naContext);

                int rowsIn      = 0;
                int rowsLocated = 0;
                naClassLoader.Load(cursor, null, ref rowsIn, ref rowsLocated);

                return(true);
            }

            return(false);
        }
Example #31
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;
            }
        }
Example #32
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;
            }
        }
Example #33
0
        /// <summary>
        /// 按聚类号对凸包进行渲染
        /// </summary>
        /// <param name="pGeoFeatureLayer"></param>
        /// <param name="fieldName"></param>
        public void DefinePolygonUniqueValueRenderer(IGeoFeatureLayer pGeoFeatureLayer, string fieldName)
        {
            IRandomColorRamp pRandomColorRamp = new RandomColorRampClass();

            //Create the color ramp for the symbols in the renderer.
            pRandomColorRamp.MinSaturation = 20;
            pRandomColorRamp.MaxSaturation = 40;
            pRandomColorRamp.MinValue      = 85;
            pRandomColorRamp.MaxValue      = 100;
            pRandomColorRamp.StartHue      = 76;
            pRandomColorRamp.EndHue        = 188;
            pRandomColorRamp.UseSeed       = true;
            pRandomColorRamp.Seed          = 43;

            //Create the renderer.
            IUniqueValueRenderer pUniqueValueRenderer = new UniqueValueRendererClass();

            ISimpleFillSymbol pSimpleFillSymbol = new SimpleFillSymbolClass();

            pSimpleFillSymbol.Style         = esriSimpleFillStyle.esriSFSSolid;
            pSimpleFillSymbol.Outline.Width = 0.4;

            /*  ISimpleMarkerSymbol pSimpleMarkerSymbol = new SimpleMarkerSymbolClass();
             * pSimpleMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
             * pSimpleMarkerSymbol.Size = 5;
             * pSimpleMarkerSymbol.Outline = true;
             * IRgbColor pLineRgbColor = new RgbColorClass();
             * pLineRgbColor.Red = 0;
             * pLineRgbColor.Green = 0;
             * pLineRgbColor.Blue = 0;
             * pSimpleMarkerSymbol.OutlineColor = pLineRgbColor as IColor;
             */
            //These properties should be set prior to adding values.
            pUniqueValueRenderer.FieldCount = 1;
            pUniqueValueRenderer.set_Field(0, fieldName);
            pUniqueValueRenderer.DefaultSymbol    = pSimpleFillSymbol as ISymbol;
            pUniqueValueRenderer.UseDefaultSymbol = true;

            IDisplayTable  pDisplayTable  = pGeoFeatureLayer as IDisplayTable;
            IFeatureCursor pFeatureCursor = pDisplayTable.SearchDisplayTable(null, false) as IFeatureCursor;
            IFeature       pFeature       = pFeatureCursor.NextFeature();


            bool ValFound;
            int  fieldIndex;

            IFields pFields = pFeatureCursor.Fields;

            fieldIndex = pFields.FindField(fieldName);
            while (pFeature != null)
            {
                ISimpleFillSymbol pClassSymbol = new SimpleFillSymbolClass();
                pClassSymbol.Style         = esriSimpleFillStyle.esriSFSSolid;
                pClassSymbol.Outline.Width = 0.4;

                /*    ISimpleMarkerSymbol pClassSymbol = new SimpleMarkerSymbolClass();
                 * pClassSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
                 * pClassSymbol.Size = 5;
                 * pClassSymbol.Outline = true;
                 * pClassSymbol.OutlineColor = pLineRgbColor as IColor;
                 */
                string classValue;
                classValue = pFeature.get_Value(fieldIndex).ToString();

                //Test to see if this value was added to the renderer. If not, add it.
                ValFound = false;
                for (int i = 0; i <= pUniqueValueRenderer.ValueCount - 1; i++)
                {
                    if (pUniqueValueRenderer.get_Value(i) == classValue)
                    {
                        ValFound = true;
                        break; //Exit the loop if the value was found.
                    }
                }
                //If the value was not found, it's new and will be added.
                if (ValFound == false)
                {
                    pUniqueValueRenderer.AddValue(classValue, fieldName, pClassSymbol as ISymbol);
                    pUniqueValueRenderer.set_Label(classValue, classValue);
                    pUniqueValueRenderer.set_Symbol(classValue, pClassSymbol as ISymbol);
                }
                pFeature = pFeatureCursor.NextFeature();
            }
            //Since the number of unique values is known, the color ramp can be sized and the colors assigned.
            pRandomColorRamp.Size = pUniqueValueRenderer.ValueCount;
            bool bOK;

            pRandomColorRamp.CreateRamp(out bOK);

            IEnumColors pEnumColors = pRandomColorRamp.Colors;

            pEnumColors.Reset();
            for (int j = 0; j <= pUniqueValueRenderer.ValueCount - 1; j++)
            {
                string xv;
                xv = pUniqueValueRenderer.get_Value(j);
                if (xv != "")
                {
                    ISimpleFillSymbol pSimpleFillColor = pUniqueValueRenderer.get_Symbol(xv) as ISimpleFillSymbol;
                    pSimpleFillColor.Color = pEnumColors.Next();
                    pUniqueValueRenderer.set_Symbol(xv, pSimpleFillColor as ISymbol);
                }
            }
            pGeoFeatureLayer.Renderer     = (IFeatureRenderer)pUniqueValueRenderer;
            pGeoFeatureLayer.DisplayField = fieldName;
        }