示例#1
0
        /// <summary>
        /// create feature class of output
        /// </summary>
        /// <param name="workspace">object workspace</param>
        /// <param name="spatialReference">spatial reference of feature class of output</param>
        /// <param name="nameFeatureClass">name of feature class</param>
        /// <returns>object feature class</returns>
        private static IFeatureClass CreateFeatureClassOutput(IWorkspace workspace, ISpatialReference spatialReference, string nameFeatureClass)
        {
            IFeatureClassDescription featureClassDescription = new FeatureClassDescriptionClass();
            IObjectClassDescription objectClassDescription = (IObjectClassDescription)featureClassDescription;

            IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;

            // Create the fields collection.
            IFields fields = new FieldsClass();
            IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

            IField oidField = new FieldClass();
            IFieldEdit oidFieldEdit = (IFieldEdit)oidField;
            oidFieldEdit.Name_2 = "OBJECTID";
            oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
            fieldsEdit.AddField(oidField);

            // Create the Shape field.
            IField shapeField = new Field();
            IFieldEdit shapeFieldEdit = (IFieldEdit)shapeField;

            // Set up the geometry definition for the Shape field.
            IGeometryDef geometryDef = new GeometryDefClass();
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
            geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;

            // By setting the grid size to 0, you're allowing ArcGIS to determine the appropriate grid sizes for the feature class.
            // If in a personal geodatabase, the grid size will be 1000. If in a file or ArcSDE geodatabase, the grid size
            // will be based on the initial loading or inserting of features.
            geometryDefEdit.HasM_2 = false;
            geometryDefEdit.HasZ_2 = false;

            geometryDefEdit.SpatialReference_2 = spatialReference;

            // Set standard field properties.
            shapeFieldEdit.Name_2 = featureClassDescription.ShapeFieldName;
            shapeFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
            shapeFieldEdit.GeometryDef_2 = geometryDef;
            shapeFieldEdit.IsNullable_2 = true;
            shapeFieldEdit.Required_2 = true;
            fieldsEdit.AddField(shapeField);

            IField idField = new FieldClass();
            IFieldEdit idIsolaFieldEdit = (IFieldEdit)idField;
            idIsolaFieldEdit.Name_2 = Program.nameFieldIdOutput;
            idIsolaFieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger;
            fieldsEdit.AddField(idField);

            // Use IFieldChecker to create a validated fields collection.
            IFieldChecker fieldChecker = new FieldCheckerClass();
            IEnumFieldError enumFieldError = null;
            IFields validatedFields = null;
            fieldChecker.ValidateWorkspace = workspace;
            fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

            return featureWorkspace.CreateFeatureClass(nameFeatureClass, fields, objectClassDescription.InstanceCLSID, objectClassDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, featureClassDescription.ShapeFieldName, string.Empty);
        }
示例#2
0
文件: SEEDAO.cs 项目: EAWCS1/SUITT
        public void insert(Transaction current, SEE see, ISpatialReference utmSR)
        {
            // Create table on datastore PGDB first?
            current.TxId = see.RestID;
            IPolygon sourcePolygon = see.Shape;
            //sourcePolygon.Project(utmSR);

            IFields fields = new FieldsClass();
            IFieldsEdit fieldsEdit = (IFieldsEdit)fields;
            fieldsEdit.FieldCount_2 = 3;
            //Create the Object ID field.
            IField fieldUserDefined = new Field();
            IFieldEdit fieldEdit = (IFieldEdit)fieldUserDefined;
            fieldEdit.Name_2 = "OBJECTID";
            fieldEdit.AliasName_2 = "OBJECT ID";
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
            fieldsEdit.set_Field(0, fieldUserDefined);
            // Create the Shape field.
            fieldUserDefined = new Field();
            fieldEdit = (IFieldEdit)fieldUserDefined;
            // Set up the geometry definition for the Shape field.
            IGeometryDef geometryDef = new GeometryDefClass();
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
            geometryDefEdit.GeometryType_2 = ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolygon;
            // By setting the grid size to 0, you're allowing ArcGIS to determine the appropriate grid sizes for the feature class.
            // If in a personal geodatabase, the grid size will be 1000. If in a file or ArcSDE geodatabase, the grid size
            // will be based on the initial loading or inserting of features.
            geometryDefEdit.GridCount_2 = 1;
            geometryDefEdit.set_GridSize(0, 0);
            geometryDefEdit.HasM_2 = false;
            geometryDefEdit.HasZ_2 = false;
            //Assign the spatial reference that was passed in, possibly from
            //IGeodatabase.SpatialReference for the containing feature dataset.
            if (see.Shape.SpatialReference != null)
            {
                geometryDefEdit.SpatialReference_2 = see.Shape.SpatialReference;
            }
            //if (utmSR == null)
            //{
            //    ISpatialReferenceFactory2 sre = (ISpatialReferenceFactory2)new SpatialReferenceEnvironment();
            //    utmSR = sre.CreateSpatialReference((int)esriSRProjCSType.esriSRProjCS_NAD1983UTM_10N);
            //}

            //geometryDefEdit.SpatialReference_2 = utmSR;// see.Shape.SpatialReference;
            // Set standard field properties.
            fieldEdit.Name_2 = "SHAPE";
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
            fieldEdit.GeometryDef_2 = geometryDef;
            fieldEdit.IsNullable_2 = true;
            fieldEdit.Required_2 = true;
            fieldsEdit.set_Field(1, fieldUserDefined);
            // Create a field of type double to hold some information for the features.
            fieldUserDefined = new Field();
            fieldEdit = (IFieldEdit)fieldUserDefined;
            fieldEdit.Name_2 = "SPATIAL_EDIT_EXTENT_SP_ID";
            fieldEdit.AliasName_2 = "SPATIAL_EDIT_EXTENT_SP_ID";
            fieldEdit.Editable_2 = true;
            fieldEdit.IsNullable_2 = false;
            fieldEdit.Length_2 = 125;
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            fieldsEdit.set_Field(2, fieldUserDefined);
            // Create a feature class description object to use for specifying the CLSID and EXTCLSID.
            IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass();
            IObjectClassDescription ocDesc = (IObjectClassDescription)fcDesc;
            ESRI.ArcGIS.esriSystem.UID CLSID = new ESRI.ArcGIS.esriSystem.UIDClass();

            // The enumFieldError enumerator can be inspected at this point to determine
            // which fields were modified during validation.
            IFeatureClass fc = osdb.CreateFeatureClass(OSDB_SEE_NAME, fields, ocDesc.InstanceCLSID, ocDesc.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDesc.ShapeFieldName, "");

            //IGeoDatasetSchemaEdit fd_ed = (IGeoDatasetSchemaEdit)fc;
            //ISpatialReference oldSR = ((IGeoDataset)fc).SpatialReference;
            //if (fd_ed.CanAlterSpatialReference && !oldSR.Equals(utmSR))
            //{
            //    // does not reproject the data
            //    // doees alter all child feature classes
            //    fd_ed.AlterSpatialReference(utmSR);
            //}

            IWorkspaceEdit wse = (IWorkspaceEdit)osdb;
            wse.StartEditing(false);
            wse.StartEditOperation();

            try
            {
                fc = osdb.OpenFeatureClass(OSDB_SEE_NAME);
            }
            catch(Exception e)
            {
                MessageBox.Show("OSDB Feature Class " + OSDB_SEE_NAME + " Not Found in SUITT",
                    "EXCEPTION", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                throw new HandledException(e);
            }

            IFeatureCursor fcrs = null;

            try
            {
                fcrs = fc.Insert(false);
                IFeatureBuffer buffer = fc.CreateFeatureBuffer();

                buffer.set_Value(fcrs.FindField(SEE_ID_COL), RestTransactionManager.Instance.NewTransactionSeeID);
                //buffer.set_Value(fcrs.FindField(OSDB_NAME_COL),current.OperationalDatasetName);

                //string t = current.Description;
                //if (t != null && t.Length > EDIT_INTENT_COL_LNG)
                //{
                //    t = t.Substring(0, EDIT_INTENT_COL_LNG);
                //}
                //buffer.set_Value(fcrs.FindField(EDIT_INTENT_COL), t);

                //buffer.set_Value(fcrs.FindField(OPEN_DATE_COL),current.CreationDate);
                //t = current.PGDB.FullName;
                //buffer.set_Value(fcrs.FindField(PGDB_PATH_COL), t);

                IPolygon p = sourcePolygon;
                if(p!=null)
                {
                    //p.Project(utmSR);
                    p.Project(((IGeoDataset)fc).SpatialReference);
                }
                buffer.Shape = p;

                fcrs.InsertFeature(buffer);

                fcrs.Flush();

                // Explicitly release the cursor.
                Marshal.ReleaseComObject(fcrs);

                // Stop editing.
                wse.StopEditOperation();
                wse.StopEditing(true);
            }
            catch(Exception e)
            {
                // Failed while writing the SEE area poygon to the PGDB?
                // We should carry on with the transaction, but the SEE area will be lost

                MessageBox.Show("Error occured storing SEE geometry. " + e.Message);
            }
            finally
            {
                if(fcrs != null)
                {
                    Utils.Release(fcrs);
                }
            }
        }
示例#3
0
        public static IFeatureClass CreateFeatureClass(IWorkspace workspace, IFeatureDataset featureDataset, String featureClassName, IFields fields)
        {
            IFeatureClass featureClass;
            String strShapeField = "";
            var featureWorkspace = workspace as IFeatureWorkspace;
            IObjectClassDescription objectClassDescription = new FeatureClassDescriptionClass();

            #region 简单校验
            if (featureClassName == "") return null;
            //if (workspace.get_NameExists(esriDatasetType.esriDTFeatureClass, featureClassName))
            //{
            //    featureClass = featureWorkspace.OpenFeatureClass(featureClassName);
            //    return featureClass;
            //}

            if (fields == null)
            {
                fields = objectClassDescription.RequiredFields;
                IFieldsEdit fieldsEdit = (IFieldsEdit)fields;
                IField field = new FieldClass();
                IFieldEdit fieldEdit = (IFieldEdit)field;
                fieldEdit.Name_2 = "Name";
                fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                fieldsEdit.AddField(field);
                fields = (IFields)fieldsEdit;
            }

            var feaClsDes = objectClassDescription as IFeatureClassDescription;
            strShapeField = feaClsDes.ShapeFieldName;
            #endregion

            //查询几何字段
            if (strShapeField == "")
            {
                for (int j = 0; j < fields.FieldCount; j++)
                {
                    if (fields.get_Field(j).Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        strShapeField = fields.get_Field(j).Name;
                    }
                }
            }

            // 字段检查
            IFieldChecker fieldChecker = new FieldCheckerClass();
            IEnumFieldError enumFieldError = null;
            IFields validatedFields = null;
            fieldChecker.ValidateWorkspace = (IWorkspace)workspace;
            fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

            //创建要素类
            if (featureDataset == null)
            {
                featureClass = featureWorkspace.CreateFeatureClass(featureClassName, validatedFields, objectClassDescription.InstanceCLSID, objectClassDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, strShapeField, "");
            }
            else
            {
                featureClass = featureDataset.CreateFeatureClass(featureClassName, validatedFields, objectClassDescription.InstanceCLSID, objectClassDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, strShapeField, "");
            }
            return featureClass;
        }
示例#4
0
        public static IFields CreateFields(esriGeometryType geoType)
        {
            IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
            IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription;
            IFields fields = ocDescription.RequiredFields;

            int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName);
            IField field = fields.get_Field(shapeFieldIndex);
            IGeometryDef geometryDef = field.GeometryDef;
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
            geometryDefEdit.GeometryType_2 = geoType;
            ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            var sr = spatialReferenceFactory.CreateGeographicCoordinateSystem(4326);
            geometryDefEdit.SpatialReference_2 = sr;

            IFieldsEdit fieldsEdit = (IFieldsEdit)fields;
            field = new FieldClass();
            IFieldEdit fieldEdit = (IFieldEdit)field;
            fieldEdit.Name_2 = "Name";
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            fieldsEdit.AddField(field);

            return fields;
        }
        private void CreateAndPopulateTurnFeatureClass(string outputFileGdbPath, string fdsName,
                                                       string ProhibMPTableName, string tempStatsTableName,
                                                       IGPMessages messages, ITrackCancel trackcancel)
        {
            // Determine the number of AltID fields we need (the same as the MAX_SEQNR value).

            Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
            var wsf = Activator.CreateInstance(factoryType) as IWorkspaceFactory;
            var fws = wsf.OpenFromFile(outputFileGdbPath, 0) as IFeatureWorkspace;
            ITable tempStatsTable = fws.OpenTable(tempStatsTableName);
            short numAltIDFields = 2;
            if (tempStatsTable.RowCount(null) == 1)
                numAltIDFields = (short)((double)(tempStatsTable.GetRow(1).get_Value(tempStatsTable.FindField("MAX_SEQNR"))));

            // Open the MP table and find the fields we need

            ITable mpTable = fws.OpenTable(ProhibMPTableName);
            int seqNrField = mpTable.FindField("SEQNR");
            int trpElIDField = mpTable.FindField("TRPELID");
            int idFieldOnMP = mpTable.FindField("ID");
            int mpJnctIDField = mpTable.FindField("JNCTID");

            // Create a temporary template feature class

            var fcd = new FeatureClassDescriptionClass() as IFeatureClassDescription;
            var ocd = fcd as IObjectClassDescription;
            var fieldsEdit = ocd.RequiredFields as IFieldsEdit;
            IField fieldOnMPTable = mpTable.Fields.get_Field(idFieldOnMP);  // use the ID field as a template for the AltID fields
            for (short i = 1; i <= numAltIDFields; i++)
            {
                IFieldEdit newField = new FieldClass();
                newField.Name_2 = "AltID" + i;
                newField.Precision_2 = fieldOnMPTable.Precision;
                newField.Scale_2 = fieldOnMPTable.Scale;
                newField.Type_2 = fieldOnMPTable.Type;
                fieldsEdit.AddField(newField as IField);
            }
            fieldsEdit.AddField(fieldOnMPTable);
            fieldOnMPTable = mpTable.Fields.get_Field(mpJnctIDField);
            fieldsEdit.AddField(fieldOnMPTable);
            var fieldChk = new FieldCheckerClass() as IFieldChecker;
            IEnumFieldError enumFieldErr = null;
            IFields validatedFields = null;
            fieldChk.ValidateWorkspace = fws as IWorkspace;
            fieldChk.Validate(fieldsEdit as IFields, out enumFieldErr, out validatedFields);
            var tempFC = fws.CreateFeatureClass("TheTemplate", validatedFields, ocd.InstanceCLSID, ocd.ClassExtensionCLSID,
                                                esriFeatureType.esriFTSimple, fcd.ShapeFieldName, "") as IDataset;

            // Create the turn feature class from the template, then delete the template

            Geoprocessor gp = new Geoprocessor();
            CreateTurnFeatureClass createTurnFCTool = new CreateTurnFeatureClass();
            string pathToFds = outputFileGdbPath + "\\" + fdsName;
            createTurnFCTool.out_location = pathToFds;
            createTurnFCTool.out_feature_class_name = TurnFCName;
            createTurnFCTool.maximum_edges = numAltIDFields;
            createTurnFCTool.in_template_feature_class = outputFileGdbPath + "\\TheTemplate";
            gp.Execute(createTurnFCTool, trackcancel);
            tempFC.Delete();

            // Open the new turn feature class and find all the fields on it

            IFeatureClass turnFC = fws.OpenFeatureClass(TurnFCName);
            int[] altIDFields = new int[numAltIDFields];
            int[] edgeFCIDFields = new int[numAltIDFields];
            int[] edgeFIDFields = new int[numAltIDFields];
            int[] edgePosFields = new int[numAltIDFields];
            for (short i = 0; i < numAltIDFields; i++)
            {
                altIDFields[i] = turnFC.FindField("AltID" + (i + 1));
                edgeFCIDFields[i] = turnFC.FindField("Edge" + (i + 1) + "FCID");
                edgeFIDFields[i] = turnFC.FindField("Edge" + (i + 1) + "FID");
                edgePosFields[i] = turnFC.FindField("Edge" + (i + 1) + "Pos");
            }
            int edge1endField = turnFC.FindField("Edge1End");
            int idFieldOnTurnFC = turnFC.FindField("ID");
            int turnFCJnctIDField = turnFC.FindField("JNCTID");

            // Look up the FCID of the Streets feature class

            IFeatureClass streetsFC = fws.OpenFeatureClass(StreetsFCName);
            int streetsFCID = streetsFC.FeatureClassID;

            // Set up queries

            var ts = new TableSortClass() as ITableSort;
            ts.Fields = "ID, SEQNR";
            ts.set_Ascending("ID", true);
            ts.set_Ascending("SEQNR", true);
            ts.QueryFilter = new QueryFilterClass();
            ts.Table = mpTable;
            ts.Sort(null);
            ICursor mpCursor = ts.Rows;
            IFeatureCursor turnFCCursor = turnFC.Insert(true);
            IFeatureBuffer turnBuffer = turnFC.CreateFeatureBuffer();

            // Write the field values to the turn feature class accordingly

            turnBuffer.set_Value(edge1endField, "?");  // dummy value; will be updated in a later calculation
            int numFeatures = 0;
            IRow mpRow = mpCursor.NextRow();
            while (mpRow != null)
            {
                // Transfer the non-edge identifying field values to the buffer
                turnBuffer.set_Value(idFieldOnTurnFC, mpRow.get_Value(idFieldOnMP));
                turnBuffer.set_Value(turnFCJnctIDField, mpRow.get_Value(mpJnctIDField));

                // Write the AltID values to the buffer
                int seq = (int)(mpRow.get_Value(seqNrField));
                int lastEntry;
                do
                {
                    lastEntry = seq;
                    turnBuffer.set_Value(altIDFields[lastEntry - 1], mpRow.get_Value(trpElIDField));
                    mpRow = mpCursor.NextRow();
                    if (mpRow == null) break;
                    seq = (int)(mpRow.get_Value(seqNrField));
                } while (seq != 1);

                // Zero-out the unused fields
                for (int i = lastEntry; i < numAltIDFields; i++)
                    turnBuffer.set_Value(altIDFields[i], 0);

                // Write the FCID and Pos field values to the buffer
                for (short i = 0; i < numAltIDFields; i++)
                {
                    double altID = (double)(turnBuffer.get_Value(altIDFields[i]));
                    if (altID != 0)
                    {
                        turnBuffer.set_Value(edgeFCIDFields[i], streetsFCID);
                        turnBuffer.set_Value(edgeFIDFields[i], 1);
                        turnBuffer.set_Value(edgePosFields[i], 0.5);
                    }
                    else
                    {
                        turnBuffer.set_Value(edgeFCIDFields[i], 0);
                        turnBuffer.set_Value(edgeFIDFields[i], 0);
                        turnBuffer.set_Value(edgePosFields[i], 0);
                    }
                }

                // Create the turn feature
                turnFCCursor.InsertFeature(turnBuffer);
                numFeatures++;

                if ((numFeatures % 100) == 0)
                {
                    // check for user cancel

                    if (trackcancel != null && !trackcancel.Continue())
                        throw (new COMException("Function cancelled."));
                }
            }

            // Flush any outstanding writes to the turn feature class
            turnFCCursor.Flush();

            // Update the Edge1End values

            AddMessage("Updating the Edge1End values...", messages, trackcancel);

            MakeFeatureLayer makeFeatureLayerTool = new MakeFeatureLayer();
            makeFeatureLayerTool.in_features = pathToFds + "\\" + TurnFCName;
            makeFeatureLayerTool.out_layer = "Turn_Layer";
            gp.Execute(makeFeatureLayerTool, trackcancel);

            AddJoin addJoinTool = new AddJoin();
            addJoinTool.in_layer_or_view = "Turn_Layer";
            addJoinTool.in_field = "AltID1";
            addJoinTool.join_table = pathToFds + "\\" + StreetsFCName;
            addJoinTool.join_field = "ID";
            gp.Execute(addJoinTool, trackcancel);

            CalculateField calcFieldTool = new CalculateField();
            calcFieldTool.in_table = "Turn_Layer";
            calcFieldTool.field = TurnFCName + ".Edge1End";
            calcFieldTool.expression = "x";
            calcFieldTool.code_block = "Select Case [" + TurnFCName + ".JNCTID]\n  Case [" + StreetsFCName + ".F_JNCTID]: x = \"N\"\n  Case [" + StreetsFCName + ".T_JNCTID]: x = \"Y\"\n  Case Else: x = \"?\"\nEnd Select";
            calcFieldTool.expression_type = "VB";
            gp.Execute(calcFieldTool, trackcancel);

            RemoveJoin removeJoinTool = new RemoveJoin();
            removeJoinTool.in_layer_or_view = "Turn_Layer";
            removeJoinTool.join_name = StreetsFCName;
            gp.Execute(removeJoinTool, trackcancel);

            Delete deleteTool = new Delete();
            deleteTool.in_data = "Turn_Layer";
            gp.Execute(deleteTool, trackcancel);

            AddMessage("Updating the EdgeFID values...", messages, trackcancel);

            // Create a temporary network dataset for updating the EdgeFID values

            IDENetworkDataset dends = new DENetworkDatasetClass();
            dends.SupportsTurns = true;
            dends.Buildable = true;
            (dends as IDataElement).Name = StreetsFCName;
            (dends as IDEGeoDataset).SpatialReference = (streetsFC as IGeoDataset).SpatialReference;
            IArray sourceArray = new ArrayClass();
            var efs = new EdgeFeatureSourceClass() as IEdgeFeatureSource;
            (efs as INetworkSource).Name = StreetsFCName;
            efs.UsesSubtypes = false;
            efs.ClassConnectivityGroup = 1;
            efs.ClassConnectivityPolicy = esriNetworkEdgeConnectivityPolicy.esriNECPEndVertex;
            sourceArray.Add(efs);
            var tfs = new TurnFeatureSourceClass() as INetworkSource;
            tfs.Name = TurnFCName;
            sourceArray.Add(tfs);
            dends.Sources = sourceArray;
            var fdxc = fws.OpenFeatureDataset(fdsName) as IFeatureDatasetExtensionContainer;
            var dsCont = fdxc.FindExtension(esriDatasetType.esriDTNetworkDataset) as IDatasetContainer2;
            var tempNDS = dsCont.CreateDataset(dends as IDEDataset) as IDataset;

            // Set the EdgeFID field values by running UpdateByAlternateIDFields

            UpdateByAlternateIDFields updateByAltIDTool = new UpdateByAlternateIDFields();
            updateByAltIDTool.in_network_dataset = pathToFds + "\\" + StreetsFCName;
            updateByAltIDTool.alternate_ID_field_name = "ID";
            gp.Execute(updateByAltIDTool, trackcancel);

            // Delete the temporary network dataset

            tempNDS.Delete();

            // Write the turn geometries

            TurnGeometryUtilities.WriteTurnGeometry(outputFileGdbPath, StreetsFCName, TurnFCName,
                                                    numAltIDFields, 0.3, messages, trackcancel);

            // Index the turn geometries

            AddMessage("Creating spatial index on the turn feature class...", messages, trackcancel);

            AddSpatialIndex addSpatialIndexTool = new AddSpatialIndex();
            addSpatialIndexTool.in_features = pathToFds + "\\" + TurnFCName;
            gp.Execute(addSpatialIndexTool, trackcancel);

            return;
        }
示例#6
0
        ///<summary>Simple helper to create a featureclass in a geodatabase.</summary>
        /// 
        ///<param name="workspace">An IWorkspace2 interface</param>
        ///<param name="featureDataset">An IFeatureDataset interface or Nothing</param>
        ///<param name="featureClassName">A System.String that contains the name of the feature class to open or create. Example: "states"</param>
        ///<param name="fields">An IFields interface</param>
        ///<param name="clsid">A UID value or Nothing. Example "esriGeoDatabase.Feature" or Nothing</param>
        ///<param name="clsext">A UID value or Nothing (this is the class extension if you want to reference a class extension when creating the feature class).</param>
        ///<param name="strConfigKeyword">An empty System.String or RDBMS table string for ArcSDE. Example: "myTable" or ""</param>
        ///  
        ///<returns>An IFeatureClass interface or a Nothing</returns>
        ///  
        ///<remarks>
        ///  (1) If a 'featureClassName' already exists in the workspace a reference to that feature class 
        ///      object will be returned.
        ///  (2) If an IFeatureDataset is passed in for the 'featureDataset' argument the feature class
        ///      will be created in the dataset. If a Nothing is passed in for the 'featureDataset'
        ///      argument the feature class will be created in the workspace.
        ///  (3) When creating a feature class in a dataset the spatial reference is inherited 
        ///      from the dataset object.
        ///  (4) If an IFields interface is supplied for the 'fields' collection it will be used to create the
        ///      table. If a Nothing value is supplied for the 'fields' collection, a table will be created using 
        ///      default values in the method.
        ///  (5) The 'strConfigurationKeyword' parameter allows the application to control the physical layout 
        ///      for this table in the underlying RDBMSfor example, in the case of an Oracle database, the 
        ///      configuration keyword controls the tablespace in which the table is created, the initial and 
        ///     next extents, and other properties. The 'strConfigurationKeywords' for an ArcSDE instance are 
        ///      set up by the ArcSDE data administrator, the list of available keywords supported by a workspace 
        ///      may be obtained using the IWorkspaceConfiguration interface. For more information on configuration 
        ///      keywords, refer to the ArcSDE documentation. When not using an ArcSDE table use an empty 
        ///      string (ex: "").
        ///</remarks>
        internal IFeatureClass CreateFeatureClass(IWorkspace2 workspace, IFeatureDataset featureDataset,
                                                  string featureClassName,
                                                  IFields fields, ESRI.ArcGIS.esriSystem.UID clsid,
                                                  ESRI.ArcGIS.esriSystem.UID clsext, string strConfigKeyword)
        {
            if (string.IsNullOrEmpty(featureClassName))
                return null;

            IFeatureClass featureClass;
            var featureWorkspace = (IFeatureWorkspace)workspace; // Cast may throw exception

            if (workspace.NameExists[esriDatasetType.esriDTFeatureClass, featureClassName])
            //feature class with that name already exists
            {
                featureClass = featureWorkspace.OpenFeatureClass(featureClassName);
                return featureClass;
            }

            // assign the class id value if not assigned
            if (clsid == null)
            {
                clsid = new ESRI.ArcGIS.esriSystem.UIDClass { Value = "esriGeoDatabase.Feature" };
                //Works for shapefiles as well
            }

            IObjectClassDescription objectClassDescription = new FeatureClassDescriptionClass();

            // if a fields collection is not passed in then supply our own
            if (fields == null)
            {
                // create the fields using the required fields method
                fields = objectClassDescription.RequiredFields;
                var fieldsEdit = (IFieldsEdit)fields; // Explicit Cast
                IField field = new FieldClass();

                // create a user defined text field
                var fieldEdit = (IFieldEdit)field; // Explicit Cast

                // setup field properties
                fieldEdit.Name_2 = "SampleField";
                fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                fieldEdit.IsNullable_2 = true;
                fieldEdit.AliasName_2 = "Sample Field Column";
                fieldEdit.DefaultValue_2 = "test";
                fieldEdit.Editable_2 = true;
                fieldEdit.Length_2 = 100;

                // add field to field collection
                fieldsEdit.AddField(field);
                fields = fieldsEdit;
            }

            string strShapeField = "";

            // locate the shape field
            for (int j = 0; j < fields.FieldCount; j++)
            {
                if (fields.Field[j].Type != esriFieldType.esriFieldTypeGeometry)
                    continue;
                strShapeField = fields.Field[j].Name;
                break;
            }

            // Use IFieldChecker to create a validated fields collection.
            IFieldChecker fieldChecker = new FieldCheckerClass();
            IEnumFieldError enumFieldError;
            IFields validatedFields;
            fieldChecker.ValidateWorkspace = (IWorkspace)workspace;
            fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

            // The enumFieldError enumerator can be inspected at this point to determine
            // which fields were modified during validation.

            // finally create and return the feature class
            featureClass = featureDataset == null
                               ? featureWorkspace.CreateFeatureClass(featureClassName, validatedFields, clsid, clsext,
                                                                     esriFeatureType.esriFTSimple, strShapeField,
                                                                     strConfigKeyword)
                               : featureDataset.CreateFeatureClass(featureClassName, validatedFields, clsid, clsext,
                                                                   esriFeatureType.esriFTSimple, strShapeField,
                                                                   strConfigKeyword);
            return featureClass;
        }
        public static IFeatureClass CreateSignsFeatureClass(IFeatureClass linesFeatureClass, string name)
        {
            // Locations are all relative to the location of the reference lines.
            // For geodatabase, signs feature class is at the same location and the streets table
            // is at the level of the containing feature dataset.
            // For shapefile, both are at the same location as the reference lines.

            // start with the initial set of required fields for a feature class

            IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
            IObjectClassDescription ocDescription = fcDescription as IObjectClassDescription;
            IFieldsEdit outFields = ocDescription.RequiredFields as IFieldsEdit;

            // make the shape field to be of type polyline with the same spatial reference as the reference lines

            IField shapeField = outFields.get_Field(outFields.FindField(fcDescription.ShapeFieldName));
            IGeometryDefEdit geomDefEdit = shapeField.GeometryDef as IGeometryDefEdit;
            geomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline;
            geomDefEdit.SpatialReference_2 = (linesFeatureClass as IGeoDataset).SpatialReference;

            // add the other fields to the feature class

            IFieldEdit field = new FieldClass();
            field.Name_2 = "ExitName";
            field.Type_2 = esriFieldType.esriFieldTypeString;
            field.Length_2 = 24;
            outFields.AddField(field);

            string currentNumber;

            for (int i = 0; i < MaxBranchCount; i++)
            {
                currentNumber = Convert.ToString(i, System.Globalization.CultureInfo.InvariantCulture);

                field = new FieldClass();
                field.Name_2 = "Branch" + currentNumber;
                field.Type_2 = esriFieldType.esriFieldTypeString;
                field.Length_2 = 180;
                outFields.AddField(field);

                field = new FieldClass();
                field.Name_2 = "Branch" + currentNumber + "Dir";
                field.Type_2 = esriFieldType.esriFieldTypeString;
                field.Length_2 = 5;
                outFields.AddField(field);

                field = new FieldClass();
                field.Name_2 = "Branch" + currentNumber + "Lng";
                field.Type_2 = esriFieldType.esriFieldTypeString;
                field.Length_2 = 2;
                outFields.AddField(field);

                field = new FieldClass();
                field.Name_2 = "Toward" + currentNumber;
                field.Type_2 = esriFieldType.esriFieldTypeString;
                field.Length_2 = 180;
                outFields.AddField(field);

                field = new FieldClass();
                field.Name_2 = "Toward" + currentNumber + "Lng";
                field.Type_2 = esriFieldType.esriFieldTypeString;
                field.Length_2 = 2;
                outFields.AddField(field);
            }

            // make the feature class

            IFeatureDataset pFeatureDataset = linesFeatureClass.FeatureDataset;
            IWorkspace pWorkspace = (linesFeatureClass as IDataset).Workspace;

            if (pFeatureDataset != null)
                return pFeatureDataset.CreateFeatureClass(name, outFields, ocDescription.InstanceCLSID,
                    ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, "");
            else if (pWorkspace is IFeatureWorkspace)
                return (pWorkspace as IFeatureWorkspace).CreateFeatureClass(name, outFields, ocDescription.InstanceCLSID,
                    ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, "");
            else
                return null;   // not expected
        }
示例#8
0
        /// <summary>
        /// 创建多边形shp
        /// </summary>
        /// <param name="pPolygon"></param>
        /// <param name="shpPath"></param>
        public static void CreatePolygonFeatureClass(IPolygon pPolygon, string shpfolder, string shpname)
        {
            IWorkspaceFactory pWorkSpaceFac = new ShapefileWorkspaceFactoryClass();
            IWorkspaceEdit pWorkspaceEdit = (IWorkspaceEdit)pWorkSpaceFac;
            IFeatureWorkspace pFeatureWorkSpace = pWorkSpaceFac.OpenFromFile(shpfolder, 0) as IFeatureWorkspace;

            //创建字段集2
            IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
            IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription;//创建必要字段
            IFields fields = ocDescription.RequiredFields;
            int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName);
            IField field = fields.get_Field(shapeFieldIndex);
            IGeometryDef geometryDef = field.GeometryDef;
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
            //geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
            //geometryDefEdit.SpatialReference_2 = spatialReference;
            geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;

            ISpatialReferenceFactory pSpatialRefFac = new SpatialReferenceEnvironmentClass();
            IProjectedCoordinateSystem pcsSys = pSpatialRefFac.CreateProjectedCoordinateSystem((int)esriSRProjCS4Type.esriSRProjCS_Xian1980_3_Degree_GK_Zone_39);
            geometryDefEdit.SpatialReference_2 = pcsSys;

            IFieldChecker fieldChecker = new FieldCheckerClass();
            IEnumFieldError enumFieldError = null;
            IFields validatedFields = null; //将传入字段 转成 validatedFields
            fieldChecker.ValidateWorkspace = (IWorkspace)pFeatureWorkSpace;
            fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

            field = new FieldClass();
            IFieldsEdit pFieldsEdit = (IFieldsEdit)fields;
            IFieldEdit pFieldEdit = (IFieldEdit)field;
            pFieldEdit = (IFieldEdit)field;
            pFieldEdit.Name_2 = "面积";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
            pFieldsEdit.AddField(field);

            pWorkspaceEdit.StartEditOperation();
            IFeatureClass pFeatureClass = pFeatureWorkSpace.CreateFeatureClass(shpname, validatedFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, "");
            pPolygon = new PolygonClass();
            IArea s = pPolygon as IArea;
             double area = s.Area;
            IFeature pfeature = pFeatureClass.CreateFeature();
            pfeature.Shape = pPolygon;
            try
            {
                pfeature.set_Value(pfeature.Fields.FindField("面积"), area.ToString());
                pfeature.Store();
            }
            catch
            {
                MessageBox.Show(area.ToString());
            }
            pWorkspaceEdit.StopEditOperation();
        }
        private void CreateAndPopulateTurnFeatureClass(string outputFileGdbPath, string fdsName,
                                                       string ProhibRdmsTableName, string tempStatsTableName,
                                                       IGPMessages messages, ITrackCancel trackcancel)
        {
            // Determine the number of AltID fields we need (one more than the MAX_SEQ_NUMBER value).

            Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
            var wsf = Activator.CreateInstance(factoryType) as IWorkspaceFactory;
            var fws = wsf.OpenFromFile(outputFileGdbPath, 0) as IFeatureWorkspace;
            ITable tempStatsTable = fws.OpenTable(tempStatsTableName);
            short numAltIDFields = 2;
            if (tempStatsTable.RowCount(null) == 1)
                numAltIDFields = (short)(1 + (double)(tempStatsTable.GetRow(1).get_Value(tempStatsTable.FindField("MAX_SEQ_NUMBER"))));

            // Open the Rdms table and find the fields we need

            ITable rdmsTable = fws.OpenTable(ProhibRdmsTableName);
            int seqNumberField = rdmsTable.FindField("SEQ_NUMBER");
            int linkIDFieldOnRdms = rdmsTable.FindField("LINK_ID");
            int manLinkIDField = rdmsTable.FindField("MAN_LINKID");
            int condIDFieldOnRdms = rdmsTable.FindField("COND_ID");
            int endOfLkFieldOnRdms = rdmsTable.FindField("END_OF_LK");

            // Create a temporary template feature class

            var fcd = new FeatureClassDescriptionClass() as IFeatureClassDescription;
            var ocd = fcd as IObjectClassDescription;
            var fieldsEdit = ocd.RequiredFields as IFieldsEdit;
            IField fieldOnRdmsTable = rdmsTable.Fields.get_Field(linkIDFieldOnRdms);  // use the LINK_ID field as a template for the AltID fields
            for (short i = 1; i <= numAltIDFields; i++)
            {
                IFieldEdit newField = new FieldClass();
                newField.Name_2 = "AltID" + i;
                newField.Precision_2 = fieldOnRdmsTable.Precision;
                newField.Scale_2 = fieldOnRdmsTable.Scale;
                newField.Type_2 = fieldOnRdmsTable.Type;
                fieldsEdit.AddField(newField as IField);
            }
            fieldOnRdmsTable = rdmsTable.Fields.get_Field(condIDFieldOnRdms);
            fieldsEdit.AddField(fieldOnRdmsTable);
            var fieldChk = new FieldCheckerClass() as IFieldChecker;
            IEnumFieldError enumFieldErr = null;
            IFields validatedFields = null;
            fieldChk.ValidateWorkspace = fws as IWorkspace;
            fieldChk.Validate(fieldsEdit as IFields, out enumFieldErr, out validatedFields);
            var tempFC = fws.CreateFeatureClass("TheTemplate", validatedFields, ocd.InstanceCLSID, ocd.ClassExtensionCLSID,
                                                esriFeatureType.esriFTSimple, fcd.ShapeFieldName, "") as IDataset;

            // Create the turn feature class from the template, then delete the template

            Geoprocessor gp = new Geoprocessor();
            CreateTurnFeatureClass createTurnFCTool = new CreateTurnFeatureClass();
            string pathToFds = outputFileGdbPath + "\\" + fdsName;
            createTurnFCTool.out_location = pathToFds;
            createTurnFCTool.out_feature_class_name = TurnFCName;
            createTurnFCTool.maximum_edges = numAltIDFields;
            createTurnFCTool.in_template_feature_class = outputFileGdbPath + "\\TheTemplate";
            gp.Execute(createTurnFCTool, trackcancel);
            tempFC.Delete();

            // Open the new turn feature class and find all the fields on it

            IFeatureClass turnFC = fws.OpenFeatureClass(TurnFCName);
            int[] altIDFields = new int[numAltIDFields];
            int[] edgeFCIDFields = new int[numAltIDFields];
            int[] edgeFIDFields = new int[numAltIDFields];
            int[] edgePosFields = new int[numAltIDFields];
            for (short i = 0; i < numAltIDFields; i++)
            {
                altIDFields[i] = turnFC.FindField("AltID" + (i + 1));
                edgeFCIDFields[i] = turnFC.FindField("Edge" + (i + 1) + "FCID");
                edgeFIDFields[i] = turnFC.FindField("Edge" + (i + 1) + "FID");
                edgePosFields[i] = turnFC.FindField("Edge" + (i + 1) + "Pos");
            }
            int edge1endField = turnFC.FindField("Edge1End");
            int condIDFieldOnTurnFC = turnFC.FindField("COND_ID");

            // Look up the FCID of the Streets feature class

            IFeatureClass streetsFC = fws.OpenFeatureClass(StreetsFCName);
            int streetsFCID = streetsFC.FeatureClassID;

            // Set up queries

            var ts = new TableSortClass() as ITableSort;
            ts.Fields = "COND_ID, SEQ_NUMBER";
            ts.set_Ascending("COND_ID", true);
            ts.set_Ascending("SEQ_NUMBER", true);
            ts.QueryFilter = new QueryFilterClass();
            ts.Table = rdmsTable;
            ts.Sort(null);
            ICursor rdmsCursor = ts.Rows;
            IFeatureCursor turnFCCursor = turnFC.Insert(true);
            IFeatureBuffer turnBuffer = turnFC.CreateFeatureBuffer();

            // Write the field values to the turn feature class accordingly

            int numFeatures = 0;
            IRow rdmsRow = rdmsCursor.NextRow();
            while (rdmsRow != null)
            {
                // Transfer the non-edge identifying field values to the buffer
                turnBuffer.set_Value(condIDFieldOnTurnFC, rdmsRow.get_Value(condIDFieldOnRdms));

                // Write the Edge1End field value to the buffer
                switch ((string)(rdmsRow.get_Value(endOfLkFieldOnRdms)))
                {
                    case "N":
                        turnBuffer.set_Value(edge1endField, "Y");
                        break;
                    case "R":
                        turnBuffer.set_Value(edge1endField, "N");
                        break;
                    default:
                        break;    // not expected
                }

                // Write the AltID values to the buffer
                turnBuffer.set_Value(altIDFields[0], rdmsRow.get_Value(linkIDFieldOnRdms));
                short seq = (short)(rdmsRow.get_Value(seqNumberField));
                short lastEntry;
                do
                {
                    lastEntry = seq;
                    turnBuffer.set_Value(altIDFields[lastEntry], rdmsRow.get_Value(manLinkIDField));
                    rdmsRow = rdmsCursor.NextRow();
                    if (rdmsRow == null) break;
                    seq = (short)(rdmsRow.get_Value(seqNumberField));
                } while (seq != 1);

                // Zero-out the unused fields
                for (int i = lastEntry + 1; i < numAltIDFields; i++)
                    turnBuffer.set_Value(altIDFields[i], 0);

                // Write the FCID and Pos field values to the buffer
                for (short i = 0; i < numAltIDFields; i++)
                {
                    int altID = (int)(turnBuffer.get_Value(altIDFields[i]));
                    if (altID != 0)
                    {
                        turnBuffer.set_Value(edgeFCIDFields[i], streetsFCID);
                        turnBuffer.set_Value(edgeFIDFields[i], 1);
                        turnBuffer.set_Value(edgePosFields[i], 0.5);
                    }
                    else
                    {
                        turnBuffer.set_Value(edgeFCIDFields[i], 0);
                        turnBuffer.set_Value(edgeFIDFields[i], 0);
                        turnBuffer.set_Value(edgePosFields[i], 0);
                    }
                }

                // Create the turn feature
                turnFCCursor.InsertFeature(turnBuffer);
                numFeatures++;

                if ((numFeatures % 100) == 0)
                {
                    // check for user cancel

                    if (trackcancel != null && !trackcancel.Continue())
                        throw (new COMException("Function cancelled."));
                }
            }

            // Flush any outstanding writes to the turn feature class
            turnFCCursor.Flush();

            messages.AddMessage("Updating the EdgeFID values...");

            // Create a temporary network dataset for updating the EdgeFID values

            IDENetworkDataset dends = new DENetworkDatasetClass();
            dends.SupportsTurns = true;
            dends.Buildable = true;
            (dends as IDataElement).Name = StreetsFCName;
            (dends as IDEGeoDataset).SpatialReference = (streetsFC as IGeoDataset).SpatialReference;
            IArray sourceArray = new ArrayClass();
            var efs = new EdgeFeatureSourceClass() as IEdgeFeatureSource;
            (efs as INetworkSource).Name = StreetsFCName;
            efs.UsesSubtypes = false;
            efs.ClassConnectivityGroup = 1;
            efs.ClassConnectivityPolicy = esriNetworkEdgeConnectivityPolicy.esriNECPEndVertex;
            sourceArray.Add(efs);
            var tfs = new TurnFeatureSourceClass() as INetworkSource;
            tfs.Name = TurnFCName;
            sourceArray.Add(tfs);
            dends.Sources = sourceArray;
            var fdxc = fws.OpenFeatureDataset(fdsName) as IFeatureDatasetExtensionContainer;
            var dsCont = fdxc.FindExtension(esriDatasetType.esriDTNetworkDataset) as IDatasetContainer2;
            var tempNDS = dsCont.CreateDataset(dends as IDEDataset) as IDataset;

            // Set the EdgeFID field values by running UpdateByAlternateIDFields

            UpdateByAlternateIDFields updateByAltIDTool = new UpdateByAlternateIDFields();
            updateByAltIDTool.in_network_dataset = pathToFds + "\\" + StreetsFCName;
            updateByAltIDTool.alternate_ID_field_name = "LINK_ID";
            gp.Execute(updateByAltIDTool, trackcancel);

            // Delete the temporary network dataset

            tempNDS.Delete();

            // Write the turn geometries

            TurnGeometryUtilities.WriteTurnGeometry(outputFileGdbPath, StreetsFCName, TurnFCName,
                                                    numAltIDFields, 0.3, messages, trackcancel);

            // Index the turn geometries

            messages.AddMessage("Creating spatial index on the turn feature class...");

            AddSpatialIndex addSpatialIndexTool = new AddSpatialIndex();
            addSpatialIndexTool.in_features = pathToFds + "\\" + TurnFCName;
            gp.Execute(addSpatialIndexTool, trackcancel);

            return;
        }
示例#10
0
        /// <summary>
        /// �����ֶμ���
        /// </summary>
        /// <param name="ocDescription">Ҫ��������</param>
        /// <param name="tableStructureNode">��ṹ�ڵ�</param>
        /// <returns></returns>
        private IFields CreateFileds(TableStructureNode tableStructureNode, FeatureCodeNode featureCodeNode)
        {
            try
            {
                ///�����ֶμ���
                IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
                IObjectClassDescription ocDescription = new ObjectClassDescriptionClass();
                IFields fields = ocDescription.RequiredFields;

                //�������ļ���ȡͼ������
                string sGeometryType = "";
                Metadata.MetaTable pMetaTalbe = Metadata.MetaDataFile.MetaTabls[tableStructureNode.TableName] as Metadata.MetaTable;
                if (pMetaTalbe != null)
                {
                    sGeometryType = Metadata.MetaDataFile.GraphConfig.GetGraphTypeMark(pMetaTalbe.Type);
                }

                //����ͼ������
                if (sGeometryType != "NoneGeometry")
                {
                    ocDescription = (IObjectClassDescription)fcDescription;
                    fields = ocDescription.RequiredFields;
                    int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName);
                    IField pGeometryfield = fields.get_Field(shapeFieldIndex);
                    IGeometryDef geometryDef = pGeometryfield.GeometryDef;
                    IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
                    if (sGeometryType == "Point")
                        geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
                    else if (sGeometryType == "Line")
                        geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline;
                    else if (sGeometryType == "Polygon")
                        geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;

                }
                IFieldsEdit fieldsEdit = fields as IFieldsEdit;
                // ������ṹ����
                int FieldCount = tableStructureNode.FieldNodes.Count;
                for (int i = 0; i < FieldCount; i++)
                {
                    IField field = new FieldClass();
                    IFieldEdit fieldEdit = (IFieldEdit)field;
                    ///��ȡ�ֶ���Ϣ
                    FieldNode pFieldNode = tableStructureNode.FieldNodes[i];
                    if (pFieldNode != null)
                    {
                        ///�����ֶ�ֵ
                        fieldEdit.Name_2 = pFieldNode.FieldName;

                        //�������л�ȡ����
                        if (pMetaTalbe != null)
                            fieldEdit.AliasName_2 = pMetaTalbe.GetFiledALisNameByCode(pFieldNode.FieldName);
                        esriFieldType type = esriFieldType.esriFieldTypeString;
                        switch (pFieldNode.FieldType)
                        {
                            case "Char":
                                type = esriFieldType.esriFieldTypeString;
                                break;
                            case "Int":
                                type = esriFieldType.esriFieldTypeInteger;
                                break;
                            case "Float":
                                type = esriFieldType.esriFieldTypeDouble;
                                break;
                            case "Time":
                                type = esriFieldType.esriFieldTypeDate;
                                break;
                            case "DateTime":
                                type = esriFieldType.esriFieldTypeDate;
                                break;
                            case "Varchar":
                                type = esriFieldType.esriFieldTypeString;
                                break;
                            case "Varbin":
                                type = esriFieldType.esriFieldTypeString;
                                break;
                            default:
                                break;
                        }
                        fieldEdit.Type_2 = type;
                        fieldEdit.Length_2 = pFieldNode.FieldLength;
                        fieldEdit.Precision_2 = pFieldNode.FieldPrecision;
                        fieldsEdit.AddField(field);
                    }
                }
                return fields;
            }
            catch(Exception ex)
            {
                LogAPI.WriteErrorLog(ex);
                return null;
            }
        }
示例#11
0
        private IFeatureClass CreateFeatureClass(IFeatureDataset featureDataset,TableStructureNode tableStructureNode, FeatureCodeNode featureCodeNode)
        {
            try
            {
                if (featureDataset != null)
                {
                    IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass();
                    IObjectClassDescription ocDesc = (IObjectClassDescription)fcDesc;

                    ///�������ݱ��ֶ�
                    IFieldChecker fieldChecker = new FieldCheckerClass();
                    IEnumFieldError enumFieldError = null;
                    IFields validatedFields = CreateFileds(tableStructureNode, featureCodeNode);
                    ///�ֶ���Ϣ��֤
                    IFields fixFields = null;
                    fieldChecker.ValidateWorkspace = featureDataset.Workspace;
                    fieldChecker.Validate(validatedFields, out enumFieldError, out fixFields);

                    ////����FeatureClass
                    IFeatureClass featureClass = null;
                    if (tableStructureNode.IsGeometryTable)
                    {
                        ////������ע��FeatureClass
                        if (featureCodeNode.GeometryType != "")
                        {
                            featureClass = featureDataset.CreateFeatureClass(featureCodeNode.TableName,
                               fixFields, ocDesc.InstanceCLSID, ocDesc.ClassExtensionCLSID,
                               esriFeatureType.esriFTSimple, fcDesc.ShapeFieldName, "");
                        }
                        else
                        {
                            ///����ע��
                            IFormattedTextSymbol pTxtSymbo=new TextSymbolClass();

                            IFeatureWorkspaceAnno pFeatureWorkspaceAnno = this.m_pIDataset.Workspace as IFeatureWorkspaceAnno;

                            IGraphicsLayerScale pGraphSacle = new GraphicsLayerScaleClass();
                            pGraphSacle.Units = ESRI.ArcGIS.esriSystem.esriUnits.esriFeet;
                            //pGraphSacle.ReferenceScale=1000;

                            ISymbolCollection pSymbolCollection = new SymbolCollectionClass();

                            IAnnotateLayerProperties pAnnoLayerProp = new LabelEngineLayerPropertiesClass();
                            pAnnoLayerProp.FeatureLinked = true;
                            pAnnoLayerProp.CreateUnplacedElements = false;
                            pAnnoLayerProp.DisplayAnnotation = true;
                            pAnnoLayerProp.UseOutput = true;

                            IAnnotationExpressionEngine pAnnoExpressionEngine =new AnnotationVBScriptEngineClass();
                            ILabelEngineLayerProperties pLabelEngineLayerProperties = pAnnoLayerProp as ILabelEngineLayerProperties;
                            pLabelEngineLayerProperties.ExpressionParser = pAnnoExpressionEngine;
                            pLabelEngineLayerProperties.Expression = "[DESCRIPTION]";
                            pLabelEngineLayerProperties.IsExpressionSimple = true;
                            pLabelEngineLayerProperties.Offset = 0;
                            pLabelEngineLayerProperties.SymbolID = 0;
                            pLabelEngineLayerProperties.Symbol = pTxtSymbo;

                            IAnnotateLayerTransformationProperties pAnnoLayerTransProp = pAnnoLayerProp as IAnnotateLayerTransformationProperties;
                            pAnnoLayerTransProp.ReferenceScale=200;
                            pAnnoLayerTransProp.Units= ESRI.ArcGIS.esriSystem.esriUnits.esriFeet;
                            pAnnoLayerTransProp.ScaleRatio=1;

                            IAnnotateLayerPropertiesCollection pAnnoLayerProptyCollection =new AnnotateLayerPropertiesCollectionClass();
                           pAnnoLayerProptyCollection.Add(pAnnoLayerProp);

                           featureClass= pFeatureWorkspaceAnno.CreateAnnotationClass(featureCodeNode.TableName,fixFields,ocDesc.InstanceCLSID
                               ,ocDesc.ClassExtensionCLSID,fcDesc.ShapeFieldName,"",featureDataset,null,
                               pAnnoLayerProptyCollection, pGraphSacle, pSymbolCollection,true);
                        }
                    }
                    else
                    {
                        ///�����ǿռ�����
                    }
                    return featureClass;
                }
                return null;
            }
            catch(Exception ex)
            {
                LogAPI.WriteErrorLog(ex);
                return null;
            }
        }
        public static IFeatureClass createGoogleMapsEngineCatalogFeatureClass(ref log4net.ILog log, ref GoogleMapsEngineToolsExtensionForArcGIS ext)
        {
            try
            {
                // temporary directory to store workspace 
                string workspacedirectory = ext.getLocalWorkspaceDirectory().FullName;

                // add the directory to the cleanup list
                // TODO: Replace with scratch
                ext.addTemporaryDirectory(new System.IO.DirectoryInfo(workspacedirectory));

                // determine the workspace name for the geodatabase
                //string workspacefoldername = Properties.Settings.Default.extension_gdb_workspacename;
                // TODO: Use sctach workspace instead of creating a temporary one
                string workspacefoldername = "GME_Data_" + System.Guid.NewGuid().ToString().Replace("-", "");

                // define a workspace to do work
                IWorkspace workspace = null;

                // attempt to open or create the workspace
                try
                {
                    // check to see if the workspace already exists, if so, open it
                    if (System.IO.Directory.Exists(workspacedirectory + "\\" + workspacefoldername))
                    {
                        workspace = Extension.Data.GeodatabaseUtilities.openFileGeodatabaseWorkspace(ref log, workspacedirectory, workspacefoldername);
                        ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)workspace;
                        ESRI.ArcGIS.Geodatabase.IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(Properties.Resources.GeodatabaseUtilities_schema_FeatureClassName);
                        ESRI.ArcGIS.Geodatabase.IDataset pdataset = (ESRI.ArcGIS.Geodatabase.IDataset)featureClass;
                        if (pdataset.CanDelete())
                            pdataset.Delete();

                        pdataset = null;
                        featureClass = null;
                        featureWorkspace = null;

                        // TODO: Open instead of delete/replace
                        //if (arcgis.ext.gdb.GeodatabaseUtilities.deleteFileGeodatabaseWorkspace(workspacedirectory, workspacefoldername))
                        //workspace = arcgis.ext.gdb.GeodatabaseUtilities.createFileGeodatabaseWorkspace(workspacedirectory, workspacefoldername);
                    }
                    else
                    {
                        // workspace doesn't exist, create the workspace
                        workspace = Extension.Data.GeodatabaseUtilities.createFileGeodatabaseWorkspace(ref log, workspacedirectory, workspacefoldername);
                    }
                }
                catch (System.Exception ex)
                {
                    // unable to create the fgdb or unable to delete the fc within the fgdb
                    log.Error(ex);
                    System.Windows.Forms.MessageBox.Show("Unable to create or delete an existing feature class.");
                }

                // verify the workspace is open
                if (workspace != null)
                {
                    // create a new feature workspace to work spatially
                    IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace;

                    // create a spatial reference for the Google Earth Builder data (always in 4326)
                    SpatialReferenceEnvironment sRefEnvGEB = new SpatialReferenceEnvironment();
                    ISpatialReference sGEBRef = sRefEnvGEB.CreateGeographicCoordinateSystem(4326);

                    // for this feature class, create and determine the field
                    IFields fields = new FieldsClass();
                    IFieldsEdit fieldsEdit = (IFieldsEdit)fields;
                    fieldsEdit.FieldCount_2 = 10;

                    //Create the Object ID field.
                    IField fusrDefinedField = new Field();
                    IFieldEdit fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField;
                    fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_OBJECTID_Name;
                    fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_OBJECTID_AliasName;
                    fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
                    fieldsEdit.set_Field(0, fusrDefinedField);

                    //Create the CustomerId field.
                    fusrDefinedField = new Field();
                    fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField;
                    fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_CustomerId_Name;
                    fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_CustomerId_AliasName;
                    fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                    fieldsEdit.set_Field(1, fusrDefinedField);

                    //Create the MapAssetId field.
                    fusrDefinedField = new Field();
                    fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField;
                    fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_MapAssetId_Name;
                    fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_MapAssetId_AliasName;
                    fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                    fieldsEdit.set_Field(2, fusrDefinedField);

                    //Create the AssetId field.
                    fusrDefinedField = new Field();
                    fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField;
                    fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetId_Name;
                    fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetId_AliasName;
                    fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                    fieldsEdit.set_Field(3, fusrDefinedField);

                    //Create the ParentAssetId field.
                    fusrDefinedField = new Field();
                    fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField;
                    fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_ParentAssetId_Name;
                    fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_ParentAssetId_AliasName;
                    fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                    fieldsEdit.set_Field(4, fusrDefinedField);

                    //Create the AssetType field.
                    fusrDefinedField = new Field();
                    fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField;
                    fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetType_Name;
                    fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetType_AliasName;
                    fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                    fieldsEdit.set_Field(5, fusrDefinedField);

                    //Create the AssetName field.
                    fusrDefinedField = new Field();
                    fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField;
                    fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetName_Name;
                    fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetName_AliasName;
                    fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                    fieldsEdit.set_Field(6, fusrDefinedField);

                    //Create the AssetDescription field.
                    fusrDefinedField = new Field();
                    fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField;
                    fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetDescription_Name;
                    fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetDescription_AliasName;
                    fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                    fieldsEdit.set_Field(7, fusrDefinedField);

                    //Create the MapSharedWith field.
                    fusrDefinedField = new Field();
                    fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField;
                    fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_MapSharedWith_Name;
                    fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_MapSharedWith_AliasName;
                    fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                    fieldsEdit.set_Field(8, fusrDefinedField);

                    // Create the Shape field.
                    fusrDefinedField = new Field();
                    fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField;
                    // Set up the geometry definition for the Shape field.
                    IGeometryDef geometryDef = new GeometryDefClass();
                    IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
                    geometryDefEdit.GeometryType_2 = ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolygon;
                    // By setting the grid size to 0, you're allowing ArcGIS to determine the appropriate grid sizes for the feature class. 
                    // If in a personal geodatabase, the grid size will be 1000. If in a file or ArcSDE geodatabase, the grid size
                    // will be based on the initial loading or inserting of features.
                    geometryDefEdit.GridCount_2 = 1;
                    geometryDefEdit.set_GridSize(0, 0);
                    geometryDefEdit.HasM_2 = false;
                    geometryDefEdit.HasZ_2 = false;
                    //Assign the spatial reference that was passed in, possibly from
                    //IGeodatabase.SpatialReference for the containing feature dataset.
                    geometryDefEdit.SpatialReference_2 = sGEBRef;
                    // Set standard field properties.
                    fusrDefinedFieldEdit.Name_2 = "SHAPE";
                    fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
                    fusrDefinedFieldEdit.GeometryDef_2 = geometryDef;
                    fusrDefinedFieldEdit.IsNullable_2 = true;
                    fusrDefinedFieldEdit.Required_2 = true;
                    fieldsEdit.set_Field(9, fusrDefinedField);

                    // Create a feature class description object to use for specifying the CLSID and EXTCLSID.
                    IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass();
                    IObjectClassDescription ocDesc = (IObjectClassDescription)fcDesc;

                    IFeatureClass fc = featureWorkspace.CreateFeatureClass(
                        Properties.Resources.GeodatabaseUtilities_schema_FeatureClassName, // Feature Class Name
                        fields, // Feature Class Fields (defined above)
                        ocDesc.InstanceCLSID, 
                        ocDesc.ClassExtensionCLSID, 
                        esriFeatureType.esriFTSimple, 
                        fcDesc.ShapeFieldName, // Shape Field Name
                        "" // Keyword Configurations
                        );

                    // return the feature class
                    return fc;
                }
                else
                {
                    // end gracefully, maybe prompt the user that the toolbar wasn't able to create a workspcae
                    throw new Exception("Unable to open local geodatabase.");
                }
            }
            catch (System.Exception ex)
            {
                // an error occured
                log.Error(ex);

                // throw an exception
                throw new Exception("An unknown exception occured while attempting to create a local feature class.");
            }
        }
        public IFeatureClass CreateFeatureClassWithFieldsGeoRef(String featureClassName, IFeatureWorkspace featureWorkspace)
        {
            GeoJson geoJson = new GeoJson();
            try
            {
                // Instantiate a feature class description to get the required fields.
                IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
                IObjectClassDescription ocDescription = (IObjectClassDescription)
                  fcDescription;
                IFields fields = ocDescription.RequiredFields;
                IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

                addFeatureFeild("URI", "URI", esriFieldType.esriFieldTypeString, fieldsEdit);
                // Use IFieldChecker to create a validated fields collection.
                IFieldChecker fieldChecker = new FieldCheckerClass();
                IEnumFieldError enumFieldError = null;
                IFields validatedFields = null;
                fieldChecker.ValidateWorkspace = (IWorkspace)featureWorkspace;
                fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

                // The enumFieldError enumerator can be inspected at this point to determine
                // which fields were modified during validation.
                // Create the feature class.
                IFeatureClass featureClass = featureWorkspace.CreateFeatureClass
                  (featureClassName, validatedFields, ocDescription.InstanceCLSID,
                  ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple,
                  fcDescription.ShapeFieldName, "");

                return featureClass;
            }
            catch (Exception e)
            {
                Log.WriteLine("CreateFeatureClassWithFields: " + e.Message);
            }
            return null;
        }
        /// <summary>
        /// Add Feature class and its feilds
        /// </summary>
        /// <param name="featureClassName"></param>
        /// <param name="featureWorkspace"></param>
        /// <returns></returns>
        public IFeatureClass CreateFeatureClassWithFields(String featureClassName, IFeatureWorkspace featureWorkspace, string dir)
        {
            GeoJson geoJson = new GeoJson();
            try
            {
                _featureInJSON = geoJson.readGeoJsonFile(dir);

                // Instantiate a feature class description to get the required fields.
                IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
                IObjectClassDescription ocDescription = (IObjectClassDescription)
                  fcDescription;
                IFields fields = ocDescription.RequiredFields;
                IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

                for (int i = 0; i < 9; i++)
                {
                    if (_featureInJSON.fields[i].name == "OBJECTID")
                        continue;
                    else
                        addFeatureFeild(_featureInJSON.fields[i].name, _featureInJSON.fields[i].alias, (esriFieldType)Enum.Parse(typeof(esriFieldType), _featureInJSON.fields[i].type), fieldsEdit);
                }
                // Use IFieldChecker to create a validated fields collection.
                IFieldChecker fieldChecker = new FieldCheckerClass();
                IEnumFieldError enumFieldError = null;
                IFields validatedFields = null;
                fieldChecker.ValidateWorkspace = (IWorkspace)featureWorkspace;
                fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

                // The enumFieldError enumerator can be inspected at this point to determine
                // which fields were modified during validation.
                // Create the feature class.
                IFeatureClass featureClass = featureWorkspace.CreateFeatureClass
                  (featureClassName, validatedFields, ocDescription.InstanceCLSID,
                  ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple,
                  fcDescription.ShapeFieldName, "");

                return featureClass;
            }
            catch (Exception e)
            {
                Log.WriteLine("CreateFeatureClassWithFields: " + e.Message);
            }
            return null;
        }
示例#15
0
        public static void CreatePolygonFeature(IPolygon pPolygon, string shpfolder, string shpname)
        {
            IWorkspaceFactory pWorkSpaceFac = new ShapefileWorkspaceFactoryClass();
            IFeatureWorkspace pFeatureWorkSpace = pWorkSpaceFac.OpenFromFile(shpfolder, 0) as IFeatureWorkspace;
            try
            {//如果图层存在则删除
                FileInfo fFile = new FileInfo(shpfolder + @"\" + shpname + ".shp");//
                if (fFile.Exists)
                {

                        DirectoryInfo fold = new DirectoryInfo(shpfolder);
                        FileInfo[] files = fold.GetFiles(shpname + ".*");
                        foreach (FileInfo f in files)
                        {
                            f.Delete();
                        }

                }

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

            //创建字段集2
            IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
            IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription;//创建必要字段
            IFields fields = ocDescription.RequiredFields;
            int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName);
            IField field = fields.get_Field(shapeFieldIndex);
            IGeometryDef geometryDef = field.GeometryDef;
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;

            geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
            ISpatialReferenceFactory pSpatialRefFac = new SpatialReferenceEnvironmentClass();

            IGeographicCoordinateSystem pcsSys = pSpatialRefFac.CreateGeographicCoordinateSystem(4490);
            geometryDefEdit.SpatialReference_2 = pcsSys;

            IFieldChecker fieldChecker = new FieldCheckerClass();
            IEnumFieldError enumFieldError = null;
            IFields validatedFields = null; //将传入字段 转成 validatedFields
            fieldChecker.ValidateWorkspace = (IWorkspace)pFeatureWorkSpace;
            fieldChecker.Validate(fields, out enumFieldError, out validatedFields);
            /*
            field = new FieldClass();
            IFieldsEdit pFieldsEdit = (IFieldsEdit)fields;
            IFieldEdit pFieldEdit = (IFieldEdit)field;
            pFieldEdit = (IFieldEdit)field;
            pFieldEdit.Name_2 = "面积";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;

            pFieldsEdit.AddField(field);*/
            IArea s = pPolygon as IArea;
            double area = Math.Abs(s.Area * 10000);
            double length = Math.Abs(pPolygon.Length * 100);
            MessageBox.Show("该区域面积为:" + Convert.ToDouble(area).ToString("0.000") + "平方公里(km2)" + "\r\n" + "边长为:" + Convert.ToDouble(length).ToString("0.000") + "千米(KM)");
            try
            {
                IFeatureClass pFeatureClass;

                pFeatureClass = pFeatureWorkSpace.CreateFeatureClass(shpname, validatedFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, "");

                IFeature pFeature = pFeatureClass.CreateFeature();
                pFeature.Shape = pPolygon;
                //pFeature.set_Value(pFeature.Fields.FindField("面积"), area);
                pFeature.Store();
            }
            catch(Exception ex)
            {
                 MessageBox.Show(ex.Message);

            }
        }
示例#16
0
        //coordinate 点坐标创建shp图层。
        public static void CreatePolygonFeatureclass(IPolygon pPolygon, string shpfolder, string shpname)
        {
            IWorkspaceFactory pWorkSpaceFac = new ShapefileWorkspaceFactoryClass();
            IFeatureWorkspace pFeatureWorkSpace = pWorkSpaceFac.OpenFromFile(shpfolder, 0) as IFeatureWorkspace;
            try
            {//如果图层存在则删除
                FileInfo fFile = new FileInfo(shpfolder + @"\" + shpname+ ".shp");//
                if (fFile.Exists)
                {
                    if (MessageBox.Show("此文件名已经存在,要覆盖吗?", "覆盖文件", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                    {

                        DirectoryInfo fold = new DirectoryInfo(shpfolder);
                        FileInfo[] files = fold.GetFiles(shpname + ".*");
                        foreach (FileInfo f in files)
                        {
                            f.Delete();
                        }

                    }
                    else
                        return;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            //if (File.Exists(shpfolder+shpname))//如果shp存在则替换它。
            //{
            //    if (MessageBox.Show("发现同名文件,是否覆盖源文件?", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            //    {
            //        IFeatureClass featureclass = pFeatureWorkSpace.OpenFeatureClass(shpname);

            //        IDataset pDataset = featureclass as IDataset;
            //        pDataset.Delete();
            //    }
            //    else
            //        return;
            //}
            //创建字段集2
            IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
            IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription;//创建必要字段
            IFields fields = ocDescription.RequiredFields;
            int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName);
            IField field = fields.get_Field(shapeFieldIndex);
            IGeometryDef geometryDef = field.GeometryDef;
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
            //geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
            //geometryDefEdit.SpatialReference_2 = spatialReference;

            geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
            ISpatialReferenceFactory pSpatialRefFac = new SpatialReferenceEnvironmentClass();
               // IProjectedCoordinateSystem pcsSys = pSpatialRefFac.CreateProjectedCoordinateSystem((int)esriSRProjCS4Type.esriSRProjCS_Xian1980_3_Degree_GK_Zone_39);
            IGeographicCoordinateSystem pcsSys = pSpatialRefFac.CreateGeographicCoordinateSystem(4490);
            geometryDefEdit.SpatialReference_2 = pcsSys;

            IFieldChecker fieldChecker = new FieldCheckerClass();
            IEnumFieldError enumFieldError = null;
            IFields validatedFields = null; //将传入字段 转成 validatedFields
            fieldChecker.ValidateWorkspace = (IWorkspace)pFeatureWorkSpace;
            fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

            field = new FieldClass();
            IFieldsEdit pFieldsEdit = (IFieldsEdit)fields;
            IFieldEdit pFieldEdit = (IFieldEdit)field;
            pFieldEdit = (IFieldEdit)field;
            pFieldEdit.Name_2 = "面积";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
            pFieldsEdit.AddField(field);
            IArea s = pPolygon as IArea;
            double area = s.Area*100;
            double length=pPolygon.Length*100;
            MessageBox.Show("该区域面积为:" + Convert.ToDouble(area).ToString("0.000") + "平方公里(km2)" +"\r\n" + "边长为:" + Convert.ToDouble(length).ToString("0.000") + "千米(KM)");
            try
            {
                IFeatureClass pFeatureClass;
                //pFeatureClass = pFeatureWorkSpace.OpenFeatureClass(shpname);
                pFeatureClass = pFeatureWorkSpace.CreateFeatureClass(shpname, validatedFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, "");

                IFeature pFeature = pFeatureClass.CreateFeature();
                pFeature.Shape = pPolygon;
               // pFeature.set_Value(pFeature.Fields.FindField("面积"), area);
                pFeature.Store();
            }
            catch
            {
               // MessageBox.Show("存储失败!请检查目录下是否有同名文件···", "提示");
                //return;
            }
        }
        /// <summary>
        /// creates a new featrue class
        /// </summary>
        /// <param name="wks">the workspace to create from</param>
        /// <param name="polyFtrClsName">name of the feature class</param>
        /// <param name="atrflds">name of the fields</param>
        /// <param name="geoType">the geotype</param>
        /// <param name="sr">spatial reference</param>
        /// <returns>newly created featureclass</returns>
        public IFeatureClass createFeatureClass(IWorkspace2 wks, string polyFtrClsName, IFields atrflds, esriGeometryType geoType, ISpatialReference sr)
        {
            IFeatureClass tFtr = null;
            try
            {
                IFeatureWorkspace ftrWks = (IFeatureWorkspace)wks;
                polyFtrClsName = getSafeOutputNameNonRaster((IWorkspace)wks, polyFtrClsName);
                IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
                IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription;
                IFields fields = ocDescription.RequiredFields;
                if (atrflds != null)
                {
                    IFieldsEdit fieldsEdit = (IFieldsEdit)fields;
                    for (int i = 0; i < atrflds.FieldCount; i++)
                    {
                        IField fld = atrflds.get_Field(i);
                        IField nFld = new FieldClass();
                        IFieldEdit nFldE = (IFieldEdit)nFld;
                        nFldE.Name_2 = fld.Name;
                        if (fld.Type != esriFieldType.esriFieldTypeOID)
                        {
                            nFldE.Type_2 = fld.Type;
                            fieldsEdit.AddField(nFld);
                        }
                    }
                }
                // Find the shape field in the required fields and modify its GeometryDef to// use point geometry and to set the spatial reference.int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName);
                IField field = fields.get_Field(fields.FindField(fcDescription.ShapeFieldName));
                IGeometryDef geometryDef = field.GeometryDef;
                IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
                geometryDefEdit.GeometryType_2 = geoType;
                geometryDefEdit.SpatialReference_2 = sr;

                // Use IFieldChecker to create a validated fields collection.
                IFieldChecker fieldChecker = new FieldCheckerClass();
                IEnumFieldError enumFieldError = null;
                IFields validatedFields = null;
                fieldChecker.ValidateWorkspace = (IWorkspace)wks;
                fieldChecker.Validate(fields, out enumFieldError, out validatedFields);
                tFtr = ftrWks.CreateFeatureClass(polyFtrClsName, validatedFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, "");
            }
            catch(Exception e)
            {
                Console.WriteLine("Error: " + e.ToString());
            }
            return tFtr;
        }
示例#18
0
        //This is the full GPX 1.1 schema.
        //Option 1 - Add all schema defined fields, even if they are not used
        //TODO - Option 2 - Scan file and only use fields used in this file.
        //var search = Root.Descendants(_ns + type.Path);
        private IFields BuildFields(GpxFeatureClass featureClass)
        {
            var description = new FeatureClassDescriptionClass();
            var fields = (IFieldsEdit)description.RequiredFields;
            IFieldEdit field = new FieldClass();

            //Geometry
            var geometryIndex = fields.FindField(description.ShapeFieldName);
            var geometry = (IGeometryDefEdit)fields.Field[geometryIndex].GeometryDef;
            geometry.GeometryType_2 = featureClass.GeometryType;
            geometry.SpatialReference_2 = SpatialReference;
            geometry.HasM_2 = false;
            geometry.HasZ_2 = true;  //FIXME - this may be false.

            //Common Fields
            field.Name_2 = "name";
            field.AliasName_2 = "Name";
            field.Type_2 = esriFieldType.esriFieldTypeString;
            fields.AddField(field);

            // ReSharper disable UseObjectOrCollectionInitializer
            //These COM classes do not support object initializers
            field = new FieldClass();
            field.Name_2 = "cmt";
            field.AliasName_2 = "Comment";
            field.Type_2 = esriFieldType.esriFieldTypeString;
            fields.AddField(field);

            field = new FieldClass();
            field.Name_2 = "desc";
            field.AliasName_2 = "Description";
            field.Type_2 = esriFieldType.esriFieldTypeString;
            fields.AddField(field);

            field = new FieldClass();
            field.Name_2 = "src";
            field.AliasName_2 = "Source";
            field.Type_2 = esriFieldType.esriFieldTypeString;
            fields.AddField(field);

            field = new FieldClass();
            field.Name_2 = "link";
            field.AliasName_2 = "Hyperlink";
            //field.Type_2 = esriFieldType.esriFieldTypeXML;
            //XML datatype is not fully supported in Desktop (i.e. no value is displayed, and export to shapefile will fail)
            field.Type_2 = esriFieldType.esriFieldTypeString;
            fields.AddField(field);

            //GPX 1.0
            field = new FieldClass();
            field.Name_2 = "url";
            field.AliasName_2 = "Url link";
            field.Type_2 = esriFieldType.esriFieldTypeString;
            fields.AddField(field);

            //GPX 1.0
            field = new FieldClass();
            field.Name_2 = "urlname";
            field.AliasName_2 = "Url Name";
            field.Type_2 = esriFieldType.esriFieldTypeString;
            fields.AddField(field);

            field = new FieldClass();
            field.Name_2 = "type";
            field.AliasName_2 = "Type";
            field.Type_2 = esriFieldType.esriFieldTypeString;
            fields.AddField(field);

            field = new FieldClass();
            field.Name_2 = "extensions";
            //field.Type_2 = esriFieldType.esriFieldTypeXML;
            field.Type_2 = esriFieldType.esriFieldTypeString;
            fields.AddField(field);

            //Only for Routes and Tracks
            if (featureClass.Path == "rte" || featureClass.Path == "trk")
            {
                field = new FieldClass();
                field.Name_2 = "number";
                field.AliasName_2 = featureClass.Path == "rte" ? "Route Number" : "Track Number";
                field.Type_2 = esriFieldType.esriFieldTypeInteger;
                fields.AddField(field);
            }

            //Only for Points
            if (featureClass.Path == "wpt" || featureClass.Path == "trkpt" || featureClass.Path == "rtept")
            {
                field = new FieldClass();
                field.Name_2 = "ele";
                field.AliasName_2 = "Elevation";
                field.Type_2 = esriFieldType.esriFieldTypeDouble;
                fields.AddField(field);

                field = new FieldClass();
                field.Name_2 = "time";
                field.AliasName_2 = "Time (UTC)";
                field.Type_2 = esriFieldType.esriFieldTypeDate;
                fields.AddField(field);

                field = new FieldClass();
                field.Name_2 = "magvar";
                field.Type_2 = esriFieldType.esriFieldTypeDouble;
                fields.AddField(field);

                field = new FieldClass();
                field.Name_2 = "geoidheight";
                field.Type_2 = esriFieldType.esriFieldTypeDouble;
                fields.AddField(field);

                field = new FieldClass();
                field.Name_2 = "sym";
                field.AliasName_2 = "Symbol";
                field.Type_2 = esriFieldType.esriFieldTypeString;
                fields.AddField(field);

                field = new FieldClass();
                field.Name_2 = "fix";
                field.AliasName_2 = "GpsFix";
                field.Type_2 = esriFieldType.esriFieldTypeString;
                field.Length_2 = 4;
                fields.AddField(field);

                field = new FieldClass();
                field.Name_2 = "sat";
                field.AliasName_2 = "Satellites";
                field.Type_2 = esriFieldType.esriFieldTypeInteger;
                fields.AddField(field);

                field = new FieldClass();
                field.Name_2 = "hdop";
                field.AliasName_2 = "HDOP";
                field.Type_2 = esriFieldType.esriFieldTypeDouble;
                fields.AddField(field);

                field = new FieldClass();
                field.Name_2 = "vdop";
                field.AliasName_2 = "VDOP";
                field.Type_2 = esriFieldType.esriFieldTypeDouble;
                fields.AddField(field);

                field = new FieldClass();
                field.Name_2 = "pdop";
                field.AliasName_2 = "PDOP";
                field.Type_2 = esriFieldType.esriFieldTypeDouble;
                fields.AddField(field);

                field = new FieldClass();
                field.Name_2 = "ageofdgpsdata";
                field.Type_2 = esriFieldType.esriFieldTypeDouble;
                fields.AddField(field);

                field = new FieldClass();
                field.Name_2 = "dgpsid";
                field.Type_2 = esriFieldType.esriFieldTypeInteger;
                fields.AddField(field);
                // ReSharper restore UseObjectOrCollectionInitializer
            }

            return fields;
        }
示例#19
0
        /// <summary>Create a feature class in a existing FGDB </summary>
        /// <param name="FGDBPath">Path to the existing FGDB</param>
        /// <param name="FCname">Name of the new FeatureClass</param>
        /// <param name="field2add">List of Ifields</param>
        /// <param name="srs">the srs of the shapefile</param>
        /// <param name="geomType">the type geometry: point, polyline, polygon, ...</param>
        /// <param name="deleteIfExists">Overwrite existing FeatureClass</param>
        /// <returns>the Feuture Class loaded in a IFeatureClass</returns>
        public static IFeatureClass createFeatureClass(string FGDBPath, string FCname, List<IField> field2add,
                                              ISpatialReference srs, esriGeometryType geomType, bool deleteIfExists = true)
        {
            DirectoryInfo fgbInfo = new DirectoryInfo(FGDBPath);

            if (FGDBPath == "" || FCname == "") return null; // name was not passed in

            IFeatureClass featureClass;

            // Instantiate a feature class description to get the required fields.
            IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
            IObjectClassDescription ocDescription = fcDescription as IObjectClassDescription;

            IFields fields = ocDescription.RequiredFields;
            IFieldsEdit fieldsEdit = (IFieldsEdit) fields ;

            // Find the shape field in the required fields and modify its GeometryDef to
            // use wanted geometry and to set the spatial reference.
            IField shapeField = null;
            for (int j = 0; j < fields.FieldCount; j++)
            {
                if (fields.get_Field(j).Type == ESRI.ArcGIS.Geodatabase.esriFieldType.esriFieldTypeGeometry)
                {
                    shapeField = fields.get_Field(j);
                    break;
                }
            }
            if (shapeField == null) return null;

            int shapeFieldIndex = fields.FindField(shapeField.Name);
            IField geofield = fields.get_Field(shapeFieldIndex);
            IGeometryDef geometryDef = geofield.GeometryDef;
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
            geometryDefEdit.GeometryType_2 = geomType;
            geometryDefEdit.SpatialReference_2 = srs;

            foreach (IField field in field2add)
            {
                fieldsEdit.AddField(field);
            }

            IWorkspaceFactory2 workspaceFactory = new ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactoryClass();
            IWorkspace2 workspace = (IWorkspace2)workspaceFactory.OpenFromFile(FGDBPath, 0);
            IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;

            string validatedName = ValidateTableName((IWorkspace)workspace, FCname);

            if (workspace.get_NameExists(esriDatasetType.esriDTFeatureClass, validatedName))
            {
                if (deleteIfExists)
                {
                    if (!deleteFeatureClass(fgbInfo.FullName + "\\" + validatedName))
                    {
                        throw new Exception(validatedName + " exists and cannot be deleted");
                    }
                }
                else
                {
                    throw new Exception(validatedName + " exists");
                }
            }

            IFields validatedFields = validateFields((IWorkspace) workspace, fields);

            //create the feature class
            featureClass = featureWorkspace.CreateFeatureClass(validatedName, validatedFields,
                                       ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID,
                                       esriFeatureType.esriFTSimple, shapeField.Name, "");
            return featureClass;
        }
示例#20
0
        private static IFields CreateGdbFields()
        {
            IObjectClassDescription objectClassDescription = new FeatureClassDescriptionClass();
            // create the required fields
            IFields fields = objectClassDescription.RequiredFields;
            var fieldsEdit = (IFieldsEdit)fields;

            IFieldEdit fieldEdit = new FieldClass();
            fieldEdit.Name_2 = "Col";
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger;
            fieldEdit.AliasName_2 = "Column";
            fieldsEdit.AddField(fieldEdit);

            // ReSharper disable UseObjectOrCollectionInitializer
            // The field class COM object does not support object initializers
            fieldEdit = new FieldClass();
            fieldEdit.Name_2 = "Row";
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger;
            fieldsEdit.AddField(fieldEdit);

            fieldEdit = new FieldClass();
            fieldEdit.Name_2 = "Col_Label";
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            fieldEdit.AliasName_2 = "Column Label";
            fieldEdit.Length_2 = 20;
            fieldsEdit.AddField(fieldEdit);

            fieldEdit = new FieldClass();
            fieldEdit.Name_2 = "Row_Label";
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            fieldEdit.AliasName_2 = "Row Label";
            fieldEdit.Length_2 = 20;
            fieldsEdit.AddField(fieldEdit);

            fieldEdit = new FieldClass();
            fieldEdit.Name_2 = "Cell_Label";
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            fieldEdit.AliasName_2 = "Cell Label";
            fieldEdit.Length_2 = 20;
            fieldsEdit.AddField(fieldEdit);

            fieldEdit = new FieldClass();
            fieldEdit.Name_2 = "Page";
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger;
            fieldEdit.AliasName_2 = "Page Number";
            fieldsEdit.AddField(fieldEdit);
            // ReSharper restore UseObjectOrCollectionInitializer

            return fields;
        }
示例#21
0
        /// <summary>Create a ESRI shapefile </summary>
        /// <param name="shapeFilePath">the path to the shapefile</param>
        /// <param name="field2add">List of Ifields</param>
        /// <param name="srs">the srs of the shapefile</param>
        /// <param name="geomType">the type geometry: point, polyline, polygon, ...</param>
        /// <param name="deleteIfExists">Overwrite existing FeatureClass</param>
        /// <returns>the shapefile loaded in a IFeatureClass</returns>
        public static IFeatureClass createShapeFile(string shapeFilePath, List<IField> field2add , 
                                  ISpatialReference srs, esriGeometryType geomType, bool deleteIfExists = true)
        {
            FileInfo shapeInfo = new FileInfo(shapeFilePath);

            // Instantiate a feature class description to get the required fields.
            IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
            IObjectClassDescription ocDescription = fcDescription as IObjectClassDescription;

            IFields fields = ocDescription.RequiredFields;
            IFieldsEdit fieldsEdit = fields as IFieldsEdit;

            // Find the shape field in the required fields and modify its GeometryDef to
            // use wanted geometry and to set the spatial reference.
            int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName);
            IField geofield = fields.get_Field(shapeFieldIndex);
            IGeometryDef geometryDef = geofield.GeometryDef;
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
            geometryDefEdit.GeometryType_2 = geomType;
            geometryDefEdit.SpatialReference_2 = srs;

            foreach (IField field in field2add)
            {
                fieldsEdit.AddField(field);
            }

            IWorkspaceFactory workspaceFactory = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass();
            IWorkspace workspace = workspaceFactory.OpenFromFile( shapeInfo.DirectoryName , 0);
            IFeatureWorkspace featureWorkspace = (IFeatureWorkspace) workspace; // Explict Cast

            if ( shapeInfo.Exists )
            {
                if (deleteIfExists)
                {
                    if (!deleteFeatureClass(shapeInfo.FullName))
                    {
                        throw new Exception(shapeInfo.Name + " exists and cannot be deleted");
                    }
                }
                else
                {
                    throw new Exception(shapeInfo.Name + " exists");
                }
            }

            IFields validatedFields = validateFields((IWorkspace)workspace, fields);

            IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(shapeInfo.Name, validatedFields,
                                               ocDescription.InstanceCLSID,  ocDescription.ClassExtensionCLSID,
                                               esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, "");

            return featureClass;
        }
示例#22
0
        /// <summary>
        /// 创建一个新的FeatureClass
        /// </summary>
        /// <param name="FeatureWorkspace">要素命名空间</param>
        /// <param name="Name">名称</param>
        /// <param name="esriGeometryType">类型</param>
        /// <param name="FieldDict">字段已经类型</param>
        /// <returns></returns>
        private static IFeatureClass Create(IFeatureWorkspace FeatureWorkspace, string Name, ESRI.ArcGIS.Geometry.esriGeometryType esriGeometryType,Dictionary<string,esriFieldType> FieldDict)
        {
            IFields pFields = new FieldsClass();
            IFieldsEdit pFieldsEdit = pFields as IFieldsEdit;
            IField pField = new FieldClass();
            IFieldEdit pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Name_2 = "shape";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
            IGeometryDef pGeometryDef = new GeometryDefClass();
            IGeometryDefEdit pGeometryDefEdit = pGeometryDef as IGeometryDefEdit;
            pGeometryDefEdit.GeometryType_2 = esriGeometryType;

            ISpatialReferenceFactory pSpatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            ISpatialReference pSpatialReference = pSpatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);
            pSpatialReference.SetDomain(-6000000, 6000000, -6000000, 6000000);
            pGeometryDefEdit.SpatialReference_2 = pSpatialReference;
            pFieldEdit.GeometryDef_2 = pGeometryDef;
            pFieldsEdit.AddField(pField);

            pField = new FieldClass();
            pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Name_2 = "FID";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
            pFieldsEdit.AddField(pField);

            foreach (var key in FieldDict.Keys)
            {
                if (key.ToUpper() == "SHAPE"||key.ToUpper()=="OBJECTID")
                {
                    continue;
                }
                pField = new FieldClass();
                pFieldEdit = pField as IFieldEdit;
                pFieldEdit.Name_2 = key;
                pFieldEdit.Type_2 = FieldDict[key];
                pFieldsEdit.AddField(pField);
            }

            IFeatureClassDescription featureClassDescription = new FeatureClassDescriptionClass();
            IObjectClassDescription objectClassDescription = featureClassDescription as IObjectClassDescription;
            IFeatureClass featureClass = FeatureWorkspace.CreateFeatureClass(Name, pFields, objectClassDescription.InstanceCLSID, objectClassDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, "shape", "");
            return featureClass;
        }
        public void MakeScratchPoints()
        {
            try
            {
                IMxDocument pmxdoc = ArcMap.Document as IMxDocument;
                IMap pmap = pmxdoc.FocusMap;

                ILayer pShorePoints = FindLayer(pmap, "ShorePoints");

                if (pShorePoints != null)
                {
                    pmap.DeleteLayer(pShorePoints);
                }

                IScratchWorkspaceFactory workspaceFactory = new FileGDBScratchWorkspaceFactoryClass();
                IScratchWorkspaceFactory2 workspaceFactory2 = workspaceFactory as IScratchWorkspaceFactory2;
                IWorkspace scratchWorkspace = workspaceFactory2.CreateNewScratchWorkspace();

                IFeatureWorkspace pFeatWorkspace = scratchWorkspace as IFeatureWorkspace;

                // This function creates a new feature class in a supplied feature dataset by building all of the
                // fields from scratch. IFeatureClassDescription (or IObjectClassDescription if the table is
                // created at the workspace level) can be used to get the required fields and are used to
                // get the InstanceClassID and ExtensionClassID.
                // Create new fields collection with the number of fields you plan to add. Must add at least two fields
                // for a feature class: Object ID and Shape field.
                IFields fields = new FieldsClass();
                IFieldsEdit fieldsEdit = (IFieldsEdit)fields;
                fieldsEdit.FieldCount_2 = 3;

                // Create Object ID field.
                IField fieldUserDefined = new Field();

                IFieldEdit fieldEdit = (IFieldEdit)fieldUserDefined;
                fieldEdit.Name_2 = "OBJECTID";
                fieldEdit.AliasName_2 = "OBJECT ID";
                fieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
                fieldsEdit.set_Field(0, fieldUserDefined);

                // Create Shape field.
                fieldUserDefined = new Field();
                fieldEdit = (IFieldEdit)fieldUserDefined;

                // Set up geometry definition for the Shape field.
                // You do not have to set the spatial reference, as it is inherited from the feature dataset.
                IGeometryDef geometryDef = new GeometryDefClass();
                IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
                geometryDefEdit.GeometryType_2 = ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint;
                geometryDefEdit.SpatialReference_2 = pmap.SpatialReference;
                // By setting the grid size to 0, you are allowing ArcGIS to determine the appropriate grid sizes for the feature class.
                // If in a personal geodatabase, the grid size is 1,000. If in a file or ArcSDE geodatabase, the grid size
                // is based on the initial loading or inserting of features.
                geometryDefEdit.GridCount_2 = 1;
                geometryDefEdit.set_GridSize(0, 0);
                geometryDefEdit.HasM_2 = false;
                geometryDefEdit.HasZ_2 = false;

                // Set standard field properties.
                fieldEdit.Name_2 = "SHAPE";
                fieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
                fieldEdit.GeometryDef_2 = geometryDef;
                fieldEdit.IsNullable_2 = true;
                fieldEdit.Required_2 = true;
                fieldsEdit.set_Field(1, fieldUserDefined);

                // Create a field of type double to hold some information for the features.
                fieldUserDefined = new Field();

                fieldEdit = (IFieldEdit)fieldUserDefined;
                fieldEdit.Name_2 = "ID";
                fieldEdit.AliasName_2 = "ID";
                fieldEdit.Editable_2 = true;
                fieldEdit.IsNullable_2 = false;
                fieldEdit.Precision_2 = 2;
                fieldEdit.Scale_2 = 5;
                fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
                fieldsEdit.set_Field(2, fieldUserDefined);

                // Create a feature class description object to use for specifying the CLSID and EXTCLSID.
                IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass();
                IObjectClassDescription ocDesc = (IObjectClassDescription)fcDesc;

                IFeatureClass pLineFClass = pFeatWorkspace.CreateFeatureClass("ShorePoints", fields, ocDesc.InstanceCLSID, ocDesc.ClassExtensionCLSID, esriFeatureType.esriFTSimple, "SHAPE", "");

                IFeatureLayer pFeatureLayer = new FeatureLayerClass();
                pFeatureLayer.FeatureClass = pLineFClass;

                pFeatureLayer.Name = "ShorePoints";
                pmxdoc.AddLayer(pFeatureLayer);
            }

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