/// <summary> 
        /// Create the polyline feature class 
        /// </summary> 
        /// <param name="featWorkspace">IFeatureWorkspace</param> 
        /// <param name="name">Name of the featureclass</param> 
        /// <returns>IFeatureClass</returns> 
        private IFeatureClass CreatePolylineFeatureClass(IFeatureWorkspace featWorkspace, string name)
        {
            IFieldsEdit pFldsEdt = new FieldsClass();
            IFieldEdit pFldEdt = new FieldClass();

            pFldEdt = new FieldClass();
            pFldEdt.Type_2 = esriFieldType.esriFieldTypeOID;
            pFldEdt.Name_2 = "OBJECTID";
            pFldEdt.AliasName_2 = "OBJECTID";
            pFldsEdt.AddField(pFldEdt);

            IGeometryDefEdit pGeoDef;
            pGeoDef = new GeometryDefClass();
            pGeoDef.GeometryType_2 = esriGeometryType.esriGeometryPolyline;
            pGeoDef.SpatialReference_2 = ArcMap.Document.FocusMap.SpatialReference;

            pFldEdt = new FieldClass();
            pFldEdt.Name_2 = "SHAPE";
            pFldEdt.AliasName_2 = "SHAPE";
            pFldEdt.Type_2 = esriFieldType.esriFieldTypeGeometry;
            pFldEdt.GeometryDef_2 = pGeoDef;
            pFldsEdt.AddField(pFldEdt);

            IFeatureClass pFClass = featWorkspace.CreateFeatureClass(name, pFldsEdt, null, null, esriFeatureType.esriFTSimple, "SHAPE", "");

            return pFClass;
        }
        private IEnumerable<OSMTurnInfo> EnumerateOsmTurnRestrictions(IFeatureWorkspace fws)
        {
            OSMUtility osmUtility = new OSMUtility();
            ITable tableRelation = fws.OpenTable(_osmDataset.Name + "_osm_relation");
            try
            {
                TaskManager.StartProgress(tableRelation.RowCount(null));

                using (ComReleaser cr = new ComReleaser())
                {
                    ICursor cursor = tableRelation.Search(null, false);
                    cr.ManageLifetime(cursor);

                    int idxTags = cursor.FindField("osmTags");
                    int idxMembers = cursor.FindField("osmMembers");

                    IRow row = null;
                    while ((row = cursor.NextRow()) != null)
                    {
                        tag[] tags = osmUtility.retrieveOSMTags(row, idxTags, _osmDataset.Workspace);
                        var tagsRestriction = tags.Where(t => t.k.Equals("restriction", StringComparison.CurrentCultureIgnoreCase));

                        foreach (tag tagRestrict in tagsRestriction)
                        {
                            OSMTurnInfo turn = new OSMTurnInfo();

                            turn.TurnType = tagRestrict.v;

                            foreach (member m in osmUtility.retrieveMembers(row, idxMembers))
                            {
                                if (m.role.Equals("from", StringComparison.CurrentCultureIgnoreCase))
                                    turn.From = m;
                                else if (m.role.Equals("to", StringComparison.CurrentCultureIgnoreCase))
                                    turn.To = m;
                                else if (m.role.Equals("via", StringComparison.CurrentCultureIgnoreCase))
                                    turn.Via = m;
                            }

                            if (turn.HasValidMembers())
                            {
                                turn.FromFeature = FindEdgeFeature(turn.From.@ref);
                                turn.ToFeature = FindEdgeFeature(turn.To.@ref);
                                turn.ViaFeature = FindJunctionFeature(turn.Via.@ref);

                                if (turn.HasValidFeatures())
                                    yield return turn;
                            }
                        }

                        TaskManager.StepProgress();
                    }
                }
            }
            finally
            {
                TaskManager.EndProgress();
            }
        }
Beispiel #3
0
        //http://resources.esri.com/help/9.3/arcgisengine/arcobjects/esriGeoDatabase/IFeatureWorkspace.CreateFeatureClass_Example.htm
        static IFeatureClass CreateFeatureClass(string name, IFeatureWorkspace ftrSpc, esriGeometryType type, int epsg, List<dynamic> extraFields)
        {
            IFeatureClass ftrc = null;
            if(null != ftrSpc && null != name)
            {
                IFieldsEdit flds = new FieldsClass();
                flds.FieldCount_2 = 2 + (extraFields == null ? 0 : extraFields.Count);

                IFieldEdit fld = new FieldClass();
                fld.Name_2 = OBJECT_ID;
                fld.Type_2 = esriFieldType.esriFieldTypeOID;
                flds.Field_2[0] = fld;

                fld = new FieldClass();
                fld.Name_2 = SHP_NAME;
                fld.Type_2 = esriFieldType.esriFieldTypeGeometry;
                fld.GeometryDef_2 = CreateGeometryDef(type, epsg);
                flds.Field_2[1] = fld;
                int eidx = 2;
                foreach(var efld in extraFields)
                {
                    fld = new FieldClass();
                    fld.Name_2 = efld.Name;
                    fld.Type_2 = efld.Type;
                    flds.Field_2[eidx++] = fld;
                }
                ftrc = ftrSpc.CreateFeatureClass(name, flds, null, null, esriFeatureType.esriFTSimple, SHP_NAME, null);
            }
            return ftrc;
        }
Beispiel #4
0
        static IFeatureClass CreateFeatureClass(IFeatureWorkspace workspace, string name, ISpatialReference outSR)
        {
            IFieldsEdit fields = new FieldsClass();

            IFieldEdit field = new FieldClass();
            field.Type_2 = esriFieldType.esriFieldTypeOID;
            field.Name_2 = "OBJECTID";
            field.AliasName_2 = "OBJECTID";
            fields.AddField(field);

            IGeometryDefEdit geom = new GeometryDefClass();
            geom.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
            geom.SpatialReference_2 = outSR;
            geom.HasM_2 = true;
            geom.HasZ_2 = false;

            field = new FieldClass();
            field.Name_2 = "SHAPE";
            field.AliasName_2 = "SHAPE";
            field.Type_2 = esriFieldType.esriFieldTypeGeometry;
            field.GeometryDef_2 = geom;
            fields.AddField(field);

            return workspace.CreateFeatureClass(name, fields, null, null, esriFeatureType.esriFTSimple, "SHAPE", "");
        }
Beispiel #5
0
 //public int OID_INDEX { get { return _colOidIndex; } }
 //public int SHAPE_INDEX { get { return _colShapeIndex; } }
 public TnGeoDatabaseObject(IWorkspace workspace)
 {
     _workspace = workspace;
     _featureWorkspace = (IFeatureWorkspace)_workspace;
     _lstColWithIndex = new List<TnColWithIndexPair>();
     //iniObject();
     //InitIndex();
     //setAliasFieldsName();
 }
Beispiel #6
0
        static void CreateGrid(TileInfo tiles, int level, IFeatureWorkspace destination, String name)
        {
            ISpatialReferenceFactory2 sEnv = new SpatialReferenceEnvironment() as ISpatialReferenceFactory2;
            ISpatialReference sr = sEnv.CreateSpatialReference((int)tiles.spatialReference);
            sr.SetMDomain(-137434824702, 0);
            IFeatureClass fc = CreateFeatureClass(destination, name, sr);
            LOD lod = tiles.lods[level];
            double width = tiles.width * lod.resolution;
            double height = tiles.height * lod.resolution;
            double y = tiles.originY;
            long row = 0;
            double maxX = -(tiles.originX + width);
            double minY = -(tiles.originY - height);
            while (y > minY)
            {
                double x = tiles.originX;
                long col = 0;
                while (x < maxX)
                {
                    RingClass ring = new RingClass();
                    IPoint tl = new PointClass();
                    tl.PutCoords(x, y);
                    tl.M = -(((col & 0xFFFF) << 16) + (row & 0xFFFF));
                    ring.AddPoint(tl);
                    IPoint tr = new PointClass();
                    tr.PutCoords(x + width, y);
                    tr.M = -((((col + 1) & 0xFFFF) << 16) + (row & 0xFFFF));
                    ring.AddPoint(tr);
                    IPoint br = new PointClass();
                    br.PutCoords(x + width, y - width);
                    br.M = -((((col + 1) & 0xFFFF) << 16) + ((row + 1) & 0xFFFF));
                    ring.AddPoint(br);
                    IPoint bl = new PointClass();
                    bl.PutCoords(x, y - width);
                    bl.M = -(((col & 0xFFFF) << 16) + ((row + 1) & 0xFFFF));
                    ring.AddPoint(bl);

                    ring.AddPoint(tl);

                    ring.Close();
                    PolygonClass polygon = new PolygonClass();
                    polygon.AddGeometry(ring);
                    IFeature polyFeature = fc.CreateFeature();
                    polyFeature.Shape = polygon;
                    polyFeature.Store();
                    x += width;
                    col += 1;
                }
                row += 1;
                y -= height;
            }
            IFeatureClassDescriptor fd = new FeatureClassDescriptorClass();
            fd.Create(fc, null, "OBJECTID");
        }
Beispiel #7
0
        public SEEDAO(ISDUTExtension ext)
        {
            /*
            string path = ext.get_SystemValue(DAOUtils.ISDUT_SEE_TEMP);

            Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.AccessWorkspaceFactory");
            IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
            IFeatureWorkspace workspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(path, 0);
            */

            this.osdb = (IFeatureWorkspace)ext.TransactionManager.Current().PGDBConnection;
            this.ext = ext;
        }
        public static IQueryDef CreateQueryDef(IFeatureWorkspace featureWorkspace,
            String tables, String subFields, String whereClause)
        {
            // Create the query definition.
            IQueryDef queryDef = featureWorkspace.CreateQueryDef();

            // Provide a list of table(s) to join.
            queryDef.Tables = tables;

            // Declare the subfields to retrieve.
            queryDef.SubFields = subFields; // must be qualified if multiple tables !!

            // Assign a where clause to filter the results.
            queryDef.WhereClause = whereClause;

            return queryDef;
        }
        //Constructor
        /// <summary>
        /// default constructor
        /// </summary>
        public mapserviceutility()
        {
            gisProdServer = @"http://services.arcgisonline.com/ArcGIS/services";
            appDir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
            string mpLcDb = esriUtil.Properties.Settings.Default.MapServicesLocalDatabase;
            Console.WriteLine("default location = ." + mpLcDb + ".");
            if (mpLcDb == "\"\""||!System.IO.Directory.Exists(mpLcDb))
            {
                mpLcDb = getLocalDB();
                esriUtil.Properties.Settings.Default.MapServicesLocalDatabase = mpLcDb;
                esriUtil.Properties.Settings.Default.Save();
            }
            servWks = gdutil.OpenWorkSpace(LcCacheDb);
            fWks = (IFeatureWorkspace)servWks;
            IWorkspace2 wks2 = (IWorkspace2)fWks;

            if(wks2.get_NameExists(esriDatasetType.esriDTTable,"SERVICECONNECTIONS"))
            {
                try
                {
                    tblCon = fWks.OpenTable("SERVICECONNECTIONS");
                    tblSrv = fWks.OpenTable("SERVICES");
                    tblLyr = fWks.OpenTable("LAYERS");
                }
                catch
                {
                    createConnectionDb();
                    updateConnectionTable(gisProdServer);
                }
            }
            else
            {
                try
                {
                    createConnectionDb();
                    updateConnectionTable(gisProdServer);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
        }
Beispiel #10
0
        public static IDatasetContainer3 GetDatasetContainer(IFeatureWorkspace featureWorkspace, string fdName)
        {
            IDatasetContainer3 datasetContainer = null;

            if (featureWorkspace is IWorkspace2)
            {
                IWorkspace2 workspace = featureWorkspace as IWorkspace2;
                bool fdExists = workspace.get_NameExists(esriDatasetType.esriDTFeatureDataset, fdName);
                if (!fdExists)
                    throw new Exception("Feature Dataset does not exist.");
            }

            IFeatureDatasetExtensionContainer fdExtensionContainer = (IFeatureDatasetExtensionContainer)featureWorkspace.OpenFeatureDataset(fdName);
            datasetContainer = (IDatasetContainer3)fdExtensionContainer.FindExtension(esriDatasetType.esriDTNetworkDataset);
            if (datasetContainer == null)
                throw new Exception("NATestNetworkDataset: dataset container should not be null");

            return datasetContainer;
        }
Beispiel #11
0
        private void BoboDataGeneration(IFeatureClass featureClass, IFeatureWorkspace featureWorkspace)
        {
            ((IWorkspaceEdit)featureWorkspace).StartEditing(true);
            ((IWorkspaceEdit)featureWorkspace).StartEditOperation();

            IFeatureCursor featureCursor = featureClass.Insert(false);
            int XCoord;
            int YCoord;
            int histValue;
            Random random = new Random();

            for(int i = 0; i < 1000; i++)
            {
                //Generate random values for points and for point values

                XCoord = random.Next(-179, 179);
                YCoord = random.Next(-89, 89);
                histValue = random.Next(1, 255);

                int histoGramData = featureCursor.Fields.FindField("HistoField");
                //Andrew Method
                //IFeature f = featureClass.CreateFeature();
                //f.Value[histoGramData] = histValue;
                //f.Shape = new Point() {X = XCoord, Y = YCoord};
                //f.Store();
                //Nohe method
                IFeatureBuffer featureBuffer = featureClass.CreateFeatureBuffer();
                featureBuffer.Value[histoGramData] = histValue;
                featureBuffer.Shape = new Point() { X = XCoord, Y = YCoord };

                featureCursor.InsertFeature(featureBuffer);

            }
            //featureCursor.Flush();
            ((IWorkspaceEdit)featureWorkspace).StopEditOperation();
            ((IWorkspaceEdit) featureWorkspace).StopEditing(true);
        }
Beispiel #12
0
        //删除名称对象
        public static void DeleteByName(IFeatureWorkspace pFeaWorkspace, IDatasetName pDatasetName)
        {
            IFeatureWorkspaceManage pWorkspaceManager = pFeaWorkspace as IFeatureWorkspaceManage;

            pWorkspaceManager?.DeleteByName(pDatasetName);
        }
Beispiel #13
0
        private void buttonOk_Click(object sender, EventArgs e)
        {
            //检验参数是否正确设置
            double bufferDistance;

            double.TryParse(txtBufferDistance.Text, out bufferDistance);
            if (0.0 == bufferDistance)
            {
                MessageBox.Show("距离设置错误!");
                return;
            }

            if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(txtOutputPath.Text)) || ".shp" != System.IO.Path.GetExtension(txtOutputPath.Text))
            {
                MessageBox.Show("输出格式错误!");
                return;
            }

            if (ComboBoxLayer.Items.Count <= 0)
            {
                return;
            }

            IFeatureLayer pFeatureLayer = (IFeatureLayer)GetLayerByName(ComboBoxLayer.SelectedItem.ToString());

            Geoprocessor gp = new Geoprocessor();

            gp.OverwriteOutput = true;
            gp.AddOutputsToMap = true;

            string unit = "Kilometers";

            ESRI.ArcGIS.AnalysisTools.Buffer buffer = new ESRI.ArcGIS.AnalysisTools.Buffer(pFeatureLayer, txtOutputPath.Text, Convert.ToString(bufferDistance) + " " + unit);
            IGeoProcessorResult results             = (IGeoProcessorResult)gp.Execute(buffer, null);

            //添加缓冲区图层到当前地图中
            string fileDirectory = txtOutputPath.Text.ToString().Substring(0, txtOutputPath.Text.LastIndexOf("\\"));
            int    j;

            j = txtOutputPath.Text.LastIndexOf("\\");
            string            tmpstr            = txtOutputPath.Text.ToString().Substring(j + 1);
            IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactoryClass();
            IWorkspace        pWS = pWorkspaceFactory.OpenFromFile(fileDirectory, 0);
            IFeatureWorkspace pFS = pWS as IFeatureWorkspace;
            //IFeatureClass pfc = pFS.OpenFeatureClass(this.ComboBoxLayer.SelectedText+ "_buffer.shp");
            IFeatureClass pfc = pFS.OpenFeatureClass(tmpstr);
            IFeatureLayer pfl = new FeatureLayerClass();

            pfl.FeatureClass = pfc;
            pfl.Name         = pfc.AliasName;

            IRgbColor pColor = new RgbColorClass();

            pColor.Red          = 255;
            pColor.Green        = 0;
            pColor.Blue         = 0;
            pColor.Transparency = 255;
            //产生一个线符号对象
            ILineSymbol pOutline = new SimpleLineSymbolClass();

            pOutline.Width = 2;
            pOutline.Color = pColor;
            //设置颜色属性
            pColor              = new RgbColorClass();
            pColor.Red          = 255;
            pColor.Green        = 0;
            pColor.Blue         = 0;
            pColor.Transparency = 100;
            //设置填充符号的属性
            ISimpleFillSymbol pFillSymbol = new SimpleFillSymbol();

            pFillSymbol.Color   = pColor;
            pFillSymbol.Outline = pOutline;
            pFillSymbol.Style   = esriSimpleFillStyle.esriSFSSolid;

            ISimpleRenderer  pRen;
            IGeoFeatureLayer pGeoFeatLyr = pfl as IGeoFeatureLayer;

            pRen                 = pGeoFeatLyr.Renderer as ISimpleRenderer;
            pRen.Symbol          = pFillSymbol as ISymbol;
            pGeoFeatLyr.Renderer = pRen as IFeatureRenderer;

            ILayerEffects pLayerEffects = pfl as ILayerEffects;

            pLayerEffects.Transparency = 150;

            frmMain.m_mapControl.AddLayer((ILayer)pfl, 0);
            MessageBox.Show(ComboBoxLayer.SelectedText + "缓存生成成功!");
        }
Beispiel #14
0
        public IFeatureClass CreateStandAloneAnnotationClass(IDataset dataset, string annoname)
        {
            #region 创建Anno图层
            IFeatureClass featureClass = null;
            try
            {
                //ILayer pLayer = m_pmap.get_Layer(0);
                //IFeatureLayer pFeatureLayer = pLayer as IFeatureLayer;
                //ILayer pSrcLayer = pLayer;
                //IFeatureClass featureClass = pFeatureLayer.FeatureClass;

                //IDataset dataset = (IDataset)featureClass;//cast for the feature workspace from the workspace
                IFeatureWorkspace     featureWorkspace     = (IFeatureWorkspace)dataset.Workspace;
                IFeatureWorkspaceAnno featureWorkspaceAnno = (IFeatureWorkspaceAnno)dataset.Workspace;//set up the reference scale
                ESRI.ArcGIS.Carto.IGraphicsLayerScale graphicLayerScale = new ESRI.ArcGIS.Carto.GraphicsLayerScaleClass();
                IGeoDataset geoDataset = (IGeoDataset)dataset;
                graphicLayerScale.Units          = ESRI.ArcGIS.esriSystem.esriUnits.esriMeters;
                graphicLayerScale.ReferenceScale = 500;//set up symbol collection
                ESRI.ArcGIS.Display.ISymbolCollection symbolCollection = new ESRI.ArcGIS.Display.SymbolCollectionClass();
                #region "MakeText"
                ESRI.ArcGIS.Display.IFormattedTextSymbol myTextSymbol = new ESRI.ArcGIS.Display.TextSymbolClass();        //set the font for myTextSymbol
                stdole.IFontDisp myFont = new stdole.StdFontClass() as stdole.IFontDisp;
                myFont.Name       = "Courier New";
                myFont.Size       = 9;
                myTextSymbol.Font = myFont;//set the Color for myTextSymbol to be Dark Red
                ESRI.ArcGIS.Display.IRgbColor rgbColor = new ESRI.ArcGIS.Display.RgbColorClass();
                rgbColor.Red                     = 150;
                rgbColor.Green                   = 0;
                rgbColor.Blue                    = 0;
                myTextSymbol.Color               = (ESRI.ArcGIS.Display.IColor)rgbColor;//Set other properties for myTextSymbol
                myTextSymbol.Angle               = 0;
                myTextSymbol.RightToLeft         = false;
                myTextSymbol.VerticalAlignment   = ESRI.ArcGIS.Display.esriTextVerticalAlignment.esriTVABaseline;
                myTextSymbol.HorizontalAlignment = ESRI.ArcGIS.Display.esriTextHorizontalAlignment.esriTHAFull;
                myTextSymbol.CharacterSpacing    = 200;
                myTextSymbol.Case                = ESRI.ArcGIS.Display.esriTextCase.esriTCNormal;
                #endregion
                symbolCollection.set_Symbol(0, (ESRI.ArcGIS.Display.ISymbol)myTextSymbol); //set up the annotation labeling properties including the expression
                ESRI.ArcGIS.Carto.IAnnotateLayerProperties annoProps = new ESRI.ArcGIS.Carto.LabelEngineLayerPropertiesClass();
                annoProps.FeatureLinked = false;                                           //这里控制是不是关联的注记层
                annoProps.AddUnplacedToGraphicsContainer = false;
                annoProps.CreateUnplacedElements         = true;
                annoProps.DisplayAnnotation = true;
                annoProps.UseOutput         = true;
                ESRI.ArcGIS.Carto.ILabelEngineLayerProperties layerEngineLayerProps = (ESRI.ArcGIS.Carto.ILabelEngineLayerProperties)annoProps;
                ESRI.ArcGIS.Carto.IAnnotationExpressionEngine annoExpressionEngine  = new ESRI.ArcGIS.Carto.AnnotationVBScriptEngineClass();
                layerEngineLayerProps.ExpressionParser   = annoExpressionEngine;
                layerEngineLayerProps.Expression         = "[RefName]";
                layerEngineLayerProps.IsExpressionSimple = true;
                layerEngineLayerProps.Offset             = 0;
                layerEngineLayerProps.SymbolID           = 0;
                layerEngineLayerProps.Symbol             = myTextSymbol;
                ESRI.ArcGIS.Carto.IAnnotateLayerTransformationProperties annoLayerTransProp =
                    (ESRI.ArcGIS.Carto.IAnnotateLayerTransformationProperties)annoProps;
                annoLayerTransProp.ReferenceScale = graphicLayerScale.ReferenceScale;
                annoLayerTransProp.Units          = graphicLayerScale.Units;
                annoLayerTransProp.ScaleRatio     = 1;
                ESRI.ArcGIS.Carto.IAnnotateLayerPropertiesCollection annoPropsColl = new ESRI.ArcGIS.Carto.AnnotateLayerPropertiesCollectionClass();
                annoPropsColl.Add(annoProps);//use the AnnotationFeatureClassDescription to get the list of required
                //fields and the default name of the shape field
                IObjectClassDescription  oCDesc = new ESRI.ArcGIS.Carto.AnnotationFeatureClassDescriptionClass();
                IFeatureClassDescription fCDesc = (IFeatureClassDescription)oCDesc;//create the new class

                featureClass = featureWorkspaceAnno.CreateAnnotationClass(annoname, oCDesc.RequiredFields, oCDesc.InstanceCLSID, oCDesc.ClassExtensionCLSID,
                                                                          fCDesc.ShapeFieldName, "", (IFeatureDataset)dataset, null, annoPropsColl, graphicLayerScale, symbolCollection, true);
                //给新建的图层添加子层
                ISubtypes subtypes = (ISubtypes)featureClass;
                subtypes.SubtypeFieldName = "AnnotationClassID";
                subtypes.AddSubtype(1, "GCD");
                subtypes.AddSubtype(2, "DLDW");
                subtypes.AddSubtype(3, "JMD");
                subtypes.AddSubtype(4, "SXSS");
                subtypes.AddSubtype(5, "DLSS");
                subtypes.AddSubtype(6, "ZBTZ");
                subtypes.AddSubtype(7, "TK");
                subtypes.DefaultSubtypeCode = 1;
                return(featureClass);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(featureClass);
            }
            #endregion
        }
Beispiel #15
0
        //*******************************************************************************************************************************************
        //若使用数据库版本,并且没有选中融合,说明冲突要素没有发生变化,则需要将冲突要素保存起来,在写入更新日志时,要排除这些记录
        //同理,若使用数据库版本,选中融合,但是融合不成功,说明要素还是没有发生变化,也需要将这一类要素存储起来,在写入更新日志时,排除这些记录

        //若使用当前版本覆盖数据库版本,不用清除更新日志记录表里面冲突要素对应的更新日志信息,但是要修改历史库相应的要素,将以前的更改数据置为无效
        //*******************************************************************************************************************************************
        /// <summary>
        /// 保存需要排除的冲突要素记录
        /// </summary>
        /// <param name="defVerName">默认版本名称</param>
        /// <param name="bChildWin">true表示用当前版本替换前一版本,false表示使用数据库版本</param>
        /// <param name="beMerge">true表示融合冲突要素几何形状,false表示不融合</param>
        /// <param name="eError"></param>
        /// <returns></returns>
        public Dictionary <string, Dictionary <int, List <int> > > ReconcileVersion(string defVerName, bool bChildWin, bool beMerge, out Exception eError)
        {
            Dictionary <string, Dictionary <int, List <int> > > conflictFeaClsDic = null; //产生冲突的要素类信息

            bool bLock            = true;                                                 //true获得锁
            bool bebortIfConflict = false;                                                //检测到冲突时,版本协调是否停止,true停止,false不停止
            //bool bChildWin = false;                 //true替换上一个版本(冲突版本),false用上一个版本(冲突版本)
            bool battributeCheck = false;                                                 //false若为true则只有修改同一个属性时才检测出冲突

            //bool beMerge = true;                   //对于产生冲突的要素是否融合
            eError = null;

            IVersionEdit4 pVersionEdit4 = v_WSEdit as IVersionEdit4; //版本编辑

            if (pVersionEdit4 == null)
            {
                eError = new Exception("获取当前版本编辑出错!");
                return(null);
            }
            try
            {
                //协调版本
                if (pVersionEdit4.Reconcile4(defVerName, bLock, bebortIfConflict, bChildWin, battributeCheck))
                {
                    //存在冲突,冲突处理方式分为3种: 使用当前版本、使用数据库版本、使用自定义处理方式(未实现)
                    IFeatureWorkspace pOrgFWS     = null;       //原始数据工作空间
                    IFeatureWorkspace pReconWS    = null;       //第一个编辑冲突版本工作空间
                    IFeatureWorkspace pPreReconWS = null;       //第二个编辑冲突版本工作空间(正在编辑的)

                    pOrgFWS = pVersionEdit4.CommonAncestorVersion as IFeatureWorkspace;
                    if (pOrgFWS == null)
                    {
                        eError = new Exception("原始数据库工作空间为空!");
                        return(null);
                    }
                    pReconWS = pVersionEdit4.ReconcileVersion as IFeatureWorkspace;
                    if (pReconWS == null)
                    {
                        eError = new Exception("第一个编辑冲突版本工作空间为空!");
                        return(null);
                    }
                    pPreReconWS = pVersionEdit4.PreReconcileVersion as IFeatureWorkspace;
                    if (pPreReconWS == null)
                    {
                        eError = new Exception("第二个编辑冲突版本工作空间为空!");
                        return(null);
                    }

                    conflictFeaClsDic = new Dictionary <string, Dictionary <int, List <int> > >();
                    #region 对冲突要素类进行处理
                    //获取产生冲突的要素
                    IEnumConflictClass pEnumConflictCls = pVersionEdit4.ConflictClasses;
                    if (pEnumConflictCls == null)
                    {
                        return(null);
                    }
                    pEnumConflictCls.Reset();
                    IConflictClass pConflictCls = pEnumConflictCls.Next();
                    //遍历冲突要素类,对冲突要素进行处理
                    while (pConflictCls != null)
                    {
                        if (pConflictCls.HasConflicts)
                        {
                            //若该要素类存在冲突要素
                            IDataset pdt        = pConflictCls as IDataset;
                            string   feaClsName = ""; //冲突要素类名称
                            feaClsName = pdt.Name;
                            if (feaClsName.Contains("."))
                            {
                                feaClsName = feaClsName.Substring(feaClsName.IndexOf('.') + 1);
                            }

                            IFeatureClass pFeaCls         = null;                                          //需要编辑的featureclass
                            IFeatureClass pOrgFeaCls      = null;                                          //冲突原始要素类
                            IFeatureClass pReconFeaCls    = null;                                          //第一个编辑冲突版本要素类
                            IFeatureClass pPreReconFeaCls = null;                                          //第二个编辑版本冲突要素类
                            IFeature      pOrgFea         = null;                                          //原始要素类中产生冲突对应的要素
                            IFeature      pReconFea       = null;                                          //第一个编辑版本中产生冲突的要素
                            IFeature      pPreReconFea    = null;                                          //第二个编辑版本中产生冲突的要素

                            Dictionary <int, List <int> > feaOIDDic = new Dictionary <int, List <int> >(); //用来保存产生冲突的要素类信息
                            List <int> OidLst = null;                                                      //用来保存产生冲突的要素oid集合

                            try
                            {
                                pFeaCls = (v_WSEdit as IFeatureWorkspace).OpenFeatureClass(feaClsName);
                                //获取不同版本对应的冲突要素类
                                pOrgFeaCls      = pOrgFWS.OpenFeatureClass(feaClsName);
                                pReconFeaCls    = pReconWS.OpenFeatureClass(feaClsName);
                                pPreReconFeaCls = pPreReconWS.OpenFeatureClass(feaClsName);
                            }
                            catch (Exception ex)
                            {
                                //******************************************
                                //guozheng added System Exception log
                                if (SysCommon.Log.Module.SysLog == null)
                                {
                                    SysCommon.Log.Module.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog();
                                }
                                SysCommon.Log.Module.SysLog.Write(ex);
                                //******************************************
                                eError = new Exception("获取冲突要素类出错!");
                                //******************************************
                                //guozheng added System Exception log
                                if (SysCommon.Log.Module.SysLog == null)
                                {
                                    SysCommon.Log.Module.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog();
                                }
                                SysCommon.Log.Module.SysLog.Write(eError);
                                //******************************************
                                //if (!bChildWin &&beMerge)
                                //{
                                //    //使用数据库版本,未进行融合,保要素信息存冲突
                                //    return;
                                //}
                                pConflictCls = pEnumConflictCls.Next();
                                continue;
                            }

                            #region 处理冲突(进行融合),并保存冲突要素信息
                            //在上一个版本(目标冲突版本)被修改,修改用2表示,但是在当前版本被删除的选择集
                            ISelectionSet deUpSelSet = pConflictCls.DeleteUpdates;
                            if (deUpSelSet != null)
                            {
                                #region 进行冲突处理,并保存产生冲突的要素信息,这种情况不能融合
                                IEnumIDs enumIDs = deUpSelSet.IDs;
                                int      ppoid   = -1;
                                ppoid = enumIDs.Next();

                                OidLst = new List <int>();
                                //遍历冲突要素类中存在的修改删除冲突要素
                                while (ppoid != -1)
                                {
                                    if (beMerge)
                                    {
                                        // 融合
                                        //eError = new Exception("编辑区域重叠,不能融合\n要素OID为:" + ppoid + ",要素类名称为:" + feaClsName + "。\n处理为用当前编辑覆盖原有编辑!");
                                    }
                                    if (bChildWin == false)
                                    {
                                        //使用数据库版本,保存产生冲突的要素信息
                                        if (!OidLst.Contains(ppoid))
                                        {
                                            OidLst.Add(ppoid);
                                        }
                                        if (!feaOIDDic.ContainsKey(2))
                                        {
                                            feaOIDDic.Add(2, OidLst);
                                        }
                                        else
                                        {
                                            if (!feaOIDDic[2].Contains(ppoid))
                                            {
                                                feaOIDDic[2].Add(ppoid);
                                            }
                                        }
                                    }
                                    ppoid = enumIDs.Next();
                                }
                                #endregion
                            }

                            //在上一个版本(目标冲突版本)被删除,删除用3表示,但是在当前版本被修改的选择集
                            ISelectionSet upDeSelSet = pConflictCls.UpdateDeletes;
                            if (upDeSelSet != null)
                            {
                                #region 进行冲突处理,并保存产生冲突的要素信息
                                IEnumIDs enumIDs = upDeSelSet.IDs;
                                int      ppoid   = -1;
                                ppoid  = enumIDs.Next();
                                OidLst = new List <int>();
                                //遍历要素类中存在的删除修改冲突
                                while (ppoid != -1)
                                {
                                    if (beMerge)
                                    {
                                        // 融合
                                        //SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "编辑区域重叠,不能融合\n要素OID为:" + ppoid + ",要素类名称为:" + feaClsName + "。");
                                    }
                                    if (bChildWin == false)
                                    {
                                        //使用数据库版本,保存产生冲突的融合不了的要素信息
                                        if (!OidLst.Contains(ppoid))
                                        {
                                            OidLst.Add(ppoid);
                                        }
                                        if (!feaOIDDic.ContainsKey(3))
                                        {
                                            feaOIDDic.Add(3, OidLst);
                                        }
                                        else
                                        {
                                            if (!feaOIDDic[3].Contains(ppoid))
                                            {
                                                feaOIDDic[3].Add(ppoid);
                                            }
                                        }
                                    }
                                    ppoid = enumIDs.Next();
                                }
                                #endregion
                            }

                            //在上一个版本(目标冲突版本)被修改,修改用2表示,但是在当前版本被修改的选择集
                            ISelectionSet upUpSelSet = pConflictCls.UpdateUpdates;
                            if (upUpSelSet != null)
                            {
                                #region 进行冲突处理,并保存产生冲突的要素信息
                                IEnumIDs enumIDs = upUpSelSet.IDs;
                                int      ppoid   = -1;
                                ppoid  = enumIDs.Next();
                                OidLst = new List <int>();
                                //遍历要素类中存在的修改修改冲突要素
                                while (ppoid != -1)
                                {
                                    if (pPreReconFeaCls == null || pReconFeaCls == null || pOrgFeaCls == null)
                                    {
                                        break;
                                    }
                                    pPreReconFea = pPreReconFeaCls.GetFeature(ppoid);
                                    pReconFea    = pReconFeaCls.GetFeature(ppoid);
                                    pOrgFea      = pOrgFeaCls.GetFeature(ppoid);
                                    if (pPreReconFea == null || pReconFea == null || pOrgFea == null)
                                    {
                                        break;
                                    }
                                    IConstructMerge constructMerge = new GeometryEnvironmentClass();  //融合变量
                                    IGeometry       newGeometry    = null;                            //融合后的几何形状
                                    if (beMerge)
                                    {
                                        #region 融合
                                        try
                                        {
                                            newGeometry = constructMerge.MergeGeometries(pOrgFea.ShapeCopy, pReconFea.ShapeCopy, pPreReconFea.ShapeCopy);
                                        }
                                        catch (Exception ex)
                                        {
                                            //SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "编辑区域重叠,不能融合");
                                            //******************************************
                                            //guozheng added System Exception log
                                            if (SysCommon.Log.Module.SysLog == null)
                                            {
                                                SysCommon.Log.Module.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog();
                                            }
                                            SysCommon.Log.Module.SysLog.Write(ex);
                                            //******************************************
                                            if (bChildWin == false)
                                            {
                                                //若用原来的版本替换现在的版本并且不能融合,说明该要素没有发生变化,应该在日志记录表里面排除掉
                                                //保存产生冲突的要素信息
                                                if (!OidLst.Contains(ppoid))
                                                {
                                                    OidLst.Add(ppoid);
                                                }
                                                if (!feaOIDDic.ContainsKey(2))
                                                {
                                                    feaOIDDic.Add(2, OidLst);
                                                }
                                                else
                                                {
                                                    if (!feaOIDDic[2].Contains(ppoid))
                                                    {
                                                        feaOIDDic[2].Add(ppoid);
                                                    }
                                                }
                                            }

                                            ppoid = enumIDs.Next();
                                            continue;
                                        }
                                        IFeature ppfea = pFeaCls.GetFeature(ppoid);
                                        ppfea.Shape = newGeometry;
                                        ppfea.Store();
                                        #endregion
                                    }
                                    else
                                    {
                                        #region  融合
                                        if (bChildWin == false)
                                        {
                                            //若用原来的版本替换现在的版本并且不能融合,说明该要素没有发生变化,应该在日志记录表里面排除掉
                                            //保存产生冲突的要素信息
                                            if (!OidLst.Contains(ppoid))
                                            {
                                                OidLst.Add(ppoid);
                                            }
                                            if (!feaOIDDic.ContainsKey(2))
                                            {
                                                feaOIDDic.Add(2, OidLst);
                                            }
                                            else
                                            {
                                                if (!feaOIDDic[2].Contains(ppoid))
                                                {
                                                    feaOIDDic[2].Add(ppoid);
                                                }
                                            }
                                        }
                                        #endregion
                                    }
                                    ppoid = enumIDs.Next();
                                }
                                #endregion
                            }

                            if (!conflictFeaClsDic.ContainsKey(feaClsName))
                            {
                                if (feaOIDDic != null)
                                {
                                    if (feaOIDDic.Count > 0)
                                    {
                                        conflictFeaClsDic.Add(feaClsName, feaOIDDic);
                                    }
                                }
                            }
                            #endregion
                        }
                        pConflictCls = pEnumConflictCls.Next();
                    }
                    #endregion
                }
                return(conflictFeaClsDic);
            }
            catch (Exception ex)
            {
                //******************************************
                //guozheng added System Exception log
                if (SysCommon.Log.Module.SysLog == null)
                {
                    SysCommon.Log.Module.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog();
                }
                SysCommon.Log.Module.SysLog.Write(ex);
                //******************************************
                eError = new Exception("版本协调出错!");
                return(null);
            }
        }
Beispiel #16
0
        public IFeatureClass CreateShapeFile(DataSet ds, string strOutShpName, ISpatialReference pSRF)
        {
            try
            {
                DirectoryInfo    di         = new DirectoryInfo(strOutShpName);
                string           filefolder = di.Parent.FullName;
                ClsGDBDataCommon cdc        = new ClsGDBDataCommon();
                //cdc.OpenFromShapefile(filefolder);
                IFields     pFields     = new FieldsClass();
                IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields;

                //设置字段
                IField     pField     = new FieldClass();
                IFieldEdit pFieldEdit = (IFieldEdit)pField;

                //创建类型为几何类型的字段
                IGeometryDef     pGeoDef     = new GeometryDefClass();
                IGeometryDefEdit pGeoDefEdit = (IGeometryDefEdit)pGeoDef;
                pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;

                pGeoDefEdit.HasM_2             = false;
                pGeoDefEdit.HasZ_2             = false;
                pGeoDefEdit.SpatialReference_2 = pSRF;

                pFieldEdit.Name_2        = "SHAPE";
                pFieldEdit.Type_2        = esriFieldType.esriFieldTypeGeometry;
                pFieldEdit.GeometryDef_2 = pGeoDef;
                //pFieldEdit.IsNullable_2 = true;
                //pFieldEdit.Required_2 = true;
                pFieldsEdit.AddField(pField);

                for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                {
                    pField            = new FieldClass();
                    pFieldEdit        = (IFieldEdit)pField;
                    pFieldEdit.Name_2 = ds.Tables[0].Columns[i].ColumnName;
                    pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                    if (ds.Tables[0].Columns[i].ColumnName.Contains("Z_高程"))
                    {
                        pFieldEdit.Name_2 = "Z_高程(米";
                    }
                    if (ds.Tables[0].Columns[i].ColumnName.Contains("里程"))
                    {
                        pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
                    }

                    pFieldEdit.IsNullable_2 = true;
                    pFieldsEdit.AddField(pField);
                }

                ClsGDBDataCommon comm     = new ClsGDBDataCommon();
                IWorkspace       inmemWor = comm.OpenFromShapefile(filefolder);
                // ifeatureworkspacee
                IFeatureWorkspace pFeatureWorkspace = inmemWor as IFeatureWorkspace;
                IFeatureClass     pFeatureClass     = pFeatureWorkspace.CreateFeatureClass(di.Name, pFields, null, null, esriFeatureType.esriFTSimple, "SHAPE", "");

                return(pFeatureClass);
                //IFeatureLayer pFeatureLayer = new FeatureLayerClass();
                //pFeatureLayer.FeatureClass = pFeatureClass;
                //pFeatureLayer.Name = System.IO.Path.GetFileNameWithoutExtension(di.Name);
                //m_mapControl.AddLayer(pFeatureLayer as ILayer, 0);
                //m_mapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
            }
            catch (SystemException ee)
            {
                MessageBox.Show(ee.Message);
                return(null);
            }
        }
Beispiel #17
0
        public void CreateLineShpFile(string fileName, ISpatialReference pSRF)
        {
            //判断需要生成的线文件是否存在,若不存在则创建文件,若存在则将新添加的线写入文件
            if (File.Exists(fileName))
            {
                MessageBox.Show("file already exist, please change file name!");
                return;
            }
            else
            {
                string pLineFile = fileName;
                string pFilePath = System.IO.Path.GetDirectoryName(pLineFile);
                string pFileName = System.IO.Path.GetFileName(pLineFile);
                //打开工作空间
                IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass();
                IFeatureWorkspace pWS  = (IFeatureWorkspace)pWSF.OpenFromFile(pFilePath, 0);

                //判断文件是否存在,若不存在则创建文件
                if (!(File.Exists(fileName)))
                {
                    const string strShapeFieldName = "shape";
                    //设置字段集
                    IFields     pFields     = new FieldsClass();
                    IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields;

                    //设置字段
                    IField     pField     = new FieldClass();
                    IFieldEdit pFieldEdit = (IFieldEdit)pField;

                    //创建类型为几何类型的字段
                    pFieldEdit.Name_2 = strShapeFieldName;
                    pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
                    //为esriFieldTypeGeometry类型的字段创建几何定义,包括类型和空间参照
                    IGeometryDef     pGeoDef     = new GeometryDefClass(); //The geometry definition for the field if IsGeometry is TRUE.
                    IGeometryDefEdit pGeoDefEdit = (IGeometryDefEdit)pGeoDef;
                    pGeoDefEdit.GeometryType_2     = esriGeometryType.esriGeometryPolyline;
                    pGeoDefEdit.SpatialReference_2 = pSRF;
                    pFieldEdit.GeometryDef_2       = pGeoDef;
                    pFieldsEdit.AddField(pField);

                    //add length field
                    pField                  = new FieldClass();
                    pFieldEdit              = (IFieldEdit)pField;
                    pFieldEdit.Name_2       = "length";
                    pFieldEdit.Type_2       = esriFieldType.esriFieldTypeDouble;
                    pFieldEdit.IsNullable_2 = true;
                    pFieldsEdit.AddField(pField);

                    //add length field
                    pField                  = new FieldClass();
                    pFieldEdit              = (IFieldEdit)pField;
                    pFieldEdit.Name_2       = "质量";
                    pFieldEdit.Type_2       = esriFieldType.esriFieldTypeString;
                    pFieldEdit.IsNullable_2 = true;
                    pFieldsEdit.AddField(pField);

                    //创建shapefile线图层
                    pWS.CreateFeatureClass(pFileName, pFields, null, null, esriFeatureType.esriFTSimple, strShapeFieldName, "");
                }
            }
        }
        protected override void OnClick()
        {
            string straboPath = Environment.GetEnvironmentVariable(ArcStrabo2Extension.EnvironmentVariableSTRABO_HOME, EnvironmentVariableTarget.User);
            string tessPath   = Environment.GetEnvironmentVariable(ArcStrabo2Extension.EnvironmentVariableTESS_DATA, EnvironmentVariableTarget.User);

            if (ArcStrabo2Extension.PathSet == false)
            {
                if (String.IsNullOrEmpty(straboPath) == true)
                {
                    MessageBox.Show(ArcStrabo2Extension.ErrorMsgNoStraboHome);
                    return;
                }
                if (String.IsNullOrEmpty(tessPath) == true)
                {
                    MessageBox.Show(ArcStrabo2Extension.ErrorMsgNoTess_Data);
                    return;
                }

                ////Initialize directories
                bool Initialize_straboPath_Correct = ArcStrabo2Extension.initialize_straboPath_directories(straboPath);

                if (Initialize_straboPath_Correct == false)
                {
                    MessageBox.Show(ArcStrabo2Extension.ErrorMsgNoStraboHomeWritePermission);
                    return;
                }
                ArcStrabo2Extension.PathSet = true;
            }

            #region Text Recognition
            ////Save Positive and Negative Layer and making GeoJason File
            ComboBoxLayerSelector layerNameCombo = ComboBoxLayerSelector.GetLayerNameComboBox();

            ////Select correct raster map layer
            RasterLayer rasterlayer = new RasterLayer();
            rasterlayer = ((RasterLayer)layerNameCombo.GetSelectedLayer());
            string input_data_source_directory;
            try
            {
                input_data_source_directory = rasterlayer.FilePath;
            }
            catch (Exception)
            {
                // Handle no input map error
                MessageBox.Show(ArcStrabo2Extension.ErrorMsgNoInputMap, "Input Map Error", MessageBoxButtons.OK);
                return;
            }

            ////Select language from combo box in toolbar
            ComboBoxLanguageSelector languageNameCombo = ComboBoxLanguageSelector.GetLanguageNameComboBox();
            string lng = languageNameCombo.Get_selected_language();
            if (lng == null)
            {
                MessageBox.Show(ArcStrabo2Extension.ErrorMsgNoInputLanguage, "Input Language Error", MessageBoxButtons.OK);
                return;
            }

            ////Set Log Directory Path
            Log.SetLogDir(ArcStrabo2Extension.Log_Path);
            Log.SetOutputDir(ArcStrabo2Extension.Log_Path);

            Log.WriteLine("MakingTextLabelGeoJsonFile Method Start SIMA");
            IMap            map             = ArcMap.Document.FocusMap;
            ArcStraboObject arcStraboObject = new ArcStraboObject();
            arcStraboObject.MakingTextLabelGeoJsonFile(ArcStrabo2Extension.Text_Result_Path);
            Log.WriteLine("MakingTextLabelGeoJsonFile Method Finish");

            ////Run TextExtraction Layer from Strabo.core and load raster Layer
            Log.WriteLine("textLayerExtract Medthod Start SIMA");
            arcStraboObject.textLayerExtract(input_data_source_directory, ArcStrabo2Extension.Text_Result_Path);
            Log.WriteLine("textLayerExtract Method Finish");

            Log.WriteLine("AddRasterLayer Method Start SIMA");
            arcStraboObject.AddRasterLayer(ArcStrabo2Extension.Text_Result_Path, ArcStrabo2Extension.TextLayerPNGFileName);
            Log.WriteLine("AddRasterLayer Method Finish");

            ////Run TextIdentifier Method
            Log.WriteLine("textIndentification Method Start SIMA");
            System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;

            ///// Attempting to create cancel feature window
            //DialogResult result = MessageBox.Show("Text Recognition is running.", "Application Running", MessageBoxButtons.OKCancel);
            //if (result == DialogResult.Cancel)
            //{
            //    return;
            //}
            //else if (result == DialogResult.OK)

            arcStraboObject.textIndentification(ArcStrabo2Extension.Text_Result_Path + "\\", ArcStrabo2Extension.Intermediate_Result_Path + "\\", ArcStrabo2Extension.TextLayerPNGFileName);
            System.Windows.Forms.Cursor.Current = Cursors.Default;
            Log.WriteLine("textIndentification Method Finish");

            ////OCR Part
            Log.WriteLine("ExtractTextToGEOJSON Method Start SANJUALI");
            System.Windows.Forms.Cursor.Current = Cursors.AppStarting;

            //// Select language from combo box in toolbar
            //ComboBoxLanguageSelector languageNameCombo = ComboBoxLanguageSelector.GetLanguageNameComboBox();
            //string lng = languageNameCombo.Get_selected_language();
            //if (lng == null)
            //{
            //    MessageBox.Show(ArcStrabo2Extension.ErrorMsgNoInputLanguage, "Input Language Error", MessageBoxButtons.OK);
            //    return;
            //}
            Strabo.Core.OCR.WrapperTesseract language = new Strabo.Core.OCR.WrapperTesseract(tessPath, lng);
            /// Strabo.Core.OCR.WrapperTesseract language = new Strabo.Core.OCR.WrapperTesseract(tessPath);
            language.ExtractTextToGEOJSON(ArcStrabo2Extension.Intermediate_Result_Path, ArcStrabo2Extension.Text_Result_Path, ArcStrabo2Extension.TesseractResultsJSONFileName);
            Log.WriteLine("ExtractTextToGEOJSON Method Finish");
            System.Windows.Forms.Cursor.Current = Cursors.Default;

            ////Add Polygon of OCR Layer
            Log.WriteLine("CreateFeatureClassWithFields Method Start SIMA");
            IWorkspace        workspace        = arcStraboObject.CreateShapefileWorkspace(ArcStrabo2Extension.Text_Result_Path);
            IFeatureWorkspace featureworkspace = (IFeatureWorkspace)workspace;
            string            tesseDataPath    = ArcStrabo2Extension.Text_Result_Path + "\\" + ArcStrabo2Extension.TesseractResultsJSONFileName;

            IFeatureClass featureClass = arcStraboObject.CreateFeatureClassWithFields(ArcStrabo2Extension.TextLayerOCRShapefile, featureworkspace, tesseDataPath);
            IFeatureLayer featureLayer = arcStraboObject.CreateFeatureLayer(featureClass);
            Log.WriteLine("CreateFeatureClassWithFields Method Finish");

            Log.WriteLine("AddPolygon Method Start");
            arcStraboObject.AddPolygon(featureLayer, featureworkspace, tesseDataPath);
            Log.WriteLine("AddPolygon Method Finish");

            Log.ArchiveLog();
            MessageBox.Show("Text recognition finished!", "Done", MessageBoxButtons.OK);
            #endregion
        }
        /// <summary>
        /// 最短路径分析
        /// </summary>
        /// <param name="mapControl">地图控件</param>
        /// <param name="gdbfileName">数据库文件</param>
        /// <param name="featureDatasetName">要素集名字</param>
        /// <param name="ndsName">网络数据集名字</param>
        /// <param name="featureClasses">参数要素类及其阈值,其中键值包括:Stops(路线经过结点),Barriers,PolylineBarriers,PolygonBarriers</param>
        /// <param name="isShowDataBase">是否显示网络数据集</param>
        ///  <param name="isShowNalayer">是否显示网络分析图层</param>
        ///  <param name="routeLayer">最近路线图层</param>
        public static bool Short_Path(AxMapControl mapControl, string gdbfileName, string featureDatasetName, string ndsName, IDictionary <string, DecorateRouteFeatureClass> featureClasses, bool isShowDataBase, bool isShowNalayer, ref ILayer routeLayer)
        {
            //首先判断输入的参数要素类是否合法
            if (!FeatureClassKeyIsRight(featureClasses))
            {
                throw new Exception("参数字典错误");
            }
            // mapControl.ClearLayers();
            //打开工作空间
            IFeatureWorkspace pFeatureWorkspace = OpenWorkspace(gdbfileName) as IFeatureWorkspace;

            if (pFeatureWorkspace == null)
            {
                return(false);
            }
            //获取网络数据集
            INetworkDataset pNetworkDataset = OpenNetworkDataset(pFeatureWorkspace as IWorkspace, featureDatasetName, ndsName);

            if (pNetworkDataset == null)
            {
                Debug.Print("无法获取网络数据集");
                return(false);
            }
            //获取网络分析上下文
            INAContext pNAContext = CreateNAContext(pNetworkDataset);
            //打开节点图层 一般和网络数据集放置在一起 名称是xxx_Junctions
            IFeatureClass pVertexFC = pFeatureWorkspace.OpenFeatureClass(ndsName + "_Junctions");
            ILayer        pLayer    = null;

            // 显示网络数据集图层
            if (isShowDataBase)
            {
                INetworkLayer pNetworkLayer = new NetworkLayerClass();
                pNetworkLayer.NetworkDataset = pNetworkDataset;
                pLayer      = pNetworkLayer as ILayer;
                pLayer.Name = "网络数据集";
                mapControl.AddLayer(pLayer, 0);
            }
            //创建网络分析图层
            INALayer naLayer = pNAContext.Solver.CreateLayer(pNAContext);

            //显示网络分析图层
            if (isShowNalayer)
            {
                pLayer                  = naLayer as ILayer;
                pLayer.Name             = pNAContext.Solver.DisplayName;
                pLayer.SpatialReference = mapControl.SpatialReference;
                mapControl.AddLayer(pLayer, 0);
                IActiveView        pActiveView        = mapControl.ActiveView;
                IMap               pMap               = pActiveView.FocusMap;
                IGraphicsContainer pGraphicsContainer = pMap as IGraphicsContainer;
                mapControl.Refresh();
            }
            INASolver naSolver = pNAContext.Solver;

            //插入相关数据
            foreach (var value in featureClasses)
            {
                LoadNANetWorkLocations(pNAContext, value.Key, value.Value.FeatureClass, value.Value.SnapTolerance);
            }
            //插入经过点
            //LoadNANetWorkLocations(pNAContext,"Stops", stopFeatureClass, 30);
            //插入障碍点
            //    LoadNANetWorkLocations(pNAContext, "Barriers", barriesFeatureClass, 30);
            IGPMessages gpMessages = new GPMessagesClass();

            //  SetSolverSettings(pNAContext);
            //寻找最短路径
            try
            {
                pNAContext.Solver.Solve(pNAContext, gpMessages, new CancelTrackerClass());
                routeLayer = naLayer.get_LayerByNAClassName("Routes");
            }
            catch (Exception e)
            {
                Debug.Print("无法找到最短路径:" + e.Message);
                return(false);
            }
            mapControl.Refresh();
            if (gpMessages != null)
            {
                for (int i = 0; i < gpMessages.Count; i++)
                {
                    switch (gpMessages.GetMessage(i).Type)
                    {
                    case esriGPMessageType.esriGPMessageTypeError:
                        Debug.Print("错误 " + gpMessages.GetMessage(i).ErrorCode.ToString() + " " + gpMessages.GetMessage(i).Description);
                        break;

                    case esriGPMessageType.esriGPMessageTypeWarning:
                        Debug.Print("警告 " + gpMessages.GetMessage(i).Description);
                        break;

                    default:
                        Debug.Print("信息 " + gpMessages.GetMessage(i).Description);
                        break;
                    }
                }
            }
            return(true);
        }
Beispiel #20
0
        public TopoNetwork GetNetwork()
        {
            if (TopoNetworkManager.Instance.Exists(this._objectId))
            {
                return(TopoNetworkManager.Instance.GetTopoNetWorkByObjectId(this._objectId));
            }
            string         path         = Config.GetConfigValue("2DMdbTopo");
            TopoNetwork    network      = null;
            IFeatureClass  featureClass = null;
            IQueryFilter   filter       = null;
            IFeatureCursor cursor       = null;
            IFeature       feature      = null;

            try
            {
                IWorkspaceFactory pWsFt = new AccessWorkspaceFactory();
                IFeatureWorkspace pWs   = pWsFt.OpenFromFile(path, 0) as IFeatureWorkspace;
                featureClass     = pWs.OpenFeatureClass(_name);
                filter           = new QueryFilter();
                filter.SubFields = "A_FC,Edge,P_FC,PNode,E_FC,ENode,Geometry_Length";
                int index1 = featureClass.Fields.FindField("A_FC");
                int index2 = featureClass.Fields.FindField("Edge");
                int index3 = featureClass.Fields.FindField("P_FC");
                int index4 = featureClass.Fields.FindField("PNode");
                int index5 = featureClass.Fields.FindField("E_FC");
                int index6 = featureClass.Fields.FindField("ENode");
                int index7 = featureClass.Fields.FindField("Geometry_Length");

                Dictionary <string, Edge> dictEdge = new Dictionary <string, Edge>();  // 边字典
                Dictionary <string, Node> dictNode = new Dictionary <string, Node>();  // 点字典
                cursor = featureClass.Search(filter, false);
                while ((feature = cursor.NextFeature()) != null)
                {
                    string edgeFC, edgeOid, snodeFC, snodeOid, enodeFC, enodeOid;

                    if (feature.get_Value(index1) != null)
                    {
                        edgeFC = feature.get_Value(index1).ToString();
                    }
                    else
                    {
                        edgeFC = "0";
                    }
                    if (feature.get_Value(index2) != null)
                    {
                        edgeOid = feature.get_Value(index2).ToString();
                    }
                    else
                    {
                        edgeOid = BitConverter.ToString(ObjectIdGenerator.Generate()).Replace("-", string.Empty).ToLowerInvariant();
                    }
                    if (feature.get_Value(index3) != null)
                    {
                        snodeFC = feature.get_Value(index3).ToString();
                    }
                    else
                    {
                        snodeFC = "0";
                    }
                    if (feature.get_Value(index4) != null)
                    {
                        snodeOid = feature.get_Value(index4).ToString();
                    }
                    else
                    {
                        snodeOid = BitConverter.ToString(ObjectIdGenerator.Generate()).Replace("-", string.Empty).ToLowerInvariant();
                    }
                    if (feature.get_Value(index5) != null)
                    {
                        enodeFC = feature.get_Value(index5).ToString();
                    }
                    else
                    {
                        enodeFC = "0";
                    }
                    if (feature.get_Value(index6) != null)
                    {
                        enodeOid = feature.get_Value(index6).ToString();
                    }
                    else
                    {
                        enodeOid = BitConverter.ToString(ObjectIdGenerator.Generate()).Replace("-", string.Empty).ToLowerInvariant();
                    }

                    double edgeLength = double.MaxValue;
                    if (feature.get_Value(index7) != null)
                    {
                        edgeLength = (double)feature.get_Value(index7);
                    }
                    //if (feature.get_Value(index7) != null && feature.get_Value(index7) is IPolyline)
                    //{
                    //    IPolyline line = feature.get_Value(index7) as IPolyline;
                    //    edgeLength = line.Length;
                    //}

                    Node   sn  = null;
                    Node   en  = null;
                    string key = snodeFC + "_" + snodeOid;
                    if (!dictNode.ContainsKey(key))
                    {
                        if (NodeManager.Instance.GetNodeByID(key) == null)
                        {
                            sn = new Node(snodeFC, snodeOid);
                            NodeManager.Instance.Add(sn);
                        }
                        else
                        {
                            sn = NodeManager.Instance.GetNodeByID(key);
                        }
                        dictNode.Add(key, sn);
                    }
                    else
                    {
                        sn = dictNode[key];
                    }
                    key = enodeFC + "_" + enodeOid;
                    if (!dictNode.ContainsKey(key))
                    {
                        if (NodeManager.Instance.GetNodeByID(key) == null)
                        {
                            en = new Node(enodeFC, enodeOid);
                            NodeManager.Instance.Add(en);
                        }
                        else
                        {
                            en = NodeManager.Instance.GetNodeByID(key);
                        }
                        dictNode.Add(key, en);
                    }
                    else
                    {
                        en = dictNode[key];
                    }
                    if (sn == null || en == null)
                    {
                        continue;
                    }
                    key = edgeFC + "_" + edgeOid;
                    if (!dictEdge.ContainsKey(key))
                    {
                        Edge e = null;
                        if (EdgeManager.Instance.GetEdgeByID(key) == null)
                        {
                            e = new Edge(edgeFC, edgeOid, sn, en, edgeLength);
                            EdgeManager.Instance.Add(e);
                        }
                        else
                        {
                            e = EdgeManager.Instance.GetEdgeByID(key);
                        }
                        dictEdge.Add(key, e);
                    }
                }
                network = new TopoNetwork(this._objectId, dictNode);
                TopoNetworkManager.Instance.Add(this.ObjectId, network);
                return(network);
            }

            catch (System.Exception ex)
            {
                return(null);
            }
            finally
            {
                if (cursor != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(cursor);
                    cursor = null;
                }
                if (feature != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(feature);
                    feature = null;
                }
            }
        }
Beispiel #21
0
        /// <summary>
        /// Load the information from the MajorCities featureclass to the locations table
        /// </summary>
        private void PopulateLocationsTable()
        {
            string path = System.IO.Path.Combine(m_installationFolder + @"\..", @"DeveloperKit10.4\Samples\data\USZipCodeData\");

            //open the featureclass
            IWorkspaceFactory wf           = new ShapefileWorkspaceFactoryClass() as IWorkspaceFactory;
            IWorkspace        ws           = wf.OpenFromFile(path, 0);
            IFeatureWorkspace fw           = ws as IFeatureWorkspace;
            IFeatureClass     featureClass = fw.OpenFeatureClass("ZipCode_Boundaries_US_Major_Cities");
            //map the name and zip fields
            int    zipIndex  = featureClass.FindField("ZIP");
            int    nameIndex = featureClass.FindField("NAME");
            string cityName;
            long   zip;

            try
            {
                //iterate through the features and add the information to the table
                IFeatureCursor fCursor = null;
                fCursor = featureClass.Search(null, true);
                IFeature feature = fCursor.NextFeature();
                int      index   = 0;

                while (null != feature)
                {
                    object obj = feature.get_Value(nameIndex);
                    if (obj == null)
                    {
                        continue;
                    }
                    cityName = Convert.ToString(obj);

                    obj = feature.get_Value(zipIndex);
                    if (obj == null)
                    {
                        continue;
                    }
                    zip = long.Parse(Convert.ToString(obj));
                    if (zip <= 0)
                    {
                        continue;
                    }

                    //add the current location to the location table
                    DataRow r = m_locations.Rows.Find(zip);
                    if (null == r)
                    {
                        r    = m_locations.NewRow();
                        r[1] = zip;
                        r[2] = cityName;
                        lock (m_locations)
                        {
                            m_locations.Rows.Add(r);
                        }
                    }

                    feature = fCursor.NextFeature();

                    index++;
                }

                //release the feature cursor
                Marshal.ReleaseComObject(fCursor);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.Message);
            }
        }
Beispiel #22
0
        public override bool Check(ref List <Error> checkResult)
        {
            IFeatureWorkspace ipFtWS = (IFeatureWorkspace)m_BaseWorkspace;

            try
            {
                List <Error>  pResult   = new List <Error>();
                string        strAlias  = m_pFieldPara.strAlias;
                List <string> listLayer = m_pFieldPara.m_LyrFldMap;
                System.Collections.Hashtable hashtable = new System.Collections.Hashtable();

                for (int i = 0; i < listLayer.Count; i++)
                {
                    string strTemp = listLayer[i];
                    int    nIndex  = strTemp.IndexOf('&');
                    if (nIndex < 0)
                    {
                        continue;
                    }
                    string str = strTemp.Substring(0, nIndex);
                    if (!hashtable.Contains(str))
                    {
                        hashtable.Add(str, "");
                    }
                }

                DataTable dtLayer = new DataTable();
                string    strSQL  = "select AttrTableName,LayerName,LayerID from LR_DicLayer";

                dtLayer = Hy.Common.Utility.Data.AdoDbHelper.GetDataTable(SysDbHelper.GetSysDbConnection(), strSQL);
                if (dtLayer == null)
                {
                    return(false);
                }

                foreach (DataRow drLayer in dtLayer.Rows)
                {
                    if (drLayer != null)
                    {
                        string strLayerCode = drLayer["AttrTableName"].ToString();
                        string strLayerName = drLayer["LayerName"].ToString();
                        int    nLayerID     = Convert.ToInt32(drLayer["LayerID"]);

                        if (!hashtable.Contains(strLayerName))
                        {
                            continue;
                        }

                        IFeatureClass pFtCls = null;
                        try
                        {
                            pFtCls = ipFtWS.OpenFeatureClass(strLayerCode);
                        }
                        catch
                        {
                            continue;
                        }
                        IFields pFields = pFtCls.Fields;

                        if (pFields == null)
                        {
                            continue;
                        }
                        int    lFieldCount = pFields.FieldCount;
                        IField pField;

                        DataTable dtFields     = new DataTable();
                        string    strSQLFields = "select * from LR_DicField where LayerID = " + nLayerID + "";
                        dtFields = Hy.Common.Utility.Data.AdoDbHelper.GetDataTable(SysDbHelper.GetSysDbConnection(), strSQLFields);
                        if (dtFields == null)
                        {
                            FieldError LRFieldErrorInfo = new FieldError();
                            LRFieldErrorInfo.DefectLevel     = this.DefectLevel;
                            LRFieldErrorInfo.strAttrTabName  = strLayerName;
                            LRFieldErrorInfo.strFieldName    = null;
                            LRFieldErrorInfo.m_strRuleInstID = this.m_InstanceID;
                            LRFieldErrorInfo.strErrorMsg     = string.Format("{0}层对应的属性字段,在《土地利用现状数据库标准》中不存在", strLayerName);

                            pResult.Add(LRFieldErrorInfo);

                            continue;
                        }

                        ///检查图层中是否存在多余字段
                        for (int i = 0; i < lFieldCount; i++)
                        {
                            if (strLayerName == "注记")
                            {
                                break;
                            }
                            pField = pFields.get_Field(i);
                            if (pField.Name.ToUpper().Contains("OBJECTID") ||
                                pField.Name.ToLower().Contains("shape"))
                            {
                                continue;
                            }

                            int k           = 0;
                            int nFieldCount = dtFields.Rows.Count;
                            for (k = 0; k < nFieldCount; k++)
                            {
                                DataRow drField    = dtFields.Rows[k];
                                string  strStdName = drField["FieldName"].ToString();
                                string  strStdCode = drField["FieldCode"].ToString();
                                if (strStdCode.Trim().Equals("objectid", StringComparison.OrdinalIgnoreCase) ||
                                    strStdCode.Trim().Equals("object id", StringComparison.OrdinalIgnoreCase) ||
                                    strStdCode.Trim().Equals("shape", StringComparison.OrdinalIgnoreCase))
                                {
                                    continue;
                                }
                                if (pField.Name.Trim().Equals(strStdCode.Trim(), StringComparison.OrdinalIgnoreCase))
                                {
                                    break;
                                }
                            }
                            if (k == nFieldCount)
                            {
                                if (!pField.AliasName.Contains("本软件"))
                                {
                                    FieldError LRFieldErrorInfo2 = new FieldError();
                                    LRFieldErrorInfo2.DefectLevel     = this.DefectLevel;
                                    LRFieldErrorInfo2.strAttrTabName  = strLayerName;
                                    LRFieldErrorInfo2.strFieldName    = pField.Name;
                                    LRFieldErrorInfo2.m_strRuleInstID = this.m_InstanceID;
                                    LRFieldErrorInfo2.strErrorMsg     = string.Format(Helper.ErrMsgFormat.ERR_410100001_1, strLayerName, pField.Name);

                                    pResult.Add(LRFieldErrorInfo2);
                                }
                            }
                        }

                        ///检查标准中的字段在图层中是否存在,已经图层的字段是否和标准相符合
                        //二次for循环迭代控制器,add by wangxiang 20111201
                        int flag = 0;
                        foreach (DataRow drField in dtFields.Rows)
                        {
                            if (drField != null)
                            {
                                string strStdName = drField["FieldName"].ToString();
                                string strStdCode = drField["FieldCode"].ToString();

                                if (strStdCode.Trim().Equals("objectid", StringComparison.OrdinalIgnoreCase) ||
                                    strStdCode.Trim().Equals("object id", StringComparison.OrdinalIgnoreCase) ||
                                    strStdCode.Trim().Equals("shape", StringComparison.OrdinalIgnoreCase))
                                {
                                    continue;
                                }

                                int nStdType = Convert.ToInt32(drField["FieldType"]);


                                string strStdFldType = Hy.Common.Utility.Data.AdoDbHelper.GetFieldTypeName(nStdType);

                                FieldError FieldErrInfo1 = new FieldError();
                                FieldErrInfo1.DefectLevel     = this.DefectLevel;
                                FieldErrInfo1.strAttrTabName  = strLayerName;
                                FieldErrInfo1.strFieldName    = "" + strStdCode + "(" + strStdName + ")";
                                FieldErrInfo1.strStdFieldType = strStdFldType;
                                FieldErrInfo1.m_strRuleInstID = this.m_InstanceID;

                                int i = 0;
                                for (i = 0; i < lFieldCount && flag < lFieldCount; i++)
                                {
                                    pField = pFields.get_Field(i);


                                    if (pField.Name.Trim() == strStdCode.Trim())
                                    {
                                        flag++;
                                        esriFieldType pType = pField.Type;

                                        if (nStdType == 3)
                                        {
                                            nStdType = 4;
                                        }
                                        esriFieldType pDTType = TopoHelper.en_GetEsriFieldByEnum(nStdType);
                                        if (pType == pDTType)
                                        {
                                            if (pType != esriFieldType.esriFieldTypeString)
                                            {
                                                break;
                                            }

                                            if (pField.Length != Convert.ToInt32(drField["Length"])) //字段长度不正确
                                            {
                                                if (strLayerCode.Equals("JBNTBHTB", StringComparison.OrdinalIgnoreCase) && pField.Name.Trim().Equals("jbnttbbh", StringComparison.OrdinalIgnoreCase))
                                                {
                                                    FieldErrInfo1.strErrorMsg = string.Format(Helper.ErrMsgFormat.ERR_410100001_4, strLayerName, pField.Name, pField.Length, Convert.ToInt32(drField["Length"]));
                                                }
                                                else
                                                {
                                                    FieldErrInfo1.strErrorMsg = string.Format(Helper.ErrMsgFormat.ERR_410100001_4, strLayerName, pField.Name, pField.Length, Convert.ToInt32(drField["Length"]));
                                                }
                                                pResult.Add(FieldErrInfo1);
                                                break;
                                            }


                                            break;
                                        }
                                        else
                                        {
                                            if (pDTType != esriFieldType.esriFieldTypeBlob)
                                            {
                                                FieldErrInfo1.strErrorMsg = string.Format(Helper.ErrMsgFormat.ERR_410100001_3, strLayerName, pField.Name, TopoHelper.en_GetFieldTypebyEsriField(pType), TopoHelper.en_GetFieldTypebyEsriField(pDTType));
                                                pResult.Add(FieldErrInfo1);
                                            }

                                            break;
                                        }
                                    }
                                }

                                if (i == lFieldCount)
                                {
                                    if (drField["FieldOption"].ToString().Trim() != "fz")
                                    {
                                        FieldErrInfo1.strErrorMsg = string.Format(Helper.ErrMsgFormat.ERR_410100001_2, strLayerName, drField["FieldName"].ToString());
                                        pResult.Add(FieldErrInfo1);
                                    }
                                }
                            }
                        }
                        if (pFtCls != null)
                        {
                            Marshal.ReleaseComObject(pFtCls);
                            pFtCls = null;
                        }
                    }
                }

                checkResult = pResult;
            }
            catch (Exception ex)
            {
                SendMessage(enumMessageType.Exception, ex.ToString());
                return(false);
            }

            return(true);
        }
Beispiel #23
0
        /// <summary>
        /// 创建实体表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreateEntiTable_Click(object sender, EventArgs e)
        {
            //显示进度条
            this.labelX1.Visible            = true;
            this.progressBarXEntiDB.Visible = true;

            IWorkspaceFactory2 pWorkspaceFactory = new FileGDBWorkspaceFactoryClass() as IWorkspaceFactory2;
            //20180131
            string path = System.IO.Path.GetDirectoryName(this.txbGdbPath.Text);
            //string entitableName = this.txbEntiName.Text.ToString();
            string entitableName = System.IO.Path.GetFileName(this.txbGdbPath.Text);

            IWorkspace2       pWorkspace       = pWorkspaceFactory.OpenFromFile(path, 0) as IWorkspace2;
            IFeatureWorkspace featureWorkspace = pWorkspace as IFeatureWorkspace;


            IMapControl4         pMainMapControl = ClsControl.MapControlMain;
            IMap                 pMap            = pMainMapControl.Map;
            List <IFeatureLayer> pFeatlayerList  = new List <IFeatureLayer>();

            //把dbf表转换成为ITable
            string dbfPath      = System.IO.Path.GetDirectoryName(this.txbVersionPath.Text);
            string dbfName      = System.IO.Path.GetFileName(this.txbVersionPath.Text);
            ITable versionTable = OpenDBFTable(dbfPath, dbfName);

            int pBarNumberTotal = 0;

            if (pMap != null)
            {
                ClsCommon pClsCommon = new ClsCommon();
                pFeatlayerList = pClsCommon.GetFeatureLayers(pMap);

                ITable entitable = null;

                //如果表存在,就删除数据
                if (pWorkspace.get_NameExists(esriDatasetType.esriDTTable, entitableName))
                {
                    entitable = featureWorkspace.OpenTable(entitableName);
                    //IWorkspaceEdit workspaceEdit = pWorkspace as IWorkspaceEdit;
                    //workspaceEdit.StartEditing(true);
                    //workspaceEdit.StartEditOperation();

                    //ICursor cursor = entitable.Search(null, false);
                    //IRow r = cursor.NextRow();
                    //while (r != null)
                    //{
                    //    r.Delete();
                    //    r = cursor.NextRow();
                    //}
                    //workspaceEdit.StopEditOperation();
                    //workspaceEdit.StopEditing(true);
                }
                //如果表不存在,就创建字段创建表
                else
                {
                    IFields fileds = null;
                    fileds    = CreateEntiTableFields(pWorkspace);
                    entitable = CreateTable(pWorkspace, entitableName, fileds);
                }

                //进度条
                ClsBarSync pBarEntiDB = new ClsBarSync(progressBarXEntiDB);
                pBarEntiDB.SetStep(1);

                foreach (IFeatureLayer pFeatureLay in pFeatlayerList)
                {
                    IFeatureClass pFeatureCls = pFeatureLay.FeatureClass;
                    int           pCount      = pFeatureCls.FeatureCount(null);
                    pBarNumberTotal += pCount;
                    //pBarEntiDB.PerformOneStep();
                }
                pBarEntiDB.SetMax(pBarNumberTotal);
                foreach (IFeatureLayer pFeatureLay in pFeatlayerList)
                {
                    IFeatureClass pFeatureCls     = pFeatureLay.FeatureClass;
                    string        pFeatureLayname = pFeatureLay.Name;
                    FillEntiTable(pFeatureCls, entitable, versionTable, pFeatureLayname, pBarEntiDB);
                    //pBarEntiDB.PerformOneStep();
                }
            }

            //DialogResult dr = MessageBox.Show("内容?", "对话框标题", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            DialogResult dr = MessageBox.Show("实体表创建成功!", "实体表提示信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

            if (dr == DialogResult.OK)
            {
                //点确定的代码
                this.Close();
            }
            else
            {
                //点取消的代码
            }
            //MessageBox.Show("实体表创建成功!");
        }
        private void IsHluLayer(int ixMap, int ixLayer)
        {
            if (_pipeData == null) _pipeData = new List<string>();

            IFeatureLayer hluLayerBak = _hluLayer;
            int[] hluFieldMapBak = _hluFieldMap;
            string[] hluFieldNamesBak = _hluFieldNames;
            IFeatureClass hluFeatureClassBak = _hluFeatureClass;
            IFeatureWorkspace hluWSBak = _hluWS;
            string hluTableNameBak = _hluTableName;
            ISQLSyntax hluSqlSyntaxBak = _hluSqlSyntax;
            string quotePrefixBak = _quotePrefix;
            string quoteSuffixBak = _quoteSuffix;

            _pipeCalling = true;

            _hluLayer = null;

            try
            {
                lock (_pipeData)
                {
                    // clear the pipe
                    _pipeData.Clear();

                    // Get the correct map based on the map number.
                    IMap map = ((IMxDocument)_application.Document).Maps.get_Item(ixMap);

                    UID uid = new UIDClass();
                    uid.Value = typeof(IFeatureLayer).GUID.ToString("B");

                    // Loop through each layer in the map looking for the correct layer
                    // by number (order).
                    int j = 0;
                    IEnumLayer layers = map.get_Layers(uid, true);
                    ILayer layer = layers.Next();
                    while (layer != null)
                    {
                        if (j == ixLayer)
                        {
                            IFeatureLayer featureLayer = layer as IFeatureLayer;
                            if (IsHluLayer(featureLayer))
                            {
                                _hluView = map as IActiveView;
                                _pipeData.Add("true");
                                _pipeData.Add(_pipeTransmissionInterrupt);
                                _pipeData.AddRange(_hluFieldMap.Select(ix => ix.ToString()));
                                _pipeData.Add(_pipeTransmissionInterrupt);
                                _pipeData.AddRange(_hluFieldNames);
                            }
                            else
                            {
                                _pipeData.Add("false");
                            }
                        }
                        layer = layers.Next();
                        j++;
                    }
                }
            }
            catch
            {
                _pipeData.Clear();
            }
            finally
            {
                _pipeCalling = false;
            }

            //---------------------------------------------------------------------
            // CHANGED: CR31 (Switching between GIS layers)
            // Reset the class properties if there has been an error or if
            // the layer is not valid.
            if (_hluLayer == null)
            {
                _hluLayer = hluLayerBak;
                _hluFieldMap = hluFieldMapBak;
                _hluFieldNames = hluFieldNamesBak;
                _hluFeatureClass = hluFeatureClassBak;
                _hluWS = hluWSBak;
                _hluTableName = hluTableNameBak;
                _hluSqlSyntax = hluSqlSyntaxBak;
                _quotePrefix = quotePrefixBak;
                _quoteSuffix = quoteSuffixBak;
            }
            //---------------------------------------------------------------------
        }
        private void OnOpenDocument()
        {
            IDocument document = _docEvents as IDocument;

            _hluWS = null;
            _hluLayer = null;
            _hluFeatureClass = null;
            _hluView = null;
            RemoveActiveViewEvents(_focusMap);
            _focusMap = ((IMxDocument)document).FocusMap;

            if (IsHluWorkspace(((IMxDocument)document).Maps))
                SetupActiveViewEvents(_focusMap);
        }
        public void DuplicatesInOtherWorkspace()
        {
            IDomain domain1 = DomainUtils.AddDomain(_workspace,
                                                    DomainUtils.CreateCodedValueDomain(
                                                        "DOM_FIELD1",
                                                        esriFieldType.esriFieldTypeInteger,
                                                        "Description of DOM_FIELD1",
                                                        new CodedValue(1, "Value 1"),
                                                        new CodedValue(2, "Value 2")));
            IDomain domain2 = DomainUtils.AddDomain(_workspace,
                                                    DomainUtils.CreateCodedValueDomain(
                                                        "DOM_FIELD2",
                                                        esriFieldType.esriFieldTypeInteger,
                                                        "Description of DOM_FIELD2",
                                                        new CodedValue(1, "Value 1"),
                                                        new CodedValue(2, "Value 2")));

            // domain (not used in table) with duplicate name - this should not be reported since duplicates are searched in target (?)
            DomainUtils.AddDomain(_workspace,
                                  DomainUtils.CreateCodedValueDomain("DOM_FIELD3",
                                                                     esriFieldType
                                                                     .esriFieldTypeInteger,
                                                                     "Description of DOM_FIELD2",
                                                                     new CodedValue(1,
                                                                                    "Value 1"),
                                                                     new CodedValue(2,
                                                                                    "Value 2")));

            IField field1 = FieldUtils.CreateField("FIELD1", esriFieldType.esriFieldTypeInteger);
            IField field2 = FieldUtils.CreateField("FIELD2", esriFieldType.esriFieldTypeInteger);
            IField field3 = FieldUtils.CreateTextField("FIELD3", 20);

            ((IFieldEdit)field1).Domain_2 = domain1;
            ((IFieldEdit)field2).Domain_2 = domain2;

            ITable table = DatasetUtils.CreateTable(_workspace,
                                                    MethodBase.GetCurrentMethod().Name,
                                                    FieldUtils.CreateOIDField(),
                                                    field1, field2, field3);

            // add domains/table to target workspace

            IFeatureWorkspace targetWorkspace =
                TestWorkspaceUtils.CreateTestFgdbWorkspace($"{GetType().Name}_target");

            // same name, same description --> should be considered equal, no duplicate
            DomainUtils.AddDomain(targetWorkspace,
                                  DomainUtils.CreateCodedValueDomain("DOM_FIELD1",
                                                                     esriFieldType
                                                                     .esriFieldTypeInteger,
                                                                     "Description of DOM_FIELD1",
                                                                     new CodedValue(1,
                                                                                    "Value 1"),
                                                                     new CodedValue(2,
                                                                                    "Value 2")));

            // different name, same description --> should be reported
            DomainUtils.AddDomain(targetWorkspace,
                                  DomainUtils.CreateCodedValueDomain("DOM_FIELD4",
                                                                     esriFieldType
                                                                     .esriFieldTypeInteger,
                                                                     "Description of DOM_FIELD2",
                                                                     new CodedValue(1,
                                                                                    "Value 1"),
                                                                     new CodedValue(2,
                                                                                    "Value 2")));

            // different name, same description --> should be reported
            DomainUtils.AddDomain(targetWorkspace,
                                  DomainUtils.CreateRangeDomain("DOM_FIELD5",
                                                                esriFieldType.esriFieldTypeInteger,
                                                                0, 100,
                                                                "Description of DOM_FIELD2"));

            ITable targetTable = DatasetUtils.CreateTable(targetWorkspace,
                                                          MethodBase.GetCurrentMethod().Name,
                                                          FieldUtils.CreateOIDField(),
                                                          FieldUtils.CreateTextField("FIELD1",
                                                                                     10));

            const int  maxLength    = 25;
            const bool noDuplicates = true;
            var        runner       =
                new QaTestRunner(new QaSchemaFieldDomainDescriptions(table, maxLength,
                                                                     noDuplicates,
                                                                     targetTable));

            runner.Execute();

            Assert.AreEqual(1, runner.Errors.Count);
        }
Beispiel #27
0
        private void TestConnectSDEData(string server, string instance,string database, string user, string password, string version)
        {
            try
            {
                m_pWorkspaceFactory = new  SdeWorkspaceFactoryClass();
                m_pPropSet = new PropertySetClass();
                //���ãӣģ�����������Ϣ
                m_pPropSet.SetProperty("SERVER", server);
                m_pPropSet.SetProperty("INSTANCE", instance);
                m_pPropSet.SetProperty("Database", database);
                m_pPropSet.SetProperty("User", user);
                m_pPropSet.SetProperty("password", password);
                m_pPropSet.SetProperty("version", version);
                m_pWorkspace = m_pWorkspaceFactory.Open(m_pPropSet, 0);
                m_pFeatureWorkspace = m_pWorkspace as  IFeatureWorkspace;
                /////////////////////////////////////////////////////////
                IEnumDatasetName pEnumDSName = m_pWorkspace.get_DatasetNames(esriDatasetType.esriDTFeatureDataset);
                IDatasetName pSDEDsName = pEnumDSName.Next();
                treeView1.Nodes.Clear();
                TreeNode node1;
                while (pSDEDsName != null)
                {
                    node1=treeView1.Nodes.Add(pSDEDsName.Name);
                    LoadAllFeatClass(node1,pSDEDsName.Name );
                    pSDEDsName = pEnumDSName.Next();
                }

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

            }
        }
 public void Setup()
 {
     _workspace = TestWorkspaceUtils.CreateTestFgdbWorkspace(GetType().Name);
 }
        public static List<string> GetAllExpressDesigns()
        {
            ICursor cur = null;
            ICursor cur2 = null;
            ICursor cur3 = null;
            List<string> designNames = new List<string>();
            List<DesignFeature> designFeatures = new List<DesignFeature>();
            HashSet<int> expressFeatureDesignsIds = new HashSet<int>();
            try {
                IWorkspaceFactory wsf = new SdeWorkspaceFactoryClass();
                var ws = wsf.OpenFromFile(Common.GetConfiguration("SDEConnectionFile"), 0);
                _fws = ws as IFeatureWorkspace;
                IFeatureWorkspaceManage2 fwsm2 = (IFeatureWorkspaceManage2)_fws;
                Workspace = fwsm2;
                var qd = _fws.CreateQueryDef();
                qd.Tables = "schneiderville.sde.mm_express_features";
                cur = qd.Evaluate();
                IRow r = cur.NextRow();
                Dictionary<int, string> IdToClassName = new Dictionary<int, string>();
                while (r != null)
                {
                    DesignFeature df = new DesignFeature();
                    df.ExpressFeatureDesignID = Convert.ToInt32( r.get_Value(r.Fields.FindField("DESIGNID")));
                    df.FeatureOID = Convert.ToInt32(r.get_Value(r.Fields.FindField("FEATUREOID")));
                    df.FeatureClassID = Convert.ToInt32(r.get_Value(r.Fields.FindField("FEATURECLASSID")));
                    if (IdToClassName.ContainsKey(df.FeatureClassID) == false)
                    {
                        string className = fwsm2.GetObjectClassNameByID(df.FeatureClassID);
                        IdToClassName.Add(df.FeatureClassID, className);
                    }
                    designFeatures.Add(df);
                    if (expressFeatureDesignsIds.Contains(df.ExpressFeatureDesignID) == false)
                    {
                        expressFeatureDesignsIds.Add(df.ExpressFeatureDesignID);
                        var qd2 = _fws.CreateQueryDef();
                        qd2.Tables = "schneiderville.SDE.mm_express_designs";
                        qd2.WhereClause = "OBJECTID = " + df.ExpressFeatureDesignID;
                        qd2.SubFields= "OBJECTID,DESIGNID";
                        cur2 = qd2.Evaluate();
                        IRow r2 = cur2.NextRow();
                        if (r2 != null)
                        {

                            int wmsDesignOID = Convert.ToInt32(r2.get_Value(r2.Fields.FindField("DESIGNID")));
                            var qd3 = _fws.CreateQueryDef();
                            qd3.Tables = "schneiderville.process.mm_wms_design";
                            qd3.WhereClause = "ID = " + wmsDesignOID;
                            qd3.SubFields = "ID,NAME";
                            cur3 = qd3.Evaluate();
                            IRow r3 = cur3.NextRow();
                            if (r3 != null)
                            {
                                string designName = r3.get_Value(r3.Fields.FindField("NAME")).ToString();
                                designNames.Add(designName + " (" + df.ExpressFeatureDesignID + ")"); //Express Design ID in parentheses
                            }
                        }
                        try {

                            Marshal.FinalReleaseComObject(cur2);
                            Marshal.FinalReleaseComObject(cur3);
                        }
                        catch { }
                    }
                    r = cur.NextRow();
                }
                GetNameByID = IdToClassName;
                _designFeatures = designFeatures;
                return designNames;
            }
            finally {
                Marshal.FinalReleaseComObject(cur);
            }
        }
        private IFeatureClass CreateFeatureClassFromGeometry(IGeometry pGeometry, IFeatureWorkspace pOutFeatWorkspace, int wkid)
        {
            // thanks to http://bcdcspatial.blogspot.co.uk/2011/12/some-random-arcobjects-that-make.html
            // which was the only place i could find an answer to the problem I was having - the last
            // argument to createfeatureclass is null NOT an empty string
            try
            {
                IFields tFields = new FieldsClass() as IFields;
                IFieldsEdit tFieldsEdit = (IFieldsEdit)tFields;
                IField tShpFld = new Field();
                IFieldEdit tShpEd = (IFieldEdit)tShpFld;
                tShpEd.Type_2 = esriFieldType.esriFieldTypeGeometry;
                tShpEd.Name_2 = "Shape";

                IGeometryDef tGeomDef = new GeometryDef();
                IGeometryDefEdit tGdEdit = (IGeometryDefEdit)tGeomDef;
                tGdEdit.GeometryType_2 = pGeometry.GeometryType;

                ISpatialReferenceFactory2 tSRFac = new SpatialReferenceEnvironment() as ISpatialReferenceFactory2;
                ISpatialReference tSpatRef = tSRFac.CreateSpatialReference(wkid);
                ISpatialReferenceResolution tSpatRefRes = (ISpatialReferenceResolution)tSpatRef;
                tSpatRefRes.ConstructFromHorizon();

                tGdEdit.SpatialReference_2 = tSpatRef;
                tShpEd.GeometryDef_2 = tGeomDef;
                tFieldsEdit.AddField(tShpFld);

                IObjectClassDescription tOCDesc = new FeatureClassDescription();
                for (int i = 0; i < tOCDesc.RequiredFields.FieldCount; i++)
                {
                    IField tField = tOCDesc.RequiredFields.get_Field(i);
                    if (tFieldsEdit.FindField(tField.Name) == -1)
                    {
                        tFieldsEdit.AddField(tField);
                    }
                }
                string tFCName = "tmp" + Guid.NewGuid().ToString("N");
                IFeatureClass tFC = pOutFeatWorkspace.CreateFeatureClass(
                    tFCName, tFields, null, null, esriFeatureType.esriFTSimple, "Shape", null);
                IFeature tGeomAsFeature = tFC.CreateFeature();
                tGeomAsFeature.Shape = pGeometry;
                tGeomAsFeature.Store();
                return tFC;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                logger.LogMessage(ServerLogger.msgType.error, "CreateFeatureClassFromGeometry", 99,
                              "Could not create feature class " + e.Message + e.Source + e.StackTrace);
                throw e;

            }
        }
Beispiel #31
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="featureClassName"></param>
        /// <param name="classExtensionUID"></param>
        /// <param name="featureWorkspace"></param>
        /// <returns></returns>
        public IFeatureClass CreateFeatureClassToAccessDB(string featureClassName, UID classExtensionUID, IFeatureWorkspace featureWorkspace)
        {
            //创建字段集合
            IFields     pFields     = new FieldsClass();
            IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields;

            //定义单个的字段
            IField     pField     = new FieldClass();
            IFieldEdit pFieldEdit = (IFieldEdit)pField;

            pFieldEdit.Name_2 = "OID";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
            pFieldsEdit.AddField(pField);
            //为要素类创建几何定义和空间参考
            IGeometryDef     geometryDef = new GeometryDefClass();
            IGeometryDefEdit pGeoDefEdit = geometryDef as IGeometryDefEdit;

            pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;  //指定创建的要素类的要素类型
            ISpatialReferenceFactory    spatialReferenceFactory    = new SpatialReferenceEnvironmentClass();
            ISpatialReference           spatialReference           = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_Beijing1954);
            ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference;

            spatialReferenceResolution.ConstructFromHorizon();
            ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference;

            spatialReferenceTolerance.SetDefaultXYTolerance();

            pGeoDefEdit.SpatialReference_2 = spatialReference;  //设置要素类的空间参考
            //将几何字段添加到字段集合
            IField     geometryField     = new FieldClass();
            IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField;

            geometryFieldEdit.Name_2        = "shape";
            geometryFieldEdit.Type_2        = esriFieldType.esriFieldTypeGeometry;
            geometryFieldEdit.GeometryDef_2 = geometryDef;
            pFieldsEdit.AddField(geometryField);
            //创建字段name
            IField     nameField     = new FieldClass();
            IFieldEdit nameFieldEdit = (IFieldEdit)nameField;

            nameFieldEdit.Name_2   = "Name";
            nameFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            nameFieldEdit.Length_2 = 20;
            pFieldsEdit.AddField(nameField);
            IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(featureClassName, pFields, null, classExtensionUID, esriFeatureType.esriFTSimple, "Shape", "");

            return(featureClass);
        }
Beispiel #32
0
        void ILandpriceView.LoadPrice()
        {
            if (_conn == null)
            {
                _conn = new SdeConnection();
                _sdeConn = (ISdeConnectionInfo)_conn;
                _fw = (IFeatureWorkspace)_sdeConn.Workspace;
                _fcName = new TnFeatureClassName(_sdeConn.Workspace);
                _tblName = new TnTableName(_sdeConn.Workspace);

            }
            //MessageBox.Show(string.Format("line 122 GLandPriceView layerCount={0}", _mapView.GetMapControl().LayerCount));
            //if (_mapView.GetMapControl().LayerCount == 0)
            //{
            //    MessageBox.Show(string.Format("line 125 GLandPriceView layerCount={0}", _mapView.GetMapControl().LayerCount));
            //    _tgdName = string.Format("{0}_{1}", DataNameTemplate.Thua_Gia_Dat, _conf.NamApDung);
            //    IFeatureClass fc = _fw.OpenFeatureClass(_tgdName);
            //    IFeatureLayer fl = new FeatureLayerClass();
            //    fl.FeatureClass = fc;
            //    fl.Name = fc.AliasName;
            //    ILayer layer = (ILayer)fl;
            //    _mapView.AddLayer(layer);
            //}

            _controller.LoadPrice();
        }
Beispiel #33
0
        /// <summary>
        /// Occurs when this command is clicked
        /// </summary>
        public override void OnClick()
        {
            // TODO: Add ShortPathSolveCommand.OnClick implementation
            //string name = NetWorkAnalysClass.getPath(path) + "\\data\\HuanbaoGeodatabase.gdb";
            string            name        = NetWorkAnalysClass.getPath(path) + "\\Data\\TestNet.gdb";
            IFeatureWorkspace pFWorkspace = NetWorkAnalysClass.OpenWorkspace(name) as IFeatureWorkspace;

            //"RouteNetwork", "BaseData"参数不可更改
            networkDataset = NetWorkAnalysClass.OpenPathNetworkDataset(pFWorkspace as IWorkspace, "NetWork_wy_ND", "NetWork_wy");
            m_NAContext    = NetWorkAnalysClass.CreatePathSolverContext(networkDataset);
            //通过网络数据集创建网络分析上下文
            //打开要素数据集
            inputFClass   = pFWorkspace.OpenFeatureClass("Stops");
            barriesFClass = pFWorkspace.OpenFeatureClass("Barries");
            if (IfLayerExist("NetworkDataset") == false)
            {
                ILayer        layer;
                INetworkLayer networkLayer;
                networkLayer = new NetworkLayerClass();
                networkLayer.NetworkDataset = networkDataset;
                layer      = networkLayer as ILayer;
                layer.Name = "NetworkDataset";
                m_hookHelper.ActiveView.FocusMap.AddLayer(layer);
                layer.Visible = false;
            }
            if (IfLayerExist(m_NAContext.Solver.DisplayName) == true)
            {
                for (int i = 0; i < m_hookHelper.FocusMap.LayerCount; i++)
                {
                    if (m_hookHelper.FocusMap.get_Layer(i).Name == m_NAContext.Solver.DisplayName)
                    {
                        m_hookHelper.FocusMap.DeleteLayer(m_hookHelper.FocusMap.get_Layer(i));
                    }
                }
            }
            INALayer naLayer = m_NAContext.Solver.CreateLayer(m_NAContext);
            ILayer   pLayer  = naLayer as ILayer;

            pLayer.Name = m_NAContext.Solver.DisplayName;
            m_hookHelper.ActiveView.FocusMap.AddLayer(pLayer);
            if (inputFClass.FeatureCount(null) < 2)
            {
                MessageBox.Show("只有一个站点,不能进行路径分析!");
                return;
            }
            IGPMessages gpMessages = new GPMessagesClass();

            //加载站点要素,并设置容差
            NetWorkAnalysClass.LoadNANetworkLocations("Stops", inputFClass, m_NAContext, 50);
            //加载障碍点要素,并设置容差
            NetWorkAnalysClass.LoadNANetworkLocations("Barriers", barriesFClass, m_NAContext, 5);
            INASolver naSolver = m_NAContext.Solver;//创建网络分析对象

            try
            {
                naSolver.Solve(m_NAContext, gpMessages, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("未能找到有效路径" + ex.Message, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                return;
            }
            for (int i = 0; i < m_hookHelper.FocusMap.LayerCount; i++)
            {
                if (m_hookHelper.FocusMap.get_Layer(i).Name == m_NAContext.Solver.DisplayName)
                {
                    ICompositeLayer pCompositeLayer = m_hookHelper.FocusMap.get_Layer(i) as ICompositeLayer;
                    {
                        for (int t = 0; t < pCompositeLayer.Count; t++)
                        {
                            ILayer pResultLayer = pCompositeLayer.get_Layer(t);
                            if (pResultLayer.Name == "Stops" || pResultLayer.Name == "Barriers")
                            {
                                pResultLayer.Visible = false;
                                continue;
                            }
                        }
                    }
                }
            }
            IGeoDataset geoDataset;
            IEnvelope   envelope;

            geoDataset = m_NAContext.NAClasses.get_ItemByName("Routes") as IGeoDataset;
            envelope   = geoDataset.Extent;
            if (!envelope.IsEmpty)
            {
                envelope.Expand(1.1, 1.1, true);
            }
            m_hookHelper.ActiveView.Extent = envelope;
            m_hookHelper.ActiveView.Refresh();
        }
        private IWorkspaceEdit StartEditingWorkspace(IFeatureWorkspace editWS)
        {
            IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)editWS;
            IMultiuserWorkspaceEdit multiUserWSEdit = editWS as IMultiuserWorkspaceEdit;
            if (multiUserWSEdit != null)
            {
                if (multiUserWSEdit.SupportsMultiuserEditSessionMode(esriMultiuserEditSessionMode.esriMESMNonVersioned))
                    multiUserWSEdit.StartMultiuserEditing(esriMultiuserEditSessionMode.esriMESMNonVersioned);
                else if (multiUserWSEdit.SupportsMultiuserEditSessionMode(esriMultiuserEditSessionMode.esriMESMVersioned))
                    multiUserWSEdit.StartMultiuserEditing(esriMultiuserEditSessionMode.esriMESMVersioned);
                else
                    throw new Exception("Cannot start multiuser editing session");
            }
            else
            {
                workspaceEdit.StartEditing(true);
            }
            workspaceEdit.StartEditOperation();

            return workspaceEdit;
        }
Beispiel #35
0
        //added by chulili 20110802褚丽丽添加函数,根据nodeKey获取地物类,直接读取数据源连接信息,读取地物类
        public static IFeatureClass GetFeatureClassByNodeKey(string strNodeKey)
        {
            if (strNodeKey.Equals(""))
            {
                return(null);
            }
            //目录树路径变量:_layerTreePath
            XmlDocument pXmldoc = new XmlDocument();

            if (!File.Exists(_layerTreePath))
            {
                SysCommon.ModSysSetting.CopyLayerTreeXmlFromDataBase(Plugin.ModuleCommon.TmpWorkSpace, _layerTreePath);
            }
            else
            {
                File.Delete(_layerTreePath);
                SysCommon.ModSysSetting.CopyLayerTreeXmlFromDataBase(Plugin.ModuleCommon.TmpWorkSpace, _layerTreePath);
            }
            if (!File.Exists(_layerTreePath))
            {
                return(null);
            }
            //打开展示图层树,获取图层节点
            pXmldoc.Load(_layerTreePath);
            string  strSearch = "//Layer[@NodeKey=" + "'" + strNodeKey + "'" + "]";
            XmlNode pNode     = pXmldoc.SelectSingleNode(strSearch);

            if (pNode == null)
            {
                return(null);
            }
            //获取图层名,数据源id
            string strFeaClassName = "";
            string strDBSourceID   = "";

            try
            {
                strFeaClassName = pNode.Attributes["Code"].Value;
                strDBSourceID   = pNode.Attributes["ConnectKey"].Value;
            }
            catch
            { }
            //根据数据源id,获取数据源信息
            SysGisTable sysTable    = new SysGisTable(Plugin.ModuleCommon.TmpWorkSpace);
            Exception   eError      = null;
            object      objConnstr  = sysTable.GetFieldValue("DATABASEMD", "CONNECTIONINFO", "ID=" + strDBSourceID, out eError);
            string      conninfostr = "";

            if (objConnstr != null)
            {
                conninfostr = objConnstr.ToString();
            }
            object objType = sysTable.GetFieldValue("DATABASEMD", "DATAFORMATID", "ID=" + strDBSourceID, out eError);
            int    type    = -1;

            if (objType != null)
            {
                type = int.Parse(objType.ToString());
            }
            //根据数据源连接信息,获取数据源连接
            IWorkspace pWorkspace = GetWorkSpacefromConninfo(conninfostr, type);

            if (pWorkspace == null)
            {
                return(null);
            }
            //打开地物类
            IFeatureWorkspace pFeaWorkSpace = pWorkspace as IFeatureWorkspace;
            IFeatureClass     pFeaClass     = null;

            try
            {
                pFeaClass = pFeaWorkSpace.OpenFeatureClass(strFeaClassName);
            }
            catch
            { }
            if (File.Exists(_layerTreePath))
            {
                File.Delete(_layerTreePath);
            }
            return(pFeaClass);
        }
        /// <summary>
        /// Determines whether at least one of the layers in all the maps is an HLU layer
        /// and returns the field mapping of the first HLU layer found, plus a list of all
        /// the HLU layers found.
        /// Triggered from ArcMapApp after the required document has been opened.
        /// </summary>
        /// <param></param>
        /// <returns></returns>
        public void IsHluWorkspace()
        {
            IFeatureLayer hluLayerBak = _hluLayer;
            int[] hluFieldMapBak = _hluFieldMap;
            string[] hluFieldNamesBak = _hluFieldNames;
            IFeatureClass hluFeatureClassBak = _hluFeatureClass;
            IFeatureWorkspace hluWSBak = _hluWS;
            string hluTableNameBak = _hluTableName;
            ISQLSyntax hluSqlSyntaxBak = _hluSqlSyntax;
            string quotePrefixBak = _quotePrefix;
            string quoteSuffixBak = _quoteSuffix;

            _pipeCalling = true;

            if (_pipeData == null) _pipeData = new List<string>();

            try
            {
                lock (_pipeData)
                {
                    // clear the pipe
                    _pipeData.Clear();

                    _hluLayer = null;
                    IMaps maps = ((IMxDocument)_application.Document).Maps;
                    IMap map = null;

                    UID uid = new UIDClass();
                    uid.Value = typeof(IFeatureLayer).GUID.ToString("B");

                    for (int i = 0; i < maps.Count; i++)
                    {
                        map = maps.get_Item(i);
                        int j = 0;
                        IEnumLayer layers = map.get_Layers(uid, true);
                        ILayer layer = layers.Next();
                        while (layer != null)
                        {
                            //---------------------------------------------------------------------
                            // CHANGED: CR19 (Feature layer position in GIS)
                            // Only check geofeature layers in the document (to see if they are
                            // valid HLU layers) to save having to check layers (e.g. coverage
                            // annotation layers) that can't possibly be valid.
                            if (layer is IGeoFeatureLayer)
                            {
                                IFeatureLayer featureLayer = layer as IFeatureLayer;
                                if (IsHluLayer(featureLayer))
                                {
                                    _hluView = map as IActiveView;
                                    // Return details of the first valid HLU layer found (the map number,
                                    // map name, layer number, field indexes and field names).
                                    _pipeData.AddRange(new string[] { i.ToString(), map.Name, j.ToString() });
                                    _pipeData.Add(_pipeTransmissionInterrupt);
                                    _pipeData.AddRange(_hluFieldMap.Select(ix => ix.ToString()));
                                    _pipeData.Add(_pipeTransmissionInterrupt);
                                    _pipeData.AddRange(_hluFieldNames);
                                    return;
                                }
                            }
                            //---------------------------------------------------------------------
                            layer = layers.Next();
                            j++;
                        }
                    }
                }
            }
            catch { }
            finally
            {
                _pipeCalling = false;
                _hluLayer = hluLayerBak;
                _hluFieldMap = hluFieldMapBak;
                _hluFieldNames = hluFieldNamesBak;
                _hluFeatureClass = hluFeatureClassBak;
                _hluWS = hluWSBak;
                _hluTableName = hluTableNameBak;
                _hluSqlSyntax = hluSqlSyntaxBak;
                _quotePrefix = quotePrefixBak;
                _quoteSuffix = quoteSuffixBak;
            }
        }
Beispiel #37
0
        //元素方式
        //private void addGeometryEle(IPolygon pPolygon)
        //{
        //    ISimpleFillSymbol pFillSymbol = new SimpleFillSymbolClass();
        //    ISimpleLineSymbol pLineSymbol = new SimpleLineSymbolClass();
        //    IPolygonElement pPolygonEle = new PolygonElementClass();
        //    try
        //    {
        //        //颜色对象
        //        IRgbColor pRGBColor = new RgbColorClass();
        //        pRGBColor.UseWindowsDithering = false;
        //        ISymbol pSymbol = (ISymbol)pFillSymbol;
        //        pSymbol.ROP2 = esriRasterOpCode.esriROPNotXOrPen;

        //        pRGBColor.Red = 255;
        //        pRGBColor.Green = 170;
        //        pRGBColor.Blue = 0;
        //        pLineSymbol.Color = pRGBColor;

        //        pLineSymbol.Width = 0.8;
        //        pLineSymbol.Style = esriSimpleLineStyle.esriSLSSolid;
        //        pFillSymbol.Outline = pLineSymbol;

        //        pFillSymbol.Color = pRGBColor;
        //        pFillSymbol.Style = esriSimpleFillStyle.esriSFSDiagonalCross;

        //        IElement pEle = pPolygonEle as IElement;
        //        pEle.Geometry = pPolygon as IGeometry;
        //        pEle.Geometry.SpatialReference = pPolygon.SpatialReference;
        //        (pEle as IFillShapeElement).Symbol = pFillSymbol;
        //        (pEle as IElementProperties).Name="ImpExtentOutMap";
        //        (m_Hook.ArcGisMapControl.Map as IGraphicsContainer).AddElement(pEle, 0);
        //        (m_Hook.ArcGisMapControl.Map as IActiveView).PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);

        //        IGraphicsContainer pGra = m_Hook.ArcGisMapControl.Map as IGraphicsContainer;
        //        IActiveView pAv = pGra as IActiveView;
        //        pGra.Reset();
        //        IElement pEle2 = pGra.Next();
        //        while (pEle2 != null)
        //        {
        //            if ((pEle2 as IElementProperties).Name == "ImpExtentOutMap")
        //            {
        //                //pGra.DeleteElement(pEle);

        //                //pGra.Reset();
        //            }
        //            pEle2 = pGra.Next();
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show("绘制导入范围出错:" + ex.Message, "提示");
        //        pFillSymbol = null;
        //    }
        //}

        #region
        /// <summary>
        /// 从文件路径获得一个PolyGon
        /// </summary>
        /// <param name="path">文件全路径</param>
        /// <returns></returns>
        private IPolygon GetPolyGonFromFile(string path)
        {
            IPolygon pGon = null;

            if (path.EndsWith(".mdb"))
            {
                string            errmsg       = "";
                IWorkspaceFactory pwf          = new AccessWorkspaceFactoryClass();
                IWorkspace        pworkspace   = pwf.OpenFromFile(path, 0);
                IEnumDataset      pEnumdataset = pworkspace.get_Datasets(esriDatasetType.esriDTFeatureClass);
                pEnumdataset.Reset();
                IDataset pDataset = pEnumdataset.Next();
                while (pDataset != null)
                {
                    IFeatureClass pFeatureclass = pDataset as IFeatureClass;
                    if (pFeatureclass.ShapeType != esriGeometryType.esriGeometryPolygon && pFeatureclass.ShapeType != esriGeometryType.esriGeometryPolyline)
                    {
                        pDataset = pEnumdataset.Next();
                        continue;
                    }
                    else if (pFeatureclass.ShapeType == esriGeometryType.esriGeometryPolygon)
                    {
                        IFeatureCursor pCursor  = pFeatureclass.Search(null, false);
                        IFeature       pFeature = pCursor.NextFeature();
                        if (pFeature != null)
                        {
                            pGon = pFeature.Shape as IPolygon;
                            break;
                        }
                        else
                        {
                            pDataset = pEnumdataset.Next();
                            continue;
                        }
                    }
                    else if (pFeatureclass.ShapeType == esriGeometryType.esriGeometryPolyline)
                    {
                        IFeatureCursor pCursor  = pFeatureclass.Search(null, false);
                        IFeature       pFeature = pCursor.NextFeature();
                        if (pFeature != null)
                        {
                            IPolyline pPolyline = pFeature.Shape as IPolyline;
                            pGon = GetPolygonFormLine(pPolyline);
                            if (pGon.IsClosed == false)
                            {
                                errmsg   = "选择的要素不能构成封闭多边形!";
                                pGon     = null;
                                pDataset = pEnumdataset.Next();
                                continue;
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
                if (pGon == null)
                {
                    IEnumDataset pEnumdataset1 = pworkspace.get_Datasets(esriDatasetType.esriDTFeatureDataset);
                    pEnumdataset1.Reset();
                    pDataset = pEnumdataset1.Next();
                    while (pDataset != null)
                    {
                        IFeatureDataset pFeatureDataset = pDataset as IFeatureDataset;
                        IEnumDataset    pEnumDataset2   = pFeatureDataset.Subsets;
                        pEnumDataset2.Reset();
                        IDataset pDataset1 = pEnumDataset2.Next();
                        while (pDataset1 != null)
                        {
                            if (pDataset1 is IFeatureClass)
                            {
                                IFeatureClass pFeatureclass = pDataset1 as IFeatureClass;
                                if (pFeatureclass.ShapeType != esriGeometryType.esriGeometryPolygon && pFeatureclass.ShapeType != esriGeometryType.esriGeometryPolyline)
                                {
                                    pDataset1 = pEnumDataset2.Next();
                                    continue;
                                }
                                else if (pFeatureclass.ShapeType == esriGeometryType.esriGeometryPolygon)
                                {
                                    IFeatureCursor pCursor  = pFeatureclass.Search(null, false);
                                    IFeature       pFeature = pCursor.NextFeature();
                                    if (pFeature != null)
                                    {
                                        pGon = pFeature.Shape as IPolygon;
                                        break;
                                    }
                                    else
                                    {
                                        pDataset1 = pEnumDataset2.Next();
                                        continue;
                                    }
                                }
                                else if (pFeatureclass.ShapeType == esriGeometryType.esriGeometryPolyline)
                                {
                                    IFeatureCursor pCursor  = pFeatureclass.Search(null, false);
                                    IFeature       pFeature = pCursor.NextFeature();
                                    if (pFeature != null)
                                    {
                                        IPolyline pPolyline = pFeature.Shape as IPolyline;
                                        pGon = GetPolygonFormLine(pPolyline);
                                        if (pGon.IsClosed == false)
                                        {
                                            errmsg    = "选择的要素不能构成封闭多边形!";
                                            pGon      = null;
                                            pDataset1 = pEnumDataset2.Next();
                                            continue;
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        if (pGon != null)
                        {
                            break;
                        }
                        pDataset = pEnumdataset1.Next();
                    }
                }
                if (pGon == null)
                {
                    if (errmsg != "")
                    {
                        MessageBox.Show(errmsg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("请选择一个包含面要素和线要素的文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    return(pGon);
                }
            }
            else if (path.EndsWith(".shp"))
            {
                IWorkspaceFactory pwf               = new ShapefileWorkspaceFactoryClass();
                string            filepath          = System.IO.Path.GetDirectoryName(path);
                string            filename          = path.Substring(path.LastIndexOf("\\") + 1);
                IFeatureWorkspace pFeatureworkspace = (IFeatureWorkspace)pwf.OpenFromFile(filepath, 0);
                IFeatureClass     pFeatureclass     = pFeatureworkspace.OpenFeatureClass(filename);
                if (pFeatureclass.ShapeType == esriGeometryType.esriGeometryPolygon)
                {
                    IFeatureCursor pCursor  = pFeatureclass.Search(null, false);
                    IFeature       pFeature = pCursor.NextFeature();
                    if (pFeature != null)
                    {
                        pGon = pFeature.Shape as IPolygon;
                    }
                }
                else if (pFeatureclass.ShapeType == esriGeometryType.esriGeometryPolyline)
                {
                    IFeatureCursor pCursor  = pFeatureclass.Search(null, false);
                    IFeature       pFeature = pCursor.NextFeature();
                    if (pFeature != null)
                    {
                        IPolyline pPolyline = pFeature.Shape as IPolyline;
                        pGon = GetPolygonFormLine(pPolyline);
                        if (pGon.IsClosed == false)
                        {
                            MessageBox.Show("选择的线要素不能构成封闭多边形!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return(null);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("请选择一个面或者线要素文件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return(null);
                }
            }
            else if (path.EndsWith(".txt"))
            {
                string txtpath = path;
                System.IO.StreamReader smRead = new System.IO.StreamReader(txtpath, System.Text.Encoding.Default); //设置路径
                string line;

                IPointCollection pc = pGon as IPointCollection;
                double           x, y;
                while ((line = smRead.ReadLine()) != null)
                {
                    if (line.IndexOf(",") > 0)
                    {
                        try
                        {
                            x = double.Parse(line.Substring(0, line.IndexOf(",")));
                            y = double.Parse(line.Substring(line.IndexOf(",") + 1));
                        }
                        catch
                        {
                            MessageBox.Show("文本文件格式不正确!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            smRead.Close();
                            return(null);
                        }
                        IPoint tmpPoint = new ESRI.ArcGIS.Geometry.Point();
                        tmpPoint.X = x;
                        tmpPoint.Y = y;
                        object ep = System.Reflection.Missing.Value;

                        pc.AddPoint(tmpPoint, ref ep, ref ep);
                    }
                }
                smRead.Close();
                ICurve pCurve = pGon as ICurve;
                if (pCurve.IsClosed == false)
                {
                    if (pCurve.IsClosed == false)
                    {
                        //自动闭合
                        IPolygon2 pPolygon2 = pGon as IPolygon2;
                        pPolygon2.Close();
                    }
                }
            }
            return(pGon);
        }
Beispiel #38
0
        private void buttonX_ok_Click(object sender, EventArgs e)
        {
            //add all point
            List <IPoint> pointList = new List <IPoint>();

            Microsoft.Office.Interop.Excel.Application myExcel = new Microsoft.Office.Interop.Excel.Application();
            object missing = System.Reflection.Missing.Value;

            myExcel.Application.Workbooks.Open(textBoxX1.Text, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); //this.txtFile.Text为Excel文件的全路径
            Microsoft.Office.Interop.Excel.Workbook myBook = myExcel.Workbooks[1];

            //获取第一个Sheet
            Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)myBook.Sheets[1];
            string sheetName = sheet.Name; //Sheet名

            myBook.Close(Type.Missing, Type.Missing, Type.Missing);
            myExcel.Quit();

            //read excel file to creat Field
            string          strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + this.textBoxX1.Text + ";Extended Properties=Excel 8.0";
            OleDbConnection conn   = new OleDbConnection(strCon);
            string          sql1   = string.Format("select * from [{0}$]", sheetName);

            conn.Open();

            OleDbDataAdapter myCommand = new OleDbDataAdapter(sql1, strCon);
            DataSet          ds        = new DataSet();

            myCommand.Fill(ds);
            conn.Close();

            int xIndex = 0;
            int yIndex = 0;
            int zIndex = 0;

            for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
            {
                if (ds.Tables[0].Columns[i].ColumnName == "X_经度")
                {
                    xIndex = i;
                }
                if (ds.Tables[0].Columns[i].ColumnName == "Y_纬度")
                {
                    yIndex = i;
                }
                if (ds.Tables[0].Columns[i].ColumnName.Contains("Z_高程"))
                {
                    zIndex = i;
                }
            }

            ISpatialReference pSpaReference = new UnknownCoordinateSystemClass();

            pSpaReference.SetDomain(-8000000, 8000000, -800000, 8000000);
            IFeatureClass pFt = CreateShapeFile(ds, this.textBoxX2.Text, pSpaReference);

            if (pFt == null)
            {
                return;
            }
            else
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    //根据XY坐标添加点,edit attribute
                    IsNumberic isNum = new IsNumberic();
                    ESRI.ArcGIS.Geometry.IPoint pPoint = new ESRI.ArcGIS.Geometry.PointClass();
                    if (ds.Tables[0].Rows[i][xIndex].ToString() == "" || ds.Tables[0].Rows[i][xIndex].ToString() == " ")
                    {
                        break;
                    }
                    if (isNum.IsNumber(ds.Tables[0].Rows[i][xIndex].ToString()) && isNum.IsNumber(ds.Tables[0].Rows[i][yIndex].ToString()))
                    {
                        pPoint.X = System.Convert.ToSingle(ds.Tables[0].Rows[i][xIndex].ToString());
                        pPoint.Y = System.Convert.ToSingle(ds.Tables[0].Rows[i][yIndex].ToString());
                        pPoint.Z = System.Convert.ToSingle(ds.Tables[0].Rows[i][zIndex].ToString());
                        IFeature pFeature = pFt.CreateFeature();
                        pFeature.Shape = pPoint;

                        pFeature.Store();
                        for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                        {
                            if (ds.Tables[0].Columns[j].ColumnName.Contains("里程"))
                            {
                                continue;
                            }
                            //pFeature.set_Value(pFeature.Fields.FindField(ds.Tables[0].Columns[j].ColumnName), ds.Tables[0].Rows[i][j]);
                            pFeature.set_Value(j + 2, ds.Tables[0].Rows[i][j].ToString());
                        }
                        pFeature.Store();

                        pointList.Add(pPoint);
                    }
                    else
                    {
                        MessageBox.Show("the" + i + "rows x and y value is unvalid!");
                    }
                }
            }

            ClsGDBDataCommon processDataCommon = new ClsGDBDataCommon();
            string           strInputPath      = System.IO.Path.GetDirectoryName(textBoxX2.Text);
            string           strInputName      = System.IO.Path.GetFileName(textBoxX2.Text);

            IFeatureLayer pFeatureLayer = new FeatureLayerClass();

            pFeatureLayer.FeatureClass = pFt;
            pFeatureLayer.Name         = System.IO.Path.GetFileNameWithoutExtension(System.IO.Path.GetFileNameWithoutExtension(strInputName));


            //create line shape file
            IPointCollection PointCollection = ReadPoint(pFeatureLayer);
            string           lineName        = strInputPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(strInputName) + "_line.shp";

            CreateLineShpFile(lineName, pSpaReference);
            //将所有的点连接成线
            List <IPolyline> Polyline       = CreatePolyline(PointCollection);
            List <double>    lineLengthList = new List <double>();
            //将连接成的线添加到线图层中
            string pLineFile = lineName;
            string pFilePath = System.IO.Path.GetDirectoryName(pLineFile);
            string pFileName = System.IO.Path.GetFileName(pLineFile);
            //打开工作空间
            IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass();
            IFeatureWorkspace pWS  = (IFeatureWorkspace)pWSF.OpenFromFile(pFilePath, 0);
            //写入实体对象
            IFeatureLayer plineLayer = new FeatureLayerClass();

            plineLayer.FeatureClass = pWS.OpenFeatureClass(pFileName);
            AddFeature(plineLayer, Polyline, pointList, lineLengthList);
            plineLayer.Name = pFeatureLayer.Name + "_line";

            m_pMapCtl.AddLayer(plineLayer as ILayer, 0);
            m_pMapCtl.AddLayer(pFeatureLayer as ILayer, 0);
            m_pMapCtl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);

            ImpSymbolFromFile(textBoxX3.Text, pFeatureLayer, plineLayer);

            this.Close();
        }
Beispiel #39
0
        static void CopyAndLabel(IFeatureClass inFC, IFeatureWorkspace destination, String name)
        {
            IFieldsEdit outFields = new FieldsClass();
            ISpatialReference outSR = null;
            for (int i = 0; i < inFC.Fields.FieldCount; i += 1) {
                IField field = inFC.Fields.get_Field(i);
                if (field.Type == esriFieldType.esriFieldTypeGeometry) {
                    outSR = field.GeometryDef.SpatialReference;
                } else {
                    outFields.AddField(field);
                }
            }
            outSR.SetMDomain(-137434824702, 137434824702);

            IGeometryDefEdit geom = new GeometryDefClass();
            geom.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
            geom.SpatialReference_2 = outSR;
            geom.HasM_2 = true;
            geom.HasZ_2 = false;

            IFieldEdit geomField = new FieldClass();
            geomField.Name_2 = "SHAPE";
            geomField.AliasName_2 = "SHAPE";
            geomField.Type_2 = esriFieldType.esriFieldTypeGeometry;
            geomField.GeometryDef_2 = geom;
            outFields.AddField(geomField);

            IFeatureClass outFC = destination.CreateFeatureClass(name, outFields, null, null, esriFeatureType.esriFTSimple, "SHAPE", "");
            // Start numbering from 1, because index 0 is used by clipping cell
            int vIndex = 1;
            IFeatureCursor featureCursor = inFC.Search(null, true);
            IFeature inFeature;
            while ((inFeature = featureCursor.NextFeature()) != null) {
                IFeature outFeature = outFC.CreateFeature();
                for (int i = 0; i < outFields.FieldCount; i += 1) {
                    IField field = outFields.Field[i];
                    if (field.Editable && (field.Type != esriFieldType.esriFieldTypeGeometry)) {
                        outFeature.set_Value(i, inFeature.get_Value(i));
                    }
                }
                IPolygon4 inShape = inFeature.Shape as IPolygon4;
                PolygonClass outShape = new PolygonClass();

                IGeometryBag extRingBag = inShape.ExteriorRingBag;
                IGeometryCollection extRings = extRingBag as IGeometryCollection;
                for (int i = 0; i < extRings.GeometryCount; i += 1) {
                    IGeometry inExtRingGeom = extRings.get_Geometry(i);
                    IPointCollection inExtRing = inExtRingGeom as IPointCollection;
                    RingClass outExtRing = new RingClass();
                    for (int j = 0; j < inExtRing.PointCount; j += 1) {
                        IPoint point = inExtRing.get_Point(j);
                        point.M = vIndex;
                        vIndex += 2;
                        outExtRing.AddPoint(point);
                    }
                    outShape.AddGeometry(outExtRing);
                    IGeometryBag intRingBag = inShape.get_InteriorRingBag(inExtRingGeom as IRing);
                    IGeometryCollection intRings = intRingBag as IGeometryCollection;
                    for (int j = 0; j < intRings.GeometryCount; j += 1) {
                        IGeometry intRingGeom = intRings.get_Geometry(j);
                        IPointCollection inIntRing = intRingGeom as IPointCollection;
                        RingClass outIntRing = new RingClass();
                        for (int k = 0; k < inIntRing.PointCount; k += 1) {
                            IPoint point = inExtRing.get_Point(k);
                            point.M = vIndex;
                            vIndex += 2;
                            outIntRing.AddPoint(point);
                        }
                        outShape.AddGeometry(outIntRing);
                    }
                }
                outFeature.Shape = outShape;
                outFeature.Store();
            }
        }
Beispiel #40
0
        //Function: Create Shapefile
        //Date: 2019/4/12
        public IFeatureClass CreateShapefile(IFields fields, string sParentDirectory,
                                             string sWorkspaceName, //the name of the folder that contains the shapefile
                                             string sFilename,
                                             string sGeometryType)  //the geometry type of shapefile
        {
            IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass();
            IWorkspaceName    workspaceName    = workspaceFactory.Create(sParentDirectory, sWorkspaceName, null, 0);

            ESRI.ArcGIS.esriSystem.IName name = workspaceName as ESRI.ArcGIS.esriSystem.IName;

            IWorkspace        workspace        = (IWorkspace)name.Open();
            IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace;

            IFieldsEdit fieldsEdit = fields as IFieldsEdit;

            IFieldEdit fieldEdit = new FieldClass();

            fieldEdit.Name_2      = "OID";
            fieldEdit.AliasName_2 = "序号";
            fieldEdit.Type_2      = esriFieldType.esriFieldTypeOID;
            fieldsEdit.AddField((IField)fieldEdit);

            fieldEdit             = new FieldClass();
            fieldEdit.Name_2      = "Name";
            fieldEdit.AliasName_2 = "名称";
            fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
            fieldsEdit.AddField((IField)fieldEdit);

            //Change shape type
            IGeometryDefEdit  geoDefEdit       = new GeometryDefClass();
            ISpatialReference spatialReference = m_map.SpatialReference;

            geoDefEdit.SpatialReference_2 = spatialReference;
            if (sGeometryType == "Point")
            {
                geoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
            }
            else if (sGeometryType == "Line")
            {
                geoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryLine;
            }
            else if (sGeometryType == "Polygon")
            {
                geoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
            }

            //change shapetype
            fieldEdit = new FieldClass();
            string sShapeFieldName = "Shape";

            fieldEdit.Name_2        = sShapeFieldName;
            fieldEdit.AliasName_2   = "形状";
            fieldEdit.Type_2        = esriFieldType.esriFieldTypeGeometry;
            fieldEdit.GeometryDef_2 = geoDefEdit;
            fieldsEdit.AddField((IField)fieldEdit);

            //create feature class
            IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(sFilename,
                                                                             fields, null, null, esriFeatureType.esriFTSimple, "Shape", "");

            if (featureClass == null)
            {
                return(null);
            }
            return(featureClass);
        }
Beispiel #41
0
 public IFeatureClass GetFeatureClass(IFeatureWorkspace pWorkSpace, string pFeatureName)
 {
     if (pWorkSpace == null) return null;
     try
     {
         return pWorkSpace.OpenFeatureClass(pFeatureName);
     }
     catch
     {
         return null;
     }
 }
Beispiel #42
0
        private DataTable OpenVec(Dictionary <string, DataType> Dic)
        {
            IWorkspaceFactory pWorkspaceFactory = new FileGDBWorkspaceFactoryClass();
            IWorkspace        pVecWorkspace     = pWorkspaceFactory.OpenFromFile(m_VecPath, 0);
            IFeatureWorkspace pFeatureWorkspace = pVecWorkspace as IFeatureWorkspace;
            IEnumDataset      pEnumDataset      = pVecWorkspace.get_Datasets(esriDatasetType.esriDTAny) as IEnumDataset;

            pEnumDataset.Reset();
            IDataset pDataset = pEnumDataset.Next();

            while (null != pDataset)
            {
                if (pDataset is IFeatureClass)//SHP文件
                {
                    if (pDataset.Name.ToUpper().Equals("PROVINCE"))
                    {
                        IFeatureClass pFeatureClass = pFeatureWorkspace.OpenFeatureClass(pDataset.Name);
                        if (null == pFeatureClass)
                        {
                            return(null);
                        }
                        //加载图层
                        IFeatureLayer pFeaLayer = new FeatureLayerClass();
                        pFeaLayer.Name         = pDataset.Name;
                        pFeaLayer.FeatureClass = pFeatureClass;
                        m_MapControl.AddLayer(pFeaLayer as ILayer, 0);
                        m_MapControl.Refresh();
                        //读取字段
                        DataTable mDtResult = new DataTable();
                        mDtResult.Columns.Add("字段名", typeof(System.String));
                        mDtResult.Columns.Add("类型", typeof(System.String));
                        mDtResult.Columns.Add("长度", typeof(System.String));
                        mDtResult.Columns.Add("最大值", typeof(System.String));
                        mDtResult.Columns.Add("最小值", typeof(System.String));
                        foreach (var value in Dic)
                        {
                            DataRow DtRow = mDtResult.NewRow();
                            DtRow[0] = value.Key;
                            for (int i = 0; i < pFeatureClass.Fields.FieldCount; i++)
                            {
                                if (pFeatureClass.Fields.Field[i].Name == value.Key)
                                {
                                    if (pFeatureClass.Fields.Field[i].Type == value.Value.Texttype)
                                    {
                                        DtRow[1] = "类型为" + pFeatureClass.Fields.Field[i].Type.ToString() + ",正确";
                                    }
                                    else
                                    {
                                        DtRow[1] = "类型为" + pFeatureClass.Fields.Field[i].Type.ToString() + ",错误,实际应为" + value.Value.Texttype;
                                    }
                                    if (pFeatureClass.Fields.Field[i].Length <= value.Value.Length)
                                    {
                                        DtRow[2] = "最大长度为" + pFeatureClass.Fields.Field[i].Length.ToString() + ",正确";
                                    }
                                    else
                                    {
                                        DtRow[2] = "最大长度超过" + value.Value.Length.ToString();
                                    }
                                    if (value.Value.Max > 999999)
                                    {
                                        DtRow[3] = "最大值无限制";
                                    }
                                    else
                                    {
                                        DtRow[3] = QueryMax(pFeatureClass, value.Value.Max, value.Key);
                                    }
                                    if (value.Value.Min < -999999)
                                    {
                                        DtRow[4] = "最小值无限制";
                                    }
                                    else
                                    {
                                        DtRow[4] = QueryMin(pFeatureClass, value.Value.Min, value.Key);
                                    }
                                    break;
                                }
                            }
                            mDtResult.Rows.Add(DtRow);
                        }
                        return(mDtResult);
                    }
                }
                pDataset = pEnumDataset.Next();
            }
            return(null);
        }
        /// <summary>
        /// Find and load the cost attributes into a combo box
        /// <summary>
        /// <param name="featureWorkspace">The workspace that holds the input feature class</param>
        /// <returns>Success</returns>
        private bool LoadLocations(IFeatureWorkspace featureWorkspace)
		{
			IFeatureClass inputFeatureClass = null;
			try
			{
				inputFeatureClass = featureWorkspace.OpenFeatureClass(txtInputFacilities.Text);
			}
			catch (Exception)
			{
				MessageBox.Show("Specified input feature class does not exist");
				return false;
			}

			INamedSet classes = m_NAContext.NAClasses;
			INAClass naClass = classes.get_ItemByName("Facilities") as INAClass;

			// delete existing locations, except barriers
			naClass.DeleteAllRows();

			// Create a NAClassLoader and set the snap tolerance (meters unit)
			INAClassLoader naClassLoader = new NAClassLoaderClass();
			naClassLoader.Locator = m_NAContext.Locator;
			((INALocator3)naClassLoader.Locator).MaxSnapTolerance = 500;
			naClassLoader.NAClass = naClass;

			// Create field map to automatically map fields from input class to NAClass
			INAClassFieldMap naClassFieldMap = new NAClassFieldMapClass();
			naClassFieldMap.CreateMapping(naClass.ClassDefinition, inputFeatureClass.Fields);
			naClassLoader.FieldMap = naClassFieldMap;

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

			// load network locations
			int rowsIn = 0;
			int rowsLocated = 0;
			naClassLoader.Load(inputFeatureClass.Search(null, true) as ICursor, null, ref rowsIn, ref rowsLocated);

			if (rowsLocated <= 0)
			{
				MessageBox.Show("Facilities were not loaded from input feature class");
				return false;
			}

			// Message all of the network analysis agents that the analysis context has changed
			INAContextEdit naContextEdit = m_NAContext as INAContextEdit;
			naContextEdit.ContextChanged();

			return true;
		}
Beispiel #44
0
        public void SetupFixture()
        {
            _lic.Checkout();

            _testWs = TestWorkspaceUtils.CreateTestFgdbWorkspace("TestUnreferencedRows");
        }
        public void Shutdown()
        {
            _hluLayer = null;
            _hluFeatureClass = null;
            _hluFeatureSelection = null;
            _hluWS = null;
            _hluSqlSyntax = null;
            _hluView = null;
            _hluFieldMap = null;
            _hluFieldNames = null;
            _hluUidFieldOrdinals = null;
            _selectFieldOrdinals = null;

            _pipeSelDel = null;
            _selectedRowsUniqueDel = null;
            _flashSelFeatDel = null;
            _splitFeatDel = null;
            _splitFeatLogDel = null;
            _mergeFeatDel = null;
            _mergeFeatLogDel = null;
            _updAttsDel = null;
            _updAttsSelDel = null;
            _updAttsBulkDel = null;
            _selByQDefDel = null;
            _selByQFilterDel = null;
            _selByJoinDel = null;
            _zoomSelDel = null;
            _zoomSelCursorDel = null;
            _exportDel = null;
            _isHluWorkspaceDel = null;
            _ListHluLayersDel = null;
            _isHluLayerDel = null;
            _isEditingDel = null;

            if (PipeManager != null)
            {
                PipeManager = null;
            }

            RemoveActiveViewEvents(_focusMap);
        }
Beispiel #46
0
        private void button1_Click(object sender, EventArgs e)
        {
            double bufferDistance;

            double.TryParse(txtBufferDistance.Text, out bufferDistance);
            if (0.0 == bufferDistance)
            {
                MessageBox.Show("距离设置错误", "Error!");
                return;
            }
            if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(txtOutputPath.Text)) || ".shp" != System.IO.Path.GetExtension(txtOutputPath.Text))
            {
                MessageBox.Show("输出格式错误!");
                return;
            }
            if (comboBoxLayer.Items.Count <= 0)
            {
                return;
            }
            DataOperator  pDo = new DataOperator(m_map, null);
            IFeatureLayer pFl = (IFeatureLayer)pDo.GetLayerbyName(comboBoxLayer.SelectedItem.ToString());
            Geoprocessor  gp  = new Geoprocessor();

            gp.OverwriteOutput = true;
            gp.AddOutputsToMap = true;
            string unit = "Kilometers";

            ESRI.ArcGIS.AnalysisTools.Buffer buffer = new ESRI.ArcGIS.AnalysisTools.Buffer(pFl, txtOutputPath.Text, Convert.ToString(bufferDistance) + "" + unit);
            try
            {
                IGeoProcessorResult results = (IGeoProcessorResult)gp.Execute(buffer, null);
            }
            catch
            {
            }
            string fileDirectory = txtOutputPath.Text.ToString().Substring(0, txtOutputPath.Text.LastIndexOf("\\"));
            int    j;

            j = txtOutputPath.Text.LastIndexOf("\\");
            string            tmpstr = txtOutputPath.Text.ToString().Substring(j + 1);
            IWorkspaceFactory pWsf   = new ShapefileWorkspaceFactory() as IWorkspaceFactory;
            IWorkspace        pWs    = pWsf.OpenFromFile(fileDirectory, 0);
            IFeatureWorkspace pFs    = pWs as IFeatureWorkspace;
            IFeatureClass     pFc    = pFs.OpenFeatureClass(tmpstr);
            IFeatureLayer     pfl    = new FeatureLayer() as IFeatureLayer;

            pfl.FeatureClass = pFc;
            IRgbColor pColor = new RgbColor() as IRgbColor;

            pColor.Red          = 255;
            pColor.Green        = 0;
            pColor.Blue         = 0;
            pColor.Transparency = 255;
            ILineSymbol pOutline = new SimpleLineSymbol();

            pOutline.Width      = 2;
            pOutline.Color      = pColor;
            pColor              = new RgbColor();
            pColor.Red          = 255;
            pColor.Green        = 0;
            pColor.Blue         = 0;
            pColor.Transparency = 100;
            ISimpleFillSymbol pFillSymbol = new SimpleFillSymbol();

            pFillSymbol.Color   = pColor;
            pFillSymbol.Outline = pOutline;
            pFillSymbol.Style   = esriSimpleFillStyle.esriSFSSolid;
            ISimpleRenderer  pRen;
            IGeoFeatureLayer pGeofl = pfl as IGeoFeatureLayer;

            pRen            = pGeofl.Renderer as ISimpleRenderer;
            pRen.Symbol     = pFillSymbol as ISymbol;
            pGeofl.Renderer = pRen as IFeatureRenderer;
            ILayerEffects pLayerEffects = pfl as ILayerEffects;

            pLayerEffects.Transparency = 150;
            m_mapControl.AddLayer((ILayer)pfl, 0);
            MessageBox.Show(comboBoxLayer.SelectedText + "缓冲区生成成功!");
        }
        //---------------------------------------------------------------------

        /// <summary>
        /// Determines whether the layer passed is an HLU layer, sets all related fields except _hluView 
        /// (which it cannot obtain from the layer) and sets up the selection changed event handler for the
        /// layer if it is an HLU layer.
        /// </summary>
        /// <param name="layer"></param>
        /// <returns></returns>
        private bool IsHluLayer(IFeatureLayer layer)
        {
            try
            {
                //---------------------------------------------------------------------
                // CHANGED: CR31 (Switching between GIS layers)
                // Don't update the class properties unless an HLU layer (_hluLayer)
                // has not already been selected so that other feature layers can
                // be examined to see if they are also valid HLU layers (without
                // overwritting the class properties of the first layer).
                int[] hluFieldMap;
                string[] hluFieldNames;

                if (HluDbIsRunning && ArcMapAppHelperClass.IsHluLayer(layer,
                new FieldsClass(), new FieldCheckerClass(), _validWorkspaces, _typeMapSystemToSql,
                ref _hluLayerStructure, out hluFieldMap, out hluFieldNames))
                {
                    IFeatureLayer hluLayer = layer as IFeatureLayer;
                    IFeatureClass hluFeatureClass = hluLayer.FeatureClass;
                    IWorkspace hluWorkspace = ((IDataset)hluFeatureClass).Workspace;
                    IFeatureWorkspace hluWS = hluWorkspace as IFeatureWorkspace;
                    if ((!_pipeCalling) || (_hluLayer == null)) SetupSelectionChangedEvent(hluLayer);

                    int[] hluUidFieldOrdinals = new int[3];
                    hluUidFieldOrdinals[0] = hluFieldMap[_hluLayerStructure.incidColumn.Ordinal];
                    hluUidFieldOrdinals[1] = hluFieldMap[_hluLayerStructure.toidColumn.Ordinal];
                    hluUidFieldOrdinals[2] = hluFieldMap[_hluLayerStructure.toid_fragment_idColumn.Ordinal];

                    string[] hluFieldSysTypeNames = new string[hluFeatureClass.Fields.FieldCount];
                    Type sysType;
                    for (int i = 0; i < hluFeatureClass.Fields.FieldCount; i++)
                    {
                        if (_typeMapSQLToSystem.TryGetValue((int)hluFeatureClass.Fields.get_Field(i).Type, out sysType))
                            hluFieldSysTypeNames[i] = sysType.FullName;
                    }

                    string hluTableName = ((IDataset)hluFeatureClass).Name;
                    ISQLSyntax hluSqlSyntax = (ISQLSyntax)hluWS;
                    string quotePrefix =
                        hluSqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix);
                    string quoteSuffix =
                       hluSqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix);

                    if (_hluLayer == null)
                    {
                        _hluLayer = hluLayer;
                        _hluFeatureClass = hluFeatureClass;
                        _hluWS = hluWS;
                        _hluWSisSDE = hluWorkspace.WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace;
                        _hluUidFieldOrdinals = hluUidFieldOrdinals;
                        _hluFieldSysTypeNames = hluFieldSysTypeNames;
                        _hluTableName = hluTableName;
                        _hluSqlSyntax = hluSqlSyntax;
                        _quotePrefix = quotePrefix;
                        _quoteSuffix = quoteSuffix;
                        _hluFieldMap = hluFieldMap;
                        _hluFieldNames = hluFieldNames;
                    }
                    //---------------------------------------------------------------------

                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                _hluLayer = null;
                _hluFeatureClass = null;
                _hluTableName = null;
                _hluWS = null;
                _hluWSisSDE = false;
                _hluView = null;
                _hluFieldMap = null;
                _hluFieldNames = null;
                _hluUidFieldOrdinals = null;
                _selectFieldOrdinals = null;
                _hluSqlSyntax = null;
                _quotePrefix = null;
                _quoteSuffix = null;
                return false;
            }
        }
Beispiel #48
0
 private static IWorkspaceContext CreateWorkspaceContext(
     [NotNull] Model model,
     [NotNull] IFeatureWorkspace workspace)
 {
     return(new MasterDatabaseWorkspaceContext(workspace, model));
 }
        //---------------------------------------------------------------------

        #endregion

        #region Event Handlers

        private void OnNewDocument()
        {
            IDocument document = _docEvents as IDocument;

            _hluWS = null;
            _hluLayer = null;
            _hluFeatureClass = null;
            _hluView = null;
            _hluWSisSDE = false;
            RemoveActiveViewEvents(_focusMap);
            _focusMap = ((IMxDocument)document).FocusMap;
            SetupActiveViewEvents(_focusMap);
        }
Beispiel #50
0
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if (Validate(true) == false)
            {
                return;
            }
            string locType = label1.Tag != null?label1.Tag.ToString() : "";

            if (string.IsNullOrEmpty(locType))
            {
                return;
            }
            object          createLoc;
            IWorkspace2     workspace2 = null;
            IObjectTemplate template   = null;

            if (_isSingle)
            {
                template = _template;
            }
            else
            {
                template = _plugin.TemplateDatabase.Templates.FirstOrDefault(c => c.Name == cmbTemplate.SelectedItem.ToString());
            }

            if (template == null)
            {
                return;
            }
            if (locType.Contains("Dataset"))
            {
                IGxDataset      pDataset = txtDB.Tag as IGxDataset;
                IFeatureDataset fDataset = ((IGxObject)pDataset).InternalObjectName.Open();
                workspace2 = fDataset.Workspace as IWorkspace2;
                createLoc  = fDataset;
            }
            else
            {
                IGxDatabase       pDatabase = txtDB.Tag as IGxDatabase;
                IFeatureWorkspace workspace = ((IGxObject)pDatabase).InternalObjectName.Open();
                workspace2 = workspace as IWorkspace2;
                createLoc  = workspace;
            }

            if (createLoc == null)
            {
                return;
            }
            string      fcName     = txtName.EditValue.ToString().Trim();
            IWorkspace2 workSpace2 = createLoc is IFeatureDataset
                ? ((IFeatureDataset)createLoc).Workspace as IWorkspace2
                : createLoc as IWorkspace2;

            if (workSpace2.NameExists[esriDatasetType.esriDTFeatureClass, fcName])
            {
                MessageService.Current.Warn("该名称已经存在,请重新输入!");
                return;
            }
            ISpatialReference pSpatialReference = _map.SpatialReference;

            IFieldsEdit pFieldsEdit = new Fields() as IFieldsEdit;
            IField      pField      = FieldHelper.CreateOIDField();

            pFieldsEdit.AddField(pField);
            if (locType.Contains("Dataset"))
            {
                IGeoDataset pFDataset = createLoc as IGeoDataset;
                pField            = FieldHelper.CreateGeometryField(template.GeometryType, pFDataset.SpatialReference);
                pSpatialReference = pFDataset.SpatialReference;
                pFieldsEdit.AddField(pField);
            }
            else
            {
                pField = FieldHelper.CreateGeometryField(template.GeometryType, _map.SpatialReference);
                pFieldsEdit.AddField(pField);
            }
            string keyName = "";

            foreach (YTField ytField in template.Fields)
            {
                pField = ytField.CreateField();
                pFieldsEdit.AddField(pField);
                if (ytField.IsKey)
                {
                    keyName = ytField.Name;
                }
            }

            IFeatureClass pClass = WorkspaceOperator.CreateFeatureClass(createLoc, txtName.Text, pSpatialReference, template.FeatureType,
                                                                        template.GeometryType, (IFields)pFieldsEdit, null, null, "");

            if (pClass == null)
            {
                MessageService.Current.Info("创建失败!");
                return;
            }
            if (pClass != null && chkIndex.Checked == false)
            {
                MapHelper.AddFeatureLayer((IBasicMap)_map, pClass);
                MessageService.Current.Info("创建成功并已经加载图层!");
                DialogResult = DialogResult.OK;
                return;
            }
            IEnvelope pEnv = new Envelope() as IEnvelope;

            pEnv.PutCoords(Convert.ToDouble(txtXMin.Text), Convert.ToDouble(txtYMin.Text), Convert.ToDouble(txtXMax.Text), Convert.ToDouble(txtYMax.Text));

            IWorkspaceEdit pWksEdit = ((IDataset)pClass).Workspace as IWorkspaceEdit;

            pWksEdit.StartEditing(false);
            pWksEdit.StartEditOperation();
            IndexHelper.CreateGridIndex(pClass, pEnv, Convert.ToDouble(txtWidth.Text),
                                        Convert.ToDouble(txtHeight.Text), keyName);
            pWksEdit.StopEditOperation();
            pWksEdit.StopEditing(true);
            MapHelper.AddFeatureLayer((IBasicMap)_map, pClass);
            MessageService.Current.Info("创建成功并已经加载图层!");
            DialogResult = DialogResult.OK;
        }
        private void OnActiveViewEventsItemDeleted(object Item)
        {
            if (_hluLayer == null) return;

            IFeatureLayer layer = Item as IFeatureLayer;
            if (layer == null) return;

            if (layer.Equals(_hluLayer))
            {
                try
                {
                    _hluLayerSelectionChangedHandler.FeatureLayerSelectionChanged -=
                        _hluLayerSelectionEvent_FeatureLayerSelectionChanged;
                }
                catch { }
                _hluLayer = null;
                _hluFeatureClass = null;
                _hluWS = null;
                _hluView = null;
                _hluFieldMap = null;
                _hluFieldNames = null;
            }
        }
        public static ITable OpenTable(
            [NotNull] IFeatureWorkspace workspace,
            [NotNull] string gdbDatasetName,
            [CanBeNull] string oidFieldName = null,
            [CanBeNull] SpatialReferenceDescriptor spatialReferenceDescriptor = null)
        {
            Assert.ArgumentNotNull(workspace, nameof(workspace));
            Assert.ArgumentNotNull(gdbDatasetName, nameof(gdbDatasetName));

            var sqlWorksace = workspace as ISqlWorkspace;

            if (sqlWorksace == null ||
                DatasetUtils.IsRegisteredAsObjectClass((IWorkspace)workspace, gdbDatasetName))
            {
                return(DatasetUtils.OpenTable(workspace, gdbDatasetName));
            }

            IQueryDescription queryDescription;

            try
            {
                string query = $"SELECT * FROM {gdbDatasetName}";
                queryDescription = sqlWorksace.GetQueryDescription(query);
            }
            catch (Exception ex)
            {
                _msg.WarnFormat(
                    "Unable to get query description for unregistered table {0}: {1}",
                    gdbDatasetName, ex.Message);

                return(DatasetUtils.OpenTable(workspace, gdbDatasetName));
            }

            bool hasUnknownSref =
                queryDescription.SpatialReference == null ||
                queryDescription.SpatialReference is IUnknownCoordinateSystem;

            bool hasUnknownOid =
                StringUtils.IsNullOrEmptyOrBlank(queryDescription.OIDColumnName) ||
                queryDescription.IsOIDMappedColumn;

            if (!hasUnknownOid && (!hasUnknownSref || !queryDescription.IsSpatialQuery))
            {
                return(DatasetUtils.OpenTable(workspace, gdbDatasetName));
            }

            if (hasUnknownOid)
            {
                if (StringUtils.IsNotEmpty(oidFieldName))
                {
                    queryDescription.OIDFields = oidFieldName;
                }
                else
                {
                    IField uniqueIntegerField = GetUniqueIntegerField(workspace, gdbDatasetName);

                    if (uniqueIntegerField != null)
                    {
                        queryDescription.OIDFields = uniqueIntegerField.Name;
                    }
                }
            }

            if (hasUnknownSref && queryDescription.IsSpatialQuery)
            {
                queryDescription.SpatialReference = spatialReferenceDescriptor.SpatialReference;
            }

            try
            {
                // NOTE: the unqualified name of the query class must start with a '%'
                string queryLayerName =
                    DatasetUtils.GetQueryLayerClassName(workspace, gdbDatasetName);

                _msg.DebugFormat("Opening query layer with name {0}", queryLayerName);

                ITable queryClass = sqlWorksace.OpenQueryClass(queryLayerName, queryDescription);

                // NOTE: the query class is owned by the *connected* user, not by the owner of the underlying table/view

                string queryClassName = DatasetUtils.GetName(queryClass);

                _msg.DebugFormat("Name of opened query layer class: {0}", queryClassName);

                _tableNamesByQueryClassNames[queryClassName] = gdbDatasetName;

                return(queryClass);
            }
            catch (Exception ex)
            {
                _msg.WarnFormat(
                    "Unable to open unregistered table {0} as query layer: {1}",
                    gdbDatasetName, ex.Message);

                return(DatasetUtils.OpenTable(workspace, gdbDatasetName));
            }
        }
        public void OpenTurnFeatureClass(IFeatureWorkspace fws, string turnClassName)
        {
            TurnFeatureClass = fws.OpenFeatureClass(turnClassName);

            idxEdge1End = TurnFeatureClass.FindField("Edge1End");
            idxEdge1FCID = TurnFeatureClass.FindField("Edge1FCID");
            idxEdge1FID = TurnFeatureClass.FindField("Edge1FID");
            idxEdge1Pos = TurnFeatureClass.FindField("Edge1Pos");
            idxEdge2FCID = TurnFeatureClass.FindField("Edge2FCID");
            idxEdge2FID = TurnFeatureClass.FindField("Edge2FID");
            idxEdge2Pos = TurnFeatureClass.FindField("Edge2Pos");
            idxRestrict = TurnFeatureClass.FindField("RestrictionType");
        }
Beispiel #54
0
        private IFeatureClass CreatePatchClass(IWorkspace2 workspace, IFeatureDataset featureDataset, IFeatureClass sourceClass, string suffixName, bool isAddAttr = false)
        {
            IDataset pDataset         = sourceClass as IDataset;
            string   featureClassName = pDataset.Name + suffixName;

            IFeatureClass     featureClass;
            IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;                  // Explicit Cast

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

            UID CLSID = new UIDClass();

            CLSID.Value = "esriGeoDatabase.Feature";


            IObjectClassDescription objectClassDescription = new FeatureClassDescriptionClass();
            IFields fields;

            fields = objectClassDescription.RequiredFields;
            IFieldsEdit       fieldsEdit = fields as IFieldsEdit;
            ISpatialReference sSpatial   = null;

            for (int i = 0; i < sourceClass.Fields.FieldCount; i++)
            {
                IField sField = sourceClass.Fields.Field[i];
                if (sField.Type == esriFieldType.esriFieldTypeBlob)
                {
                    continue;
                }
                if (sField.Type == esriFieldType.esriFieldTypeGeometry)
                {
                    IGeometryDef def = sField.GeometryDef;
                    sSpatial = def.SpatialReference;
                    continue;
                }
                if (sField.Type == esriFieldType.esriFieldTypeOID)
                {
                    continue;
                }
                if (sField.Type == esriFieldType.esriFieldTypeRaster)
                {
                    continue;
                }
                if (sField.Editable == false)
                {
                    continue;
                }
                if (isAddAttr)
                {
                    IClone pClone = sField as IClone;
                    fieldsEdit.AddField(pClone.Clone() as IField);
                }
            }

            IField     newField     = new FieldClass();
            IFieldEdit newFieldEdit = newField as IFieldEdit;

            newFieldEdit.Name_2      = "LinkOID";
            newFieldEdit.Type_2      = esriFieldType.esriFieldTypeInteger;
            newFieldEdit.AliasName_2 = "原始OID";
            fieldsEdit.AddField(newField);

            String strShapeField = "";

            // locate the shape field
            for (int j = 0; j < fields.FieldCount; j++)
            {
                if (fields.get_Field(j).Type == esriFieldType.esriFieldTypeGeometry)
                {
                    strShapeField = fields.get_Field(j).Name;
                    IGeometryDef     def     = fields.get_Field(j).GeometryDef;
                    IGeometryDefEdit defEdit = def as IGeometryDefEdit;
                    defEdit.GeometryType_2 = esriGeometryType.esriGeometryMultiPatch;
                    if (featureDataset == null)
                    {
                        defEdit.SpatialReference_2 = sSpatial;
                    }
                    defEdit.HasZ_2 = true;
                }
            }

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

            fieldChecker.ValidateWorkspace = (IWorkspace)workspace;
            fieldChecker.Validate(fields, out enumFieldError, out validatedFields);


            // finally create and return the feature class
            if (featureDataset == null)// if no feature dataset passed in, create at the workspace level
            {
                featureClass = featureWorkspace.CreateFeatureClass(featureClassName, validatedFields, CLSID, null, esriFeatureType.esriFTSimple, strShapeField, "");
            }
            else
            {
                featureClass = featureDataset.CreateFeatureClass(featureClassName, validatedFields, CLSID, null, esriFeatureType.esriFTSimple, strShapeField, "");
            }
            return(featureClass);
        }
 /// <summary>
 /// Delete a featureclass
 /// </summary>
 /// <param name="fWorkspace">IFeatureWorkspace</param>
 /// <param name="fcName">Name of featureclass to delete</param>
 private void DeleteFeatureClass(IFeatureWorkspace fWorkspace, string fcName)
 {
     IDataset ipDs = fWorkspace.OpenFeatureClass(fcName) as IDataset;
     ipDs.Delete();
 }
Beispiel #56
0
        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.");
            }
        }
Beispiel #57
0
 public MetadataDAO(IFeatureWorkspace workspace)
 {
     this.workspace = workspace;
 }
Beispiel #58
0
        //为xml节点赋数据源,递归调用
        private bool SetDbsourceOfXmlnode(DevComponents.AdvTree.Node pNode, XmlDocument pXmldoc, string strDbsource, IWorkspace pWorkspace, List <IDataset> pListDataset, List <string> pListTypeOfDataset)
        {
            //判断参数是否有效
            if (pNode == null)
            {
                return(false);
            }
            if (strDbsource.Equals(""))
            {
                return(false);
            }
            if (pWorkspace == null)
            {
                return(false);
            }
            string strTag      = pNode.Tag.ToString();
            string strNodeName = strTag;

            if (strNodeName.Contains("DataDIR"))
            {
                strNodeName = "DataDIR";
            }
            switch (strNodeName)
            {
            case "Root":
            case "DIR":
            case "DataDIR":
                if (pNode.Nodes.Count > 0)
                {
                    for (int i = 0; i < pNode.Nodes.Count; i++)
                    {
                        DevComponents.AdvTree.Node pTmpNode = pNode.Nodes[i];
                        SetDbsourceOfXmlnode(pTmpNode, pXmldoc, strDbsource, pWorkspace, pListDataset, pListTypeOfDataset);
                    }
                    //string strNodeKey = pNode.Name;
                    //XmlNode pNewXmlNode = pXmldoc.SelectSingleNode("//" + strNodeName + "[@NodeKey='" + strNodeKey + "']");
                    //if (pNewXmlNode != null)
                    //{
                    //    pNode.DataKey = pNewXmlNode as object;
                    //}
                }
                break;

            case "Layer":
                try
                {
                    bool    tag       = false;
                    string  strSearch = "//" + strNodeName + "[@NodeKey='" + pNode.Name + "']";
                    XmlNode pXmlnode  = pXmldoc.SelectSingleNode(strSearch);
                    if (pXmlnode == null)
                    {
                        return(false);
                    }
                    if (!(pXmlnode is XmlElement))
                    {
                        return(false);
                    }
                    XmlElement pNodeEle = pXmlnode as XmlElement;
                    //为节点设置数据源,后续还应添加数据集(数据集根据数据源、地物类名称得到)
                    //added by chulili 20110725 从数据源获取地物类,得到地物类所在数据集
                    string            strFeaClsName = pNodeEle.Attributes["Code"].Value.ToString();
                    string            strDataType   = pNodeEle.Attributes["DataType"].Value.ToString();
                    IFeatureWorkspace pFeaWks       = pWorkspace as IFeatureWorkspace;
                    if (pFeaWks != null)
                    {
                        //IFeatureClass pFeaCls = pFeaWks.OpenFeatureClass(strFeaClsName);
                        //if (pFeaCls != null)
                        //{
                        //    IFeatureDataset pDataSet = pFeaCls.FeatureDataset;
                        //    if (pDataSet != null)
                        //    {
                        //        pNodeEle.SetAttribute("FeatureDatasetName", pDataSet.Name);
                        //    }
                        //    else
                        //    {
                        //        pNodeEle.SetAttribute("FeatureDatasetName", "");
                        //    }
                        //}
                        //else//直接根据名称获取不到
                        //{
                        string TrueFeaClsName = strFeaClsName.Substring(strFeaClsName.IndexOf(".") + 1);

                        if (pListDataset != null)
                        {
                            if (strDataType.Equals("FC"))
                            {
                                for (int i = 0; i < pListDataset.Count; i++)        //循环地物类集合
                                {
                                    if (tag)
                                    {
                                        break;          //如果已经匹配上,跳出循环
                                    }
                                    if (pListTypeOfDataset[i].Equals("FC"))
                                    {
                                        IDataset     pDataset     = pListDataset[i];
                                        IEnumDataset pEnumDataset = pDataset.Subsets;
                                        IDataset     ptmpDataset  = pEnumDataset.Next();
                                        while (ptmpDataset != null)         //循环集合中的地物类
                                        {
                                            string pFeaClsName = ptmpDataset.Name;
                                            if (pFeaClsName.Equals(strFeaClsName))          //先对整个地物类名称进行匹配
                                            {
                                                pNodeEle.SetAttribute("FeatureDatasetName", pDataset.Name);
                                                pNodeEle.SetAttribute("Code", ptmpDataset.Name);
                                                tag = true;
                                                break;
                                            }
                                            ptmpDataset = pEnumDataset.Next();
                                        }
                                    }
                                }
                                if (!tag)
                                {
                                    for (int i = 0; i < pListDataset.Count; i++)        //循环地物类集合
                                    {
                                        if (tag)
                                        {
                                            break;          //如果已经匹配上,跳出循环
                                        }
                                        if (pListTypeOfDataset[i].Equals("FC"))
                                        {
                                            IDataset     pDataset     = pListDataset[i];
                                            IEnumDataset pEnumDataset = pDataset.Subsets;
                                            IDataset     ptmpDataset  = pEnumDataset.Next();
                                            while (ptmpDataset != null)         //循环集合中的地物类
                                            {
                                                string pFeaClsName = ptmpDataset.Name;
                                                if (pFeaClsName.Substring(pFeaClsName.IndexOf(".") + 1) == TrueFeaClsName)         //再去掉用户名进行匹配
                                                {
                                                    pNodeEle.SetAttribute("FeatureDatasetName", pDataset.Name);
                                                    pNodeEle.SetAttribute("Code", ptmpDataset.Name);
                                                    tag = true;
                                                    break;
                                                }
                                                ptmpDataset = pEnumDataset.Next();
                                            }
                                        }
                                    }
                                }
                            }
                            else if (strDataType.Equals("RC") || strDataType.Equals("RD"))
                            {
                                for (int i = 0; i < pListDataset.Count; i++)        //循环地物类集合
                                {
                                    if (tag)
                                    {
                                        break;          //如果已经匹配上,跳出循环
                                    }
                                    if (pListTypeOfDataset[i].Equals("RC") || pListTypeOfDataset[i].Equals("RD"))
                                    {
                                        IDataset pDataset = pListDataset[i];
                                        if (pDataset != null)         //循环集合中的地物类
                                        {
                                            string RCname = pDataset.Name;
                                            if (RCname.Equals(strFeaClsName))          //先对整个地物类名称进行匹配
                                            {
                                                pNodeEle.SetAttribute("FeatureDatasetName", pDataset.Name);
                                                pNodeEle.SetAttribute("Code", pDataset.Name);
                                                pNodeEle.SetAttribute("DataType", pListTypeOfDataset[i]);
                                                tag = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                                if (!tag)
                                {
                                    for (int i = 0; i < pListDataset.Count; i++)        //循环地物类集合
                                    {
                                        if (tag)
                                        {
                                            break;          //如果已经匹配上,跳出循环
                                        }
                                        if (pListTypeOfDataset[i].Equals("FC") || pListTypeOfDataset[i].Equals("RD"))
                                        {
                                            IDataset pDataset = pListDataset[i];
                                            if (pDataset != null)         //循环集合中的地物类
                                            {
                                                string pFeaClsName = pDataset.Name;
                                                if (pFeaClsName.Substring(pFeaClsName.IndexOf(".") + 1) == TrueFeaClsName)         //再去掉用户名进行匹配
                                                {
                                                    pNodeEle.SetAttribute("FeatureDatasetName", pDataset.Name);
                                                    pNodeEle.SetAttribute("Code", pDataset.Name);
                                                    pNodeEle.SetAttribute("DataType", pListTypeOfDataset[i]);
                                                    tag = true;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        //}
                    }
                    //end added by chulili
                    if (tag)
                    {
                        pNodeEle.SetAttribute("ConnectKey", strDbsource);
                    }
                    //added by chulili 20110630 非常重要,只有这样关联上,图层节点才能在视图浏览中正确显示
                    //pNode.DataKey = pXmlnode as object;
                    ModuleMap.SetDataKey(pNode, pXmlnode);
                }
                catch (Exception e)
                {
                    string strinfo = e.Message;
                }
                break;
            }
            return(true);
        }
Beispiel #59
0
 private IFeatureClass CreateGridFeatureClass(Grid grid, IFeatureWorkspace workspace, IFeatureDataset dataset,
                                              string featureClassName)
 {
     try
     {
         IFields fields;
         if (workspace is IGxFolder)
         {
             MessageBox.Show(@"Creating Shapefile " + featureClassName + @" in " +
                             ((IWorkspace)workspace).PathName);
             if (!ValidateShapefileName())
             {
                 MessageBox.Show(@"Shapefile may exist, name may be too long," +
                                 @"folder may not exist, folder may be readonly,", @"Error");
                 return null;
             }
             fields = CreateShapefileFields();
         }
         else
         {
             string msg = dataset == null
                              ? string.Format("Creating {0} in {1}", featureClassName,
                                              ((IWorkspace)workspace).PathName)
                              : string.Format("Creating {0} in {1}\\{2}", featureClassName,
                                              ((IWorkspace)workspace).PathName, dataset.Name);
             MessageBox.Show(msg);
             if (!ValidateGdbfileName())
                 return null;
             fields = CreateGdbFields();
         }
         IFeatureClass generatedFeatureClass = CreateFeatureClass((IWorkspace2)workspace, dataset,
                                                                  featureClassName, fields, null, null, "");
         if (generatedFeatureClass == null)
             return null;
         PutGridInFeatureClass(generatedFeatureClass, grid);
         return generatedFeatureClass;
     }
     catch (Exception)
     {
         //Debug.Print("Exception Creating Feature Class: {0}",ex);
         return null;
     }
 }
Beispiel #60
0
 /// <summary>
 /// Pseudocode:
 /// - Loop through all conflicts classes after the reconcile.
 /// - Loop through every UpdateUpdate conflict on the class.
 /// - Determine if geometry is in conflict on the feature.
 /// - If so, merge geometries together (handling errors) and store the feature.
 /// </summary>
 public void OnConflictsDetected(ref bool conflictsRemoved, ref bool errorOccurred, ref string errorString)
 {
     try
     {
         IVersionEdit4 versionEdit4 = (IVersionEdit4)featureWorkspace;
         // Get the various versions on which to output information.
         IFeatureWorkspace commonAncestorFWorkspace = (IFeatureWorkspace)
                                                      versionEdit4.CommonAncestorVersion;
         IFeatureWorkspace preReconcileFWorkspace = (IFeatureWorkspace)
                                                    versionEdit4.PreReconcileVersion;
         IFeatureWorkspace reconcileFWorkspace = (IFeatureWorkspace)
                                                 versionEdit4.ReconcileVersion;
         IEnumConflictClass enumConflictClass = versionEdit4.ConflictClasses;
         IConflictClass     conflictClass     = null;
         while ((conflictClass = enumConflictClass.Next()) != null)
         {
             IDataset dataset = (IDataset)conflictClass;
             // Make sure class is a feature class.
             if (dataset.Type == esriDatasetType.esriDTFeatureClass)
             {
                 String        datasetName  = dataset.Name;
                 IFeatureClass featureClass = featureWorkspace.OpenFeatureClass
                                                  (datasetName);
                 Console.WriteLine("Conflicts on feature class {0}", datasetName);
                 // Get all UpdateUpdate conflicts.
                 ISelectionSet updateUpdates = conflictClass.UpdateUpdates;
                 if (updateUpdates.Count > 0)
                 {
                     // Get conflict feature classes on the three reconcile versions.
                     IFeatureClass featureClassPreReconcile =
                         preReconcileFWorkspace.OpenFeatureClass(datasetName);
                     IFeatureClass featureClassReconcile =
                         reconcileFWorkspace.OpenFeatureClass(datasetName);
                     IFeatureClass featureClassCommonAncestor =
                         commonAncestorFWorkspace.OpenFeatureClass(datasetName);
                     // Iterate through each OID, outputting information.
                     IEnumIDs enumIDs = updateUpdates.IDs;
                     int      oid     = -1;
                     while ((oid = enumIDs.Next()) != -1)
                     //loop through all conflicting features
                     {
                         Console.WriteLine("UpdateUpdate conflicts on feature {0}", oid);
                         // Get conflict feature on the three reconcile versions.
                         IFeature featurePreReconcile =
                             featureClassPreReconcile.GetFeature(oid);
                         IFeature featureReconcile      = featureClassReconcile.GetFeature(oid);
                         IFeature featureCommonAncestor =
                             featureClassCommonAncestor.GetFeature(oid);
                         // Check to make sure each shape is different than the common ancestor (conflict is on shape field).
                         if (IsShapeInConflict(featureCommonAncestor, featurePreReconcile,
                                               featureReconcile))
                         {
                             Console.WriteLine(
                                 " Shape attribute has changed on both versions...");
                             // Geometries are in conflict ... merge geometries.
                             try
                             {
                                 IConstructMerge constructMerge = new GeometryEnvironmentClass
                                                                      ();
                                 IGeometry newGeometry = constructMerge.MergeGeometries
                                                             (featureCommonAncestor.ShapeCopy,
                                                             featureReconcile.ShapeCopy, featurePreReconcile.ShapeCopy);
                                 // Setting new geometry as a merge between the two versions.
                                 IFeature feature = featureClass.GetFeature(oid);
                                 feature.Shape = newGeometry;
                                 feature.Store();
                                 updateUpdates.RemoveList(1, ref oid);
                                 conflictsRemoved = true;
                             }
                             catch (Exception eError) //COMException comExc
                             {
                                 //******************************************
                                 //guozheng added System Exception log
                                 if (SysCommon.Log.Module.SysLog == null)
                                 {
                                     SysCommon.Log.Module.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog();
                                 }
                                 SysCommon.Log.Module.SysLog.Write(eError);
                                 //******************************************
                                 //// Check if the error is from overlapping edits.
                                 //if (comExc.ErrorCode == (int)
                                 //  fdoError.FDO_E_WORKSPACE_EXTENSION_DATASET_CREATE_FAILED ||
                                 //  comExc.ErrorCode == (int)
                                 //  fdoError.FDO_E_WORKSPACE_EXTENSION_DATASET_DELETE_FAILED)
                                 //{
                                 //    // Edited areas overlap.
                                 //    Console.WriteLine(
                                 //      "Error from overlapping edits on feature {0}", oid);
                                 //    Console.WriteLine(" Error Message: {0}", comExc.Message);
                                 //    Console.WriteLine(
                                 //      " Can't merge overlapping edits to same feature.");
                                 //}
                                 //else
                                 //{
                                 //    // Unexpected COM exception throw this to exception handler.
                                 //    throw comExc;
                                 //}
                             }
                         }
                         else
                         {
                             Console.WriteLine(
                                 " Shape field not in conflict: merge not necessary ... ");
                         }
                     }
                 }
             }
         }
     }
     catch (Exception eError)
     {
         //******************************************
         //guozheng added System Exception log
         if (SysCommon.Log.Module.SysLog == null)
         {
             SysCommon.Log.Module.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog();
         }
         SysCommon.Log.Module.SysLog.Write(eError);
         //******************************************
         //Console.WriteLine("Error Message: {0}, Error Code: {1}", comExc.Message,
         //  comExc.ErrorCode);
     }
     //catch (Exception exc)
     //{
     //    Console.WriteLine("Unhandled Exception: {0}", exc.Message);
     //}
 }