Esempio n. 1
0
        protected override void OnMouseDown(ESRI.ArcGIS.Desktop.AddIns.Tool.MouseEventArgs arg)
        {
            int            X      = arg.X;
            int            Y      = arg.Y;
            IMxApplication pMxApp = null;
            IMxDocument    pMxDoc = null;

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

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

            Tolerance = pMxDoc.SearchTolerancePixels;

            IDisplayTransformation pDispTrans = null;

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

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

            IEnvelope pSearchEnvelope = null;

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

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

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

            IIdentify pIdentify = null;

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

            IArray pIDArray = null;

            pIDArray = pIdentify.Identify(pSearchEnvelope);

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

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

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

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

            pLayer = pMxDoc.FocusMap.get_Layer(0);

            string layerName = null;

            layerName = pLayer.Name;

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

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

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

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

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

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

            pFields = pTable.Fields;
            long fldCount = 0;

            fldCount = pFields.FieldCount;

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

            gageIDFldIdx = pFields.FindField(gageIDFldName);

            IRowIdentifyObject pRowIDObj = null;

            pRowIDObj = (IRowIdentifyObject)pIDObj;

            string gageID = null;

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

            IFeatureLayerDefinition pFeatureLayerDef = null;

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

            definitionExpression = pFeatureLayerDef.DefinitionExpression;

            string whereClause = null;

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

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

            pGeoFeatureLayer = (IGeoFeatureLayer)pLayer;

            ILookupSymbol pLookupSymbol = null;

            pLookupSymbol = (ILookupSymbol)pGeoFeatureLayer.Renderer;

            IFeature pFeature = null;

            pFeature = (IFeature)pRowIDObj.Row;

            IMarkerSymbol pSymbol = null;

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

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

            IDataGraphCollection pDataGraphs = null;

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

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

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

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

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

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

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

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

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

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


            pDataGraphBase.UseSelectedSet = true;

            ITrackCancel pCancelTracker = null;

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

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

                pDataGraphs.AddDataGraph(pDataGraphBase);
            }

THEEND:
            return;

            //base.OnMouseDown(arg);
        }
Esempio n. 2
0
        // this method splits the centerline
        public void doCenterlineSplit(IFeature arcParentFeature, IPoint arcSplitPoint)
        {
            try
            {
                // set address field range fields
                string strLeftFromName  = "L_F_ADD";
                string strLeftToName    = "L_T_ADD";
                string strRightFromName = "R_F_ADD";
                string strRightToName   = "R_T_ADD";
                long   longLeftFromNum;
                long   longLeftToNum;
                long   longRightFromNum;
                long   longRightToNum;


                ICurve arcParentCurve = arcParentFeature.Shape as ICurve;

                // check if the curve is nothing
                if (arcParentCurve == null)
                {
                    MessageBox.Show("The selected polyline does not have a valid shape.", "Can Not Split", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                // check if the curve is nothing
                if (arcParentCurve.IsEmpty == true)
                {
                    MessageBox.Show("The selected polyline has an empty geometry.", "Can Not Split", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                // check if the curve is nothing
                if (arcParentCurve.Length == 0)
                {
                    MessageBox.Show("The selected polyline has a length of zero.", "Can Not Split", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }


                // make sure the required fields which contain the house numbers have been specified
                IFields arcFields = arcParentFeature.Fields;
                longLeftFromNum  = arcFields.FindField(strLeftFromName);
                longLeftToNum    = arcFields.FindField(strLeftToName);
                longRightFromNum = arcFields.FindField(strRightFromName);
                longRightToNum   = arcFields.FindField(strRightToName);

                // check for Null values in the 4 house number fields (modGlobals has comments on g_pExtension)
                if (longLeftFromNum == null | longLeftToNum == null | longRightFromNum == null | longRightToNum == null)
                {
                    MessageBox.Show("One or more of the house numbers are Null for the selected line.", "Can Not Split", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // try to get a valid house number from each of the 4 house number fields.
                // this is especially important if the fields are Text, which is common for geocoding data.
                long lngFrom_Left_HouseNum  = TryToGetValidHouseNum(arcSelectedFeature.get_Value(arcSelectedFeature.Fields.FindField("L_F_ADD")).ToString().Trim());
                long lngFrom_Right_HouseNum = TryToGetValidHouseNum(arcSelectedFeature.get_Value(arcSelectedFeature.Fields.FindField("R_F_ADD")).ToString().Trim());
                long lngTo_Left_HouseNum    = TryToGetValidHouseNum(arcSelectedFeature.get_Value(arcSelectedFeature.Fields.FindField("L_T_ADD")).ToString().Trim());
                long lngTo_Right_HouseNum   = TryToGetValidHouseNum(arcSelectedFeature.get_Value(arcSelectedFeature.Fields.FindField("R_T_ADD")).ToString().Trim());

                if (lngFrom_Left_HouseNum == -1 | lngFrom_Right_HouseNum == -1 | lngTo_Left_HouseNum == -1 | lngTo_Right_HouseNum == -1)
                {
                    MessageBox.Show("One or more of the house numbers are invalid for the selected line.  Please see the attribute table and verify that address ranges are valid.", "Can Not Split", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                bool blnMixedParity = false;

                // check left address ranges //
                // both of these values should retrun as false (if only odd numbers are on left) - meaning the to and from range for that side of the road is odd
                bool blnLeftFromIsEven = isEven(lngFrom_Left_HouseNum);
                bool blnLeftToIsEven   = isEven(lngTo_Left_HouseNum);

                // check if side of the road is both even or both odd
                if (blnLeftToIsEven != blnLeftFromIsEven)
                {
                    MessageBox.Show("The left side of the selected line has both even and odd numbers.  Ensure the left ranges are both either odd or even.", "Mixed Parity", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }


                // check right address ranges //
                // both ranges should be same
                bool blnRightFromIsEven   = isEven(lngFrom_Right_HouseNum);
                bool blnRightToIsEven     = isEven(lngTo_Right_HouseNum);
                bool blnRightSideZeros    = false;
                bool blnLeftSideZeros     = false;
                bool blnBothSidesAllZeros = false;

                // check if side of the road is both even or odd
                if (blnRightFromIsEven != blnRightToIsEven)
                {
                    MessageBox.Show("The right side of the selected line has both even and odd numbers.  Ensure the right ranges are both either odd or even.", "Mixed Parity", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // verify the 2 sides of the polyline have opposite parity (unless one side has 2 zeros)
                bool blnLeftIsEven = isEven(lngFrom_Left_HouseNum);
                bool blnOneSideHasZeros;

                // check if any of the range values are zero
                if ((lngFrom_Left_HouseNum == 0 & lngTo_Left_HouseNum == 0) | (lngFrom_Right_HouseNum == 0 & lngTo_Right_HouseNum == 0))
                {
                    blnOneSideHasZeros = true;
                }
                else
                {
                    blnOneSideHasZeros = false;
                }


                if (blnOneSideHasZeros == false)
                {
                    // check if both the right and left "from" ranges are of same parity
                    if (blnLeftFromIsEven == blnRightFromIsEven)
                    {
                        if (blnLeftFromIsEven == false)
                        {
                            MessageBox.Show("Both sides of the selected line begin with odd numbers.  Ensure one side of segment begins with an odd number and the other begins with an even number.", "Mixed Parity", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        else
                        {
                            MessageBox.Show("Both sides of the selected line begin with even numbers.  Ensure one side of segment begins with an odd number and the other begins with an even number.", "Mixed Parity", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }

                    // check if both the right and left "to" ranges are of same parity
                    if (blnLeftToIsEven == blnRightToIsEven)
                    {
                        if (blnLeftToIsEven == false)
                        {
                            MessageBox.Show("Both sides of the selected line end with odd numbers.  Ensure one side of segment ends with an odd number and the other ends with an even number.", "Mixed Parity", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        else
                        {
                            MessageBox.Show("Both sides of the selected line end with even numbers.  Ensure one side of segment ends with an odd number and the other ends with an even number.", "Mixed Parity", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                }
                else if (blnOneSideHasZeros == true)
                {
                    // check what side has the zeros, and make sure the other side has values
                    //check left side for two zeros
                    if (lngFrom_Left_HouseNum == 0 & lngTo_Left_HouseNum == 0)
                    {
                        blnLeftSideZeros = true;
                    }
                    //check right side for two zeros
                    if (lngFrom_Right_HouseNum == 0 & lngTo_Right_HouseNum == 0)
                    {
                        blnRightSideZeros = true;
                    }

                    if (blnRightSideZeros & blnLeftSideZeros)
                    {
                        MessageBox.Show("Both sides of the selected line have zero range vales.  There must be valid numbers on at least one side of the road segment.", "Zero Address Ranges", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }


                // create the point that will be used to split the selected polyline //
                if (arcSplitPoint == null)
                {
                    MessageBox.Show("A valid split point could not be created. The split point (from user mouse-click) returned null.", "Can not Split", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (arcSplitPoint.IsEmpty == true)
                {
                    MessageBox.Show("A valid split point could not be created. The split point (from user mouse-click) returned IsEmpty.", "Can not Split", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }


                // split the parent feature into 2 offspring features. we use IFeatureEdit::Split since
                // it respects geodatabase behaviour (subtypes, domains, split policies etc). it also maintains
                // M and Z values, and works for geometric networks and topological ArcInfo coverages
                IFeatureEdit arcFeatureEdit = arcParentFeature as IFeatureEdit;
                ESRI.ArcGIS.esriSystem.ISet arcNewSet;

                // start an edit operation
                clsGlobals.arcEditor.StartOperation();

                // split the segment
                arcNewSet = arcFeatureEdit.Split(arcSplitPoint);

                // make sure the segment was split into 2 segments
                if (arcNewSet.Count != 2)
                {
                    MessageBox.Show("The selected line was not split into two segments -- unknown error.  Please check selected segment and try process again.", "Can not Split", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    clsGlobals.arcEditor.AbortOperation();
                    return;
                }


                // we now need to modify the house numbers of the 2 offspring polylines. before doing this,
                // we must be sure pNewFeature1 is the offspring line that contains the parent's from vertex,
                // or our logic will not work. Since ISet::Next does not return the features in any particular
                // order, we must test and switch if needed.
                IFeature arcNewFeature1 = arcNewSet.Next() as IFeature;  // will be wrong 50% of the time
                IFeature arcNewFeature2;
                ICurve   arcNewFeatCurve1 = arcNewFeature1.Shape as ICurve;
                ICurve   arcNewFeatCurve2;

                // get the from points from each curve
                IPoint arcParentFromPnt      = arcParentCurve.FromPoint;
                IPoint arcNewFeature1FromPnt = arcNewFeatCurve1.FromPoint;

                // set up relational operator to check if points are equal
                IRelationalOperator arcRelationalOperator = arcParentFromPnt as IRelationalOperator;
                if (arcRelationalOperator.Equals(arcNewFeature1FromPnt) == true)
                {
                    // no need to switch... just set the from point for the 2nd segment (the other split segment)
                    arcNewFeature2   = arcNewSet.Next() as IFeature;
                    arcNewFeatCurve2 = arcNewFeature2.Shape as ICurve;
                }
                else // will happen 50% of the time, need to switch features
                {
                    arcNewFeature2   = arcNewFeature1;
                    arcNewFeatCurve2 = arcNewFeature2.Shape as ICurve;
                    arcNewFeature1   = arcNewSet.Next() as IFeature;
                    arcNewFeatCurve1 = arcNewFeature1.Shape as ICurve;
                }


                // get the distance along the curve (as a ratio) where the split point falls. we will need
                // this soon for the interpolation of house numbers.
                double dblDistAlongCurve = arcNewFeatCurve1.Length / (arcNewFeatCurve1.Length + arcNewFeatCurve2.Length);

                // fix the 4 house numbers that are not correct (main part of code). the other 4 numbers are
                // already correct (the FROM_LEFT and FROM_RIGHT of the first feature, and the TO_LEFT and TO_RIGHT of the second feature).
                long lngLeftNum;
                long lngRightNum;
                if (blnLeftSideZeros)
                {
                    lngLeftNum = 0;
                }
                else
                {
                    lngLeftNum = getInterpolatedHouseNumber(lngFrom_Left_HouseNum, lngTo_Left_HouseNum, dblDistAlongCurve);
                }
                if (blnRightSideZeros)
                {
                    lngRightNum = 0;
                }
                else
                {
                    lngRightNum = getInterpolatedHouseNumber(lngFrom_Right_HouseNum, lngTo_Right_HouseNum, dblDistAlongCurve);
                }



                // the following 10 lines set the TO_LEFT and TO_RIGHT numbers of the first feature //
                if (isNumeric_ACSName | isNumeric_StName) // there was an intersecting road with a numberic street name
                {
                    // use the numeric street name to populate the address ranges
                    if (isNumeric_StName) // use numeric values from street name
                    {
                        // check if intersecting numeric street name is even or odd
                        bool blnIsEven_NumericStName = isEven(Convert.ToInt64(intStreetName)); // convert b/c method is expecting long

                        if (blnIsEven_NumericStName)                                           // intersecting street is even
                        {
                            if (blnLeftSideZeros)
                            {
                                arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("L_T_ADD"), 0);
                            }
                            else
                            {
                                arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("L_T_ADD"), intStreetName - 1);
                            }
                            if (blnRightSideZeros)
                            {
                                arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("R_T_ADD"), 0);
                            }
                            else
                            {
                                arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("R_T_ADD"), intStreetName - 2);
                            }
                        }
                        else // intersecting street is odd
                        {
                            if (blnLeftSideZeros)
                            {
                                arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("L_T_ADD"), 0);
                            }
                            else
                            {
                                arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("L_T_ADD"), intStreetName - 2);
                            }
                            if (blnRightSideZeros)
                            {
                                arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("R_T_ADD"), 0);
                            }
                            else
                            {
                                arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("R_T_ADD"), intStreetName - 1);
                            }
                        }
                    }
                    else // use numeric values from acs alias field
                    {
                        // check if value is even or odd
                        bool blnIsEvenAcsName = isEven(Convert.ToInt64(intACSName));

                        if (blnIsEvenAcsName) // intersecting street is even
                        {
                            if (blnLeftSideZeros)
                            {
                                arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("L_T_ADD"), 0);
                            }
                            else
                            {
                                arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("L_T_ADD"), intACSName - 1);
                            }
                            if (blnRightSideZeros)
                            {
                                arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("R_T_ADD"), 0);
                            }
                            else
                            {
                                arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("R_T_ADD"), intACSName - 2);
                            }
                        }
                        else // intersecting street is odd
                        {
                            if (blnLeftSideZeros)
                            {
                                arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("L_T_ADD"), 0);
                            }
                            else
                            {
                                arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("L_T_ADD"), intACSName - 2);
                            }
                            if (blnRightSideZeros)
                            {
                                arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("R_T_ADD"), 0);
                            }
                            else
                            {
                                arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("R_T_ADD"), intACSName - 1);
                            }
                        }
                    }
                }
                else // there was not an intersecting road with a numberic street name
                {
                    if (lngFrom_Left_HouseNum == lngTo_Left_HouseNum) // if parent had no range of house numbers
                    {
                        arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("L_T_ADD"), lngFrom_Left_HouseNum);
                    }
                    else
                    {
                        arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("L_T_ADD"), lngLeftNum);
                    }
                    if (lngFrom_Right_HouseNum == lngTo_Right_HouseNum)
                    {
                        arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("R_T_ADD"), lngFrom_Right_HouseNum);
                    }
                    else
                    {
                        arcNewFeature1.set_Value(arcNewFeature1.Fields.FindField("R_T_ADD"), lngRightNum);
                    }
                }

                //store feature1
                arcNewFeature1.Store();

                //get field values for address ranges
                long lngFeat1_L_T_ADD = Convert.ToInt64(arcNewFeature1.get_Value(arcNewFeature1.Fields.FindField("L_T_ADD")));
                long lngFeat1_R_T_ADD = Convert.ToInt64(arcNewFeature1.get_Value(arcNewFeature1.Fields.FindField("R_T_ADD")));

                // the following lines set the FROM_LEFT and FROM_RIGHT numbers of the second feature
                // set the left_from
                if (isNumeric_ACSName | isNumeric_StName) // there was an intersecting road with a numberic street name
                {
                    // use the numeric street name to populate the address ranges
                    if (isNumeric_StName) // use numeric values from street name
                    {
                        // check if intersecting numeric street name is even or odd
                        bool blnIsEven_NumericStName = isEven(Convert.ToInt64(intStreetName)); // convert b/c method is expecting long

                        if (blnIsEven_NumericStName)                                           // intersecting street is even
                        {
                            if (blnLeftSideZeros)
                            {
                                arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("L_F_ADD"), 0);
                            }
                            else
                            {
                                arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("L_F_ADD"), intStreetName + 1);
                            }
                            if (blnRightSideZeros)
                            {
                                arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("R_F_ADD"), 0);
                            }
                            else
                            {
                                arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("R_F_ADD"), intStreetName);
                            }
                        }
                        else // intersecting street is odd
                        {
                            if (blnLeftSideZeros)
                            {
                                arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("L_F_ADD"), 0);
                            }
                            else
                            {
                                arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("L_F_ADD"), intStreetName);
                            }
                            if (blnRightSideZeros)
                            {
                                arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("R_F_ADD"), 0);
                            }
                            else
                            {
                                arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("R_F_ADD"), intStreetName + 1);
                            }
                        }
                    }
                    else  // use numeric values from acs alias field
                    {
                        // check if value is even or odd
                        bool blnIsEvenAcsName = isEven(Convert.ToInt64(intACSName));

                        if (blnIsEvenAcsName) // intersecting street is even
                        {
                            if (blnLeftSideZeros)
                            {
                                arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("L_F_ADD"), 0);
                            }
                            else
                            {
                                arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("L_F_ADD"), intACSName + 1);
                            }
                            if (blnRightSideZeros)
                            {
                                arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("R_F_ADD"), 0);
                            }
                            else
                            {
                                arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("R_F_ADD"), intACSName);
                            }
                        }
                        else // intersecting street is odd
                        {
                            if (blnLeftSideZeros)
                            {
                                arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("L_F_ADD"), 0);
                            }
                            else
                            {
                                arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("L_F_ADD"), intACSName);
                            }
                            if (blnRightSideZeros)
                            {
                                arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("R_F_ADD"), 0);
                            }
                            else
                            {
                                arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("R_F_ADD"), intACSName + 1);
                            }
                        }
                    }
                }
                else // there was not an intersecting road with a numberic street name
                {
                    if (lngFrom_Left_HouseNum < lngTo_Left_HouseNum)
                    {
                        //long intLTADD = Convert.ToInt64(arcNewFeature1.get_Value(arcNewFeature1.Fields.FindField("L_T_ADD")));
                        //arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("L_F_ADD"), arcNewFeature1.get_Value(arcNewFeature1.Fields.FindField("L_T_ADD") + 2));
                        if (blnLeftSideZeros)
                        {
                            arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("L_F_ADD"), 0);
                        }
                        else
                        {
                            arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("L_F_ADD"), lngFeat1_L_T_ADD + 2);
                        }
                    }
                    else if (lngFrom_Left_HouseNum == lngTo_Left_HouseNum) // if parent had no range of house numbers
                    {
                        arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("L_F_ADD"), lngFrom_Left_HouseNum);
                    }
                    else // if house numbers run opposite to the polyline's digitized direction
                    {
                        if (blnLeftSideZeros)
                        {
                            arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("L_F_ADD"), 0);
                        }
                        else
                        {
                            arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("L_F_ADD"), lngFeat1_L_T_ADD - 2);
                        }
                    }

                    // set the right_from for the feature 2
                    if (lngFrom_Right_HouseNum < lngTo_Right_HouseNum)
                    {
                        if (blnRightSideZeros)
                        {
                            arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("R_F_ADD"), 0);
                        }
                        else
                        {
                            arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("R_F_ADD"), lngFeat1_R_T_ADD + 2);
                        }
                    }
                    else if (lngFrom_Right_HouseNum == lngTo_Right_HouseNum)
                    {
                        arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("R_F_ADD"), lngFrom_Right_HouseNum);
                    }
                    else // if house numbers run opposite to the polyline's digitized direction
                    {
                        if (blnRightSideZeros)
                        {
                            arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("R_F_ADD"), 0);
                        }
                        else
                        {
                            arcNewFeature2.set_Value(arcNewFeature2.Fields.FindField("R_F_ADD"), lngFeat1_R_T_ADD - 2);
                        }
                    }
                }

                // store the features
                //arcNewFeature1.Store();
                arcNewFeature2.Store();

                // stop the edit operation
                clsGlobals.arcEditor.StopOperation("AGRC Split Line");
            }
            catch (Exception ex)
            {
                // abort the operation if there's an error
                clsGlobals.arcEditor.AbortOperation();


                MessageBox.Show("Error Message: " + Environment.NewLine + ex.Message + Environment.NewLine + Environment.NewLine +
                                "Error Source: " + Environment.NewLine + ex.Source + Environment.NewLine + Environment.NewLine +
                                "Error Location:" + Environment.NewLine + ex.StackTrace,
                                "UTRANS Editor tool error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return;
            }
        }
Esempio n. 3
0
        /// <summary>
        /// 按聚类号对凸包进行渲染
        /// </summary>
        /// <param name="pGeoFeatureLayer"></param>
        /// <param name="fieldName"></param>
        public void DefinePolygonUniqueValueRenderer(IGeoFeatureLayer pGeoFeatureLayer, string fieldName)
        {
            IRandomColorRamp pRandomColorRamp = new RandomColorRampClass();

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

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

            ISimpleFillSymbol pSimpleFillSymbol = new SimpleFillSymbolClass();

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

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

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


            bool ValFound;
            int  fieldIndex;

            IFields pFields = pFeatureCursor.Fields;

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

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

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

            pRandomColorRamp.CreateRamp(out bOK);

            IEnumColors pEnumColors = pRandomColorRamp.Colors;

            pEnumColors.Reset();
            for (int j = 0; j <= pUniqueValueRenderer.ValueCount - 1; j++)
            {
                string xv;
                xv = pUniqueValueRenderer.get_Value(j);
                if (xv != "")
                {
                    ISimpleFillSymbol pSimpleFillColor = pUniqueValueRenderer.get_Symbol(xv) as ISimpleFillSymbol;
                    pSimpleFillColor.Color = pEnumColors.Next();
                    pUniqueValueRenderer.set_Symbol(xv, pSimpleFillColor as ISymbol);
                }
            }
            pGeoFeatureLayer.Renderer     = (IFeatureRenderer)pUniqueValueRenderer;
            pGeoFeatureLayer.DisplayField = fieldName;
        }
Esempio n. 4
0
        private void treeLayer_AfterCheckNode(object sender, NodeEventArgs e)
        {
            this.teValue.Text = "";
            this.listBoxControlValues.Items.Clear();
            IFeatureCursor pFeatureCursor = null;
            IFeature       pFeature       = null;

            if (string.IsNullOrEmpty(this._sysFieldName))
            {
                return;
            }
            try
            {
                WaitForm.Start("正在加载列表...", "请稍后");
                HashSet <string> list = new HashSet <string>();
                foreach (TreeListNode node in this.treeLayer.GetAllCheckedNodes())
                {
                    object obj = node.GetValue("NodeObject");
                    if (obj != null && obj is SubClass)
                    {
                        SubClass sc = obj as SubClass;
                        if (sc.Parent == null)
                        {
                            continue;
                        }
                        string[] arrFc2DId = sc.Parent.Fc2D.Split(';');
                        if (arrFc2DId == null)
                        {
                            continue;
                        }
                        foreach (string fc2DId in arrFc2DId)
                        {
                            DF2DFeatureClass dffc = DF2DFeatureClassManager.Instance.GetFeatureClassByID(fc2DId);
                            if (dffc == null)
                            {
                                continue;
                            }
                            FacilityClass facc = dffc.GetFacilityClass();
                            IFeatureClass fc   = dffc.GetFeatureClass();
                            if (this._sysFieldName == "Additional")
                            {
                                if (fc == null || facc == null || facc.Name != "PipeNode")
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                if (fc == null || facc == null || facc.Name != "PipeLine")
                                {
                                    continue;
                                }
                            }

                            DFDataConfig.Class.FieldInfo fi = facc.GetFieldInfoBySystemName(this._sysFieldName);
                            if (fi == null)
                            {
                                continue;
                            }

                            IFields pFields = fc.Fields;
                            int     index   = pFields.FindField(fi.Name);
                            if (index < 0)
                            {
                                continue;
                            }
                            IField pField = pFields.get_Field(index);


                            IQueryFilter pQueryFilter = new QueryFilterClass();
                            pQueryFilter.SubFields   = pField.Name;
                            pQueryFilter.WhereClause = sc.Parent.ClassifyField + " = " + "'" + sc.Name + "'";

                            pFeatureCursor = fc.Search(pQueryFilter, false);
                            pFeature       = pFeatureCursor.NextFeature();

                            while (pFeature != null)
                            {
                                object temp = pFeature.get_Value(index);
                                if (temp == null)
                                {
                                    continue;
                                }
                                string strtemp = "";
                                switch (pField.Type)
                                {
                                case esriFieldType.esriFieldTypeDouble:
                                case esriFieldType.esriFieldTypeInteger:
                                case esriFieldType.esriFieldTypeOID:
                                case esriFieldType.esriFieldTypeSingle:
                                case esriFieldType.esriFieldTypeSmallInteger:
                                    strtemp = temp.ToString();
                                    break;

                                case esriFieldType.esriFieldTypeDate:
                                case esriFieldType.esriFieldTypeString:
                                case esriFieldType.esriFieldTypeGUID:
                                    strtemp = "'" + temp.ToString() + "'";
                                    break;

                                case esriFieldType.esriFieldTypeBlob:
                                case esriFieldType.esriFieldTypeGeometry:
                                case esriFieldType.esriFieldTypeGlobalID:
                                case esriFieldType.esriFieldTypeRaster:
                                case esriFieldType.esriFieldTypeXML:
                                default:
                                    continue;
                                }
                                if (temp != null)
                                {
                                    list.Add(strtemp);
                                }
                                pFeature = pFeatureCursor.NextFeature();
                            }
                        }
                    }
                }
                foreach (string str2 in list)
                {
                    //if (!(string.IsNullOrEmpty(str2)))
                    //{
                    this.listBoxControlValues.Items.Add(str2);
                    //}
                }
            }
            catch
            {
            }
            finally
            {
                if (pFeatureCursor != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor);
                    pFeatureCursor = null;
                }
                if (pFeature != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeature);
                    pFeature = null;
                }
                WaitForm.Stop();
            }
        }
Esempio n. 5
0
        private List <Error> GetResult(ICursor pCursor)
        {
            IRow ipRow;

            ipRow = pCursor.NextRow();
            if (ipRow == null)
            {
                return(new List <Error>());
            }

            // 判断是否有OID列
            bool bHasOID;

            bHasOID = ipRow.HasOID;

            if (!bHasOID)
            {
                SendMessage(enumMessageType.RuleError, "当前检查的对象没有OID字段,不进行检查");
                return(null);
            }

            string strErrMsg;

            if (m_structBlankPara.iType == 0)
            {
                strErrMsg = "目标字段值均为空";
            }
            else
            {
                strErrMsg = "任意目标字段值为空";
            }

            string       strErrInfo = ConstructErrorInfo();
            List <Error> pResAttr   = new List <Error>();

            IFields pFields = ipRow.Fields;
            int     nIndex  = pFields.FindField("BSM");

            while (ipRow != null)
            {
                // 添家结果记录
                Error pResInfo = new Error();
                pResInfo.DefectLevel = this.m_DefectLevel;
                pResInfo.RuleID      = this.InstanceID;

                int OID;
                OID          = ipRow.OID;
                pResInfo.OID = OID;

                if (nIndex >= 0)
                {
                    pResInfo.BSM = ipRow.get_Value(nIndex).ToString();
                }

                pResInfo.LayerName = m_structBlankPara.strFtName;

                // 错误信息
                if (m_structBlankPara.strScript.Trim() != "" && m_structBlankPara.strScript != null)
                {
                    pResInfo.Description = m_structBlankPara.strScript;
                }
                else
                {
                    pResInfo.Description = strErrInfo;
                }

                pResAttr.Add(pResInfo);

                ipRow = pCursor.NextRow();
            }
            return(pResAttr);
        }
Esempio n. 6
0
        private string get_SIDFieldName(IFields f1, IFields f2, string sidSuffix)
        {
            string theReturn = "";

            for (int i = 0; i < f1.FieldCount; i++)
            {
                string name = f1.get_Field(i).Name;
                if (name.EndsWith(sidSuffix))
                {
                    // Find a field with the same name in the table
                    int theTableIdx = f2.FindField(name);
                    if (theTableIdx >= 0)
                    {
                        theReturn = name;
                        break;
                    }
                }
            }

            return theReturn;
        }
Esempio n. 7
0
        /// <summary>
        ///  保存数据
        /// </summary>
        /// <returns></returns>
        private bool SaveData(ref List <Error> pResult)
        {
            try
            {
                string strSql;
                // 判断是图层的几何类型:点、线、面
                int nGeoType = GetLayerGeoType(pSrcFeatClass);
                // 在入口写入目标表名称
                if (nGeoType == 1) // 点
                {
                    strSql = "update LR_ResultEntryRule set TargetFeatClass2='" + m_pPara.strTargetLayer +
                             "|' where RuleInstID='" +
                             this.m_InstanceID + "'";
                    Hy.Common.Utility.Data.AdoDbHelper.ExecuteSql(null, strSql);
                }
                //else if (nGeoType == 2) // 线
                //{
                //    strSql = "update LR_ResultEntryRule set TargetFeatClass1='" + m_PointLayerName +
                //             "',TargetFeatClass2='" + m_PointLayerName + "|" + m_pPara.strTargetLayer +
                //             "' where RuleInstID='" + m_RuleInfo.strID + "'";
                //    GT_CARTO.CommonAPI.ado_ExecuteSQL(m_pResultAdoConn, strSql);
                //}
                //else if (nGeoType == 3) // 面
                //{
                //    strSql = "update LR_ResultEntryRule set TargetFeatClass1='" + m_PointLayerName +
                //             "',TargetFeatClass2='" + m_PointLayerName + "|" + m_pPara.strTargetLayer +
                //             "' where RuleInstID='" + m_RuleInfo.strID + "'";
                //    GT_CARTO.CommonAPI.ado_ExecuteSQL(m_pResultAdoConn, strSql);
                //}

                IFields pFields = pSrcFeatClass.Fields;
                int     nIndex  = pFields.FindField("BSM");

                foreach (DictionaryEntry dn in m_RepeatOIDtoOID)
                {
                    string key = dn.Key.ToString();
                    Error  err = new Error();
                    err.DefectLevel = this.m_DefectLevel;
                    err.RuleID      = this.InstanceID;
                    err.LayerName   = this.m_strSrcLayer;

                    RuleExpression.LRResultInfo pResInfo = new RuleExpression.LRResultInfo();
                    err.OID      = Convert.ToInt32(m_PointtoOID[key]);
                    err.ReferOID = dn.Value.ToString();
                    if (nIndex >= 0)
                    {
                        IFeature pFt = pSrcFeatClass.GetFeature(pResInfo.OID);
                        err.BSM = pFt.get_Value(nIndex).ToString();
                        string[] listOID  = err.ReferOID.Split(',');
                        string   listBSM2 = "";
                        for (int i = 0; i < listOID.Length; i++)
                        {
                            int      nOIDTemp = Convert.ToInt32(listOID[i]);
                            IFeature pFt1     = pSrcFeatClass.GetFeature(nOIDTemp);
                            listBSM2 += pFt1.get_Value(nIndex).ToString() + ",";
                        }
                        listBSM2     = listBSM2.Substring(0, listBSM2.Length - 1);
                        err.ReferBSM = listBSM2;
                    }
                    err.Description = string.Format("'{0}'中标识码为'{1}'与标识码为'{2}'的地物相互重叠,实地两相邻点距离不应小于{3}。", m_pPara.strTargetLayer, pResInfo.BSM, pResInfo.BSM2, m_pPara.dPointDist);
                    pResult.Add(err);
                }
            }
            catch (Exception ex)
            {
                //Hy.Check.Rule.Helper.LogAPI.CheckLog.AppendErrLogs(ex.ToString());
                //显示错误信息;
                //XtraMessageBox.Show("RulePointDist:SaveData():" + ex.Message + " ");
                return(false);
            }
            return(true);
        }
        private static void setFeatureSpatialReference(IFeatureLayer ifl_active, IName name, out IFeatureWorkspace workspace, out IWorkspaceEdit iwe, out IFields flds)
        {
            IGeoDataset igd_dest = (IGeoDataset)ifl_active.FeatureClass;
            // Open the workspace through the name object.
            workspace = (IFeatureWorkspace)name.Open();
            iwe = (IWorkspaceEdit)workspace;

            ESRI.ArcGIS.Geodatabase.IObjectClassDescription objectClassDescription = new ESRI.ArcGIS.Geodatabase.FeatureClassDescriptionClass();
            flds = objectClassDescription.RequiredFields;
            IFieldEdit fld_Edit = (IFieldEdit)flds.get_Field(flds.FindField("Shape"));

            IGeometryDefEdit pGeoDef = (IGeometryDefEdit)fld_Edit.GeometryDef;
            pGeoDef.SpatialReference_2 = igd_dest.SpatialReference;
        }
Esempio n. 9
0
        public static void DefineUniqueValueRenderer(IGeoFeatureLayer pGeoFeatureLayer, string fieldName)
        {
            IRandomColorRamp pRandomColorRamp = new RandomColorRampClass();

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

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

            ISimpleFillSymbol pSimpleFillSymbol = new SimpleFillSymbolClass();

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

            //These properties should be set prior to adding values.
            pUniqueValueRenderer.FieldCount = 1;
            pUniqueValueRenderer.set_Field(0, fieldName);
            pUniqueValueRenderer.DefaultSymbol    = pSimpleFillSymbol as ISymbol;
            pUniqueValueRenderer.UseDefaultSymbol = true;

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


            bool ValFound;
            int  fieldIndex;

            IFields pFields = pFeatureCursor.Fields;

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

                string classValue;
                classValue = pFeature.get_Value(fieldIndex) as string;

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

            pRandomColorRamp.CreateRamp(out bOK);

            IEnumColors pEnumColors = pRandomColorRamp.Colors;

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

            //'** If you didn't use a predefined color ramp in a style, use "Custom" here.
            //'** Otherwise, use the name of the color ramp you selected.

            pUniqueValueRenderer.ColorScheme = pRandomColorRamp.Name;//"Custom";

            ITable pTable   = pDisplayTable as ITable;
            bool   isString = pTable.Fields.get_Field(fieldIndex).Type ==
                              esriFieldType.esriFieldTypeString;

            pUniqueValueRenderer.set_FieldType(0, isString);
            pGeoFeatureLayer.Renderer = pUniqueValueRenderer as IFeatureRenderer;

            //This makes the layer properties symbology tab show the correct interface.
            IUID pUID = new UIDClass();

            pUID.Value = "{683C994E-A17B-11D1-8816-080009EC732A}";
            pGeoFeatureLayer.RendererPropertyPageClassID = pUID as UIDClass;
        }
Esempio n. 10
0
        /// <summary>
        /// Get the field index of the specified field in the fields collection.
        /// </summary>
        /// <param name="fields">The fields collection.</param>
        /// <param name="fieldName">The name of the field for which to get the field index.</param>
        /// <returns>Returns the field index of the given field name if it exists, -1 if it does not.</returns>
        public static int GetFieldIndex(IFields fields, string fieldName)
        {
            //string methodName = MethodInfo.GetCurrentMethod().Name;

            int index = -1;
            if (fields != null && fieldName != String.Empty)
                index = fields.FindField(fieldName);
            //else
            //    _logger.LogFormat("{0}: Null fields collection or field name parameter.", methodName, LogLevel.enumLogLevelWarn);

            return index;
        }
Esempio n. 11
0
        // 获取检查结果
        private List <Error> GetResult(ICursor pCursor)
        {
            IRow ipRow;

            ipRow = pCursor.NextRow();
            if (ipRow == null)
            {
                return(null);
            }
            // 判断是否有OID列
            bool bHasOID;

            bHasOID = ipRow.HasOID;

            if (!bHasOID)
            {
                return(null);
            }
            IFields pFields = ipRow.Fields;
            int     nIndex  = pFields.FindField("BSM");

            int nIndexJSMJ     = pFields.FindField(strField1);
            int nIndexJSMJDIST = pFields.FindField(strField2);

            //string strErrInfo = ConstructErrorInfo();
            List <Error> pResAttr = new List <Error>();

            while (ipRow != null)
            {
                int OID;
                OID = ipRow.OID;

                Error err = new Error();
                err.DefectLevel = this.m_DefectLevel;
                err.RuleID      = this.InstanceID;

                err.OID       = OID;
                err.LayerName = m_structSqlPara.strFtName; // 目标图层
                if (nIndex >= 0)
                {
                    err.BSM = ipRow.get_Value(nIndex).ToString();
                }

                // 错误信息
                if (m_structSqlPara.strScript.Contains("椭球面积计算不正确"))
                {
                    double dJSMJ     = Convert.ToDouble(ipRow.get_Value(nIndexJSMJ));
                    double dJSMJDIST = Convert.ToDouble(ipRow.get_Value(nIndexJSMJDIST));
                    double dPlus     = Math.Abs(dJSMJ - dJSMJDIST);
                    //pResInfo.strErrInfo = "数据库椭球面积为"+dJSMJ.ToString("f2")+"平方米,质检软件计算椭球面积为"+dJSMJDIST.ToString("f2")+"平方米,二者相差"+dPlus.ToString("f2")+"平方米";
                    //pResInfo.strErrInfo = string.Format(Helper.ErrMsgFormat.ERR_4401, m_structSqlPara.strFtName, pResInfo.BSM, "数据库椭球面积", dJSMJ.ToString("f2") + "平方米", dJSMJDIST.ToString("f2") + "平方米", dPlus.ToString("f2") + "平方米");
                    err.Description = string.Format("数据库中'{0}'层中标识码为'{1}'的{2}({3}平方米)与计算的椭球面积({4}平方米)不一致,两者差值为{5}平方米",
                                                    m_structSqlPara.strFtName, err.BSM, "数据库椭球面积", dJSMJ.ToString("f2"), dJSMJDIST.ToString("f2"), dPlus.ToString("f2"));
                }
                else
                {
                    err.Description = m_structSqlPara.strScript;
                    //pResInfo.strErrInfo = string.Format("'{0}'图层标识码为'{1}'的图斑地类面积的值不正确,应大于0", pResInfo.strTargetLayer, pResInfo.BSM);
                }

                pResAttr.Add(err);
                ipRow = pCursor.NextRow();
            }
            return(pResAttr);
        }
Esempio n. 12
0
        private void btnExecute_Click(object sender, EventArgs e)
        {
            string smpFtrNm = cmbSampleFeatureClass.Text;
            string depStr   = cmbDepedent.Text;
            string outPath  = txtOutputPath.Text;
            double alpha    = System.Convert.ToDouble(nudAlpha.Value);
            string uLinkStr = cmbLink.Text;

            if (smpFtrNm == null || smpFtrNm == "")
            {
                MessageBox.Show("You must select a feature Class or table", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (depStr == "" || depStr == null)
            {
                MessageBox.Show("You must select a dependent field", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (uLinkStr == "" || uLinkStr == null)
            {
                MessageBox.Show("You must select a link from the link combo box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (!cmbLink.Items.Contains(uLinkStr))
            {
                MessageBox.Show("You must select a link from the link combo box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (outPath == "" || outPath == null)
            {
                MessageBox.Show("You must select an output Path", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            List <string> lstInd = new List <string>();
            List <string> lstCat = new List <string>();

            for (int i = 0; i < lstIndependent.Items.Count; i++)
            {
                string s = lstIndependent.Items[i].ToString();
                lstInd.Add(s);
                IField fld = flds.get_Field(flds.FindField(s));
                if (fld.Type == esriFieldType.esriFieldTypeString)
                {
                    lstCat.Add(s);
                }
            }
            if (lstInd.Count < 1)
            {
                MessageBox.Show("You must select at least one independent field", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            Statistics.dataPrepGlm.LinkFunction uLink = (Statistics.dataPrepGlm.LinkFunction)Enum.Parse(typeof(Statistics.dataPrepGlm.LinkFunction), uLinkStr);
            this.Visible = false;
            ITable ftrCls = ftrDic[smpFtrNm];

            string[] depArr            = { depStr };
            Statistics.dataPrepGlm glm = new Statistics.dataPrepGlm(ftrCls, depArr, lstInd.ToArray(), lstCat.ToArray());
            glm.Link = uLink;
            glm.writeModel(outPath);
            glm.getReport(alpha);
            this.Close();
        }
Esempio n. 13
0
        private void DWGLoad()
        {
            AcadApplication     acadApp             = new AcadApplicationClass();
            IGeometryCollection pGeometryCollection = new PolygonClass();

            foreach (DataGridViewRow eRow in dataGridView1.Rows)
            {
                if (eRow.Cells[0].Value != null && (bool)eRow.Cells[0].Value == true)
                {
                    if (eRow.Cells["FileSuffix"].Value.ToString().ToLower() == "dwg")
                    {
                        object       o           = Type.Missing;
                        string       strFileName = eRow.Cells["FilePath"].Value.ToString();
                        AcadDocument acadDoc     = acadApp.Documents.Open(strFileName, true, null);
                        System.Windows.Forms.Application.DoEvents();
                        AcadLayer        acadLyer    = acadDoc.Layers.Item(1);
                        AcadSelectionSet ssetObj     = acadDoc.SelectionSets.Add("FWX");
                        short[]          vFilterType = null;
                        object[]         vFilterData = null;
                        vFilterType    = new short[1];
                        vFilterType[0] = 8;
                        vFilterData    = new object[1];
                        vFilterData[0] = "FWX";
                        //ISegmentCollection pSegmentCollection = new RingClass();
                        //pSegmentCollection.AddSegment()
                        ssetObj.Select(AcSelect.acSelectionSetAll, null, null, vFilterType, vFilterData);
                        foreach (AcadObject eEntity in ssetObj)
                        {
                            if (eEntity.ObjectName == "AcDbPolyline")
                            {
                                AcadLWPolyline pPline = (AcadLWPolyline)eEntity;
                                double[]       polyLinePoint;
                                polyLinePoint = (Double[])pPline.Coordinates;
                                int i, pointCount = polyLinePoint.Length / 2;
                                IPointCollection pPointColl = new RingClass();
                                for (i = 0; i < polyLinePoint.Length - 1; i = i + 2)
                                {
                                    IPoint pPoint = new PointClass();
                                    pPoint.X = polyLinePoint[i];
                                    pPoint.Y = polyLinePoint[i + 1];
                                    pPointColl.AddPoint(pPoint, ref o, ref o);
                                }
                                pGeometryCollection.AddGeometry(pPointColl as IRing, ref o, ref o);
                            }
                        }
                    }
                    else if (eRow.Cells["FileSuffix"].Value.ToString().ToLower() == "txt")
                    {
                        object o           = Type.Missing;
                        string strFileName = eRow.Cells["FilePath"].Value.ToString();
                        m_strPointArray.Clear();
                        StreamReader ReadFile = new StreamReader(strFileName, System.Text.Encoding.Default);
                        while (!ReadFile.EndOfStream)
                        {
                            m_strPointArray.Add(ReadFile.ReadLine());
                        }
                        ReadFile.Close();
                        IPointCollection pPointColl = new RingClass();
                        for (int i = 0; i < m_strPointArray.Count; i++)
                        {
                            if (m_strPointArray[i].StartsWith("J"))
                            {
                                string[] split  = m_strPointArray[i].Split(new Char[] { ',', ',' });
                                IPoint   pPoint = new PointClass();
                                pPoint.X = Convert.ToDouble(split[2]);
                                pPoint.Y = Convert.ToDouble(split[3]);
                                pPointColl.AddPoint(pPoint, ref o, ref o);
                            }
                        }
                        pGeometryCollection.AddGeometry(pPointColl as IRing, ref o, ref o);
                    }
                }
            }
            acadApp.Quit();
            //DWGLoaded(this.m_Popfrm, new EventArgs());//引发完成事件,有异常待研究
            System.Windows.Forms.Application.DoEvents();
            if (pGeometryCollection.GeometryCount > 0)
            {
                m_pFeature       = EngineFuntions.m_Layer_BusStation.FeatureClass.CreateFeature();
                m_pFeature.Shape = pGeometryCollection as IPolygon;
                IFields fields = m_pFeature.Fields;
                int     nIndex = fields.FindField("任务号");
                m_pFeature.set_Value(nIndex, m_strFolder.Substring(m_strFolder.LastIndexOf("\\") + 1));
                m_pFeature.Store();
                EngineFuntions.ZoomTo(m_pFeature.ShapeCopy);
            }
            else
            {
                m_pFeature = null;
            }
        }
Esempio n. 14
0
        private void save_btn_Click(object sender, EventArgs e)
        {
            try
            {
                string            fcName           = featureClass_txtbox.Text;
                Type              factoryType      = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
                IWorkspaceFactory workspaceFactory = (WorkspaceFactory)Activator.CreateInstance(factoryType);
                IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(gdbToSaveToTxtBox.Text, 0);

                System.Object objectFromXml = DeserializeAnXMLFile(xmlDocLoc_txtBox.Text);

                ISpatialReference sr;

                if (((IGeometry)objectFromXml).GeometryType == esriGeometryType.esriGeometryPolygon)
                {
                    Polygon   feature    = objectFromXml as Polygon;
                    IPolygon4 newPolygon = objectFromXml as IPolygon4;
                    sr = newPolygon.SpatialReference;
                }
                else if (((IGeometry)objectFromXml).GeometryType == esriGeometryType.esriGeometryPolyline)
                {
                    Polyline   feature    = objectFromXml as Polyline;
                    IPolyline4 newPolygon = objectFromXml as IPolyline4;
                    sr = newPolygon.SpatialReference;
                }
                else
                {
                    Point  feature  = objectFromXml as Point;
                    IPoint newPoint = feature as IPoint;
                    sr = feature.SpatialReference;
                }


                IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
                IObjectClassDescription  ocDescription = (IObjectClassDescription)fcDescription;
                IFields fields = ocDescription.RequiredFields;

                IField           field           = fields.get_Field(fields.FindField(fcDescription.ShapeFieldName));
                IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)field.GeometryDef;
                //geometryDefEdit.HasZ_2 = ((IGeometry)objectFromXml).

                if (((IZAware)objectFromXml).ZAware)
                {
                    geometryDefEdit.HasZ_2 = true;
                }

                if (((IGeometry)objectFromXml).GeometryType == esriGeometryType.esriGeometryPolygon)
                {
                    geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
                }
                else if (((IGeometry)objectFromXml).GeometryType == esriGeometryType.esriGeometryPolyline)
                {
                    geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline;
                }
                else
                {
                    geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
                }

                geometryDefEdit.SpatialReference_2 = sr;

                IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(featureClass_txtbox.Text, fields, ocDescription.InstanceCLSID,
                                                                                 ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName,
                                                                                 "");

                IFeatureCursor featureCursor = featureClass.Insert(true);
                IFeatureBuffer featureBuffer = featureClass.CreateFeatureBuffer();
                featureBuffer.Shape = (IGeometry)objectFromXml;
                featureCursor.InsertFeature(featureBuffer);

                status_txtBox.Text = "DONE";
            }
            catch (Exception ex)
            {
                status_txtBox.Text = ex.ToString();
            }
        }
Esempio n. 15
0
        private List <CPoint> LookingForNeighboursDT(IFeatureLayer pFeatureLayer, double dblThreshold, int intPtNumLast,
                                                     ref long lngTimeForSearching, ref long lngTimeForDT, ref long lngMemory, ref long lngMemoryDT,
                                                     ref long lngMemoryDTProcess, ref int intOutPut, string strTINPath)
        {
            lngMemory = GC.GetTotalMemory(true);
            //lngMemoryDT = GC.GetTotalMemory(true);
            //lngMemoryDTProcess = Process.GetProcessesByName("ContinuousGeneralizer.vshost")[0].WorkingSet64;
            long lngStartTime = System.Environment.TickCount; //record the start time

            //lngMemoryDT = Process.GetProcessesByName("ContinuousGeneralizer.vshost")[0].WorkingSet64;
            //Process .GetProcessesByName("ContinuousGeneralizer.vshost")[0].
            //create TIN
            IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
            IGeoDataset   pGDS          = (IGeoDataset)pFeatureClass;
            IEnvelope     pEnv          = (IEnvelope)pGDS.Extent;

            pEnv.SpatialReference = pGDS.SpatialReference;
            IFields pFields      = pFeatureClass.Fields;
            IField  pHeightFiled = new FieldClass();

            try
            {
                pHeightFiled = pFields.get_Field(pFields.FindField("Id"));
            }
            catch (Exception)
            {
                pHeightFiled = pFields.get_Field(pFields.FindField("ID"));
                throw;
            }

            //ITinWorkspace
            ITinEdit pTinEdit = new TinClass();

            pTinEdit.InitNew(pEnv);
            object Missing = Type.Missing;

            pTinEdit.AddFromFeatureClass(pFeatureClass, null, pHeightFiled, null, esriTinSurfaceType.esriTinHardLine, ref Missing);

            lngTimeForDT = System.Environment.TickCount - lngStartTime;   //Time for constructing DT
            //long lngMemoryafterTinEdit = GC.GetTotalMemory(false) - lngMemoryDT;
            //GC.Collect();
            //lngMemoryDT = GC.GetTotalMemory(true) - lngMemoryDT;
            //lngMemoryDTProcess = Process.GetProcessesByName("ContinuousGeneralizer.vshost")[0].WorkingSet64 - lngMemoryDTProcess;

            //C5.LinkedList<int> intLLt = new C5.LinkedList<int>();


            ITinNodeCollection pTinNodeCollection = (ITinNodeCollection)pTinEdit;
            List <CPoint>      CptLt = new List <CPoint>(pTinNodeCollection.NodeCount);

            for (int i = 1; i <= pTinNodeCollection.NodeCount; i++)   //i=1-4: super node
            {
                ITinNode pNode = pTinNodeCollection.GetNode(i);
                CPoint   cpt   = new CPoint(pNode);
                //cpt.intTS = new C5.TreeSet<int>();
                CptLt.Add(cpt);
            }
            //long lngMemoryafterfetching = GC.GetTotalMemory(true);
            //lngMemoryDT = GC.GetTotalMemory(true) - lngMemoryDT;

            //Looking for neighbours based on Breadth First Search

            if (intPtNumLast != -1)
            {
                dblThreshold = dblThreshold * Math.Pow(Convert.ToDouble(intPtNumLast) / Convert.ToDouble(CptLt.Count - 4), 0.5);  //---------------dblThreshold------------------------------------------------//

                //Math.Pow(1.8 / Convert.ToDouble(CptLt.Count - 4), 0.5);//---------------dblThreshold------------------------------------------------//
            }
            //double dblThresholdDT = (1 + Math.Sqrt(2)) / 2 * dblThreshold;

            lngTimeForSearching = System.Environment.TickCount;  //the start time
            SCG.LinkedList <int> intTargetLLt = new SCG.LinkedList <int>();
            SCG.LinkedList <int> intAllLLt    = new SCG.LinkedList <int>();
            for (int i = 0; i < CptLt.Count; i++)
            {
                CptLt[i].isTraversed = true;

                intTargetLLt = new SCG.LinkedList <int>();
                intTargetLLt.AddLast(CptLt[i].pTinNode.Index);
                intAllLLt = new SCG.LinkedList <int>();
                intAllLLt.AddLast(CptLt[i].pTinNode.Index);

                while (intTargetLLt.Count > 0)
                {
                    intTargetLLt = BSF(CptLt[i], ref CptLt, ref intTargetLLt, ref intAllLLt, dblThreshold, ref intOutPut);
                }
                intOutPut--;  //the point will take itself as a close point, so we have to minus 1
                //CptLt[i].intTS.Remove(CptLt[i].pTinNode.Index);
                RestoreIsTraversed(ref CptLt, ref intAllLLt);
                //intAllLLt.Dispose();
            }
            //long lngMemoryaftersearch = GC.GetTotalMemory(true);
            lngTimeForSearching = System.Environment.TickCount - lngTimeForSearching;  //the result time
            lngMemory           = GC.GetTotalMemory(true) - lngMemory;
            pTinEdit.SaveAs(strTINPath + "\\" + pFeatureLayer.Name, true);
            long lngFileSize = CHelpFunc.GetDirectoryLength(strTINPath + "\\" + pFeatureLayer.Name);

            lngMemory  += lngFileSize;
            lngMemoryDT = lngFileSize;

            return(CptLt);
        }
Esempio n. 16
0
        public static void ConvertLabels2StandardAnno(IMap imap_0, ILayer ilayer_0, string string_0)
        {
            int i;
            IAnnotateLayerProperties     annotateLayerProperty;
            IElementCollection           elementCollection;
            IElementCollection           elementCollection1;
            ILabelEngineLayerProperties2 d;
            ISymbolIdentifier2           symbolIdentifier2;
            IActiveView imap0 = imap_0 as IActiveView;

            if (ilayer_0 is IGeoFeatureLayer)
            {
                IGeoFeatureLayer ilayer0   = ilayer_0 as IGeoFeatureLayer;
                IWorkspace       workspace = (ilayer0 as IDataset).Workspace;
                if (workspace.Type != esriWorkspaceType.esriFileSystemWorkspace)
                {
                    IFeatureClass           featureClass = ilayer0.FeatureClass;
                    IGeoDataset             geoDataset   = featureClass as IGeoDataset;
                    IAnnotationLayerFactory fDOGraphicsLayerFactoryClass =
                        new FDOGraphicsLayerFactory() as IAnnotationLayerFactory;
                    ISymbolCollection2 symbolCollectionClass = new SymbolCollection() as ISymbolCollection2;
                    IAnnotateLayerPropertiesCollection annotateLayerPropertiesCollectionClass =
                        new AnnotateLayerPropertiesCollection();
                    IAnnotateLayerPropertiesCollection annotationProperties = ilayer0.AnnotationProperties;
                    for (i = 0; i < annotationProperties.Count; i++)
                    {
                        annotationProperties.QueryItem(i, out annotateLayerProperty, out elementCollection,
                                                       out elementCollection1);
                        if (annotateLayerProperty != null)
                        {
                            annotateLayerPropertiesCollectionClass.Add(annotateLayerProperty);
                            d = annotateLayerProperty as ILabelEngineLayerProperties2;
                            IClone symbol = d.Symbol as IClone;
                            symbolCollectionClass.AddSymbol(symbol.Clone() as ISymbol,
                                                            string.Concat(annotateLayerProperty.Class, " ", i.ToString()), out symbolIdentifier2);
                            d.SymbolID = symbolIdentifier2.ID;
                        }
                    }
                    annotateLayerProperty = null;
                    d = null;
                    IGraphicsLayerScale graphicsLayerScaleClass = new GraphicsLayerScale();
                    if (imap_0.ReferenceScale != 0)
                    {
                        graphicsLayerScaleClass.ReferenceScale = imap_0.ReferenceScale;
                    }
                    else
                    {
                        try
                        {
                            graphicsLayerScaleClass.ReferenceScale = imap_0.MapScale;
                        }
                        catch (Exception exception)
                        {
                            Logger.Current.Error("", exception, null);
                        }
                    }
                    graphicsLayerScaleClass.Units = imap_0.MapUnits;
                    IFeatureClassDescription annotationFeatureClassDescriptionClass =
                        new AnnotationFeatureClassDescription() as IFeatureClassDescription;
                    IFields requiredFields =
                        (annotationFeatureClassDescriptionClass as IObjectClassDescription).RequiredFields;
                    IField field =
                        requiredFields.Field[
                            requiredFields.FindField(annotationFeatureClassDescriptionClass.ShapeFieldName)];
                    IGeometryDefEdit geometryDef = field.GeometryDef as IGeometryDefEdit;
                    geometryDef.SpatialReference_2 = geoDataset.SpatialReference;
                    IOverposterProperties overposterProperties = (imap_0 as IMapOverposter).OverposterProperties;
                    IAnnotationLayer      annotationLayer      =
                        fDOGraphicsLayerFactoryClass.CreateAnnotationLayer(workspace as IFeatureWorkspace,
                                                                           featureClass.FeatureDataset, string_0, geometryDef, null,
                                                                           annotateLayerPropertiesCollectionClass, graphicsLayerScaleClass,
                                                                           symbolCollectionClass as ISymbolCollection, true, true, false, true, overposterProperties,
                                                                           "");
                    (annotationLayer as IGraphicsLayer).Activate(imap0.ScreenDisplay);
                    for (i = 0; i < annotateLayerPropertiesCollectionClass.Count; i++)
                    {
                        annotateLayerPropertiesCollectionClass.QueryItem(i, out annotateLayerProperty,
                                                                         out elementCollection, out elementCollection1);
                        if (annotateLayerProperty != null)
                        {
                            annotateLayerProperty.FeatureLayer      = ilayer0;
                            annotateLayerProperty.GraphicsContainer = annotationLayer as IGraphicsContainer;
                            annotateLayerProperty.AddUnplacedToGraphicsContainer = true;
                            annotateLayerProperty.CreateUnplacedElements         = true;
                            annotateLayerProperty.DisplayAnnotation  = true;
                            annotateLayerProperty.FeatureLinked      = true;
                            annotateLayerProperty.LabelWhichFeatures = esriLabelWhichFeatures.esriAllFeatures;
                            annotateLayerProperty.UseOutput          = true;
                            d                   = annotateLayerProperty as ILabelEngineLayerProperties2;
                            d.SymbolID          = i;
                            d.AnnotationClassID = i;
                            (d.OverposterLayerProperties as IOverposterLayerProperties2).TagUnplaced = true;
                        }
                    }
                    annotateLayerPropertiesCollectionClass.Sort();
                    IAnnotateMapProperties annotateMapPropertiesClass = new AnnotateMapProperties()
                    {
                        AnnotateLayerPropertiesCollection = annotateLayerPropertiesCollectionClass
                    };
                    ITrackCancel cancelTrackerClass = new CancelTracker();
                    (imap_0.AnnotationEngine as IAnnotateMap2).Label(overposterProperties, annotateMapPropertiesClass,
                                                                     imap_0, cancelTrackerClass);
                    for (i = 0; i < annotateLayerPropertiesCollectionClass.Count; i++)
                    {
                        annotateLayerPropertiesCollectionClass.QueryItem(i, out annotateLayerProperty,
                                                                         out elementCollection, out elementCollection1);
                        if (annotateLayerProperty != null)
                        {
                            annotateLayerProperty.FeatureLayer = null;
                        }
                    }
                    imap_0.AddLayer(annotationLayer as ILayer);
                    ilayer0.DisplayAnnotation = false;
                    imap0.Refresh();
                }
            }
        }
Esempio n. 17
0
        private void FrmRegionExtract_Load(object sender, EventArgs e)//图层列表出来
        {
            DataGridViewRow dgvRow   = new DataGridViewRow();
            int             LayerNum = 0;

            for (int i = 0; i < _map.LayerCount; i++)
            {
                if (_map.get_Layer(i).Visible)
                {
                    if (_map.get_Layer(i) is IGroupLayer)
                    {
                        ICompositeLayer pCompositeLayer = (ICompositeLayer)_map.get_Layer(i);
                        for (int j = 0; j < pCompositeLayer.Count; j++)
                        {
                            if (pCompositeLayer.get_Layer(j).Visible)
                            {
                                //注记层,不提取
                                if (pCompositeLayer.get_Layer(j) is IAnnotationLayer | pCompositeLayer.get_Layer(j) is GdbRasterCatalogLayer | pCompositeLayer.get_Layer(j) is IRasterLayer)
                                {
                                    continue;
                                }
                                LayerNum++;
                                IFeatureLayer pFeatLayer = pCompositeLayer.get_Layer(j) as IFeatureLayer;

                                dgvRow = dgvLayerChoose.Rows[dgvLayerChoose.Rows.Add()];
                                dgvRow.Cells[0].Value = LayerNum;
                                dgvRow.Cells[1].Value = pFeatLayer.Name;
                                dgvRow.Cells[1].Tag   = pFeatLayer;
                                DataGridViewCheckBoxCell dgvCheckBoxCell = new DataGridViewCheckBoxCell();
                                dgvCheckBoxCell       = dgvRow.Cells[2] as DataGridViewCheckBoxCell;
                                dgvCheckBoxCell.Value = true;

                                //chkFeatureLayer.Add(pFeatLayer);
                                if (pFeatLayer.Name == "省级行政区")
                                {
                                    _featureLayerRegion = pFeatLayer;
                                }
                            }
                        }
                    }
                    else
                    {
                        if (_map.get_Layer(i) is IAnnotationLayer | _map.get_Layer(i) is GdbRasterCatalogLayer | _map.get_Layer(i) is IRasterLayer)
                        {
                            continue;
                        }
                        LayerNum++;
                        IFeatureLayer pFeatLayer = _map.get_Layer(i) as IFeatureLayer;

                        dgvRow = dgvLayerChoose.Rows[dgvLayerChoose.Rows.Add()];
                        dgvRow.Cells[0].Value = LayerNum;
                        dgvRow.Cells[1].Value = pFeatLayer.Name;
                        dgvRow.Cells[1].Tag   = pFeatLayer;
                        DataGridViewCheckBoxCell dgvCheckBoxCell = new DataGridViewCheckBoxCell();
                        dgvCheckBoxCell       = dgvRow.Cells[2] as DataGridViewCheckBoxCell;
                        dgvCheckBoxCell.Value = true;


                        if (pFeatLayer.Name == "省级行政区")
                        {
                            _featureLayerRegion = pFeatLayer;
                        }
                    }
                }
            }
            strArryExpress = new string[LayerNum];

            //初始化文件类型下拉框
            this.cmbFileStyle.Items.Add("File GeoDatabase");
            this.cmbFileStyle.Items.Add("SHP File");
            this.cmbFileStyle.Items.Add("Personal GeoDatabase");
            this.cmbFileStyle.SelectedIndex = 0;
            this.cmbFileStyle.DropDownStyle = ComboBoxStyle.DropDownList;
            this.txtFileRoute.Enabled       = false;

            //行政区选择
            int RegionNum = 0;

            if (_featureLayerRegion != null)
            {
                IFeatureCursor featureCursor = _featureLayerRegion.FeatureClass.Search(null, true);
                IFeature       feature       = featureCursor.NextFeature();
                while (feature != null)
                {
                    RegionNum++;
                    IFields fields     = feature.Fields;
                    int     fieldsNum  = fields.FindField("NAME");
                    string  RegionName = feature.get_Value(fieldsNum).ToString();
                    dgvRegionChoose.Rows.Add(RegionNum, RegionName);
                    feature = featureCursor.NextFeature();
                }
            }
            //bRegionLayer = new bool[ LayerNum];
            strRegionLayer = new string[LayerNum];
            //dgvLayerChoose.ReadOnly = true;
        }
Esempio n. 18
0
 private void method_0()
 {
     if (((this.igeoFeatureLayer_0 != null) && (this.iannotateLayerProperties_0 != null)) &&
         (this.igeoFeatureLayer_0.FeatureClass != null))
     {
         this.bool_0 = false;
         IFields fields = this.igeoFeatureLayer_0.FeatureClass.Fields;
         for (int i = 0; i < fields.FieldCount; i++)
         {
             IField field = fields.get_Field(i);
             if (((((field.Type == esriFieldType.esriFieldTypeDate) ||
                    (field.Type == esriFieldType.esriFieldTypeDouble)) ||
                   ((field.Type == esriFieldType.esriFieldTypeGlobalID) ||
                    (field.Type == esriFieldType.esriFieldTypeGUID))) ||
                  (((field.Type == esriFieldType.esriFieldTypeInteger) ||
                    (field.Type == esriFieldType.esriFieldTypeOID)) ||
                   ((field.Type == esriFieldType.esriFieldTypeSingle) ||
                    (field.Type == esriFieldType.esriFieldTypeSmallInteger)))) ||
                 (field.Type == esriFieldType.esriFieldTypeString))
             {
                 this.cboFields.Properties.Items.Add(field.AliasName);
             }
         }
         this.string_0 = (this.iannotateLayerProperties_0 as ILabelEngineLayerProperties).Expression.Trim();
         this.bool_1   = (this.iannotateLayerProperties_0 as ILabelEngineLayerProperties).IsExpressionSimple;
         this.iannotationExpressionEngine_0 =
             (this.iannotateLayerProperties_0 as ILabelEngineLayerProperties).ExpressionParser;
         if (this.string_0.IndexOf("[", 1) != -1)
         {
             this.cboFields.Enabled = false;
             this.cboFields.Text    = "表达式";
         }
         else
         {
             fields = this.igeoFeatureLayer_0.FeatureClass.Fields;
             string name  = this.string_0.Substring(1, this.string_0.Length - 2).Trim();
             int    index = fields.FindField(name);
             if (index == -1)
             {
                 this.cboFields.Enabled = false;
                 this.cboFields.Text    = "表达式";
             }
             else
             {
                 this.cboFields.Enabled = true;
                 this.cboFields.Text    = fields.get_Field(index).AliasName;
             }
         }
         this.symbolItem.ScaleRatio = 0.5;
         this.itextSymbol_0         = (this.iannotateLayerProperties_0 as ILabelEngineLayerProperties).Symbol;
         this.symbolItem.Symbol     = this.itextSymbol_0;
         this.symbolItem.Invalidate();
         ILineLabelPosition lineLabelPosition =
             (this.iannotateLayerProperties_0 as ILabelEngineLayerProperties).BasicOverposterLayerProperties
             .LineLabelPosition;
         if (lineLabelPosition.Horizontal)
         {
             this.rdoLineLabelPosition.SelectedIndex = 0;
         }
         else if (lineLabelPosition.Parallel)
         {
             this.rdoLineLabelPosition.SelectedIndex = 1;
         }
         else if (lineLabelPosition.ProduceCurvedLabels)
         {
             this.rdoLineLabelPosition.SelectedIndex = 2;
         }
         else
         {
             this.rdoLineLabelPosition.SelectedIndex = 3;
         }
         this.txtOffset.Text         = lineLabelPosition.Offset.ToString();
         this.chkBelow_Right.Checked = lineLabelPosition.Below
             ? lineLabelPosition.Below
             : lineLabelPosition.Right;
         this.chkTop_Left.Checked = lineLabelPosition.Above ? lineLabelPosition.Above : lineLabelPosition.Left;
         this.chkOnTop.Checked    = lineLabelPosition.OnTop;
         this.bool_0 = true;
     }
 }
        private void OutPutData(IFeatureClass pFeatureClass, string zoneIDField, string filePath, string fileName)
        {
            try
            {
                #region 添加格网人口字段
                IFields pFields = pFeatureClass.Fields;
                string  VIIndex = "VIIndex";
                if (pFields.FindField(VIIndex) >= 0)
                {
                    VIIndex = VIIndex + 1;
                }

                IField     pField     = new FieldClass();
                IFieldEdit pFieldEdit = pField as IFieldEdit;
                pFieldEdit.Name_2      = VIIndex;
                pFieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                pFieldEdit.Editable_2  = true;
                pFieldEdit.AliasName_2 = VIIndex;
                pFieldEdit.Length_2    = int.MaxValue;
                ITable pTable = (ITable)pFeatureClass;
                pTable.AddField(pField);
                #endregion

                #region 给添加的字段赋值
                IFeatureCursor pFeatureCursor;
                pFeatureCursor = pFeatureClass.Search(null, false);
                IFeature pFeature     = pFeatureCursor.NextFeature();
                int      idIndex      = pFeatureClass.Fields.FindField(zoneIDField);
                int      areaIndex    = pFeatureClass.Fields.FindField("Shape_Area");
                int      VIIndexIndex = pFeatureClass.Fields.FindField(VIIndex);
                while (pFeature != null)
                {
                    string id   = Convert.ToString(pFeature.get_Value(idIndex));
                    double area = Convert.ToDouble(pFeature.get_Value(areaIndex));

                    if (ZoneID.Contains(id))
                    {
                        int    index = ZoneID.IndexOf(id);
                        double temp  = 0;
                        if (area != 0)
                        {
                            temp = ZoneLength[index] / area;
                        }
                        pFeature.set_Value(VIIndexIndex, temp);
                        pFeature.Store();
                    }
                    else
                    {
                        pFeature.set_Value(VIIndexIndex, 0);
                        pFeature.Store();
                    }
                    pFeature = pFeatureCursor.NextFeature();
                }
                #endregion

                #region 输出数据
                IDataset pDataset = pFeatureClass as IDataset;
                //目标文件夹或数据库;
                IWorkspace objectWorkspace = null;
                if (filePath.Contains(".gdb"))
                {
                    IWorkspaceFactory factory = new FileGDBWorkspaceFactoryClass();
                    objectWorkspace = factory.OpenFromFile(filePath, 0);
                }
                else
                {
                    IWorkspaceFactory factory = new ShapefileWorkspaceFactory();
                    objectWorkspace = factory.OpenFromFile(filePath, 0);
                }
                IFeatureClass pOutFeatureClass = IFeatureDataConverter_ConvertFeatureClass(pDataset.Workspace, objectWorkspace, pDataset.Name, fileName);
                #endregion
            }
            catch (System.Exception ex)
            {
                return;
            }
        }
Esempio n. 20
0
 public static IField QueryField(IFields pFields, string sName)
 {
     IField pField = null;
     int n = pFields.FindField(sName);
     if (n > -1)
     {
         pField = pFields.get_Field(n);
         return pField;
     }
     return pField;
 }
Esempio n. 21
0
        private void method_0(ILayer layer)
        {
            if (!(layer is IFeatureLayer) || !layer.Visible)
            {
                return;
            }
            IFeatureLayer   featureLayer = layer as IFeatureLayer;
            IFeatureClass   featureClass = featureLayer.FeatureClass;
            IFields         fields       = featureClass.Fields;
            string          text         = "节点性质";
            IBasicLayerInfo layerInfo    = _config.GetBasicLayerInfo(featureClass);

            if (featureClass.ShapeType == esriGeometryType.esriGeometryPoint)
            {
                this.m_strBuildDate = layerInfo.GetFieldName(PipeConfigWordHelper.PointWords.MSRQ);
                // this.pPipeCfg.GetPointTableFieldName("建设年代");
                text = layerInfo.GetFieldName(PipeConfigWordHelper.PointWords.TZW);
            }
            else
            {
                this.m_strBuildDate = layerInfo.GetFieldName(PipeConfigWordHelper.LineWords.MSRQ);
                // this.pPipeCfg.GetLineTableFieldName("建设年代");
            }
            int num = fields.FindField(this.m_strBuildDate);

            if (num == -1)
            {
                MessageBox.Show("建设年代字段不存在!返回");
                return;
            }

            IField field = fields.get_Field(num);

            if (layerInfo == null ||
                (layerInfo.DataType != enumPipelineDataType.Point && layerInfo.DataType != enumPipelineDataType.Line))
            {
                return;
            }
            DateTime now = DateTime.Now;

            now.ToShortDateString();
            string text2       = now.AddYears(-1 * this.m_nExpireTime).ToShortDateString();
            string whereClause = "";

            if (field.Type == esriFieldType.esriFieldTypeDate)
            {
                if (featureLayer.DataSourceType == "Personal Geodatabase Feature Class")
                {
                    whereClause = this.m_strBuildDate + "< #" + text2 + "#";
                    if (this.m_pCurLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPoint)
                    {
                        whereClause = string.Concat(new string[]
                        {
                            this.m_strBuildDate,
                            " < #",
                            text2,
                            "# AND ",
                            text,
                            " <> '直线点' AND ",
                            text,
                            " <> '转折点'"
                        });
                    }
                }
                if (featureLayer.DataSourceType == "SDE Feature Class")
                {
                    whereClause = this.m_strBuildDate + "< TO_DATE('" + text2 + "','YYYY-MM-DD')";
                    if (this.m_pCurLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPoint)
                    {
                        whereClause = string.Concat(new string[]
                        {
                            this.m_strBuildDate,
                            " < TO_DATE('",
                            text2,
                            "','YYYY-MM-DD') AND ",
                            text,
                            " <> '直线点' AND ",
                            text,
                            " <> '转折点'"
                        });
                    }
                }
            }
            else if (field.Type == (esriFieldType)4)
            {
                whereClause = this.m_strBuildDate + "< '" + text2 + "'";
                if (this.m_pCurLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPoint)
                {
                    whereClause = string.Concat(new string[]
                    {
                        this.m_strBuildDate,
                        " < '",
                        text2,
                        "' AND ",
                        text,
                        " <> '直线点' AND ",
                        text,
                        " <> '转折点'"
                    });
                }
            }
            if (field.Type == (esriFieldType)1 || field.Type == 0)
            {
                whereClause = this.m_strBuildDate + "< " + text2;
                if (this.m_pCurLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPoint)
                {
                    whereClause = string.Concat(new string[]
                    {
                        this.m_strBuildDate,
                        " < ",
                        text2,
                        " AND ",
                        text,
                        " <> '直线点' AND ",
                        text,
                        " <> '转折点'"
                    });
                }
            }
            IFeatureClass arg_396_0        = featureClass;
            IQueryFilter  queryFilterClass = new QueryFilter();

            queryFilterClass.WhereClause = (whereClause);
            IFeatureCursor featureCursor = arg_396_0.Search(queryFilterClass, false);
            ILayerFields   layerFields   = (ILayerFields)featureLayer;
            int            fieldCount    = featureLayer.FeatureClass.Fields.FieldCount;

            this.dataGridView3.Rows.Clear();
            this.dataGridView3.Columns.Clear();
            DataGridViewCellStyle columnHeadersDefaultCellStyle = new DataGridViewCellStyle();

            this.dataGridView3.ColumnHeadersDefaultCellStyle           = columnHeadersDefaultCellStyle;
            this.dataGridView3.ColumnHeadersDefaultCellStyle.BackColor = Color.FromName("Control");
            this.dataGridView3.Columns.Clear();
            this.dataGridView3.ColumnCount = fieldCount;
            for (int i = 0; i < fieldCount; i++)
            {
                IField field2    = layerFields.get_Field(i);
                string aliasName = field2.AliasName;
                this.dataGridView3.Columns[i].Name     = aliasName;
                this.dataGridView3.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            IFeature feature = featureCursor.NextFeature();
            int      num2    = 0;

            while (feature != null)
            {
                if (!feature.HasOID || feature == null)
                {
                    feature = featureCursor.NextFeature();
                }
                else
                {
                    string text3  = "esriGeometry";
                    int    length = text3.Length;
                    int    num3   = layerFields.FindField(featureLayer.FeatureClass.ShapeFieldName);
                    string text4  = featureLayer.FeatureClass.ShapeType.ToString();
                    string value  = text4.Remove(0, length);
                    this.dataGridView3.Rows.Add(new object[]
                    {
                        ""
                    });
                    int num4 = 1;
                    for (int j = 0; j < fieldCount; j++)
                    {
                        if (num3 == j)
                        {
                            this.dataGridView3[j, num2].Value = value;
                        }
                        else
                        {
                            this.dataGridView3[j, num2].Value = feature.get_Value(j).ToString();
                        }
                        num4++;
                    }
                    num2++;
                    feature = featureCursor.NextFeature();
                }
            }
            this.Text = "预警分析明析: 记录条数--" + num2.ToString();
        }
Esempio n. 22
0
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                int       num       = -1;
                DataTable dataTable = new DataTable();
                dataTable.Columns.Clear();
                _waitForm.Count = _featureLayers.Count;
                int i = 0;
                _waitForm.Worker.ReportProgress(i++, "状态: 正在汇总,请稍候...");
                if (_pointRadioChecked)
                {
                    if (!dataTable.Columns.Contains("层名"))
                    {
                        dataTable.Columns.Add("层名", typeof(string));
                    }
                    if (!dataTable.Columns.Contains("点性"))
                    {
                        dataTable.Columns.Add("点性", typeof(string));
                    }
                    if (!dataTable.Columns.Contains("个数"))
                    {
                        dataTable.Columns.Add("个数", typeof(int));
                    }
                    if (!dataTable.Columns.Contains("总数"))
                    {
                        dataTable.Columns.Add("总数", typeof(int));
                    }
                    int num2 = 0;
                    foreach (IFeatureLayer featureLayer in _featureLayers)
                    {
                        if (_waitForm.Worker.CancellationPending)
                        {
                            break;
                        }
                        _waitForm.Worker.ReportProgress(i++, "状态: 正在汇总 " + featureLayer.Name + ",请稍候...");
                        int      num3      = 0;
                        IFields  fields    = featureLayer.FeatureClass.Fields;
                        IYTField fieldInfo = pPipeCfg.GetSpecialField(featureLayer.FeatureClass.AliasName,
                                                                      PipeConfigWordHelper.PointWords.TZW);
                        if (fieldInfo == null)
                        {
                            continue;
                        }
                        string pointTableFieldName = fieldInfo.Name;
                        int    num4 = fields.FindField(pointTableFieldName);
                        if (num4 >= 0)
                        {
                            string         name          = featureLayer.Name;
                            ISpatialFilter spatialFilter = new SpatialFilter();
                            IFeatureClass  featureClass  = featureLayer.FeatureClass;
                            if (_isGeometrySet)
                            {
                                if (this.m_ipGeo != null)
                                {
                                    spatialFilter.Geometry = (this.m_ipGeo);
                                }
                                spatialFilter.SpatialRel = (esriSpatialRelEnum)(1);
                            }
                            ISelectionSet selectionSet = featureClass.Select(spatialFilter, (esriSelectionType)3,
                                                                             (esriSelectionOption)1, null);
                            ITableSort tableSort = new TableSort();
                            tableSort.Fields       = (pointTableFieldName);
                            tableSort.SelectionSet = (selectionSet);
                            tableSort.Sort(null);
                            ICursor rows = tableSort.Rows;
                            object  obj  = null;
                            int     num5 = 1;
                            IRow    row;
                            while ((row = rows.NextRow()) != null)
                            {
                                if (_waitForm.Worker.CancellationPending)
                                {
                                    break;
                                }
                                object obj2 = row.Value[num4];
                                if (obj == null || !this.ColumnEqual(obj, obj2))
                                {
                                    if (obj == null)
                                    {
                                        obj = obj2;
                                    }
                                    else
                                    {
                                        dataTable.Rows.Add(new object[]
                                        {
                                            name,
                                            obj,
                                            num5
                                        });
                                        num3 += num5;
                                        obj   = obj2;
                                        num5  = 1;
                                    }
                                }
                                else
                                {
                                    num5++;
                                }
                            }
                            num3 += num5;
                            num2 += num3;
                            dataTable.Rows.Add(new object[]
                            {
                                name,
                                obj,
                                num5,
                                num3
                            });
                        }
                    }
                    object[] array = new object[4];
                    array.SetValue("合计", 1);
                    array.SetValue(num2, 3);
                    dataTable.Rows.Add(array);
                }
                else
                {
                    if (!dataTable.Columns.Contains("层名"))
                    {
                        dataTable.Columns.Add("层名", typeof(string));
                    }
                    if (!dataTable.Columns.Contains("规格"))
                    {
                        dataTable.Columns.Add("规格", typeof(string));
                    }
                    if (!dataTable.Columns.Contains("材质"))
                    {
                        dataTable.Columns.Add("材质", typeof(string));
                    }
                    if (!dataTable.Columns.Contains("条数"))
                    {
                        dataTable.Columns.Add("条数", typeof(int));
                    }
                    if (!dataTable.Columns.Contains("长度"))
                    {
                        dataTable.Columns.Add("长度", typeof(double));
                    }
                    if (!dataTable.Columns.Contains("总条数"))
                    {
                        dataTable.Columns.Add("总条数", typeof(int));
                    }
                    if (!dataTable.Columns.Contains("总长度"))
                    {
                        dataTable.Columns.Add("总长度", typeof(double));
                    }
                    int    num6 = 0;
                    double num7 = 0.0;
                    foreach (IFeatureLayer featureLayer in _featureLayers)
                    {
                        if (_waitForm.Worker.CancellationPending)
                        {
                            break;
                        }
                        _waitForm.Worker.ReportProgress(i++, "状态: 正在汇总 " + featureLayer.Name + ",请稍候...");
                        int             num8               = 0;
                        double          num9               = 0.0;
                        IFields         fields2            = featureLayer.FeatureClass.Fields;
                        IBasicLayerInfo layerInfo          = pPipeCfg.GetBasicLayerInfo(featureLayer.FeatureClass);
                        string          lineTableFieldName = layerInfo.GetFieldName(PipeConfigWordHelper.LineWords.GJ);

                        int    num4 = fields2.FindField(lineTableFieldName);
                        string lineTableFieldName2 = layerInfo.GetFieldName(PipeConfigWordHelper.LineWords.DMCC);
                        // this.pPipeCfg.GetLineTableFieldName("断面尺寸");
                        int    num10 = fields2.FindField(lineTableFieldName2);
                        string lineTableFieldName3 = layerInfo.GetFieldName(PipeConfigWordHelper.LineWords.GXCZ);
                        // this.pPipeCfg.GetLineTableFieldName("材质");
                        int num11 = fields2.FindField(lineTableFieldName3);
                        for (int k = 0; k < fields2.FieldCount; k++)
                        {
                            IField field = fields2.Field[k];
                            if (field.Type == (esriFieldType)7)
                            {
                                num = k;
                                break;
                            }
                        }
                        if (num4 >= 0 || num10 >= 0)
                        {
                            string         name           = featureLayer.Name;
                            ISpatialFilter spatialFilter2 = new SpatialFilter();
                            IFeatureClass  featureClass2  = featureLayer.FeatureClass;
                            if (_isGeometrySet)
                            {
                                if (this.m_ipGeo != null)
                                {
                                    spatialFilter2.Geometry = (this.m_ipGeo);
                                }
                                spatialFilter2.SpatialRel = (esriSpatialRelEnum)(1);
                            }
                            ISelectionSet selectionSet2 = featureClass2.Select(spatialFilter2, (esriSelectionType)3,
                                                                               (esriSelectionOption)1, null);
                            ITableSort tableSort2 = new TableSort();
                            tableSort2.Fields = (string.Concat(new string[]
                            {
                                lineTableFieldName,
                                ",",
                                lineTableFieldName2,
                                ",",
                                lineTableFieldName3
                            }));
                            tableSort2.SelectionSet = (selectionSet2);
                            tableSort2.Sort(null);
                            ICursor rows2 = tableSort2.Rows;
                            object  obj3  = null;
                            object  obj4  = null;
                            int     num12 = 1;
                            IRow    row2;
                            double  num13 = 0.0;
                            while ((row2 = rows2.NextRow()) != null)
                            {
                                if (_waitForm.Worker.CancellationPending)
                                {
                                    break;
                                }
                                object obj5 = row2.Value[num4];
                                if (obj5 is DBNull || obj5.ToString() == "0")
                                {
                                    obj5 = row2.Value[num10];
                                }
                                object obj6 = row2.Value[num11];
                                if (row2.Value[num] is DBNull)
                                {
                                    continue;
                                }
                                IPolyline        polyline        = (IPolyline)row2.Value[num];
                                IPointCollection pointCollection = (IPointCollection)polyline;
                                double           num14           = 0.0;
                                for (int l = 0; l < pointCollection.PointCount - 1; l++)
                                {
                                    IPoint point  = pointCollection.Point[l];
                                    IPoint point2 = pointCollection.Point[l + 1];
                                    num14 +=
                                        Math.Sqrt(Math.Pow(point.X - point2.X, 2.0) +
                                                  Math.Pow(point.Y - point2.Y, 2.0) +
                                                  Math.Pow(point.Z - point.M - point2.Z + point2.M, 2.0));
                                }
                                if (obj3 == null || !this.ColumnEqual(obj3, obj5))
                                {
                                    if (obj3 == null)
                                    {
                                        obj3   = obj5;
                                        num13 += num14;
                                    }
                                    else
                                    {
                                        num13 = Math.Round(num13, 3);
                                        dataTable.Rows.Add(new object[]
                                        {
                                            name,
                                            obj3,
                                            obj4,
                                            num12,
                                            num13
                                        });
                                        num8 += num12;
                                        num9 += num13;
                                        obj3  = obj5;
                                        obj4  = null;
                                        num13 = num14;
                                        num12 = 1;
                                    }
                                }
                                else if (obj4 == null || !this.ColumnEqual(obj4, obj6))
                                {
                                    if (obj4 == null)
                                    {
                                        obj4   = obj6;
                                        num13 += num14;
                                        num12++;
                                    }
                                    else
                                    {
                                        num13 = Math.Round(num13, 3);
                                        dataTable.Rows.Add(new object[]
                                        {
                                            name,
                                            obj3,
                                            obj4,
                                            num12,
                                            num13
                                        });
                                        num8 += num12;
                                        num9 += num13;
                                        num13 = num14;
                                        obj4  = obj6;
                                        num12 = 1;
                                    }
                                }
                                else
                                {
                                    num13 += num14;
                                    num12++;
                                }
                            }
                            num8 += num12;
                            num9 += num13;
                            num6 += num8;
                            num7 += num9;
                            num13 = Math.Round(num13, 3);
                            num9  = Math.Round(num9, 3);
                            dataTable.Rows.Add(new object[]
                            {
                                name,
                                obj3,
                                obj4,
                                num12,
                                num13,
                                num8,
                                num9
                            });
                        }
                    }
                    num7 = Math.Round(num7, 3);
                    object[] array2 = new object[7];
                    array2.SetValue("合计", 1);
                    array2.SetValue(num6, 5);
                    array2.SetValue(num7, 6);
                    dataTable.Rows.Add(array2);
                }
                e.Result = dataTable;
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 23
0
 private void method_3(IMap imap_1, ILayer ilayer_0, string string_0, double double_1, IWorkspace iworkspace_1,
                       bool bool_0, bool bool_1, esriLabelWhichFeatures esriLabelWhichFeatures_1)
 {
     if ((iworkspace_1.Type != esriWorkspaceType.esriFileSystemWorkspace) && (ilayer_0 is IGeoFeatureLayer))
     {
         int num;
         IAnnotateLayerProperties     properties;
         IElementCollection           elements;
         IElementCollection           elements2;
         ILabelEngineLayerProperties2 properties2;
         IAnnotationLayer             layer2;
         IGeoFeatureLayer             layer = ilayer_0 as IGeoFeatureLayer;
         IFeatureClass                      featureClass         = layer.FeatureClass;
         IAnnotationLayerFactory            factory              = new FDOGraphicsLayerFactoryClass();
         ISymbolCollection2                 lcs                  = new SymbolCollectionClass();
         IAnnotateLayerPropertiesCollection propertiess          = new AnnotateLayerPropertiesCollectionClass();
         IAnnotateLayerPropertiesCollection annotationProperties = layer.AnnotationProperties;
         for (num = 0; num < annotationProperties.Count; num++)
         {
             annotationProperties.QueryItem(num, out properties, out elements, out elements2);
             if (properties != null)
             {
                 ISymbolIdentifier2 identifier;
                 propertiess.Add(properties);
                 properties2 = properties as ILabelEngineLayerProperties2;
                 IClone symbol = properties2.Symbol as IClone;
                 lcs.AddSymbol(symbol.Clone() as ISymbol, properties.Class + " " + num.ToString(), out identifier);
                 properties2.SymbolID = identifier.ID;
             }
         }
         properties  = null;
         properties2 = null;
         IGraphicsLayerScale scale = new GraphicsLayerScaleClass
         {
             ReferenceScale = double_1,
             Units          = imap_1.MapUnits
         };
         IFeatureClassDescription description  = new AnnotationFeatureClassDescriptionClass();
         IObjectClassDescription  description2 = description as IObjectClassDescription;
         IFields          requiredFields       = description2.RequiredFields;
         IGeometryDefEdit geometryDef          =
             requiredFields.get_Field(requiredFields.FindField(description.ShapeFieldName)).GeometryDef as
             IGeometryDefEdit;
         IGeoDataset dataset = featureClass as IGeoDataset;
         geometryDef.SpatialReference_2 = dataset.SpatialReference;
         IMapOverposter        overposter           = imap_1 as IMapOverposter;
         IOverposterProperties overposterProperties = overposter.OverposterProperties;
         if (bool_1)
         {
             this.method_2(iworkspace_1 as IFeatureWorkspaceAnno, featureClass.FeatureDataset, featureClass,
                           scale.ReferenceScale, scale.Units, propertiess, lcs as ISymbolCollection, string_0);
             layer2 = factory.OpenAnnotationLayer(iworkspace_1 as IFeatureWorkspace, featureClass.FeatureDataset,
                                                  string_0);
         }
         else
         {
             this.method_2(iworkspace_1 as IFeatureWorkspaceAnno, featureClass.FeatureDataset, null,
                           scale.ReferenceScale, scale.Units, propertiess, lcs as ISymbolCollection, string_0);
             layer2 = factory.OpenAnnotationLayer(iworkspace_1 as IFeatureWorkspace, featureClass.FeatureDataset,
                                                  string_0);
         }
         IActiveView    view          = imap_1 as IActiveView;
         IScreenDisplay screenDisplay = view.ScreenDisplay;
         (layer2 as IGraphicsLayer).Activate(screenDisplay);
         for (num = 0; num < propertiess.Count; num++)
         {
             propertiess.QueryItem(num, out properties, out elements, out elements2);
             if (properties != null)
             {
                 properties.FeatureLayer      = layer;
                 properties.GraphicsContainer = layer2 as IGraphicsContainer;
                 properties.AddUnplacedToGraphicsContainer = bool_0;
                 properties.CreateUnplacedElements         = true;
                 properties.DisplayAnnotation  = true;
                 properties.FeatureLinked      = bool_1;
                 properties.LabelWhichFeatures = esriLabelWhichFeatures_1;
                 properties.UseOutput          = true;
                 properties2                   = properties as ILabelEngineLayerProperties2;
                 properties2.SymbolID          = num;
                 properties2.AnnotationClassID = num;
                 IOverposterLayerProperties2 overposterLayerProperties =
                     properties2.OverposterLayerProperties as IOverposterLayerProperties2;
                 overposterLayerProperties.TagUnplaced = true;
             }
         }
         propertiess.Sort();
         IAnnotateMapProperties annoMapCmdProps = new AnnotateMapPropertiesClass
         {
             AnnotateLayerPropertiesCollection = propertiess
         };
         ITrackCancel trackCancel = new CancelTrackerClass();
         (imap_1.AnnotationEngine as IAnnotateMap2).Label(overposterProperties, annoMapCmdProps, imap_1,
                                                          trackCancel);
         for (num = 0; num < propertiess.Count; num++)
         {
             propertiess.QueryItem(num, out properties, out elements, out elements2);
             if (properties != null)
             {
                 properties.FeatureLayer = null;
             }
         }
         imap_1.AddLayer(layer2 as ILayer);
         layer.DisplayAnnotation = false;
         view.Refresh();
     }
 }
Esempio n. 24
0
        private IFeature GetFeature(DataRow rowError, string strLayerName)
        {
            IMap theMap = this.m_HookHelper.FocusMap;
            MapLayersController mapController = new MapLayersController(theMap);
            enumErrorType       errType       = (enumErrorType)Convert.ToInt32(rowError["ErrorType"]);

            switch (errType)
            {
            case enumErrorType.Topology:
            {
                ITopologyLayer topoLayerTarget = mapController.GetLayer(strLayerName) as ITopologyLayer;
                if (topoLayerTarget == null)
                {
                    return(null);
                }

                ITopology topology = topoLayerTarget.Topology;
                IErrorFeatureContainer errFeatureContainer = topology as IErrorFeatureContainer;
                esriTopologyRuleType   ruleType            = (esriTopologyRuleType)Convert.ToInt32(rowError[Field_Name_TopologyRuleType]);
                //string strGeoType = rowError[Field_Name_TopologyGeometryType] as string;
                //esriGeometryType geoType = (strGeoType == "点" ? esriGeometryType.esriGeometryPoint : (strGeoType == "线" ? esriGeometryType.esriGeometryLine : esriGeometryType.esriGeometryPolygon));
                esriGeometryType geoType = (esriGeometryType)Convert.ToInt32(rowError[Field_Name_TopologyGeometryType]);
                int sourceClassID        = (int)rowError["SourceLayerID"];
                int sourceOID            = (int)rowError["OID"];
                int targetClassID        = (int)rowError["TargetLayerID"];
                int targetOID            = Convert.ToInt32(rowError["OID2"]);

                return(errFeatureContainer.get_ErrorFeature((topology as IGeoDataset).SpatialReference, ruleType, geoType, sourceClassID, sourceOID, targetClassID, targetOID) as IFeature);
            }
            break;

            case enumErrorType.Normal:
            {
                IFeatureLayer flyrTarget = mapController.GetLayer(strLayerName) as IFeatureLayer;
                if (flyrTarget == null)
                {
                    return(null);
                }

                // 改为优先从OID查找定位
                if (rowError.Table.Columns.Contains(Field_Name_TargetOID) && rowError[Field_Name_TargetOID] != DBNull.Value)
                {
                    return(flyrTarget.FeatureClass.GetFeature((int)rowError[Field_Name_TargetOID]));
                }
                else if (rowError.Table.Columns.Contains(Field_Name_TargetBSM) && !string.IsNullOrEmpty(rowError[Field_Name_TargetBSM] as string))
                {
                    IQueryFilter qFilter    = new QueryFilterClass();
                    IFields      fields     = flyrTarget.FeatureClass.Fields;
                    int          fieldIndex = fields.FindField("BSM");
                    if (fieldIndex < 0)
                    {
                        return(null);
                    }

                    IField bsmField = fields.get_Field(fieldIndex);
                    if (bsmField.Type == esriFieldType.esriFieldTypeInteger)
                    {
                        qFilter.WhereClause = string.Format("BSM={0}", rowError[Field_Name_TargetBSM]);
                    }
                    else
                    {
                        qFilter.WhereClause = string.Format("BSM='{0}'", rowError[Field_Name_TargetBSM]);
                    }
                    IFeatureCursor fCursor = flyrTarget.FeatureClass.Search(qFilter, false);

                    return(fCursor.NextFeature());
                }
                else
                {
                    return(null);
                }
            }

            default: return(null);
            }
        }
Esempio n. 25
0
        public static IFeatureClass exportDataToMemery(List <Dictionary <string, object> > dicExportData, IFeatureClass memoryFeaClsOfIntersect, ISpatialReference pSpatialReference,
                                                       out string msg)
        {
            msg = string.Empty;
            IWorkspaceEdit pWorkapceEdit        = null;
            IFeatureBuffer pTargetFeatureBuffer = null;
            IFeatureCursor pTargetFeatureCursor = null;

            try
            {
                IDataset dataset = memoryFeaClsOfIntersect as IDataset;
                pWorkapceEdit = dataset.Workspace as IWorkspaceEdit;
                pWorkapceEdit.StartEditing(false);
                pWorkapceEdit.StartEditOperation();
                pTargetFeatureBuffer = memoryFeaClsOfIntersect.CreateFeatureBuffer();
                pTargetFeatureCursor = memoryFeaClsOfIntersect.Insert(true);
                IFields fieldsSource = memoryFeaClsOfIntersect.Fields; //插入
                                                                       // fieldsSource.
                foreach (var item in dicExportData)
                {
                    foreach (var key in item.Keys)
                    {
                        int i = fieldsSource.FindField(key);

                        if (string.Equals(key, "geometry"))
                        {
                            pTargetFeatureBuffer.Shape = (IGeometry)item[key];
                        }

                        if (i > -1)
                        {
                            if (fieldsSource.Field[i].Type == esriFieldType.esriFieldTypeOID || fieldsSource.Field[i].Type == esriFieldType.esriFieldTypeGeometry)
                            {
                                continue;
                            }
                            if (item[key] != null)
                            {
                                pTargetFeatureBuffer.Value[i] = item[key];
                            }
                        }
                    }
                    pTargetFeatureCursor.InsertFeature(pTargetFeatureBuffer);
                }
                pTargetFeatureCursor.Flush();
                pWorkapceEdit.StopEditOperation();
                pWorkapceEdit.StopEditing(true);
            }
            catch (Exception e)
            {
                msg = e.Data + e.HelpLink + e.HResult + e.InnerException + e.Message + e.Source;
            }
            finally
            {
                if (pWorkapceEdit != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pWorkapceEdit);
                }
                if (pTargetFeatureBuffer != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pTargetFeatureBuffer);
                }
                if (pTargetFeatureCursor != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pTargetFeatureCursor);
                }
            }
            return(memoryFeaClsOfIntersect);
        }
Esempio n. 26
0
        private IFeatureBuffer SetFLine2Feature(IFeatureBuffer fb, FLine_EDGES model, long lineNum)
        {
            if (model.WKT.Contains("\""))
            {
                model.WKT = model.WKT.Replace("\"", "");
            }
            data = model.WKT.Split(splitWKT_EDGES, StringSplitOptions.None);
            if (data.Length != 3)
            {
                Log("行号[" + lineNum.ToString() + "],WKT未能正确分割,结果为:" + data.ToString());
                return(null);
            }
            type = data[0];
            cood = data[1];

            if (type.ToUpper() != "LINESTRING")
            {
                Log("行号[" + lineNum.ToString() + "],WKT类型指示的值错误,错误值为:" + type);
                return(null);
            }

            xys = cood.Split(',');
            if (xys.Length < 2)
            {
                Log("行号[" + lineNum.ToString() + "],坐标点太少。" + xys.Length.ToString());
                return(null);
            }

            string    message  = "";
            IGeometry geometry = WKTCoordinateInfo2PolyLine(cood, out message);

            if (geometry == null)
            {
                Log("行号[" + lineNum.ToString() + "]." + message + "----------" + model.WKT);
            }
            fb.Shape = geometry;

            #region
            fieldIndex = fields.FindField("ARTPATH");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.ARTPATH;
            }
            fieldIndex = fields.FindField("COUNTYFP");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.COUNTYFP;
            }
            fieldIndex = fields.FindField("DECKEDROAD");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.DECKEDROAD;
            }
            fieldIndex = fields.FindField("DIVROAD");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.DIVROAD;
            }
            fieldIndex = fields.FindField("EXTTYP");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.EXTTYP;
            }
            fieldIndex = fields.FindField("FEATCAT");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.FEATCAT;
            }
            fieldIndex = fields.FindField("FULLNAME");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.FULLNAME;
            }
            fieldIndex = fields.FindField("GCSEFLG");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.GCSEFLG;
            }
            fieldIndex = fields.FindField("HYDROFLG");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.HYDROFLG;
            }
            fieldIndex = fields.FindField("LFROMADD");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.LFROMADD;
            }
            fieldIndex = fields.FindField("LTOADD");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.LTOADD;
            }
            fieldIndex = fields.FindField("MTFCC");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.MTFCC;
            }
            fieldIndex = fields.FindField("OFFSETL");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.OFFSETL;
            }
            fieldIndex = fields.FindField("OFFSETR");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.OFFSETR;
            }
            fieldIndex = fields.FindField("OLFFLG");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.OLFFLG;
            }
            fieldIndex = fields.FindField("PASSFLG");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.PASSFLG;
            }
            fieldIndex = fields.FindField("PERSIST");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.PERSIST;
            }
            fieldIndex = fields.FindField("RAILFLG");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.RAILFLG;
            }
            fieldIndex = fields.FindField("RFROMADD");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.RFROMADD;
            }
            fieldIndex = fields.FindField("ROADFLG");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.ROADFLG;
            }
            fieldIndex = fields.FindField("RTOADD");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.RTOADD;
            }
            fieldIndex = fields.FindField("SMID");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.SMID;
            }
            fieldIndex = fields.FindField("STATEFP");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.STATEFP;
            }
            fieldIndex = fields.FindField("TFIDL");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.TFIDL;
            }
            fieldIndex = fields.FindField("TFIDR");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.TFIDR;
            }
            fieldIndex = fields.FindField("TLID");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.TLID;
            }
            fieldIndex = fields.FindField("TNIDF");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.TNIDF;
            }
            fieldIndex = fields.FindField("TNIDT");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.TNIDT;
            }
            fieldIndex = fields.FindField("TTYP");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.TTYP;
            }
            //index = f.Fields.FindField("WKT");
            //if (index >= 0)
            //{
            //    f.Value[index] = model.WKT;
            //}
            fieldIndex = fields.FindField("ZIPL");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.ZIPL;
            }
            fieldIndex = fields.FindField("ZIPR");
            if (fieldIndex >= 0)
            {
                fb.Value[fieldIndex] = model.ZIPR;
            }
            #endregion

            return(fb);
        }
Esempio n. 27
0
        private void btn_ok_Click(object sender, EventArgs e)
        {
            try
            {
                if (this._dt.Rows.Count == 0)
                {
                    return;
                }
                if (!this.ceConnectMajorClass.Checked && !this.ceConnectFacility.Checked)
                {
                    return;
                }
                WaitForm.Start("二维数据关联设置启动...", "请稍后");
                CheckRowGroup();
                WaitForm.SetCaption("设施类关联设置进行中...");
                // 设置设施类
                HashSet <FacilityClass> listFac = _checkFacCList;
                if (listFac != null && this.ceConnectFacility.Checked)
                {
                    foreach (FacilityClass fac in listFac)
                    {
                        string strTemp = "";
                        foreach (DataRow dr in this._dt.Rows)
                        {
                            if (!(bool)dr["CheckState"])
                            {
                                continue;
                            }
                            IFeatureClass featureClass = dr["FeatureClass"] as IFeatureClass;
                            if (featureClass == null)
                            {
                                continue;
                            }
                            FacilityClass fcc = dr["FacilityClass"] as FacilityClass;
                            if (fcc == fac)
                            {
                                strTemp += featureClass.FeatureClassID + ";";
                            }
                        }
                        if (this._facDoc != null)
                        {
                            XmlNode node = this._facDoc.SelectSingleNode(".//FacilityClass[@name=\"" + fac.Name + "\"]");
                            if (node != null)
                            {
                                if (node.Attributes["fc2D"] == null)
                                {
                                    XmlAttribute attr = this._facDoc.CreateAttribute("fc2D");
                                    node.Attributes.Append(attr);
                                }
                                node.Attributes["fc2D"].Value = strTemp;
                            }
                            this._facDoc.Save(this._xmlFacFilePath);
                        }
                    }
                }
                //设施大类所属
                WaitForm.SetCaption("所属大类关联设置进行中...");
                HashSet <MajorClass> listMC = _checkMCList;
                if (listMC != null && this.ceConnectMajorClass.Checked)
                {
                    foreach (MajorClass mc in listMC)
                    {
                        string strTemp = "";
                        List <IFeatureClass> listFc = new List <IFeatureClass>();
                        foreach (DataRow dr in this._dt.Rows)
                        {
                            if (!(bool)dr["CheckState"])
                            {
                                continue;
                            }
                            IFeatureClass featureClass = dr["FeatureClass"] as IFeatureClass;
                            if (featureClass == null)
                            {
                                continue;
                            }
                            MajorClass mcc = dr["MajorClass"] as MajorClass;
                            if (mcc == mc)
                            {
                                strTemp += featureClass.FeatureClassID + ";";
                                listFc.Add(featureClass);
                            }
                        }
                        if (this._logicDoc != null)
                        {
                            XmlNode node = this._logicDoc.SelectSingleNode(".//MajorClass[@name=\"" + mc.Name + "\"]");
                            if (node != null)
                            {
                                if (node.Attributes["fc2D"] == null)
                                {
                                    XmlAttribute attr = this._logicDoc.CreateAttribute("fc2D");
                                    node.Attributes.Append(attr);
                                }
                                node.Attributes["fc2D"].Value = strTemp;
                            }
                            this._logicDoc.Save(this._xmlLogicFilePath);

                            for (int i = node.ChildNodes.Count - 1; i >= 0; i--)
                            {
                                XmlNode childNode = node.ChildNodes[i];
                                node.RemoveChild(childNode);
                            }

                            //二级分组
                            WaitForm.SetCaption("小类分组中...");
                            IQueryFilter     filter   = null;
                            IFeatureCursor   cursor   = null;
                            IFeature         pFeature = null;
                            HashSet <string> hsValues = new HashSet <string>();
                            try
                            {
                                foreach (IFeatureClass fc in listFc)
                                {
                                    WaitForm.SetCaption("要素类【" + (string.IsNullOrEmpty(fc.AliasName) ? fc.FeatureClassID.ToString() : fc.AliasName) + "】分组中...");
                                    IFields pFields = fc.Fields;
                                    int     index   = pFields.FindField(mc.ClassifyField);
                                    if (index == -1)
                                    {
                                        continue;
                                    }

                                    filter           = new QueryFilter();
                                    filter.SubFields = mc.ClassifyField;
                                    cursor           = fc.Search(filter, true);

                                    while ((pFeature = cursor.NextFeature()) != null)
                                    {
                                        if (pFeature.get_Value(index) != null)
                                        {
                                            hsValues.Add(pFeature.get_Value(index).ToString());
                                        }
                                    }
                                    if (cursor != null)
                                    {
                                        System.Runtime.InteropServices.Marshal.ReleaseComObject(cursor);
                                        cursor = null;
                                    }
                                    if (pFeature != null)
                                    {
                                        System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeature);
                                        pFeature = null;
                                    }
                                }

                                //    // 重设groupid
                                //    WaitForm.SetCaption("启动重置GroupId...");
                                //    foreach (IFeatureClass fc in listFc)
                                //    {
                                //        WaitForm.SetCaption("要素类【" + (string.IsNullOrEmpty(fc.AliasName) ? fc.FeatureClassID.ToString() : fc.AliasName) + "】重置GroupId中...");
                                //        filter = new QueryFilter();
                                //        filter.SubFields = "GroupId,oid";
                                //        int groupid = 0;
                                //        foreach (string str in hsValues)
                                //        {
                                //            filter.WhereClause = mc.ClassifyField + " = '" + str + "'";
                                //            cursor = fc.Update(filter, false);
                                //            while ((pFeature = cursor.NextFeature()) != null)
                                //            {
                                //                pFeature.set_Value(0, groupid);
                                //                cursor.UpdateFeature(pFeature);
                                //            }
                                //            groupid++;
                                //        }
                                //    }
                            }
                            catch { }
                            finally
                            {
                                if (cursor != null)
                                {
                                    System.Runtime.InteropServices.Marshal.ReleaseComObject(cursor);
                                    cursor = null;
                                }
                                if (pFeature != null)
                                {
                                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeature);
                                    pFeature = null;
                                }
                                if (filter != null)
                                {
                                    System.Runtime.InteropServices.Marshal.ReleaseComObject(filter);
                                    pFeature = null;
                                }
                            }
                            WaitForm.SetCaption("分组信息写入配置文件中...");
                            foreach (string str in hsValues)
                            {
                                XmlElement ele = this._logicDoc.CreateElement("SubClass");
                                ele.SetAttribute("name", str);
                                node.AppendChild(ele);
                            }
                            this._logicDoc.Save(this._xmlLogicFilePath);
                        }
                    }
                }
                WaitForm.Stop();
                XtraMessageBox.Show("设置成功!", "提示");
            }
            catch (Exception ex)
            {
                WaitForm.Stop();
                XtraMessageBox.Show("设置失败!", "提示");
            }
        }
Esempio n. 28
0
        private void bttCK_Click(object sender, EventArgs e)
        {
            try
            {
                string[]         strMapNo     = GetMapNo().Split(new char[] { ',' });
                IList <IFeature> pListFeature = new List <IFeature>();
                if (strMapNo == null)
                {
                    return;
                }
                Exception eError;
                string    NodeKey = "";
                if (strMapNo[0].Length == 3)//1:100万 接图表NodeKey
                {
                    NodeKey = GetNodeKey(1).ToString();
                }
                else
                {
                    switch (strMapNo[0].ToString().Substring(3, 1).ToUpper())
                    {
                    case "C":    //1:25万 接图表NodeKey
                        NodeKey = GetNodeKey(2).ToString();
                        break;

                    case "E":                               //1:5万 接图表NodeKey
                        NodeKey = GetNodeKey(3).ToString(); //不同比例尺的接图表的ID号
                        break;
                    }
                }
                if (NodeKey == "")
                {
                    MessageBox.Show("未加载对应图层", "提示!");
                }

                IFeatureClass pFeatureClass = GeoModule.GetFeatureClassByNodeKey(NodeKey);
                if (pFeatureClass == null)
                {
                    return;
                }
                for (int i = 0; i < strMapNo.Length; i++)
                {
                    IQueryFilter   pQueryFilter   = new QueryFilterClass();
                    IFeature       pFeature       = null;
                    IFeatureCursor pFeatureCursor = null;
                    //ZQ 20110807   add
                    ITable  pTable  = pFeatureClass as ITable;
                    IFields pFields = pTable.Fields;
                    IField  pField  = pFields.get_Field(pFields.FindField(GetMapNoField(NodeKey)));
                    if (pField.Type.ToString() == "esriFieldTypeString")
                    {
                        pQueryFilter.WhereClause = GetMapNoField(NodeKey).ToString() + "='" + strMapNo[i].ToString().ToUpper() + "'";
                    }
                    else if (pField.Type.ToString() == "esriFieldTypeDouble")
                    {
                        pQueryFilter.WhereClause = GetMapNoField(NodeKey).ToString() + "=" + strMapNo[i].ToString().ToUpper();
                    }
                    //end
                    pFeatureCursor = pFeatureClass.Search(pQueryFilter, false);
                    pFeature       = pFeatureCursor.NextFeature();
                    while (pFeature != null)
                    {
                        pListFeature.Add(pFeature);
                        pFeature = pFeatureCursor.NextFeature();
                    }
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor);
                }

                IGeometry pGeometry = GetLyrUnionPlygon(pListFeature);
                if (pGeometry == null)
                {
                    MessageBox.Show("不存在相关图幅信息,请认真核对图幅信息!", "提示!"); return;
                }
                this.WindowState    = FormWindowState.Minimized;
                m_MapControl.Extent = pGeometry.Envelope;
                m_MapControl.ActiveView.Refresh();
            }
            catch { }
        }
Esempio n. 29
0
        //字段集
        private IFields CreateFieldsCollectionForFeatueClass(ISpatialReference spatialReference,
                                                             esriGeometryType geometryType)
        {
            //Use the feature class description to return the required fields in a fields collection.
            IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass();
            IObjectClassDescription  ocDesc = (IObjectClassDescription)fcDesc;

            //Create the fields using the required fields method.
            IFields fields = ocDesc.RequiredFields;

            //Locate the shape field with the name from the feature class description.
            int    shapeFieldIndex = fields.FindField(fcDesc.ShapeFieldName);
            IField shapeField      = fields.get_Field(shapeFieldIndex);

            //Modify the GeometryDef object before using the fields collection to create a
            //feature class.
            IGeometryDef     geometryDef     = shapeField.GeometryDef;
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;

            //Alter the feature class geometry type to the type we need.
            geometryDefEdit.GeometryType_2 = geometryType;
            geometryDefEdit.HasZ_2         = true;
            geometryDefEdit.HasM_2         = true;
            geometryDefEdit.GridCount_2    = 1;

            //Set the first grid size to zero and allow ArcGIS to determine a valid grid size.
            geometryDefEdit.set_GridSize(0, 0);
            geometryDefEdit.SpatialReference_2 = spatialReference;

            //If it is a point collection, add Field
            if (geometryType == esriGeometryType.esriGeometryPoint)
            {
                //Create a user-defined double field for "X"
                IFieldsEdit fieldsEdit5      = (IFieldsEdit)fields;
                IField      incomeField5     = new FieldClass();
                IFieldEdit  incomeFieldEdit5 = (IFieldEdit)incomeField5;
                incomeFieldEdit5.AliasName_2  = "X";
                incomeFieldEdit5.Editable_2   = true;
                incomeFieldEdit5.IsNullable_2 = false;
                incomeFieldEdit5.Name_2       = "X";
                incomeFieldEdit5.Precision_2  = 2;
                incomeFieldEdit5.Scale_2      = 5;
                incomeFieldEdit5.Type_2       = esriFieldType.esriFieldTypeDouble;
                fieldsEdit5.AddField(incomeField5);
                //Create a user-defined double field for "Y"
                IFieldsEdit fieldsEdit6      = (IFieldsEdit)fields;
                IField      incomeField6     = new FieldClass();
                IFieldEdit  incomeFieldEdit6 = (IFieldEdit)incomeField6;
                incomeFieldEdit6.AliasName_2  = "Y";
                incomeFieldEdit6.Editable_2   = true;
                incomeFieldEdit6.IsNullable_2 = false;
                incomeFieldEdit6.Name_2       = "Y";
                incomeFieldEdit6.Precision_2  = 2;
                incomeFieldEdit6.Scale_2      = 5;
                incomeFieldEdit6.Type_2       = esriFieldType.esriFieldTypeDouble;
                fieldsEdit6.AddField(incomeField6);
                //Create a user-defined double field for "Z"
                IFieldsEdit fieldsEdit7      = (IFieldsEdit)fields;
                IField      incomeField7     = new FieldClass();
                IFieldEdit  incomeFieldEdit7 = (IFieldEdit)incomeField7;
                incomeFieldEdit7.AliasName_2  = "Z";
                incomeFieldEdit7.Editable_2   = true;
                incomeFieldEdit7.IsNullable_2 = false;
                incomeFieldEdit7.Name_2       = "Z";
                incomeFieldEdit7.Precision_2  = 2;
                incomeFieldEdit7.Scale_2      = 5;
                incomeFieldEdit7.Type_2       = esriFieldType.esriFieldTypeDouble;
                fieldsEdit7.AddField(incomeField7);
                //Create a user-defined double field for "Probability"
                IFieldsEdit fieldsEdit148      = (IFieldsEdit)fields;
                IField      incomeField148     = new FieldClass();
                IFieldEdit  incomeFieldEdit148 = (IFieldEdit)incomeField148;
                incomeFieldEdit148.AliasName_2  = "Probability";
                incomeFieldEdit148.Editable_2   = true;
                incomeFieldEdit148.IsNullable_2 = false;
                incomeFieldEdit148.Name_2       = "Probability";
                incomeFieldEdit148.Precision_2  = 2;
                incomeFieldEdit148.Scale_2      = 5;
                incomeFieldEdit148.Type_2       = esriFieldType.esriFieldTypeDouble;
                fieldsEdit148.AddField(incomeField148);
            }
            //If it is a polyline, add Field
            if (geometryType == esriGeometryType.esriGeometryPolyline)
            {
                //Create a user-defined double field for "Magnitude"
                IFieldsEdit fieldsEdit      = (IFieldsEdit)fields;
                IField      incomeField     = new FieldClass();
                IFieldEdit  incomeFieldEdit = (IFieldEdit)incomeField;
                incomeFieldEdit.AliasName_2  = "Gravity";
                incomeFieldEdit.Editable_2   = true;
                incomeFieldEdit.IsNullable_2 = false;
                incomeFieldEdit.Name_2       = "Gravity";
                incomeFieldEdit.Precision_2  = 2;
                incomeFieldEdit.Scale_2      = 5;
                incomeFieldEdit.Type_2       = esriFieldType.esriFieldTypeDouble;
                fieldsEdit.AddField(incomeField);
                //Create a user-defined double field for "Probability"
                IFieldsEdit fieldsEdit148      = (IFieldsEdit)fields;
                IField      incomeField148     = new FieldClass();
                IFieldEdit  incomeFieldEdit148 = (IFieldEdit)incomeField148;
                incomeFieldEdit148.AliasName_2  = "Probability";
                incomeFieldEdit148.Editable_2   = true;
                incomeFieldEdit148.IsNullable_2 = false;
                incomeFieldEdit148.Name_2       = "Probability";
                incomeFieldEdit148.Precision_2  = 2;
                incomeFieldEdit148.Scale_2      = 5;
                incomeFieldEdit148.Type_2       = esriFieldType.esriFieldTypeDouble;
                fieldsEdit148.AddField(incomeField148);
            }

            if (geometryType == esriGeometryType.esriGeometryMultiPatch)
            {
                //Create a user-defined double field for "Probability"
                IFieldsEdit fieldsEdit148      = (IFieldsEdit)fields;
                IField      incomeField148     = new FieldClass();
                IFieldEdit  incomeFieldEdit148 = (IFieldEdit)incomeField148;
                incomeFieldEdit148.AliasName_2  = "Probability";
                incomeFieldEdit148.Editable_2   = true;
                incomeFieldEdit148.IsNullable_2 = false;
                incomeFieldEdit148.Name_2       = "Probability";
                incomeFieldEdit148.Precision_2  = 2;
                incomeFieldEdit148.Scale_2      = 5;
                incomeFieldEdit148.Type_2       = esriFieldType.esriFieldTypeDouble;
                fieldsEdit148.AddField(incomeField148);
            }
            return(fields);
        }
Esempio n. 30
0
        /// <summary>
        ///     Gets the index for field.
        /// </summary>
        /// <param name="attributeName"> The attribute name. </param>
        /// <param name="fields"> The fields. </param>
        /// <returns> </returns>
        private static int GetIndexForField(string attributeName, IFields fields)
        {
            var findField = fields.FindField(attributeName.Trim());

            return(findField < 0 ? fields.FindFieldByAliasName(attributeName.Trim()) : findField);
        }
Esempio n. 31
0
        private bool SameIncidentLinkAttributeValue(IEnumSchematicInMemoryFeature enumInMemoryLinks, string attributeName, ISchematicRulesHelper ruleHelper)
        {
            ISchematicInMemoryFeature inMemoryFeature = null;

            enumInMemoryLinks.Reset();

            bool   bFirstVariant  = true;
            object vPreviousValue = null;
            object vCurrentValue  = null;

            inMemoryFeature = enumInMemoryLinks.Next();

            while (inMemoryFeature != null)
            {
                // Do not take account the link if the link is not displayed
                //
                // Search for an attribute with the given name
                //
                ISchematicElementClass schematicElementClass;
                schematicElementClass = inMemoryFeature.SchematicElementClass;
                ISchematicAttributeContainer attributeContainer = (ISchematicAttributeContainer)schematicElementClass;
                ISchematicAttribute          schematicAttribute = null;
                if (attributeContainer != null)
                {
                    schematicAttribute = attributeContainer.GetSchematicAttribute(attributeName, true);
                }

                if (schematicAttribute != null)
                {
                    ISchematicObject schematicObject = (ISchematicObject)inMemoryFeature;
                    vCurrentValue = schematicAttribute.GetValue(schematicObject);
                }
                else
                {
                    // If schematic attribute not existing ==> find a field in the associated feature
                    IObject iObject = null;

                    ISchematicInMemoryFeaturePrimaryAssociation primaryAssociation = (ISchematicInMemoryFeaturePrimaryAssociation)inMemoryFeature;
                    if (primaryAssociation != null)
                    {
                        iObject = primaryAssociation.AssociatedObject;
                    }

                    IRow row = (IRow)iObject;

                    int fieldIndex = 0;
                    if (row != null)
                    {
                        IFields fields = row.Fields;

                        if (fields != null)
                        {
                            fieldIndex = fields.FindField(attributeName);
                        }
                    }

                    if (fieldIndex > 0)
                    {
                        vCurrentValue = row.get_Value(fieldIndex);
                        if (DBNull.Value.Equals(vCurrentValue))
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }

                if (bFirstVariant)
                {
                    vPreviousValue = vCurrentValue;
                    bFirstVariant  = false;
                }
                else
                {
                    // Compare PreviousValue and CurrentValue
                    if (vPreviousValue.GetType() != vCurrentValue.GetType())
                    {
                        return(false);
                    }

                    if (DBNull.Value.Equals(vPreviousValue) || DBNull.Value.Equals(vCurrentValue))
                    {
                        return(false);
                    }

                    if (vPreviousValue.GetType().FullName is System.String)//Speciale Case for string.
                    {
                        string str1 = (string)vPreviousValue;
                        string str2 = (string)vCurrentValue;
                        if (string.Compare(str1, str2, true) != 0)
                        {
                            return(false);
                        }
                    }
                    else if (vPreviousValue != vCurrentValue)// == or != operator compare for Variant match the right type.
                    {
                        return(false);
                    }
                }

                inMemoryFeature = enumInMemoryLinks.Next();
            }

            return(true);
        }
Esempio n. 32
0
        private void OutputGridPopulation(IFeatureClass pFeatureClass, string gridID_Field, string outputPath, string name)
        {
            #region 添加格网人口字段
            IFields pFields = pFeatureClass.Fields;
            string  gridPop = "Population";
            if (pFields.FindField(gridPop) >= 0)
            {
                gridPop = gridPop + 1;
            }

            IField     pField     = new FieldClass();
            IFieldEdit pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Name_2      = gridPop;
            pFieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
            pFieldEdit.Editable_2  = true;
            pFieldEdit.AliasName_2 = gridPop;
            pFieldEdit.Length_2    = int.MaxValue;
            ITable pTable = (ITable)pFeatureClass;
            pTable.AddField(pField);
            #endregion

            #region 给格网人口字段赋值
            IFeatureCursor pFeatureCursor = pFeatureClass.Search(null, false);
            IFeature       pFeature       = pFeatureCursor.NextFeature();

            int grididIndex  = pFeatureClass.Fields.FindField(gridID_Field);
            int gridpopIndex = pFeatureClass.Fields.FindField(gridPop);
            while (pFeature != null)
            {
                string id = Convert.ToString(pFeature.get_Value(grididIndex));

                if (GridID.Contains(id))
                {
                    int index = GridID.IndexOf(id);
                    pFeature.set_Value(gridpopIndex, GridPopu[index]);
                    pFeature.Store();
                }
                else
                {
                    pFeature.set_Value(gridpopIndex, 0);
                    pFeature.Store();
                }

                pFeature = pFeatureCursor.NextFeature();
            }
            #endregion

            #region 输出数据
            IDataset pDataset = pFeatureClass as IDataset;
            //目标文件夹或数据库;
            IWorkspace objectWorkspace = null;
            if (outputPath.Contains(".gdb"))
            {
                IWorkspaceFactory factory = new FileGDBWorkspaceFactoryClass();
                objectWorkspace = factory.OpenFromFile(outputPath, 0);
            }
            else
            {
                IWorkspaceFactory factory = new ShapefileWorkspaceFactory();
                objectWorkspace = factory.OpenFromFile(outputPath, 0);
            }
            IFeatureClass pOutFeatureClass = IFeatureDataConverter_ConvertFeatureClass(pDataset.Workspace, objectWorkspace, pDataset.Name, name);
            IFeatureLayer pLayer           = new FeatureLayerClass
            {
                FeatureClass = pOutFeatureClass,
                Name         = pOutFeatureClass.AliasName
            };
            mMapControl.AddLayer(pLayer);
            mMapControl.ActiveView.Refresh();
            #endregion
        }
Esempio n. 33
0
        public static void ConvertLabels2StandardAnno(IMap imap_0, ILayer ilayer_0, string string_0, double double_0,
                                                      IWorkspace iworkspace_0, bool bool_0, bool bool_1, esriLabelWhichFeatures esriLabelWhichFeatures_0)
        {
            int i;
            IAnnotateLayerProperties     bool0;
            IElementCollection           elementCollection;
            IElementCollection           elementCollection1;
            ILabelEngineLayerProperties2 d;
            ISymbolIdentifier2           symbolIdentifier2;
            IAnnotationLayer             annotationLayer;

            if (iworkspace_0.Type != esriWorkspaceType.esriFileSystemWorkspace && ilayer_0 is IGeoFeatureLayer)
            {
                IGeoFeatureLayer        ilayer0      = ilayer_0 as IGeoFeatureLayer;
                IFeatureClass           featureClass = ilayer0.FeatureClass;
                IAnnotationLayerFactory fDOGraphicsLayerFactoryClass =
                    new FDOGraphicsLayerFactory() as IAnnotationLayerFactory;
                ISymbolCollection2 symbolCollectionClass = new SymbolCollection() as ISymbolCollection2;
                IAnnotateLayerPropertiesCollection annotateLayerPropertiesCollectionClass =
                    new AnnotateLayerPropertiesCollection();
                IAnnotateLayerPropertiesCollection annotationProperties = ilayer0.AnnotationProperties;
                for (i = 0; i < annotationProperties.Count; i++)
                {
                    annotationProperties.QueryItem(i, out bool0, out elementCollection, out elementCollection1);
                    if (bool0 != null)
                    {
                        annotateLayerPropertiesCollectionClass.Add(bool0);
                        d = bool0 as ILabelEngineLayerProperties2;
                        IClone symbol = d.Symbol as IClone;
                        symbolCollectionClass.AddSymbol(symbol.Clone() as ISymbol,
                                                        string.Concat(bool0.Class, " ", i.ToString()), out symbolIdentifier2);
                        d.SymbolID = symbolIdentifier2.ID;
                    }
                }
                bool0 = null;
                d     = null;
                IGraphicsLayerScale graphicsLayerScaleClass = new GraphicsLayerScale()
                {
                    ReferenceScale = double_0,
                    Units          = imap_0.MapUnits
                };
                IFeatureClassDescription annotationFeatureClassDescriptionClass =
                    new AnnotationFeatureClassDescription() as IFeatureClassDescription;
                IFields requiredFields =
                    (annotationFeatureClassDescriptionClass as IObjectClassDescription).RequiredFields;
                IField field =
                    requiredFields.Field[requiredFields.FindField(annotationFeatureClassDescriptionClass.ShapeFieldName)
                    ];
                (field.GeometryDef as IGeometryDefEdit).SpatialReference_2 =
                    (featureClass as IGeoDataset).SpatialReference;
                IOverposterProperties overposterProperties = (imap_0 as IMapOverposter).OverposterProperties;
                if (!bool_1)
                {
                    LayerOp.CreateAnnoFeatureClass(iworkspace_0 as IFeatureWorkspaceAnno, featureClass.FeatureDataset,
                                                   null, graphicsLayerScaleClass.ReferenceScale, graphicsLayerScaleClass.Units,
                                                   annotateLayerPropertiesCollectionClass, symbolCollectionClass as ISymbolCollection, string_0);
                    annotationLayer = fDOGraphicsLayerFactoryClass.OpenAnnotationLayer(
                        iworkspace_0 as IFeatureWorkspace, featureClass.FeatureDataset, string_0);
                }
                else
                {
                    LayerOp.CreateAnnoFeatureClass(iworkspace_0 as IFeatureWorkspaceAnno, featureClass.FeatureDataset,
                                                   featureClass, graphicsLayerScaleClass.ReferenceScale, graphicsLayerScaleClass.Units,
                                                   annotateLayerPropertiesCollectionClass, symbolCollectionClass as ISymbolCollection, string_0);
                    annotationLayer = fDOGraphicsLayerFactoryClass.OpenAnnotationLayer(
                        iworkspace_0 as IFeatureWorkspace, featureClass.FeatureDataset, string_0);
                }
                IActiveView imap0 = imap_0 as IActiveView;
                (annotationLayer as IGraphicsLayer).Activate(imap0.ScreenDisplay);
                for (i = 0; i < annotateLayerPropertiesCollectionClass.Count; i++)
                {
                    annotateLayerPropertiesCollectionClass.QueryItem(i, out bool0, out elementCollection,
                                                                     out elementCollection1);
                    if (bool0 != null)
                    {
                        bool0.FeatureLayer      = ilayer0;
                        bool0.GraphicsContainer = annotationLayer as IGraphicsContainer;
                        bool0.AddUnplacedToGraphicsContainer = bool_0;
                        bool0.CreateUnplacedElements         = true;
                        bool0.DisplayAnnotation  = true;
                        bool0.FeatureLinked      = bool_1;
                        bool0.LabelWhichFeatures = esriLabelWhichFeatures_0;
                        bool0.UseOutput          = true;
                        d                   = bool0 as ILabelEngineLayerProperties2;
                        d.SymbolID          = i;
                        d.AnnotationClassID = i;
                        (d.OverposterLayerProperties as IOverposterLayerProperties2).TagUnplaced = true;
                    }
                }
                annotateLayerPropertiesCollectionClass.Sort();
                IAnnotateMapProperties annotateMapPropertiesClass = new AnnotateMapProperties()
                {
                    AnnotateLayerPropertiesCollection = annotateLayerPropertiesCollectionClass
                };
                ITrackCancel cancelTrackerClass = new CancelTracker();
                (imap_0.AnnotationEngine as IAnnotateMap2).Label(overposterProperties, annotateMapPropertiesClass,
                                                                 imap_0, cancelTrackerClass);
                for (i = 0; i < annotateLayerPropertiesCollectionClass.Count; i++)
                {
                    annotateLayerPropertiesCollectionClass.QueryItem(i, out bool0, out elementCollection,
                                                                     out elementCollection1);
                    if (bool0 != null)
                    {
                        bool0.FeatureLayer = null;
                    }
                }
                imap_0.AddLayer(annotationLayer as ILayer);
                ilayer0.DisplayAnnotation = false;
                imap0.Refresh();
            }
        }
        public void AddAttributeField(string oldFeatureFile)
        {
            DriverUtils.RegisterOgrDriver();
            DataSource dataSource;
            Layer      layer;

            var isShapeFile = IsShapeInGdb(oldFeatureFile);

            if (isShapeFile)
            {
                dataSource = Ogr.Open(oldFeatureFile, 1); //second argument in open specifies mode of data, 1 RW & 0 readonly mode
                layer      = dataSource.GetLayerByIndex(0);
                var layerDefn = layer.GetLayerDefn();

                int attrFieldIndex = (int)layerDefn.GetFieldIndex("FID_GDAL");
                if (attrFieldIndex == -1)
                {
                    FieldDefn gdalFiedlDefn = new FieldDefn("FID_GDAL", FieldType.OFTInteger);

                    layer.CreateField(gdalFiedlDefn, 0);

                    Feature feature = layer.GetNextFeature();

                    while (feature != null)
                    {
                        feature.SetField("FID_GDAL", feature.GetFID()); // Add FID shapefile
                        layer.SetFeature(feature);
                        feature = layer.GetNextFeature();
                    }
                    layer.SyncToDisk();
                }
                layer.Dispose();
                dataSource.FlushCache();
            }
            else
            {
                try
                {
                    EnableEsriLiscences();

                    string gdbPath     = Path.GetDirectoryName(oldFeatureFile);
                    string featureName = Path.GetFileNameWithoutExtension(oldFeatureFile);

                    IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory();
                    IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(gdbPath, 1);
                    IFeatureClass     featureClass     = featureWorkspace.OpenFeatureClass(featureName);

                    IFields fields = featureClass.Fields;

                    if (fields.FindField("FID_GDAL") == -1)
                    {
                        // Create a Int field called "FID_GDAL" for the fields collection
                        IField     gdalField = new FieldClass();
                        IFieldEdit gField    = (IFieldEdit)gdalField;
                        gField.Name_2 = "FID_GDAL";
                        gField.Type_2 = esriFieldType.esriFieldTypeInteger;
                        //fieldsEdit.AddField(gField);

                        featureClass.AddField(gdalField);
                    }



                    IFeatureCursor featureCursor = featureClass.Search(null, false);
                    IFeature       feature       = featureCursor.NextFeature();
                    while (feature != null)
                    {
                        Console.WriteLine(feature.OID);
                        Console.WriteLine(feature.Fields.FindField("FID_GDAL"));



                        feature.set_Value(feature.Fields.FindField("FID_GDAL"), feature.OID); //  [feature.Fields.FindFieldByAliasName("FID_GDAL")]
                        feature.Store();
                        Console.WriteLine(feature.OID);
                        feature = featureCursor.NextFeature();
                    }

                    featureCursor.Flush();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
        /// <summary>
        ///     Gets the index for field.
        /// </summary>
        /// <param name="attributeName"> The attribute name. </param>
        /// <param name="fields"> The fields. </param>
        /// <returns> </returns>
        private static int GetIndexForField(string attributeName, IFields fields)
        {
            var findField = fields.FindField(attributeName.Trim());

            return findField < 0 ? fields.FindFieldByAliasName(attributeName.Trim()) : findField;
        }
Esempio n. 36
0
 /// <summary>
 /// 根据传入的字段与值的字典信息,返回sql查询语句
 /// </summary>
 /// <params name="fldvals">键值字典</params>
 /// <returns>sql查询语句</returns>
 public string CreateSqlexpression(IFields flds, Dictionary<string, string> fldvals)
 {
     string sql = "";
     int k = 0;
     foreach (string key in fldvals.Keys)
     {
         int fldindex = flds.FindField(key);
         IField fld = flds.get_Field(fldindex);
         esriFieldType type = fld.Type;
         if (k == 0)
         {
             if (type == esriFieldType.esriFieldTypeString)
             {
                 sql = "\"" + key + "\"='" + fldvals[key] + "'";
             }
             else if (type == esriFieldType.esriFieldTypeInteger)
             {
                 sql = "\"" + key + "\"=" + fldvals[key];
             }
         }
         else
         {
             if (type == esriFieldType.esriFieldTypeString)
             {
                 sql += " AND \"" + key + "\"='" + fldvals[key] + "'";
             }
             else if (type == esriFieldType.esriFieldTypeInteger)
             {
                 sql += " AND \"" + key + "\"=" + fldvals[key];
             }
         }
         k++;
     }
     return sql;
 }