コード例 #1
0
 protected ISpatialReference GetProjectedSpatialReference(int pcsType)
 {
     var pSrf = new SpatialReferenceEnvironmentClass();
     var projectedCoordinateSystem = pSrf.CreateProjectedCoordinateSystem(pcsType);
     var spatialReference = (ISpatialReference)projectedCoordinateSystem;
     return spatialReference;
 }
コード例 #2
0
 protected ISpatialReference GetGeographicSpatialReference(int gcsType)
 {
     var pSrf = new SpatialReferenceEnvironmentClass();
     var geographicCoordinateSystem = pSrf.CreateGeographicCoordinateSystem(gcsType);
     var spatialReference = (ISpatialReference)geographicCoordinateSystem;
     return spatialReference;
 }
コード例 #3
0
        private ISpatialReference GetSpatialReference(int xyCoordinateSystem)
        {
            const bool IsHighPrecision = true;

            ISpatialReference spatialReference;

            ISpatialReferenceFactory3 spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            spatialReference = spatialReferenceFactory.CreateSpatialReference(xyCoordinateSystem);

            IControlPrecision2 controlPrecision = spatialReference as IControlPrecision2;
            controlPrecision.IsHighPrecision = IsHighPrecision;

            ISpatialReferenceResolution spatialReferenceResolution = spatialReference as ISpatialReferenceResolution;
            spatialReferenceResolution.ConstructFromHorizon();
            spatialReferenceResolution.SetDefaultXYResolution();
            spatialReferenceResolution.SetDefaultZResolution();
            spatialReferenceResolution.SetDefaultMResolution();

            ISpatialReferenceTolerance spatialReferenceTolerance = spatialReference as ISpatialReferenceTolerance;
            spatialReferenceTolerance.SetDefaultXYTolerance();
            spatialReferenceTolerance.SetDefaultZTolerance();
            spatialReferenceTolerance.SetDefaultMTolerance();

            return spatialReference;
        }
コード例 #4
0
ファイル: BaseGISTools.cs プロジェクト: BNU-Chen/3DGlobe
 /// <summary>
 /// 坐标系转换-----投影坐标系转WGS84
 /// </summary>
 /// <param name="x">x坐标</param>
 /// <param name="y">y坐标</param>
 /// <returns>转换后的IPoint</returns>
 public static IPoint getGeoPoint(double x, double y)
 {
     IPoint pProjPoint = new PointClass();
     pProjPoint.PutCoords(x, y);
     ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass();
     pProjPoint.SpatialReference = pSRF.CreateProjectedCoordinateSystem((int)(esriSRProjCSType.esriSRProjCS_WGS1984UTM_31N));
     pProjPoint.Project(pSRF.CreateGeographicCoordinateSystem((int)(esriSRGeoCSType.esriSRGeoCS_WGS1984)));
     return pProjPoint;      //此时为经纬度点
 }
コード例 #5
0
        public OSMGPExport2OSM()
        {
            resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.GeoProcessing.OSMGPToolsStrings", this.GetType().Assembly);

            osmGPFactory = new OSMGPFactory();
            _osmUtility = new OSMUtility();

            ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass() as ISpatialReferenceFactory;
            m_wgs84 = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984) as ISpatialReference;
        }
コード例 #6
0
        private static ISpatialReference CreateSpatialReference(esriSRGeoCSType coordinateSystem)
        {
            ISpatialReferenceFactory sRefFactory = new SpatialReferenceEnvironmentClass();
            ISpatialReferenceResolution sRefResolution =
                sRefFactory.CreateGeographicCoordinateSystem(Convert.ToInt32(coordinateSystem)) as
                    ISpatialReferenceResolution;

            sRefResolution.ConstructFromHorizon();
            ((ISpatialReferenceTolerance) sRefResolution).SetDefaultXYTolerance();
            return sRefResolution as ISpatialReference;
        }
コード例 #7
0
        private ISpatialReference DefineGCS()
        {
            ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironmentClass();
            //ISpatialReference gcs = srFactory.CreateGeographicCoordinateSystem(wkid); 
            //ISpatialReference gcs = srFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_NAD1983N_AmericaAlbers);
            ISpatialReference gcs = srFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_NAD1983);
                
                // wkid = 4269 (GCS_NAD_1983)
                // wkid = 102008 (North American Albers Equal Area Conic)

            return gcs;
        }
コード例 #8
0
ファイル: boundingBox.cs プロジェクト: geopunt/geopunt4arcgis
        /// <summary> returns the bounds of vlaanderen </summary>
        /// <param name="srs">the spatial reference of input and output, default lam72</param>
        public boundingBox(int srs = 31370)
        {
            //handle SRS
            ISpatialReferenceFactory3 SpatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            inSRS = SpatialReferenceFactory.CreateSpatialReference(srs);

            //Set maxbounds
            ISpatialReference lam72 = SpatialReferenceFactory.CreateSpatialReference(31370);
            IEnvelope maxBounds = geopuntHelper.makeExtend(17750, 23720, 297240, 245340, lam72); //not outside flanders
            IEnvelope prjBounds = geopuntHelper.Transform(maxBounds as IGeometry, inSRS) as IEnvelope;
            Xmin = prjBounds.XMin;
            Ymin = prjBounds.YMin;
            Xmax = prjBounds.XMax;
            Ymax = prjBounds.YMax;
        }
コード例 #9
0
 private static bool IsGeographicSpatialReference(int gcsType)
 {
     try
     {
         var pSrf = new SpatialReferenceEnvironmentClass();
         var geographicCoordinateSystem = pSrf.CreateGeographicCoordinateSystem(gcsType);
         // ReSharper disable once UnusedVariable
         var spatialReference = (ISpatialReference)geographicCoordinateSystem;
         return true;
     }
     catch
     {
         return false;
     }
 }
コード例 #10
0
 private static bool IsProjectedSpatialReference(int pcsType)
 {
     try
     {
         var pSrf = new SpatialReferenceEnvironmentClass();
         var mProjectedCoordinateSystem = pSrf.CreateProjectedCoordinateSystem(pcsType);
         // ReSharper disable once UnusedVariable
         var spatialReference = (ISpatialReference)mProjectedCoordinateSystem;
         return true;
     }
     catch
     {
         return false;
     }
 }
コード例 #11
0
        public static IFeatureClass CreateFeatureClass(fulcrumform form, string pathToGeoDB)
        {
            try
            {
                ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
                IGeographicCoordinateSystem geographicCoordinateSystem = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);
                ISpatialReference sr = geographicCoordinateSystem;

                IWorkspaceFactory2 wsf = new FileGDBWorkspaceFactoryClass();
                IWorkspace2 workspace = (IWorkspace2)wsf.OpenFromFile(pathToGeoDB, 0);
                IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;

                string fcName = GetUniqueFeatureClassName(form.name, workspace);

                IFields fieldsCollection = new FieldsClass();
                IFieldEdit newField = fieldsCollection as IFieldEdit;

                IFeatureClassDescription fcDesc = new ESRI.ArcGIS.Geodatabase.FeatureClassDescriptionClass();

                IObjectClassDescription ocDesc = (IObjectClassDescription)fcDesc;
                // create required fields using the required fields method
                IFields fields = ocDesc.RequiredFields;

                //Grab the GeometryDef from the shape field, edit it and give it back
                int shapeFieldIndex = fields.FindField(fcDesc.ShapeFieldName);
                IField shapeField = fields.get_Field(shapeFieldIndex);
                IGeometryDef geomDef = shapeField.GeometryDef;
                IGeometryDefEdit geomDefEdit = (IGeometryDefEdit)geomDef;
                geomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
                geomDefEdit.GridCount_2 = 1;
                geomDefEdit.set_GridSize(0, 0);
                geomDefEdit.SpatialReference_2 = sr;

                IFields newFields = CreateNewFields(form, fields, sr);

                IFeatureClass featureClass = featureWorkspace.CreateFeatureClass
                    (fcName, newFields, ocDesc.InstanceCLSID, ocDesc.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDesc.ShapeFieldName, "");

                return featureClass;
            }
            catch (Exception e)
            {
                string errMsg = e.Message;
                return null;
            }
        }
コード例 #12
0
ファイル: boundingBox.cs プロジェクト: geopunt/geopunt4arcgis
        /// <summary> constructor: creates a Class to handle a boundingbox, 
        /// that make sure it is within Flanderers and return string string in the wanted format. </summary>
        /// <param name="xmin">lowest x-coordinate in given srs</param>
        /// <param name="ymin">lowest y-coordinate in given srs<</param>
        /// <param name="xmax">highest x-coordinate in given srs<</param>
        /// <param name="ymax">highest x-coordinate in given srs<</param>
        /// <param name="srs">the spatial reference of input and output</param>
        public boundingBox(double xmin, double ymin, double xmax, double ymax, int srs)
        {
            //handle SRS
            ISpatialReferenceFactory3 SpatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            inSRS = SpatialReferenceFactory.CreateSpatialReference(srs);

            //Set maxbounds
            ISpatialReference lam72 = SpatialReferenceFactory.CreateSpatialReference(31370);
            IEnvelope maxBounds = geopuntHelper.makeExtend(17750, 23720, 297240, 245340, lam72); //not outside flanders
            IEnvelope prjBounds = geopuntHelper.Transform(maxBounds as IGeometry, inSRS) as IEnvelope;

            if (xmin > prjBounds.XMin) Xmin = xmin;
            else Xmin = prjBounds.XMin;
            if (ymin > prjBounds.YMin) Ymin = ymin;
            else Ymin = prjBounds.YMin;
            if (xmax < prjBounds.XMax) Xmax = xmax;
            else Xmax = prjBounds.XMax;
            if (xmax < prjBounds.YMax) Ymax = ymax;
            else Ymax = prjBounds.YMax;
        }
コード例 #13
0
 private static IFeatureClass BuildQueryFeatureClass(string connection, string query, string name, string oidFields, int? srid, esriGeometryType? geometryType)
 {
     var factory = new SqlWorkspaceFactoryClass();
     var workspace = factory.OpenFromString(connection, 0);
     //var workspace = factory.OpenFromFile(@"c:\tmp\AnimalMovement.sde", 0);
     var sqlWorkspace = (ISqlWorkspace)workspace;
     var queryDescription = sqlWorkspace.GetQueryDescription(query);
     if (!String.IsNullOrEmpty(oidFields))
         queryDescription.OIDFields = oidFields;
     if (srid.HasValue)
     {
         queryDescription.Srid = srid.Value.ToString(CultureInfo.InvariantCulture);
         var srEnv = new SpatialReferenceEnvironmentClass();
         queryDescription.SpatialReference = srEnv.CreateSpatialReference(srid.Value);
     }
     if (geometryType.HasValue)
         queryDescription.GeometryType = geometryType.Value;
     sqlWorkspace.CheckDatasetName(name, queryDescription, out name);
     var queryClass = sqlWorkspace.OpenQueryClass(name, queryDescription);
     var featureClass = (IFeatureClass)queryClass;
     return featureClass;
 }
コード例 #14
0
        /// <summary>
        /// 获取矢量元数据
        /// </summary>
        private void GetVectorMeta()
        {
            textBoxLayerName.Text  = pFeatureLayer.Name;
            textBoxDataType.Text   = "矢量数据";
            textBoxCreateTime.Text = DateTime.Now.ToString("yyyy年MM月dd日 hh时mm分ss秒");

            //投影到经纬度
            IEnvelope pExtent = pFeatureLayer.AreaOfInterest;

            try
            {
                ISpatialReferenceFactory spatialrefFactory = new SpatialReferenceEnvironmentClass();
                ISpatialReference        pSR = spatialrefFactory.CreateGeographicCoordinateSystem((int)(esriSRGeoCSType.esriSRGeoCS_WGS1984));
                pExtent.Project(pSR);
            }
            catch { MessageBox.Show("输入文件空间参考有误"); }
            textBoxVMinX.Text = pExtent.XMin.ToString();
            textBoxVMinY.Text = pExtent.YMin.ToString();
            textBoxVMaxX.Text = pExtent.XMax.ToString();
            textBoxVMaxY.Text = pExtent.YMax.ToString();

            textBoxVShape.Text     = pFeatureLayer.FeatureClass.ShapeType.ToString();
            textBoxProjection.Text = (pFeatureLayer.FeatureClass as IGeoDataset).SpatialReference.Name;
        }
コード例 #15
0
        private void  CreateGeographicCoordinateSystem()
        {
            ISpatialReferenceFactory3 spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            IDatum         datum         = spatialReferenceFactory.CreateDatum((int)esriSRDatumType.esriSRDatum_OSGB1936);
            IPrimeMeridian primeMeridian = spatialReferenceFactory.CreatePrimeMeridian((int)esriSRPrimeMType.esriSRPrimeM_Greenwich);
            IUnit          unit          = spatialReferenceFactory.CreateUnit((int)esriSRUnitType.esriSRUnit_Degree);
            IGeographicCoordinateSystemEdit geographicCoordinateSystemEdit = new GeographicCoordinateSystemClass();
            object name                = "UserDefined Geographic Coordinate System";
            object alias               = "UserDefined GCS";
            object abbreviation        = "UserDefined";
            object remarks             = "User Defined Geographic Coordinate System based on OSGB1936";
            object usage               = "Suitable for the UK";
            object datumObject         = datum as object;
            object primeMeridianObject = primeMeridian as object;
            object unitObject          = unit as object;

            geographicCoordinateSystemEdit.Define(ref name, ref alias, ref abbreviation, ref remarks, ref usage, ref datumObject, ref primeMeridianObject, ref unitObject);
            IGeographicCoordinateSystem userDefinedGeographicCoordinateSystem = geographicCoordinateSystemEdit as IGeographicCoordinateSystem;


            m_map.SpatialReference = userDefinedGeographicCoordinateSystem;
            m_activeView.Refresh();
            MessageBox.Show("已将当前坐标系统转换为自定义GeographicCoordinateSystem!");
        }
コード例 #16
0
        public IPoint ProjectWgsToPulkovoWithGeoTransformation(
            IPoint inputPoint,
            CoordinateSystemModel coordinateSystemModel,
            esriTransformDirection transformationDirection)
        {
            if (inputPoint == null)
            {
                return(null);
            }

            var bufferPoint = new PointClass {
                X = inputPoint.X, Y = inputPoint.Y, SpatialReference = inputPoint.SpatialReference
            };

            //Create Spatial Reference Factory
            var spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            var targetSpatialReference  = spatialReferenceFactory.CreateGeographicCoordinateSystem(coordinateSystemModel.ESRIWellKnownID);

            var coordinateFrameGeoTransformation = new CoordinateFrameTransformationClass();

            coordinateFrameGeoTransformation.PutSpatialReferences(bufferPoint.SpatialReference, targetSpatialReference);
            coordinateFrameGeoTransformation.PutParameters(
                Constants.PulkovoToWGS.XAxisTranslation,
                Constants.PulkovoToWGS.YAxisTranslation,
                Constants.PulkovoToWGS.ZAxisTranslation,
                Constants.PulkovoToWGS.XAxisRotation,
                Constants.PulkovoToWGS.YAxisRotation,
                Constants.PulkovoToWGS.ZAxisRotation,
                Constants.PulkovoToWGS.ScaleDifference);

            var geometry = bufferPoint as IGeometry5;

            geometry.ProjectEx(targetSpatialReference, transformationDirection, coordinateFrameGeoTransformation, false, 0.0, 0.0);

            return(geometry as IPoint);
        }
コード例 #17
0
        /// <summary>
        /// 创建一个要素集
        /// </summary>
        private void CreateFeatureClass()
        {
            string path    = txt_org.Text;
            string PRJFile = txt_prj.Text;
            AccessWorkspaceFactory pAccessFact = new AccessWorkspaceFactoryClass();

            IFeatureWorkspace         pFeatureWorkspace = pAccessFact.OpenFromFile(path, 0) as IFeatureWorkspace;
            ISpatialReferenceFactory2 Isp = new SpatialReferenceEnvironmentClass();                   //创建一个空间参照的接口空间

            ISpatialReference           spatial = Isp.CreateESRISpatialReferenceFromPRJFile(PRJFile); //利用要素类的PRJ文件参照
            ISpatialReferenceResolution pSRR    = (ISpatialReferenceResolution)spatial;               //设置分辨率

            pSRR.SetDefaultXYResolution();                                                            //设置默认XY值

            ISpatialReferenceTolerance pSRT = (ISpatialReferenceTolerance)spatial;

            pSRT.SetDefaultXYTolerance();//设置默认容差值
            IWorkspace space = pFeatureWorkspace as IWorkspace;

            IEnumDatasetName Dataset_name = space.get_DatasetNames(esriDatasetType.esriDTAny);//得到有多少个要素集合名字

            Dataset_name.Reset();
            IDatasetName Name_set = Dataset_name.Next();

            while (Name_set != null)
            {
                if (Name_set.Name == "Geo_Topo_ice")
                {
                    SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "数据集已存在,不用创建!");
                    this.Close();//如果要创建的数据集已存在,就返回,并关闭窗体
                    return;
                }
                Name_set = Dataset_name.Next();
            }
            IFeatureDataset pfd = pFeatureWorkspace.CreateFeatureDataset("Geo_Topo_ice", spatial); //创建一个要素集

            IEnumDataset dst = space.get_Datasets(esriDatasetType.esriDTAny);                      //得到所有的要素类的一个集合

            dst.Reset();
            IDataset det = dst.Next();

            _AppHk.OperatorTips = "开始创建对应的要素类...";
            while (det != null)
            {
                #region 给要素集创建空的要素类
                if (det.Type == esriDatasetType.esriDTFeatureClass)                       //判定是不是要素类
                {
                    string org_name = det.Name;                                           //原始的名字
                    _AppHk.OperatorTips = "开始创建" + org_name + "要素类...";
                    IFeatureClass f_class = pFeatureWorkspace.OpenFeatureClass(org_name); //打开源要素类
                    det.Rename(org_name + "_t");                                          //把源要素类进行重命名
                    IFields     Fieldset = new FieldsClass();                             //建立一个字段集
                    IFieldsEdit sField   = Fieldset as IFieldsEdit;                       //字段集
                    if (f_class.FeatureType != esriFeatureType.esriFTAnnotation)
                    {
                        //shape
                        IGeometryDefEdit d_edit;                       //定义一个用来接收要素类的SHAPE类型
                        d_edit = new GeometryDefClass();               //实例一个操作类
                        d_edit.GeometryType_2     = f_class.ShapeType; //将源要素类的SHAPE赋值给我们要创建的几何类型
                        d_edit.SpatialReference_2 = spatial;           //空间参考

                        string OID   = f_class.OIDFieldName;           //ODI名字
                        string SHAPE = f_class.ShapeFieldName;         //SHAPE名字

                        //IFields Fieldset = new FieldsClass();//建立一个字段集
                        //IFieldsEdit sField = Fieldset as IFieldsEdit;//字段集


                        //创建要素类里的字段
                        int count = f_class.Fields.FieldCount;//确定有多少个字段

                        #region 创建字段
                        for (int n = 0; n < count; n++)
                        {
                            IField f_ield = f_class.Fields.get_Field(n);

                            IFieldEdit fieldEdit = f_ield as IFieldEdit;
                            //Annotate
                            if (f_ield.Name == SHAPE)
                            {
                                //shape field
                                fieldEdit.Type_2        = esriFieldType.esriFieldTypeGeometry; //确定字段的类型
                                fieldEdit.GeometryDef_2 = d_edit;                              //把几何类型赋值给它
                                fieldEdit.Name_2        = SHAPE;                               //把几何类型SHPAE的名字赋值给它
                                f_ield = fieldEdit as IField;
                                sField.AddField(f_ield);                                       //加入要素集
                            }
                            else if (f_ield.Name == OID)
                            {
                                //oid
                                fieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; //OID标识字段
                                fieldEdit.Name_2 = OID;                            //OID的名字
                                f_ield           = fieldEdit as IField;
                                sField.AddField(f_ield);                           //加入OID
                            }
                            else
                            {
                                //一般字段
                                fieldEdit.Name_2 = f_ield.Name;
                                fieldEdit.Type_2 = f_ield.Type;//字段的类型

                                f_ield = fieldEdit as IField;
                                sField.AddField(f_ield);
                            }
                        }
                        #endregion

                        Fieldset = sField as IFields;                                                                             //将可编辑的字段集转成一般字段集
                        pfd.CreateFeatureClass(org_name, Fieldset, f_class.CLSID, null, esriFeatureType.esriFTSimple, SHAPE, ""); //给要素集中创建要素类
                    }
                    else
                    {
                        createAnnoFeatureClass(org_name, pfd, pfd.Workspace as IFeatureWorkspace, sField, 2000);
                    }

                    det = dst.Next();//重新遍历下一个
                }
                else
                {
                    det = dst.Next();//重新遍历下一个
                }
                #endregion
            }
            _AppHk.OperatorTips = "要素集合创建成功!";
            GetValue(pFeatureWorkspace);//当对应的要素类建立好后,就开始给空要素类赋值
            SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "数据处理完成!");
            this.Close();
        }
コード例 #18
0
    /// <summary>
    /// create a WGS1984 geographic coordinate system.
    /// In this case, the underlying data provided by the service is in WGS1984.
    /// </summary>
    /// <returns></returns>
		private ISpatialReference CreateGeographicSpatialReference()
		{
			ISpatialReferenceFactory spatialRefFatcory = new SpatialReferenceEnvironmentClass();
			IGeographicCoordinateSystem geoCoordSys;
			geoCoordSys = spatialRefFatcory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);
			geoCoordSys.SetFalseOriginAndUnits(-180.0, -180.0, 5000000.0);
			geoCoordSys.SetZFalseOriginAndUnits(0.0, 100000.0);
			geoCoordSys.SetMFalseOriginAndUnits(0.0, 100000.0);

			return geoCoordSys as ISpatialReference;
		}
コード例 #19
0
ファイル: FrmHistoryMapView.cs プロジェクト: siszoey/geosufan
        private void DoAttriAnalysis()
        {
            _Progress.SetProgress("分析叠置结果...");
            Application.DoEvents();
            ISpatialReferenceFactory pSpaFac = new SpatialReferenceEnvironmentClass();
            ISpatialReference        pSpaRef = pSpaFac.CreateESRISpatialReferenceFromPRJFile(_PrjFileName);

            IWorkspaceFactory pWSFact    = new AccessWorkspaceFactoryClass();
            IWorkspace        pWorkspace = null;

            try
            {
                pWorkspace = pWSFact.OpenFromFile(_MdbPath + "\\" + _MdbName, 0);
            }
            catch
            { }
            if (pWorkspace == null)
            {
                return;
            }
            pSpaFac = null;
            pWSFact = null;
            IFeatureClass pInterFeaClass = (pWorkspace as IFeatureWorkspace).OpenFeatureClass(_IntersectName);

            IField     pField     = new FieldClass();
            IFieldEdit pFieldEdit = pField as IFieldEdit;

            pFieldEdit.Name_2      = "jsmjtmp";
            pFieldEdit.AliasName_2 = "计算面积";
            pFieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
            if (_Progress != null)
            {
                if (_Progress.UserAskCancel)
                {
                    return;
                }
            }
            pInterFeaClass.AddField(pField);
            pField = null;
            int indexJSMJ = -1;

            indexJSMJ = pInterFeaClass.Fields.FindField("jsmjtmp");
            _Progress.SetProgress("计算叠置结果的面积...");
            Application.DoEvents();
            IQueryFilter pFilter = new QueryFilterClass();

            pFilter.WhereClause = "dl<>dl_1 or lz<>lz_1";
            try
            {
                IFeatureCursor pCursor = pInterFeaClass.Search(pFilter, false);
                IFeature       pFea    = pCursor.NextFeature();
                while (pFea != null)
                {
                    if (_Progress != null)
                    {
                        if (_Progress.UserAskCancel)
                        {
                            return;
                        }
                    }

                    IClone    pClone = (IClone)pFea.Shape;
                    IGeometry pGeo   = pClone.Clone() as IGeometry;
                    pGeo.Project(pSpaRef);
                    IArea pArea = pGeo as IArea;
                    if (pArea != null)
                    {
                        pFea.set_Value(indexJSMJ, pArea.Area);
                        pFea.Store();
                    }
                    pFea = pCursor.NextFeature();
                }
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pCursor);
                pCursor = null;
            }
            catch
            { }
            _Progress.SetProgress("对叠置结果进行分析...");
            Application.DoEvents();
            if (_Progress != null)
            {
                if (_Progress.UserAskCancel)
                {
                    return;
                }
            }
            //从叠置结果生成报表
            string          connstr   = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _MdbPath + "\\" + _MdbName;
            OleDbConnection oledbconn = new OleDbConnection(connstr);

            oledbconn.Open();

            OleDbCommand pCommand = oledbconn.CreateCommand();

            ModTableFun.DropTable(oledbconn, "tmpBGJL");
            pCommand.CommandText = "select shi,xian,xiang,cun,xbh,xbh_1,dl,dl_1,lz,lz_1,jsmjtmp into tmpBGJL from " + _IntersectName + " where dl<>dl_1 or lz<>lz_1";
            pCommand.ExecuteNonQuery();
            pCommand.CommandText = "delete from tmpBGJL where jsmjtmp<0.01";
            pCommand.ExecuteNonQuery();
            OleDbDataReader   pReader = ModTableFun.GetReader(oledbconn, "select shi,xian,xiang,cun,xbh,dl_1,lz_1,dl,lz,round(jsmjtmp,2) from tmpBGJL");
            FrmAnalysisResult pFrm    = new FrmAnalysisResult();

            DevComponents.DotNetBar.Controls.DataGridViewX pGrid = pFrm.ResultGrid;
            int intIndex = pGrid.Rows.Count;

            _Progress.SetProgress("准备展示分析结果...");
            Application.DoEvents();
            if (pReader == null)
            {
                return;
            }
            while (pReader.Read())
            {
                if (_Progress != null)
                {
                    if (_Progress.UserAskCancel)
                    {
                        oledbconn.Close();
                        return;
                    }
                }
                try
                {
                    pGrid.Rows.Add(pReader.GetValue(0).ToString(), pReader.GetValue(1).ToString(), pReader.GetValue(2).ToString(), pReader.GetValue(3).ToString(), pReader.GetValue(4).ToString(), pReader.GetValue(5).ToString(), pReader.GetValue(6).ToString(), pReader.GetValue(7).ToString(), pReader.GetValue(8).ToString(), pReader.GetValue(9).ToString());

                    intIndex++;
                }
                catch
                { }
            }
            pReader.Close();
            oledbconn.Close();
            oledbconn = null;
            _Progress.Close();
            _Progress = null;
            pFrm.Show();
        }
コード例 #20
0
        /// <summary>
        /// Create a Mosaic Dataset in the geodatabase provided using the parameters defined by MDParamaters.
        /// </summary>
        /// <param name="gdbWorkspace">Geodatabase to create the Mosaic dataser in.</param>
        public void CreateMosaicDataset(IWorkspace gdbWorkspace)
        {
            try
            {
                #region Global Declarations
                IMosaicDataset                  theMosaicDataset          = null;
                IMosaicDatasetOperation         theMosaicDatasetOperation = null;
                IMosaicWorkspaceExtensionHelper mosaicExtHelper           = null;
                IMosaicWorkspaceExtension       mosaicExt = null;
                #endregion

                #region CreateMosaicDataset
                try
                {
                    Console.WriteLine("Create Mosaic Dataset: " + MDParameters.mosaicDatasetName + ".amd");
                    /// Setup workspaces.
                    /// Create Srs
                    ISpatialReferenceFactory spatialrefFactory = new SpatialReferenceEnvironmentClass();

                    // Create the mosaic dataset creation parameters object.
                    ICreateMosaicDatasetParameters creationPars = new CreateMosaicDatasetParametersClass();
                    // Set the number of bands for the mosaic dataset.
                    // If defined as zero leave defaults
                    if (MDParameters.mosaicDatasetBands != 0)
                    {
                        creationPars.BandCount = MDParameters.mosaicDatasetBands;
                    }
                    // Set the pixel type of the mosaic dataset.
                    // If defined as unknown leave defaults
                    if (MDParameters.mosaicDatasetBits != rstPixelType.PT_UNKNOWN)
                    {
                        creationPars.PixelType = MDParameters.mosaicDatasetBits;
                    }
                    // Create the mosaic workspace extension helper class.
                    mosaicExtHelper = new MosaicWorkspaceExtensionHelperClass();
                    // Find the right extension from the workspace.
                    mosaicExt = mosaicExtHelper.FindExtension(gdbWorkspace);

                    // Default is none.
                    if (MDParameters.productDefinitionKey.ToLower() != "none")
                    {
                        // Set the product definition keyword and properties.
                        // (The property is called band definition keyword and band properties in the object).
                        ((ICreateMosaicDatasetParameters2)creationPars).BandDefinitionKeyword = MDParameters.productDefinitionKey;
                        MDParameters.productDefinitionProps = SetBandProperties(MDParameters.productDefinitionKey);
                        if (MDParameters.productDefinitionProps.Count == 0)
                        {
                            Console.WriteLine("Setting production definition properties failed.");
                            return;
                        }
                        ((ICreateMosaicDatasetParameters2)creationPars).BandProperties = MDParameters.productDefinitionProps;
                    }

                    // Use the extension to create a new mosaic dataset, supplying the
                    // spatial reference and the creation parameters object created above.
                    theMosaicDataset = mosaicExt.CreateMosaicDataset(MDParameters.mosaicDatasetName,
                                                                     MDParameters.mosaicDatasetSrs, creationPars, MDParameters.configKeyword);
                }
                catch (Exception exc)
                {
                    Console.WriteLine("Exception Caught while creating Mosaic Dataset: " + exc.Message);
                    return;
                }
                #endregion

                #region OpenMosaicDataset
                Console.WriteLine("Opening Mosaic Dataset");
                theMosaicDataset = null;
                // Use the extension to open the mosaic dataset.
                theMosaicDataset = mosaicExt.OpenMosaicDataset(MDParameters.mosaicDatasetName);
                // The mosaic dataset operation interface is used to perform operations on
                // a mosaic dataset.
                theMosaicDatasetOperation = (IMosaicDatasetOperation)(theMosaicDataset);
                #endregion

                #region Preparing Raster Type
                Console.WriteLine("Preparing Raster Type");
                // Create a Raster Type Name object.
                IRasterTypeName theRasterTypeName = new RasterTypeNameClass();
                // Assign the name of the Raster Type to the name object.
                // The Name field accepts a path to an .art file as well
                // the name for a built in Raster Type.
                theRasterTypeName.Name = MDParameters.rasterTypeName;
                // Use the Open function from the IName interface to get the Raster Type object.
                IRasterType theRasterType = (IRasterType)(((IName)theRasterTypeName).Open());
                if (theRasterType == null)
                {
                    Console.WriteLine("Raster Type not found " + MDParameters.rasterTypeName);
                }

                // Set the URI Filter on the loaded raster type.
                if (MDParameters.rasterTypeProductFilter != "")
                {
                    // Get the supported URI filters from the raster type object using the
                    // raster type properties interface.
                    IArray         mySuppFilters = ((IRasterTypeProperties)theRasterType).SupportedURIFilters;
                    IItemURIFilter productFilter = null;
                    for (int i = 0; i < mySuppFilters.Count; ++i)
                    {
                        // Set the desired filter from the supported filters.
                        productFilter = (IItemURIFilter)mySuppFilters.get_Element(i);
                        if (productFilter.Name == MDParameters.rasterTypeProductFilter)
                        {
                            theRasterType.URIFilter = productFilter;
                        }
                    }
                }
                // Enable the correct templates in the raster type.
                string[] rasterProductNames = MDParameters.rasterTypeProductName.Split(';');
                bool     enableTemplate     = false;
                if (rasterProductNames.Length >= 1 && (rasterProductNames[0] != ""))
                {
                    // Get the supported item templates from the raster type.
                    IItemTemplateArray templateArray = theRasterType.ItemTemplates;
                    for (int i = 0; i < templateArray.Count; ++i)
                    {
                        // Go through the supported item templates and enable the ones needed.
                        IItemTemplate template = templateArray.get_Element(i);
                        enableTemplate = false;
                        for (int j = 0; j < rasterProductNames.Length; ++j)
                        {
                            if (template.Name == rasterProductNames[j])
                            {
                                enableTemplate = true;
                            }
                        }
                        if (enableTemplate)
                        {
                            template.Enabled = true;
                        }
                        else
                        {
                            template.Enabled = false;
                        }
                    }
                }

                if (MDParameters.dataSourceSrs != null)
                {
                    ((IRasterTypeProperties)theRasterType).SynchronizeParameters.DefaultSpatialReference =
                        MDParameters.dataSourceSrs;
                }
                #endregion

                #region Add DEM To Raster Type
                if (MDParameters.rasterTypeAddDEM && ((IRasterTypeProperties)theRasterType).SupportsOrthorectification)
                {
                    // Open the Raster Dataset
                    Type factoryType = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory");
                    IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
                    IRasterWorkspace  rasterWorkspace  = (IRasterWorkspace)workspaceFactory.OpenFromFile(
                        System.IO.Path.GetDirectoryName(MDParameters.rasterTypeDemPath), 0);;
                    IRasterDataset myRasterDataset = rasterWorkspace.OpenRasterDataset(
                        System.IO.Path.GetFileName(MDParameters.rasterTypeDemPath));

                    IGeometricFunctionArguments geometricFunctionArguments =
                        new GeometricFunctionArgumentsClass();
                    geometricFunctionArguments.DEM = myRasterDataset;
                    ((IRasterTypeProperties)theRasterType).OrthorectificationParameters =
                        geometricFunctionArguments;
                }
                #endregion

                #region Preparing Data Source Crawler
                Console.WriteLine("Preparing Data Source Crawler");
                // Create a new property set to specify crawler properties.
                IPropertySet crawlerProps = new PropertySetClass();
                // Specify a file filter
                crawlerProps.SetProperty("Filter", MDParameters.dataSourceFilter);
                // Specify whether to search subdirectories.
                crawlerProps.SetProperty("Recurse", true);
                // Specify the source path.
                crawlerProps.SetProperty("Source", MDParameters.dataSource);
                // Get the recommended crawler from the raster type based on the specified
                // properties using the IRasterBuilder interface.
                IDataSourceCrawler theCrawler = ((IRasterBuilder)theRasterType).GetRecommendedCrawler(crawlerProps);
                #endregion

                #region Add Rasters
                Console.WriteLine("Adding Rasters");
                // Create a AddRaster parameters object.
                IAddRastersParameters AddRastersArgs = new AddRastersParametersClass();
                // Specify the data crawler to be used to crawl the data.
                AddRastersArgs.Crawler = theCrawler;
                // Specify the raster type to be used to add the data.
                AddRastersArgs.RasterType = theRasterType;
                // Use the mosaic dataset operation interface to add
                // rasters to the mosaic dataset.
                theMosaicDatasetOperation.AddRasters(AddRastersArgs, null);
                #endregion

                #region Compute Pixel Size Ranges
                Console.WriteLine("Computing Pixel Size Ranges");
                // Create a calculate cellsize ranges parameters object.
                ICalculateCellSizeRangesParameters computeArgs = new CalculateCellSizeRangesParametersClass();
                // Use the mosaic dataset operation interface to calculate cellsize ranges.
                theMosaicDatasetOperation.CalculateCellSizeRanges(computeArgs, null);
                #endregion

                #region Building Boundary
                Console.WriteLine("Building Boundary");
                // Create a build boundary parameters object.
                IBuildBoundaryParameters boundaryArgs = new BuildBoundaryParametersClass();
                // Set flags that control boundary generation.
                boundaryArgs.AppendToExistingBoundary = true;
                // Use the mosaic dataset operation interface to build boundary.
                theMosaicDatasetOperation.BuildBoundary(boundaryArgs, null);
                #endregion

                if (MDParameters.buildOverviews)
                {
                    #region Defining Overviews
                    Console.WriteLine("Defining Overviews");
                    // Create a define overview parameters object.
                    IDefineOverviewsParameters defineOvArgs = new DefineOverviewsParametersClass();
                    // Use the overview tile parameters interface to specify the overview factor
                    // used to generate overviews.
                    ((IOverviewTileParameters)defineOvArgs).OverviewFactor = 3;
                    // Use the mosaic dataset operation interface to define overviews.
                    theMosaicDatasetOperation.DefineOverviews(defineOvArgs, null);
                    #endregion

                    #region Compute Pixel Size Ranges
                    Console.WriteLine("Computing Pixel Size Ranges");
                    // Calculate cell size ranges to update the Min/Max pixel sizes.
                    theMosaicDatasetOperation.CalculateCellSizeRanges(computeArgs, null);
                    #endregion

                    #region Generating Overviews
                    Console.WriteLine("Generating Overviews");
                    // Create a generate overviews parameters object.
                    IGenerateOverviewsParameters genPars = new GenerateOverviewsParametersClass();
                    // Set properties to control overview generation.
                    IQueryFilter genQuery = new QueryFilterClass();
                    ((ISelectionParameters)genPars).QueryFilter = genQuery;
                    genPars.GenerateMissingImages = true;
                    genPars.GenerateStaleImages   = true;
                    // Use the mosaic dataset operation interface to generate overviews.
                    theMosaicDatasetOperation.GenerateOverviews(genPars, null);
                    #endregion
                }

                #region Report
                Console.WriteLine("Success.");
                #endregion
            }
            catch (Exception exc)
            {
                #region Report
                Console.WriteLine("Exception Caught in CreateMD: " + exc.Message);
                Console.WriteLine("Shutting down.");
                #endregion
            }
        }
コード例 #21
0
ファイル: helpers.cs プロジェクト: BGCX261/ziggis-svn-to-git
 public static ISpatialReference setEsriSpatiaReferenceFromSrid(int srid)
 {
     //there is not always a perfect corrispondence between PostGIS srid and Esri Factory code: so we have to catch the possible error in CreateSpatialReference, and in that case set it to Unknow (it won't be possible to project layers, but at least it will be displayed)
     ISpatialReference sr;
     try
     {
         //Paolo : set Spatial Reference
         ISpatialReferenceFactory2 srf = new SpatialReferenceEnvironmentClass();
         if (srid == -1)
         {
             sr = new UnknownCoordinateSystemClass();
         }
         else
         {
             sr = srf.CreateSpatialReference(srid);
         }
         return sr;
     }
     catch
     {
         //PostGis srid is not implemented as an Esri Factory Code
         sr = new UnknownCoordinateSystemClass();
         return sr;
     }
 }
コード例 #22
0
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            _message = message;

            // classes to carry out the basic client/server communication
            HttpWebResponse httpResponse = null;
            string changeSetID = "-1";
            IGPString baseURLGPString = new GPStringClass();
            ICursor searchCursor = null;

            IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

            if (TrackCancel == null)
            {
                TrackCancel = new CancelTrackerClass();
            }

            IGPParameter userNameParameter = paramvalues.get_Element(in_userNameNumber) as IGPParameter;
            IGPString userNameGPValue = gpUtilities3.UnpackGPValue(userNameParameter) as IGPString;

            IHttpBasicGPValue userCredentialGPValue = new HttpBasicGPValue();

            if (userNameGPValue != null)
            {
                userCredentialGPValue.UserName = userNameGPValue.Value;
            }
            else
            {
                return;
            }

            IGPParameter passwordParameter = paramvalues.get_Element(in_passwordNumber) as IGPParameter;
            IGPStringHidden passwordGPValue = gpUtilities3.UnpackGPValue(passwordParameter) as IGPStringHidden;

            if (passwordGPValue != null)
            {
                userCredentialGPValue.PassWord = passwordGPValue.Value;
            }
            else
            {
                return;
            }

            ITable revisionTable = null;
            int secondsToTimeout = 10;

            try
            {
                UpdateMessages(paramvalues, envMgr, message);

                if ((message.MaxSeverity == esriGPMessageSeverity.esriGPMessageSeverityAbort) ||
                    (message.MaxSeverity == esriGPMessageSeverity.esriGPMessageSeverityError))
                {
                    message.AddMessages(message);
                    return;
                }

                IGPParameter baseURLParameter = paramvalues.get_Element(in_uploadURLNumber) as IGPParameter;
                baseURLGPString = gpUtilities3.UnpackGPValue(baseURLParameter) as IGPString;

                IGPParameter commentParameter = paramvalues.get_Element(in_uploadCommentNumber) as IGPParameter;
                IGPString uploadCommentGPString = gpUtilities3.UnpackGPValue(commentParameter) as IGPString;

                ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass() as ISpatialReferenceFactory;
                m_wgs84 = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984) as ISpatialReference;

                System.Xml.Serialization.XmlSerializer serializer = null;
                serializer = new XmlSerializer(typeof(osm));

                osm createChangeSetOSM = new osm();
                string user_displayname = "";
                int userID = -1;

                // set the "default" value of the OSM server
                int maxElementsinChangeSet = 50000;

                HttpWebRequest httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/capabilities") as HttpWebRequest;
                httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient);
                SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord);
                httpClient.Timeout = secondsToTimeout * 1000;

                createChangeSetOSM.generator = m_Generator;
                createChangeSetOSM.version = "0.6";

                changeset createChangeSet = new changeset();
                createChangeSet.id = "0";
                createChangeSet.open = changesetOpen.@false;

                List<tag> changeSetTags = new List<tag>();

                tag createdByTag = new tag();
                createdByTag.k = "created_by";
                createdByTag.v = "ArcGIS Editor for OpenStreetMap";
                changeSetTags.Add(createdByTag);

                tag commentTag = new tag();
                commentTag.k = "comment";
                commentTag.v = uploadCommentGPString.Value;
                changeSetTags.Add(commentTag);

                createChangeSet.tag = changeSetTags.ToArray();
                createChangeSetOSM.Items = new object[] { createChangeSet };

                api apiCapabilities = null;

                // retrieve some server settings

                try
                {
                    httpResponse = httpClient.GetResponse() as HttpWebResponse;

                    osm osmCapabilities = null;

                    Stream stream = httpResponse.GetResponseStream();

                    XmlTextReader xmlReader = new XmlTextReader(stream);
                    osmCapabilities = serializer.Deserialize(xmlReader) as osm;
                    xmlReader.Close();

                    apiCapabilities = osmCapabilities.Items[0] as api;
                    httpResponse.Close();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    message.AddWarning(ex.Message);
                }

                if (apiCapabilities != null)
                {
                    // read the timeout parameter
                    secondsToTimeout = Convert.ToInt32(apiCapabilities.timeout.seconds);
                    httpClient.Timeout = secondsToTimeout * 1000;

                    // update the setting of allowed features per changeset from the actual capabilities response
                    maxElementsinChangeSet = Convert.ToInt32(apiCapabilities.changesets.maximum_elements);
                }

                // retrieve some information about the user
                try
                {
                    httpClient = null;
                    httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/user/details") as HttpWebRequest;
                    httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient);
                    SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord);

                    httpResponse = httpClient.GetResponse() as HttpWebResponse;

                    osm osmCapabilities = null;

                    Stream stream = httpResponse.GetResponseStream();

                    XmlTextReader xmlReader = new XmlTextReader(stream);
                    osmCapabilities = serializer.Deserialize(xmlReader) as osm;
                    xmlReader.Close();
                    user userInformation = osmCapabilities.Items[0] as user;

                    if (userInformation != null)
                    {
                        user_displayname = userInformation.display_name;
                        userID = Convert.ToInt32(userInformation.id);
                    }
                }

                catch (ArgumentOutOfRangeException ex)
                {
                    message.AddError(120044, ex.Message);
                    return;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    message.AddWarning(ex.Message);
                }

                IGPParameter revisionTableParameter = paramvalues.get_Element(in_changesTablesNumber) as IGPParameter;
                int featureUpdateCounter = 0;

                IQueryFilter revisionTableQueryFilter = null;

                try
                {
                    gpUtilities3.DecodeTableView(gpUtilities3.UnpackGPValue(revisionTableParameter), out revisionTable, out revisionTableQueryFilter);
                }
                catch
                {
                    message.AddError(120045,resourceManager.GetString("GPTools_OSMGPUpload_missingRevisionTable"));
                    return;
                }

                int revChangeSetIDFieldIndex = revisionTable.Fields.FindField("osmchangeset");
                int revActionFieldIndex = revisionTable.Fields.FindField("osmaction");
                int revElementTypeFieldIndex = revisionTable.Fields.FindField("osmelementtype");
                int revVersionFieldIndex = revisionTable.Fields.FindField("osmversion");
                int revFCNameFieldIndex = revisionTable.Fields.FindField("sourcefcname");
                int revOldIDFieldIndex = revisionTable.Fields.FindField("osmoldid");
                int revNewIDFieldIndex = revisionTable.Fields.FindField("osmnewid");
                int revStatusFieldIndex = revisionTable.Fields.FindField("osmstatus");
                int revStatusCodeFieldIndex = revisionTable.Fields.FindField("osmstatuscode");
                int revErrorMessageFieldIndex = revisionTable.Fields.FindField("osmerrormessage");
                int revLongitudeFieldIndex = revisionTable.Fields.FindField("osmlon");
                int revLatitudeFieldIndex = revisionTable.Fields.FindField("osmlat");

                // let's find all the rows that have a different status than OK - meaning success
                IQueryFilter queryFilter = new QueryFilterClass();

                searchCursor = revisionTable.Search(queryFilter, false);
                IRow searchRowToUpdate = null;

                // lookup table to adjust all osm ID references if there are know entities
                Dictionary<long, long> nodeosmIDLookup = new Dictionary<long, long>();
                Dictionary<long, long> wayosmIDLookup = new Dictionary<long, long>();
                Dictionary<long, long> relationosmIDLookup = new Dictionary<long, long>();

                // let's pre-populate the lookup IDs with already know entities
                // it is necessary if the revision table is used more than once and in different sessions
                queryFilter.WhereClause = "NOT " + revisionTable.SqlIdentifier("osmnewid") + " IS NULL";

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    ICursor searchIDCursor = revisionTable.Search(queryFilter, false);
                    comReleaser.ManageLifetime(searchIDCursor);

                    IRow searchRow = searchIDCursor.NextRow();
                    comReleaser.ManageLifetime(searchRow);

                    while (searchRow != null)
                    {
                        if (revOldIDFieldIndex > -1 && revNewIDFieldIndex > -1)
                        {
                            string elementType = Convert.ToString(searchRow.get_Value(revElementTypeFieldIndex));

                            switch (elementType)
                            {
                                case "node":
                                    if (nodeosmIDLookup.ContainsKey(Convert.ToInt64(searchRow.get_Value(revOldIDFieldIndex))) == false)
                                    {
                                        nodeosmIDLookup.Add(Convert.ToInt64(searchRow.get_Value(revOldIDFieldIndex)), Convert.ToInt64(searchRow.get_Value(revNewIDFieldIndex)));
                                    }
                                    break;
                                case "way":
                                    if (wayosmIDLookup.ContainsKey(Convert.ToInt64(searchRow.get_Value(revOldIDFieldIndex))) == false)
                                    {
                                        wayosmIDLookup.Add(Convert.ToInt64(searchRow.get_Value(revOldIDFieldIndex)), Convert.ToInt64(searchRow.get_Value(revNewIDFieldIndex)));
                                    }
                                    break;
                                case "relation":
                                    if (relationosmIDLookup.ContainsKey(Convert.ToInt64(searchRow.get_Value(revOldIDFieldIndex))) == false)
                                    {
                                        relationosmIDLookup.Add(Convert.ToInt64(searchRow.get_Value(revOldIDFieldIndex)), Convert.ToInt64(searchRow.get_Value(revNewIDFieldIndex)));
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                        searchRow = searchIDCursor.NextRow();
                    }
                }

                IFeatureClass pointFeatureClass = null;
                int pointOSMIDFieldIndex = -1;
                IFeatureClass lineFeatureClass = null;
                IFeatureClass polygonFeatureClass = null;
                ITable relationTable = null;

                int osmDelimiterPosition = ((IDataset)revisionTable).Name.IndexOf("_osm_");
                string osmBaseName = ((IDataset)revisionTable).Name.Substring(0, osmDelimiterPosition);

                IFeatureWorkspace osmFeatureWorkspace = ((IDataset)revisionTable).Workspace as IFeatureWorkspace;

                if (osmFeatureWorkspace != null)
                {
                    pointFeatureClass = osmFeatureWorkspace.OpenFeatureClass(osmBaseName + "_osm_pt");
                    pointOSMIDFieldIndex = pointFeatureClass.FindField("OSMID");
                    lineFeatureClass = osmFeatureWorkspace.OpenFeatureClass(osmBaseName + "_osm_ln");
                    polygonFeatureClass = osmFeatureWorkspace.OpenFeatureClass(osmBaseName + "_osm_ply");
                    relationTable = osmFeatureWorkspace.OpenTable(osmBaseName + "_osm_relation");
                }

                // determine version of extension
                int internalExtensionVersion = pointFeatureClass.OSMExtensionVersion();

                string sData = OsmRest.SerializeUtils.CreateXmlSerializable(createChangeSetOSM, serializer, Encoding.ASCII, "text/xml");
                HttpWebRequest httpClient2 = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/changeset/create") as HttpWebRequest;
                httpClient2.Method = "PUT";
                httpClient2 = OSMGPDownload.AssignProxyandCredentials(httpClient2);
                SetBasicAuthHeader(httpClient2, userCredentialGPValue.EncodedUserNamePassWord);
                httpClient2.Timeout = secondsToTimeout * 1000;

                try
                {
                    Stream requestStream = httpClient2.GetRequestStream();
                    StreamWriter mywriter = new StreamWriter(requestStream);

                    mywriter.Write(sData);
                    mywriter.Close();

                    WebResponse clientResponse = httpClient2.GetResponse();
                    Stream readStream = clientResponse.GetResponseStream();
                    StreamReader streamReader = new StreamReader(readStream);
                    changeSetID = streamReader.ReadToEnd();
                    streamReader.Close();

                    message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPUpload_openChangeSet"), changeSetID));

                }
                catch (Exception ex)
                {
                    if (httpResponse != null)
                    {
                        if (httpResponse.StatusCode != System.Net.HttpStatusCode.OK)
                        {
                            foreach (var errorItem in httpResponse.Headers.GetValues("Error"))
                            {
                                message.AddError(120009, errorItem);
                            }

                            message.AddError(120009, httpResponse.StatusCode.ToString());
                            message.AddError(120009, ex.Message);
                        }
                    }
                    else
                    {
                        message.AddError(120047, ex.Message);
                    }

                    return;
                }

                IGPParameter uploadFormatParameter = paramvalues.get_Element(in_uploadFormatNumber) as IGPParameter;
                IGPBoolean useOSMChangeFormatGPValue = gpUtilities3.UnpackGPValue(uploadFormatParameter) as IGPBoolean;

                // Al Hack
                if (useOSMChangeFormatGPValue == null)
                {
                    useOSMChangeFormatGPValue = new GPBoolean();
                    useOSMChangeFormatGPValue.Value = false;
                }

                SQLFormatter sqlFormatter = new SQLFormatter(revisionTable);

                if (useOSMChangeFormatGPValue.Value == true)
                {
                    #region osmchange upload format

                    osmChange osmChangeDocument = new osmChange();
                    osmChangeDocument.generator = m_Generator;
                    osmChangeDocument.version = "0.6";

                    // xml elements to describe the changeset
                    create uploadCreates = null;
                    modify uploadModify = null;
                    delete uploadDelete = null;

                    // helper classes to keep track of elements entered into a changeset
                    List<object> listOfCreates = null;
                    List<object> listOfModifies = null;
                    List<object> listOfDeletes = null;

                    List<object> changeSetItems = new List<object>();

                    #region upload create actions
                    // loop through creates
                    queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR "
                        + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND "
                        + sqlFormatter.SqlIdentifier("osmaction") + " = 'create'";

                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        searchCursor = revisionTable.Search(queryFilter, false);
                        comReleaser.ManageLifetime(searchCursor);

                        searchRowToUpdate = searchCursor.NextRow();
                        comReleaser.ManageLifetime(searchRowToUpdate);

                        // if we have at least one entry with a create action, then add the 'create' element to the changeset representation
                        if (searchRowToUpdate != null)
                        {
                            uploadCreates = new create();
                            listOfCreates = new List<object>();
                        }

                        while (searchRowToUpdate != null)
                        {
                            try
                            {
                                if (TrackCancel.Continue() == false)
                                {
                                    closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString);
                                    return;
                                }

                                string action = String.Empty;
                                if (revActionFieldIndex != -1)
                                {
                                    action = searchRowToUpdate.get_Value(revActionFieldIndex) as string;
                                }
                                string elementType = String.Empty;
                                if (revElementTypeFieldIndex != -1)
                                {
                                    elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string;
                                }

                                string sourceFCName = String.Empty;
                                if (revFCNameFieldIndex != -1)
                                {
                                    sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string;
                                }

                                long osmOldID = -1;
                                if (revOldIDFieldIndex != -1)
                                {
                                    osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex));
                                }

                                // if the overall number of uploaded elements is too big for a single changeset we do need to split it up
                                // into multiple sets
                                if (featureUpdateCounter > 0 & (featureUpdateCounter % maxElementsinChangeSet) == 0)
                                {
                                    // add any outstanding creations to the changeset items
                                    if (listOfCreates != null && uploadCreates != null)
                                    {
                                        uploadCreates.Items = listOfCreates.ToArray();
                                        // in case there are any creates let's add them to the changeset document
                                        changeSetItems.Add(uploadCreates);
                                    }

                                    // add all the changeset items to the changeset document
                                    osmChangeDocument.Items = changeSetItems.ToArray();

                                    // submit changeset
                                    try
                                    {
                                        httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/changeset/" + changeSetID + "/upload") as HttpWebRequest;
                                        httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient);
                                        httpClient.Method = "POST";
                                        SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord);
                                        httpClient.Timeout = secondsToTimeout * 1000;

                                        string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(osmChangeDocument, null, Encoding.UTF8, "text/xml");

                                        message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPUpload_featureSubmit"), featureUpdateCounter));

                                        OsmRest.HttpUtils.Post(httpClient, sContent);

                                        httpResponse = httpClient.GetResponse() as HttpWebResponse;
                                        diffResult diffResultResonse = OsmRest.HttpUtils.GetResponse(httpResponse);

                                        // parse changes locally and update local data sources
                                        if (diffResultResonse != null)
                                        {
                                            ParseResultDiff(diffResultResonse, revisionTable, pointFeatureClass, lineFeatureClass, polygonFeatureClass, relationTable, user_displayname, userID, changeSetID, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                        }

                                    }
                                    catch (Exception ex)
                                    {
                                        closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString);
                                        message.AddError(120009, ex.Message);

                                        if (ex is WebException)
                                        {
                                            WebException webException = ex as WebException;
                                            string serverErrorMessage = webException.Response.Headers["Error"];
                                            if (!String.IsNullOrEmpty(serverErrorMessage))
                                            {
                                                message.AddError(120009, serverErrorMessage);
                                            }
                                        }

                                        if (httpResponse != null)
                                        {
                                            httpResponse.Close();
                                        }
                                        return;
                                    }
                                    finally
                                    {
                                        // reset the list and containers of modifications for the next batch
                                        listOfCreates.Clear();
                                        changeSetItems.Clear();

                                        if (httpResponse != null)
                                        {
                                            httpResponse.Close();
                                        }
                                    }

                                    if (TrackCancel.Continue() == false)
                                    {
                                        closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString);
                                        return;
                                    }

                                    CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter);
                                }

                                switch (elementType)
                                {
                                    case "node":
                                        node createNode = CreateNodeRepresentation(pointFeatureClass, action, osmOldID, changeSetID, 1, null, internalExtensionVersion);
                                        listOfCreates.Add(createNode);
                                        break;
                                    case "way":
                                        way createWay = null;
                                        if (sourceFCName.Contains("_osm_ln"))
                                        {
                                            createWay = CreateWayRepresentation(lineFeatureClass, action, osmOldID, changeSetID, 1, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion);
                                        }
                                        else if (sourceFCName.Contains("_osm_ply"))
                                        {
                                            createWay = CreateWayRepresentation(polygonFeatureClass, action, osmOldID, changeSetID, 1, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion);
                                        }
                                        listOfCreates.Add(createWay);
                                        break;
                                    case "relation":
                                        relation createRelation = null;
                                        if (sourceFCName.Contains("_osm_ln"))
                                        {
                                            createRelation = CreateRelationRepresentation((ITable)lineFeatureClass, action, osmOldID, changeSetID, 1, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                        }
                                        else if (sourceFCName.Contains("_osm_ply"))
                                        {
                                            createRelation = CreateRelationRepresentation((ITable)polygonFeatureClass, action, osmOldID, changeSetID, 1, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                        }
                                        else if (sourceFCName.Contains("_osm_relation"))
                                        {
                                            createRelation = CreateRelationRepresentation(relationTable, action, osmOldID, changeSetID, 1, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                        }
                                        listOfCreates.Add(createRelation);
                                        break;
                                    default:
                                        break;
                                }
                                // increment the counter keeping track of the submitted changes
                                featureUpdateCounter = featureUpdateCounter + 1;
                            }
                            catch
                            {
                            }
                            searchRowToUpdate = searchCursor.NextRow();
                        }

                        if (listOfCreates != null && uploadCreates != null)
                        {
                            // sort the list of created elements in the order of nodes, ways, relations
                            listOfCreates.Sort(new OSMElementComparer());

                            uploadCreates.Items = listOfCreates.ToArray();
                            // in case there are any creates let's add them to the changeset document
                            changeSetItems.Add(uploadCreates);
                        }
                    }
                    #endregion

                    #region upload modify actions
                    // loop through modifies
                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        queryFilter.WhereClause = "(" +
                            sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR "
                            + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND "
                            + sqlFormatter.SqlIdentifier("osmaction") + " = 'modify'";

                        searchCursor = revisionTable.Search(queryFilter, false);
                        comReleaser.ManageLifetime(searchCursor);

                        searchRowToUpdate = searchCursor.NextRow();

                        if (searchRowToUpdate != null)
                        {
                            uploadModify = new modify();
                            listOfModifies = new List<object>();
                        }

                        while (searchRowToUpdate != null)
                        {
                            if (TrackCancel.Continue() == false)
                            {
                                closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString);
                                return;
                            }

                            try
                            {
                                string action = String.Empty;
                                if (revActionFieldIndex != -1)
                                {
                                    action = searchRowToUpdate.get_Value(revActionFieldIndex) as string;
                                }

                                string elementType = String.Empty;
                                if (revElementTypeFieldIndex != -1)
                                {
                                    elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string;
                                }

                                string sourceFCName = String.Empty;
                                if (revFCNameFieldIndex != -1)
                                {
                                    sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string;
                                }

                                long osmOldID = -1;
                                if (revOldIDFieldIndex != -1)
                                {
                                    osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex));
                                }

                                // if the overall number of uploaded elements is too big for a single changeset we do need to split it up
                                long modifyID = -1;
                                if (revNewIDFieldIndex != -1)
                                {
                                    object osmIDValue = searchRowToUpdate.get_Value(revNewIDFieldIndex);

                                    if (osmIDValue == DBNull.Value)
                                    {
                                        osmIDValue = osmOldID;
                                    }

                                    try
                                    {
                                        modifyID = Convert.ToInt64(osmIDValue);
                                    }
                                    catch { }

                                    // modifies should only happen to osm IDs > 0
                                    // if that condition is not met let's skip this feature as something is not right
                                    if (modifyID < 0)
                                    {
                                        searchRowToUpdate = searchCursor.NextRow();
                                        continue;
                                    }
                                }

                                int osmVersion = -1;
                                if (revVersionFieldIndex != -1)
                                {
                                    osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex));
                                }

                                // into multiple sets
                                if ((featureUpdateCounter % maxElementsinChangeSet) == 0)
                                {
                                    // add any outstanding modifications to the changeset items
                                    if (listOfModifies != null && uploadModify != null)
                                    {
                                        uploadModify.Items = listOfModifies.ToArray();
                                        // in case there are any creates let's add them to the changeset document
                                        changeSetItems.Add(uploadModify);
                                    }

                                    // add all the changeset items to the changeset document
                                    osmChangeDocument.Items = changeSetItems.ToArray();

                                    // submit changeset
                                    try
                                    {
                                        httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/changeset/" + changeSetID + "/upload") as HttpWebRequest;
                                        httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient);
                                        httpClient.Method = "POST";
                                        SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord);
                                        httpClient.Timeout = secondsToTimeout * 1000;

                                        string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(osmChangeDocument, null, Encoding.UTF8, "text/xml");
                                        OsmRest.HttpUtils.Post(httpClient, sContent);

                                        httpResponse = httpClient.GetResponse() as HttpWebResponse;
                                        diffResult diffResultResonse = OsmRest.HttpUtils.GetResponse(httpResponse);

                                        // parse changes locally and update local data sources
                                        if (diffResultResonse != null)
                                        {
                                            ParseResultDiff(diffResultResonse, revisionTable, pointFeatureClass, lineFeatureClass, polygonFeatureClass, relationTable, user_displayname, userID, changeSetID, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                        }

                                    }
                                    catch (Exception ex)
                                    {
                                        closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString);
                                        message.AddError(120009, ex.Message);

                                        if (ex is WebException)
                                        {
                                            WebException webException = ex as WebException;
                                            string serverErrorMessage = webException.Response.Headers["Error"];
                                            if (!String.IsNullOrEmpty(serverErrorMessage))
                                            {
                                                message.AddError(120009, serverErrorMessage);
                                            }

                                            if (httpResponse != null)
                                            {
                                                httpResponse.Close();
                                            }
                                        }
                                        return;
                                    }
                                    finally
                                    {
                                        // reset the list and containers of modifications for the next batch
                                        listOfModifies.Clear();
                                        changeSetItems.Clear();

                                        if (httpResponse != null)
                                        {
                                            httpResponse.Close();
                                        }
                                    }

                                    if (TrackCancel.Continue() == false)
                                    {
                                        closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString);
                                        return;
                                    }

                                    CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter);
                                }

                                switch (elementType)
                                {
                                    case "node":
                                        node updateNode = CreateNodeRepresentation(pointFeatureClass, action, modifyID, changeSetID, osmVersion, null, internalExtensionVersion);
                                        listOfModifies.Add(updateNode);
                                        break;
                                    case "way":
                                        way updateWay = null;
                                        if (sourceFCName.Contains("_osm_ln"))
                                        {
                                            updateWay = CreateWayRepresentation(lineFeatureClass, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion);
                                        }
                                        else if (sourceFCName.Contains("_osm_ply"))
                                        {
                                            updateWay = CreateWayRepresentation(polygonFeatureClass, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion);
                                        }
                                        listOfModifies.Add(updateWay);
                                        break;
                                    case "relation":
                                        relation updateRelation = null;
                                        if (sourceFCName.Contains("_osm_ln"))
                                        {
                                            updateRelation = CreateRelationRepresentation((ITable)lineFeatureClass, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                        }
                                        else if (sourceFCName.Contains("_osm_ply"))
                                        {
                                            updateRelation = CreateRelationRepresentation((ITable)polygonFeatureClass, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                        }
                                        else if (sourceFCName.Contains("_osm_relation"))
                                        {
                                            updateRelation = CreateRelationRepresentation(relationTable, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                        }
                                        listOfModifies.Add(updateRelation);
                                        break;
                                    default:
                                        break;
                                }

                                // track the update/sync requests against the server
                                featureUpdateCounter = featureUpdateCounter + 1;
                            }
                            catch
                            {
                            }

                            searchRowToUpdate = searchCursor.NextRow();
                        }

                        if (listOfModifies != null && uploadModify != null)
                        {
                            uploadModify.Items = listOfModifies.ToArray();
                            // in case there are any creates let's add them to the changeset document
                            changeSetItems.Add(uploadModify);
                        }

                    }
                    #endregion

                    #region upload delete actions
                    // loop through deletes in "reverse" - relation, then way, then node
                    string[] elementTypes = new string[] { "relation", "way", "node" };

                    foreach (string osmElementType in elementTypes)
                    {
                        using (ComReleaser comReleaser = new ComReleaser())
                        {
                            queryFilter.WhereClause = "(" +  sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR "
                                + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND "
                                + sqlFormatter.SqlIdentifier("osmaction") + " = 'delete' AND "
                                + sqlFormatter.SqlIdentifier("osmelementtype") + " = '" + osmElementType + "'";

                            searchCursor = revisionTable.Search(queryFilter, false);
                            comReleaser.ManageLifetime(searchCursor);

                            searchRowToUpdate = searchCursor.NextRow();

                            if (searchRowToUpdate != null)
                            {
                                if (TrackCancel.Continue() == false)
                                {
                                    closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString);
                                    return;
                                }

                                if (uploadDelete == null)
                                {
                                    uploadDelete = new delete();
                                    listOfDeletes = new List<object>();
                                }
                            }

                            while (searchRowToUpdate != null)
                            {
                                try
                                {
                                    string action = String.Empty;
                                    if (revActionFieldIndex != -1)
                                    {
                                        action = searchRowToUpdate.get_Value(revActionFieldIndex) as string;
                                    }

                                    string elementType = String.Empty;
                                    if (revElementTypeFieldIndex != -1)
                                    {
                                        elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string;
                                    }

                                    string sourceFCName = String.Empty;
                                    if (revFCNameFieldIndex != -1)
                                    {
                                        sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string;
                                    }

                                    long osmOldID = -1;
                                    if (revOldIDFieldIndex != -1)
                                    {
                                        osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex));
                                    }

                                    int osmVersion = -1;
                                    if (revVersionFieldIndex != -1)
                                    {
                                        osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex));
                                    }

                                    // into multiple sets
                                    if ((featureUpdateCounter % maxElementsinChangeSet) == 0)
                                    {
                                        // add any outstanding creations to the changeset items
                                        if (listOfDeletes != null && uploadDelete != null)
                                        {
                                            uploadDelete.Items = listOfDeletes.ToArray();
                                            // in case there are any creates let's add them to the changeset document
                                            changeSetItems.Add(uploadDelete);
                                        }

                                        // add all the changeset items to the changeset document
                                        osmChangeDocument.Items = changeSetItems.ToArray();

                                        // submit changeset
                                        try
                                        {
                                            httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/changeset/" + changeSetID + "/upload") as HttpWebRequest;
                                            httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient);
                                            httpClient.Method = "POST";
                                            SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord);
                                            httpClient.Timeout = secondsToTimeout * 1000;

                                            string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(osmChangeDocument, null, Encoding.UTF8, "text/xml");
                                            OsmRest.HttpUtils.Post(httpClient, sContent);

                                            httpResponse = httpClient.GetResponse() as HttpWebResponse;
                                            diffResult diffResultResonse = OsmRest.HttpUtils.GetResponse(httpResponse);

                                            // parse changes locally and update local data sources
                                            if (diffResultResonse != null)
                                            {
                                                ParseResultDiff(diffResultResonse, revisionTable, pointFeatureClass, lineFeatureClass, polygonFeatureClass, relationTable, user_displayname, userID, changeSetID, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                            }

                                        }
                                        catch (Exception ex)
                                        {
                                            closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString);
                                            message.AddError(120009, ex.Message);

                                            if (ex is WebException)
                                            {
                                                WebException webException = ex as WebException;
                                                string serverErrorMessage = webException.Response.Headers["Error"];
                                                if (!String.IsNullOrEmpty(serverErrorMessage))
                                                {
                                                    message.AddError(120009, serverErrorMessage);
                                                }
                                            }

                                            if (httpResponse != null)
                                            {
                                                httpResponse.Close();
                                            }

                                            return;
                                        }
                                        finally
                                        {
                                            // reset the list and containers of modifications for the next batch
                                            listOfDeletes.Clear();
                                            changeSetItems.Clear();

                                            if (httpResponse != null)
                                            {
                                                httpResponse.Close();
                                            }
                                        }

                                        if (TrackCancel.Continue() == false)
                                        {
                                            closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString);
                                            return;
                                        }

                                        CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter);
                                    }

                                    switch (elementType)
                                    {
                                        case "node":
                                            IPoint deletePoint = null;
                                            if (revLongitudeFieldIndex != -1 && revLatitudeFieldIndex != -1)
                                            {
                                                try
                                                {
                                                    // let's reconstruct the delete point
                                                    deletePoint = new PointClass();
                                                    deletePoint.X = Convert.ToDouble(searchRowToUpdate.get_Value(revLongitudeFieldIndex));
                                                    deletePoint.Y = Convert.ToDouble(searchRowToUpdate.get_Value(revLatitudeFieldIndex));
                                                    deletePoint.SpatialReference = m_wgs84;
                                                }
                                                catch (Exception ex)
                                                {
                                                    message.AddWarning(ex.Message);
                                                }

                                                if (deletePoint == null)
                                                {
                                                    // inform the about the issue - no successful creation of point and continue on to the next delete instruction
                                                    // in the revision table
                                                    message.AddWarning(resourceManager.GetString("GPTools_OSMGPUpload_invalidPoint"));
                                                    searchRowToUpdate = searchCursor.NextRow();
                                                    continue;
                                                }
                                            }

                                            node deleteNode = CreateNodeRepresentation(pointFeatureClass, action, osmOldID, changeSetID, osmVersion, deletePoint, internalExtensionVersion);
                                            listOfDeletes.Add(deleteNode);
                                            break;
                                        case "way":
                                            way deleteWay = null;
                                            if (sourceFCName.Contains("_osm_ln"))
                                            {
                                                deleteWay = CreateWayRepresentation(lineFeatureClass, action, osmOldID, changeSetID, osmVersion, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion);
                                            }
                                            else if (sourceFCName.Contains("_osm_ply"))
                                            {
                                                deleteWay = CreateWayRepresentation(polygonFeatureClass, action, osmOldID, changeSetID, osmVersion, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion);
                                            }
                                            listOfDeletes.Add(deleteWay);
                                            break;
                                        case "relation":
                                            relation deleteRelation = null;
                                            if (sourceFCName.Contains("_osm_ln"))
                                            {
                                                deleteRelation = CreateRelationRepresentation((ITable)lineFeatureClass, action, osmOldID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                            }
                                            else if (sourceFCName.Contains("_osm_ply"))
                                            {
                                                deleteRelation = CreateRelationRepresentation((ITable)polygonFeatureClass, action, osmOldID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                            }
                                            else if (sourceFCName.Contains("_osm_relation"))
                                            {
                                                deleteRelation = CreateRelationRepresentation(relationTable, action, osmOldID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                            }
                                            listOfDeletes.Add(deleteRelation);
                                            break;
                                        default:
                                            break;
                                    }

                                    // track the update/sync requests against the server
                                    featureUpdateCounter = featureUpdateCounter + 1;
                                }
                                catch
                                {
                                }

                                searchRowToUpdate = searchCursor.NextRow();
                            }

                        }
                    }

                    if (listOfDeletes != null && uploadDelete != null)
                    {
                        uploadDelete.Items = listOfDeletes.ToArray();
                        // in case there are any creates let's add them to the changeset document
                        changeSetItems.Add(uploadDelete);
                    }
                    #endregion

                    if (TrackCancel.Continue() == false)
                    {
                        closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString);
                        return;
                    }

                    // add all the changeset items to the changeset document
                    osmChangeDocument.Items = changeSetItems.ToArray();

                    // submit changeset
                    try
                    {
                        httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/changeset/" + changeSetID + "/upload") as HttpWebRequest;
                        httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient);
                        httpClient.Method = "POST";
                        SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord);
                        httpClient.Timeout = secondsToTimeout * 1000;

                        message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPUpload_featureSubmit"), featureUpdateCounter));

                        string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(osmChangeDocument, null, Encoding.UTF8, "text/xml");
                        OsmRest.HttpUtils.Post(httpClient, sContent);

                        httpResponse = httpClient.GetResponse() as HttpWebResponse;

                        //Exception with an error HTTP 400
                        diffResult diffResultResonse = OsmRest.HttpUtils.GetResponse(httpResponse);

                        message.AddMessage(resourceManager.GetString("GPTools_OSMGPUpload_updatelocalData"));

                        // parse changes locally and update local data sources
                        if (diffResultResonse != null)
                        {
                            ParseResultDiff(diffResultResonse, revisionTable, pointFeatureClass, lineFeatureClass, polygonFeatureClass, relationTable, user_displayname, userID, changeSetID, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                        }
                    }
                    catch (Exception ex)
                    {
                        message.AddError(120009, ex.Message);

                        try
                        {
                            if (ex is WebException)
                            {
                                WebException webException = ex as WebException;
                                string serverErrorMessage = webException.Response.Headers["Error"];
                                if (!String.IsNullOrEmpty(serverErrorMessage))
                                {
                                    message.AddError(120009, serverErrorMessage);
                                }
                            }
                        }
                        catch (Exception innerexception)
                        {
                            message.AddError(120009, innerexception.Message);
                        }
                    }
                    finally
                    {
                        if (httpResponse != null)
                        {
                            httpResponse.Close();
                        }
                    }
                    #endregion
                }
                else
                {
                    #region single upload format
                    #region submit the create nodes first
                    queryFilter.WhereClause = "(" +
                        sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR "
                        + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND "
                        + sqlFormatter.SqlIdentifier("osmaction") + " = 'create'  AND "
                        + sqlFormatter.SqlIdentifier("osmelementtype") + " = 'node'";

                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        searchCursor = revisionTable.Search(queryFilter, false);
                        comReleaser.ManageLifetime(searchCursor);

                        while ((searchRowToUpdate = searchCursor.NextRow()) != null)
                        {
                            try
                            {
                                string action = String.Empty;
                                if (revActionFieldIndex != -1)
                                {
                                    action = searchRowToUpdate.get_Value(revActionFieldIndex) as string;
                                }
                                string elementType = String.Empty;
                                if (revElementTypeFieldIndex != -1)
                                {
                                    elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string;
                                }

                                string sourceFCName = String.Empty;
                                if (revFCNameFieldIndex != -1)
                                {
                                    sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string;
                                }

                                long osmOldID = -1;
                                if (revOldIDFieldIndex != -1)
                                {
                                    osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex));
                                }

                                // if the overall number of uploaded elements is too big for a single changeset we do need to split it up
                                // into multiple sets
                                if ((featureUpdateCounter % maxElementsinChangeSet) == 0)
                                {
                                    CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter);
                                }

                                osm createNode = CreateOSMNodeRepresentation(pointFeatureClass, action, osmOldID, changeSetID, -1, null, internalExtensionVersion);

                                httpClient = null;
                                httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/" + elementType + "/create") as HttpWebRequest;
                                httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient);
                                httpClient.Method = "PUT";
                                SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord);
                                httpClient.Timeout = secondsToTimeout * 1000;

                                httpResponse = null;

                                string nodeContent = OsmRest.SerializeUtils.CreateXmlSerializable(createNode, serializer, Encoding.UTF8, "text/xml");

                                if (String.IsNullOrEmpty(nodeContent))
                                {
                                    continue;
                                }

                                OsmRest.HttpUtils.Put(httpClient, nodeContent);

                                httpResponse = httpClient.GetResponse() as HttpWebResponse;

                                createNode = null;

                                // track the update/sync requests against the server
                                featureUpdateCounter = featureUpdateCounter + 1;

                                if (httpResponse != null)
                                {
                                    string newIDString = OsmRest.HttpUtils.GetResponseContent(httpResponse);

                                    nodeosmIDLookup.Add(osmOldID, Convert.ToInt64(newIDString));

                                    // update the revision table
                                    if (revNewIDFieldIndex != -1)
                                    {
                                        searchRowToUpdate.set_Value(revNewIDFieldIndex, Convert.ToString(newIDString));
                                    }
                                    if (revVersionFieldIndex != -1)
                                    {
                                        searchRowToUpdate.set_Value(revVersionFieldIndex, 1);
                                    }
                                    if (revStatusFieldIndex != -1)
                                    {
                                        searchRowToUpdate.set_Value(revStatusFieldIndex, httpResponse.StatusCode.ToString());
                                    }
                                    if (revStatusCodeFieldIndex != -1)
                                    {
                                        searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode);
                                    }
                                    if (revChangeSetIDFieldIndex != -1)
                                    {
                                        searchRowToUpdate.set_Value(revChangeSetIDFieldIndex, Convert.ToString(changeSetID));
                                    }

                                    // update the source point feature class as well
                                    updateSource((ITable)pointFeatureClass, action, osmOldID, Convert.ToInt64(newIDString), user_displayname, userID, 1, Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup,internalExtensionVersion);
                                }
                            }
                            catch (Exception ex)
                            {

                                message.AddError(120009, ex.Message);

                                if (ex is WebException)
                                {
                                    updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex);
                                }
                            }
                            finally
                            {
                                try
                                {
                                    searchRowToUpdate.Store();
                                }
                                catch (Exception ex)
                                {
                                    System.Diagnostics.Debug.WriteLine(ex.Message);
                                }

                                if (httpResponse != null)
                                {
                                    httpResponse.Close();
                                }
                            }

                            if (TrackCancel.Continue() == false)
                            {
                                closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString);
                                return;
                            }
                        }
                    }
                    #endregion

                    #region next the create ways
                    queryFilter.WhereClause = "(" +
                        sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR "
                        + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND "
                        + sqlFormatter.SqlIdentifier("osmaction") + " = 'create'  AND "
                        + sqlFormatter.SqlIdentifier("osmelementtype") + " = 'way'";

                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        searchCursor = revisionTable.Search(queryFilter, false);
                        comReleaser.ManageLifetime(searchCursor);

                        while ((searchRowToUpdate = searchCursor.NextRow()) != null)
                        {
                            try
                            {
                                string action = String.Empty;
                                if (revActionFieldIndex != -1)
                                {
                                    action = searchRowToUpdate.get_Value(revActionFieldIndex) as string;
                                }
                                string elementType = String.Empty;
                                if (revElementTypeFieldIndex != -1)
                                {
                                    elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string;
                                }

                                string sourceFCName = String.Empty;
                                if (revFCNameFieldIndex != -1)
                                {
                                    sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string;
                                }

                                long osmOldID = -1;
                                if (revOldIDFieldIndex != -1)
                                {
                                    osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex));
                                }

                                bool isPolygon = false;
                                if (sourceFCName.IndexOf("_osm_ply") > -1)
                                {
                                    isPolygon = true;
                                }

                                // if the overall number of uploaded elements is too big for a single changeset we do need to split it up
                                // into multiple sets
                                if ((featureUpdateCounter % maxElementsinChangeSet) == 0)
                                {
                                    CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter);
                                }

                                osm createWay = new osm();
                                if (isPolygon == false)
                                {
                                    createWay = CreateOSMWayRepresentation(lineFeatureClass, action, osmOldID, changeSetID, -1, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion);
                                }
                                else
                                {
                                    createWay = CreateOSMWayRepresentation(polygonFeatureClass, action, osmOldID, changeSetID, -1, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion);
                                }

                                try
                                {
                                    HttpWebRequest httpClient3 = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/" + elementType + "/create") as HttpWebRequest;
                                    httpClient3 = OSMGPDownload.AssignProxyandCredentials(httpClient3);
                                    httpClient3.Method = "PUT";
                                    SetBasicAuthHeader(httpClient3, userCredentialGPValue.EncodedUserNamePassWord);
                                    httpClient.Timeout = secondsToTimeout * 1000;

                                    string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(createWay, serializer, Encoding.UTF8, "text/xml");
                                    OsmRest.HttpUtils.Put(httpClient3, sContent);
                                    createWay = null;

                                    httpResponse = null;
                                    httpResponse = httpClient3.GetResponse() as HttpWebResponse;

                                    // track the update/sync requests against the server
                                    featureUpdateCounter = featureUpdateCounter + 1;
                                }
                                catch (Exception ex)
                                {
                                    message.AddError(120009, ex.Message);

                                    if (ex is WebException)
                                    {
                                        updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex);
                                    }
                                }

                                if (httpResponse != null)
                                {
                                    string newIDString = OsmRest.HttpUtils.GetResponseContent(httpResponse);

                                    wayosmIDLookup.Add(osmOldID, Convert.ToInt64(newIDString));

                                    // update the revision table
                                    if (revNewIDFieldIndex != -1)
                                    {
                                        searchRowToUpdate.set_Value(revNewIDFieldIndex, Convert.ToString(newIDString));
                                    }
                                    if (revVersionFieldIndex != -1)
                                    {
                                        searchRowToUpdate.set_Value(revVersionFieldIndex, 1);
                                    }
                                    if (revStatusFieldIndex != -1)
                                    {
                                        searchRowToUpdate.set_Value(revStatusFieldIndex, httpResponse.StatusCode.ToString());
                                    }
                                    if (revStatusCodeFieldIndex != -1)
                                    {
                                        searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode);
                                    }
                                    if (revChangeSetIDFieldIndex != -1)
                                    {
                                        searchRowToUpdate.set_Value(revChangeSetIDFieldIndex, Convert.ToString(changeSetID));
                                    }

                                    // update the source line/polygon feature class as well
                                    if (isPolygon == false)
                                    {
                                        updateSource((ITable)lineFeatureClass, action, osmOldID, Convert.ToInt64(newIDString), user_displayname, userID, 1, Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                    }
                                    else
                                    {
                                        updateSource((ITable)polygonFeatureClass, action, osmOldID, Convert.ToInt64(newIDString), user_displayname, userID, 1, Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                    }
                                }
                            }

                            catch (Exception ex)
                            {
                                message.AddError(120009, ex.Message);

                                if (ex is WebException)
                                {
                                    updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex);
                                }
                            }
                            finally
                            {
                                try
                                {
                                    searchRowToUpdate.Store();
                                }
                                catch (Exception ex)
                                {
                                    System.Diagnostics.Debug.WriteLine(ex.Message);
                                }

                                if (httpResponse != null)
                                {
                                    httpResponse.Close();
                                }
                            }

                            if (TrackCancel.Continue() == false)
                            {
                                closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString);

                                return;
                            }
                        }
                    }
                    #endregion

                    #region and then create relations
                    queryFilter.WhereClause = "(" +
                        sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR "
                        + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND "
                        + sqlFormatter.SqlIdentifier("osmaction") + " = 'create'  AND "
                        + sqlFormatter.SqlIdentifier("osmelementtype") + " = 'relation'";

                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        searchCursor = revisionTable.Search(queryFilter, false);
                        comReleaser.ManageLifetime(searchCursor);

                        while ((searchRowToUpdate = searchCursor.NextRow()) != null)
                        {
                            try
                            {

                                string action = String.Empty;
                                if (revActionFieldIndex != -1)
                                {
                                    action = searchRowToUpdate.get_Value(revActionFieldIndex) as string;
                                }
                                string elementType = String.Empty;
                                if (revElementTypeFieldIndex != -1)
                                {
                                    elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string;
                                }

                                string sourceFCName = String.Empty;
                                if (revFCNameFieldIndex != -1)
                                {
                                    sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string;
                                }

                                long osmOldID = -1;
                                if (revOldIDFieldIndex != -1)
                                {
                                    osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex));
                                }

                                bool isPolygon = false;
                                if (sourceFCName.IndexOf("_osm_ply") > -1)
                                {
                                    isPolygon = true;
                                }

                                // if the overall number of uploaded elements is too big for a single changeset we do need to split it up
                                // into multiple sets
                                if ((featureUpdateCounter % maxElementsinChangeSet) == 0)
                                {
                                    CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter);
                                }

                                osm createRelation = null;
                                // the relation is acutally multi-part line
                                if (sourceFCName.Contains("_osm_ln"))
                                {
                                    createRelation = CreateOSMRelationRepresentation((ITable)lineFeatureClass, action, osmOldID, changeSetID, -1, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                }
                                else if (sourceFCName.Contains("_osm_ply"))
                                {
                                    createRelation = CreateOSMRelationRepresentation((ITable)polygonFeatureClass, action, osmOldID, changeSetID, -1, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                }
                                else
                                {
                                    createRelation = CreateOSMRelationRepresentation(relationTable, action, osmOldID, changeSetID, -1, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                }
                                try
                                {
                                    HttpWebRequest httpClient4 = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/" + elementType + "/create") as HttpWebRequest;
                                    httpClient4 = OSMGPDownload.AssignProxyandCredentials(httpClient4);
                                    SetBasicAuthHeader(httpClient4, userCredentialGPValue.EncodedUserNamePassWord);
                                    httpClient4.Timeout = secondsToTimeout * 1000;
                                    string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(createRelation, serializer, Encoding.UTF8, "text/xml");

                                    OsmRest.HttpUtils.Put(httpClient4, sContent);

                                    httpResponse = null;
                                    httpResponse = httpClient4.GetResponse() as HttpWebResponse;
                                    // track the update/sync requests against the server
                                    featureUpdateCounter = featureUpdateCounter + 1;
                                }
                                catch (Exception ex)
                                {
                                    message.AddError(120009, ex.Message);

                                    if (ex is WebException)
                                    {
                                        updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex);
                                    }
                                }

                                if (httpResponse != null)
                                {
                                    string newIDString = OsmRest.HttpUtils.GetResponseContent(httpResponse);

                                    relationosmIDLookup.Add(osmOldID, Convert.ToInt64(newIDString));

                                    // update the revision table
                                    if (revNewIDFieldIndex != -1)
                                    {
                                        searchRowToUpdate.set_Value(revNewIDFieldIndex, Convert.ToString(newIDString));
                                    }
                                    if (revVersionFieldIndex != -1)
                                    {
                                        searchRowToUpdate.set_Value(revVersionFieldIndex, 1);
                                    }
                                    if (revStatusFieldIndex != -1)
                                    {
                                        searchRowToUpdate.set_Value(revStatusFieldIndex, httpResponse.StatusCode.ToString());
                                    }
                                    if (revStatusCodeFieldIndex != -1)
                                    {
                                        searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode);
                                    }
                                    if (revChangeSetIDFieldIndex != -1)
                                    {
                                        searchRowToUpdate.set_Value(revChangeSetIDFieldIndex, Convert.ToInt32(changeSetID));
                                    }

                                    if (sourceFCName.Contains("_osm_ln"))
                                    {
                                        updateSource((ITable)lineFeatureClass, action, osmOldID, Convert.ToInt64(newIDString), user_displayname, userID, 1, Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                    }
                                    else if (sourceFCName.Contains("_osm_ply"))
                                    {
                                        updateSource((ITable)polygonFeatureClass, action, osmOldID, Convert.ToInt64(newIDString), user_displayname, userID, 1, Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                    }
                                    else
                                    {
                                        // update the source table holding the relation information class as well
                                        updateSource(relationTable, action, osmOldID, Convert.ToInt64(newIDString), user_displayname, userID, 1, Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                    }
                                }
                            }

                            catch (Exception ex)
                            {
                                message.AddError(120009, ex.Message);

                                if (ex is WebException)
                                {
                                    updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex);
                                }
                            }
                            finally
                            {
                                try
                                {
                                    searchRowToUpdate.Store();
                                }
                                catch (Exception ex)
                                {
                                    System.Diagnostics.Debug.WriteLine(ex.Message);
                                }
                            }

                            if (TrackCancel.Continue() == false)
                            {
                                closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString);
                                return;
                            }
                        }
                    }
                    #endregion

                    #region after that submit the modify node, way, relation
                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        queryFilter.WhereClause = "(" +
                            sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR "
                            + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND "
                            + sqlFormatter.SqlIdentifier("osmaction") + " = 'modify'";

                        searchCursor = revisionTable.Search(queryFilter, false);
                        comReleaser.ManageLifetime(searchCursor);

                        while ((searchRowToUpdate = searchCursor.NextRow()) != null)
                        {
                            try
                            {

                                string action = String.Empty;
                                if (revActionFieldIndex != -1)
                                {
                                    action = searchRowToUpdate.get_Value(revActionFieldIndex) as string;
                                }
                                string elementType = String.Empty;
                                if (revElementTypeFieldIndex != -1)
                                {
                                    elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string;
                                }

                                string sourceFCName = String.Empty;
                                if (revFCNameFieldIndex != -1)
                                {
                                    sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string;
                                }

                                long osmOldID = -1;
                                if (revOldIDFieldIndex != -1)
                                {
                                    osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex));
                                }

                                // if the overall number of uploaded elements is too big for a single changeset we do need to split it up
                                // into multiple sets
                                if ((featureUpdateCounter % maxElementsinChangeSet) == 0)
                                {
                                    CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter);
                                }

                                switch (elementType)
                                {
                                    case "node":
                                        #region submit nodes to OSM server
                                        switch (action)
                                        {
                                            case "modify":
                                                long modifyID = -1;

                                                if (revNewIDFieldIndex != -1)
                                                {
                                                    object osmIDValue = searchRowToUpdate.get_Value(revNewIDFieldIndex);

                                                    if (osmIDValue == DBNull.Value)
                                                    {
                                                        osmIDValue = osmOldID;
                                                    }

                                                    try
                                                    {
                                                        modifyID = Convert.ToInt64(osmIDValue);
                                                    }
                                                    catch { }

                                                    // modifies should only happen to osm IDs > 0
                                                    // if that condition is not met let's skip this feature as something is not right
                                                    if (modifyID < 0)
                                                    {
                                                        continue;
                                                    }
                                                }

                                                int osmVersion = -1;
                                                if (revVersionFieldIndex != -1)
                                                {
                                                    osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex));
                                                }

                                                try
                                                {
                                                    HttpWebRequest httpClient5 = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/" + elementType + "/" + modifyID.ToString()) as HttpWebRequest;
                                                    httpClient5 = OSMGPDownload.AssignProxyandCredentials(httpClient5);
                                                    SetBasicAuthHeader(httpClient5, userCredentialGPValue.EncodedUserNamePassWord);

                                                    osm updateNode = CreateOSMNodeRepresentation(pointFeatureClass, action, modifyID, changeSetID, osmVersion, null, internalExtensionVersion);

                                                    string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(updateNode, serializer, Encoding.UTF8, "text/xml");

                                                    // if the serialized node at this time is a null or an empty string let's continue to the next point
                                                    if (String.IsNullOrEmpty(sContent))
                                                    {
                                                        continue;
                                                    }

                                                    OsmRest.HttpUtils.Put(httpClient5, sContent);

                                                    httpResponse = httpClient5.GetResponse() as HttpWebResponse;

                                                    // track the update/sync requests against the server
                                                    featureUpdateCounter = featureUpdateCounter + 1;

                                                    if (httpResponse != null)
                                                    {
                                                        string newVersionString = OsmRest.HttpUtils.GetResponseContent(httpResponse);

                                                        // update the revision table
                                                        if (revVersionFieldIndex != -1)
                                                        {
                                                            searchRowToUpdate.set_Value(revVersionFieldIndex, Convert.ToString(newVersionString));
                                                        }
                                                        if (revStatusFieldIndex != -1)
                                                        {
                                                            searchRowToUpdate.set_Value(revStatusFieldIndex, httpResponse.StatusCode.ToString());
                                                        }
                                                        if (revStatusCodeFieldIndex != -1)
                                                        {
                                                            searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode);
                                                        }
                                                        if (revChangeSetIDFieldIndex != -1)
                                                        {
                                                            searchRowToUpdate.set_Value(revChangeSetIDFieldIndex, Convert.ToInt32(changeSetID));
                                                        }

                                                        // for a modify the old id is still the new id
                                                        if (revNewIDFieldIndex != -1 && revOldIDFieldIndex != -1)
                                                        {
                                                            searchRowToUpdate.set_Value(revNewIDFieldIndex, searchRowToUpdate.get_Value(revOldIDFieldIndex));
                                                        }

                                                        // update the source point feature class as well
                                                        updateSource((ITable)pointFeatureClass, action, modifyID, modifyID, user_displayname, userID, Convert.ToInt32(newVersionString), Convert.ToInt32(changeSetID), null, null, null, internalExtensionVersion);

                                                        httpResponse.Close();
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    message.AddError(120009, ex.Message);

                                                    if (ex is WebException)
                                                    {
                                                        updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex);
                                                    }
                                                }

                                                break;
                                            case "delete":
                                                // the delete operations are handled separately
                                                break;
                                            default:
                                                break;
                                        }
                                        break;
                                        #endregion
                                    case "way":
                                        #region submit ways to the OSM server
                                        // determine if we have a polygon or a polyline feature class
                                        bool isPolygon = false;
                                        if (sourceFCName.IndexOf("_osm_ply") > -1)
                                        {
                                            isPolygon = true;
                                        }

                                        switch (action)
                                        {
                                            case "modify":

                                                long modifyID = -1;

                                                if (revNewIDFieldIndex != -1)
                                                {
                                                    object osmIDValue = searchRowToUpdate.get_Value(revNewIDFieldIndex);

                                                    if (osmIDValue == DBNull.Value)
                                                    {
                                                        osmIDValue = osmOldID;
                                                    }

                                                    try
                                                    {
                                                        modifyID = Convert.ToInt64(osmIDValue);
                                                    }
                                                    catch { }

                                                    // modifies should only happen to osm IDs > 0
                                                    // if that condition is not met let's skip this feature as something is not right
                                                    if (modifyID < 0)
                                                    {
                                                        continue;
                                                    }
                                                }

                                                int osmVersion = -1;
                                                if (revVersionFieldIndex != -1)
                                                {
                                                    osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex));
                                                }

                                                osm updateWay = new osm();
                                                if (isPolygon == false)
                                                {
                                                    updateWay = CreateOSMWayRepresentation(lineFeatureClass, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion);
                                                }
                                                else
                                                {
                                                    updateWay = CreateOSMWayRepresentation(polygonFeatureClass, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion);
                                                }
                                                try
                                                {
                                                    string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(updateWay, serializer, Encoding.UTF8, "text/xml");
                                                    httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/" + elementType + "/" + modifyID.ToString()) as HttpWebRequest;
                                                    httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient);
                                                    SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord);
                                                    OsmRest.HttpUtils.Put(httpClient, sContent);

                                                    httpResponse = httpClient.GetResponse() as HttpWebResponse;

                                                    // track the update/sync requests against the server
                                                    featureUpdateCounter = featureUpdateCounter + 1;

                                                    if (httpResponse != null)
                                                    {
                                                        string newVersionString = OsmRest.HttpUtils.GetResponseContent(httpResponse);

                                                        // update the revision table
                                                        if (revVersionFieldIndex != -1)
                                                        {
                                                            searchRowToUpdate.set_Value(revVersionFieldIndex, Convert.ToString(newVersionString));
                                                        }
                                                        if (revStatusFieldIndex != -1)
                                                        {
                                                            searchRowToUpdate.set_Value(revStatusFieldIndex, httpResponse.StatusCode.ToString());
                                                        }
                                                        if (revStatusCodeFieldIndex != -1)
                                                        {
                                                            searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode);
                                                        }
                                                        if (revChangeSetIDFieldIndex != -1)
                                                        {
                                                            searchRowToUpdate.set_Value(revChangeSetIDFieldIndex, Convert.ToInt32(changeSetID));
                                                        }

                                                        // for a modify the old id is still the new id
                                                        if (revNewIDFieldIndex != -1 && revOldIDFieldIndex != -1)
                                                        {
                                                            searchRowToUpdate.set_Value(revNewIDFieldIndex, searchRowToUpdate.get_Value(revOldIDFieldIndex));
                                                        }

                                                        // update the source line/polygon feature class as well
                                                        if (isPolygon == false)
                                                        {
                                                            updateSource((ITable)lineFeatureClass, action, modifyID, modifyID, user_displayname, userID, Convert.ToInt32(newVersionString), Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                                        }
                                                        else
                                                        {
                                                            updateSource((ITable)polygonFeatureClass, action, modifyID, modifyID, user_displayname, userID, Convert.ToInt32(newVersionString), Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);
                                                        }

                                                        httpResponse.Close();
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    message.AddError(120009, ex.Message);

                                                    if (ex is WebException)
                                                    {
                                                        updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex);
                                                    }
                                                }
                                                break;
                                            case "delete":
                                                // the delete operations are handled separately
                                                break;
                                            default:
                                                break;
                                        }
                                        break;
                                        #endregion
                                    case "relation":
                                        #region submit relations to the OSM server
                                        switch (action)
                                        {
                                            case "create":
                                                break;
                                            case "modify":

                                                long modifyID = -1;

                                                if (revNewIDFieldIndex != -1)
                                                {
                                                    object osmIDValue = searchRowToUpdate.get_Value(revNewIDFieldIndex);

                                                    if (osmIDValue == DBNull.Value)
                                                    {
                                                        osmIDValue = osmOldID;
                                                    }

                                                    try
                                                    {
                                                        modifyID = Convert.ToInt64(osmIDValue);
                                                    }
                                                    catch { }

                                                    // modifies should only happen to osm IDs > 0
                                                    // if that condition is not met let's skip this feature as something is not right
                                                    if (modifyID < 0)
                                                    {
                                                        continue;
                                                    }
                                                }

                                                int osmVersion = -1;
                                                if (revVersionFieldIndex != -1)
                                                {
                                                    osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex));
                                                }

                                                osm updateRelation = CreateOSMRelationRepresentation(relationTable, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);

                                                try
                                                {
                                                    string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(updateRelation, serializer, Encoding.UTF8, "text/xml");
                                                    httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/" + elementType + "/" + modifyID.ToString()) as HttpWebRequest;
                                                    httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient);
                                                    SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord);
                                                    OsmRest.HttpUtils.Put(httpClient, sContent);

                                                    httpResponse = httpClient.GetResponse() as HttpWebResponse;

                                                    // track the update/sync requests against the server
                                                    featureUpdateCounter = featureUpdateCounter + 1;

                                                    if (httpResponse != null)
                                                    {
                                                        string newVersionString = OsmRest.HttpUtils.GetResponseContent(httpResponse);

                                                        // update the revision table
                                                        if (revVersionFieldIndex != -1)
                                                        {
                                                            searchRowToUpdate.set_Value(revVersionFieldIndex, Convert.ToInt32(newVersionString));
                                                        }
                                                        if (revStatusFieldIndex != -1)
                                                        {
                                                            searchRowToUpdate.set_Value(revStatusFieldIndex, httpResponse.StatusCode.ToString());
                                                        }
                                                        if (revStatusCodeFieldIndex != -1)
                                                        {
                                                            searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode);
                                                        }
                                                        if (revChangeSetIDFieldIndex != -1)
                                                        {
                                                            searchRowToUpdate.set_Value(revChangeSetIDFieldIndex, Convert.ToInt32(changeSetID));
                                                        }

                                                        // for a modify the old id is still the new id
                                                        if (revNewIDFieldIndex != -1 && revOldIDFieldIndex != -1)
                                                        {
                                                            searchRowToUpdate.set_Value(revNewIDFieldIndex, searchRowToUpdate.get_Value(revOldIDFieldIndex));
                                                        }

                                                        // update the source table holding the relation information class as well
                                                        updateSource(relationTable, action, modifyID, modifyID, user_displayname, userID, Convert.ToInt32(newVersionString), Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);

                                                        httpResponse.Close();
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    message.AddError(120009, ex.Message);

                                                    if (ex is WebException)
                                                    {
                                                        updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex);
                                                    }
                                                }
                                                break;
                                            case "delete":
                                                // the delete operations are handled separately

                                                break;
                                            default:
                                                break;
                                        }
                                        break;
                                        #endregion
                                    default:
                                        break;
                                }
                            }

                            catch (Exception ex)
                            {
                                message.AddAbort(ex.Message);

                                if (ex is WebException)
                                {
                                    updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex);
                                }
                            }
                            finally
                            {
                                try
                                {
                                    searchRowToUpdate.Store();
                                }
                                catch (Exception ex)
                                {
                                    System.Diagnostics.Debug.WriteLine(ex.Message);
                                }

                                if (httpResponse != null)
                                {
                                    httpResponse.Close();
                                }
                            }

                            if (TrackCancel.Continue() == false)
                            {
                                closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString);

                                return;
                            }

                        }
                    }
                    #endregion

                    #region now let's handle the delete in the reverse order - relation first, then ways, and then nodes as the last entity
                    #region delete relations
                    // now let's handle the delete in the reverse order - relation first, then ways, and then nodes as the last entity
                    queryFilter.WhereClause = "("
                        + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR "
                        + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND "
                        + sqlFormatter.SqlIdentifier("osmaction") + " = 'delete' AND "
                        + sqlFormatter.SqlIdentifier("osmelementtype") + " = 'relation'";

                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        searchCursor = revisionTable.Search(queryFilter, false);
                        comReleaser.ManageLifetime(searchCursor);

                        while ((searchRowToUpdate = searchCursor.NextRow()) != null)
                        {

                            // if the overall number of uploaded elements is too big for a single changeset we do need to split it up
                            // into multiple sets
                            if ((featureUpdateCounter % maxElementsinChangeSet) == 0)
                            {
                                CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter);
                            }

                            long osmID = -1;
                            if (revOldIDFieldIndex != -1)
                            {
                                osmID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex));
                            }
                            int osmVersion = -1;
                            if (revVersionFieldIndex != -1)
                            {
                                osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex));
                            }

                            osm deleteRelation = CreateOSMRelationRepresentation(relationTable, "delete", osmID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion);

                            string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(deleteRelation, serializer, Encoding.UTF8, "text/xml");

                            string errorMessage = String.Empty;
                            try
                            {
                                httpResponse = OsmRest.HttpUtils.Delete(baseURLGPString.Value + "/api/0.6/relation/" + Convert.ToString(osmID), sContent, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout) as HttpWebResponse;

                                // track the update/sync requests against the server
                                featureUpdateCounter = featureUpdateCounter + 1;

                                if (revStatusFieldIndex != -1)
                                {
                                    searchRowToUpdate.set_Value(revStatusFieldIndex, (int)httpResponse.StatusCode);
                                }
                                if (revStatusCodeFieldIndex != -1)
                                {
                                    searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode);
                                }

                                if (httpResponse != null)
                                {
                                    httpResponse.Close();
                                }
                            }
                            catch (Exception ex)
                            {
                                message.AddError(120009, ex.Message);

                                if (ex is WebException)
                                {
                                    updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex);
                                }

                                if (httpResponse != null)
                                {
                                    httpResponse.Close();
                                }
                            }

                            try
                            {
                                searchRowToUpdate.Store();
                            }
                            catch { }

                            if (TrackCancel.Continue() == false)
                            {
                                closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString);
                                return;
                            }

                        }
                    }

                    #endregion

                    #region handle delete ways
                    queryFilter.WhereClause = "("
                        + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR "
                        + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND "
                        + sqlFormatter.SqlIdentifier("osmaction") + " = 'delete' AND "
                        + sqlFormatter.SqlIdentifier("osmelementtype") + " = 'way'";

                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        searchCursor = revisionTable.Search(queryFilter, false);
                        comReleaser.ManageLifetime(searchCursor);

                        while ((searchRowToUpdate = searchCursor.NextRow()) != null)
                        {

                            // if the overall number of uploaded elements is too big for a single changeset we do need to split it up
                            // into multiple sets
                            if ((featureUpdateCounter % maxElementsinChangeSet) == 0)
                            {
                                CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter);
                            }

                            long osmID = -1;
                            if (revOldIDFieldIndex != -1)
                            {
                                osmID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex));
                            }
                            int osmVersion = -1;
                            if (revVersionFieldIndex != -1)
                            {
                                osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex));
                            }

                            osm deleteWay = CreateOSMWayRepresentation(lineFeatureClass, "delete", osmID, changeSetID, osmVersion, wayosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion);

                            string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(deleteWay, serializer, Encoding.UTF8, "text/xml");

                            try
                            {
                                httpResponse = null;
                                httpResponse = OsmRest.HttpUtils.Delete(baseURLGPString.Value + "/api/0.6/way/" + Convert.ToString(osmID), sContent, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout) as HttpWebResponse;

                                // track the update/sync requests against the server
                                featureUpdateCounter = featureUpdateCounter + 1;

                                string errorMessage = String.Empty;
                                // just grab the response and set it on the database
                                if (revStatusFieldIndex != -1)
                                {
                                    searchRowToUpdate.set_Value(revStatusFieldIndex, (int)httpResponse.StatusCode);
                                }
                                if (revStatusCodeFieldIndex != -1)
                                {
                                    searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode);
                                }

                                if (httpResponse != null)
                                {
                                    httpResponse.Close();
                                }
                            }

                            catch (Exception ex)
                            {
                                message.AddError(1200009, ex.Message);

                                if (ex is WebException)
                                {
                                    updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex);
                                }

                                if (httpResponse != null)
                                {
                                    httpResponse.Close();
                                }
                            }

                            try
                            {
                                searchRowToUpdate.Store();
                            }
                            catch { }

                            if (TrackCancel.Continue() == false)
                            {
                                closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString);
                                return;
                            }
                        }
                    }

                    #endregion

                    #region handle delete points
                    queryFilter.WhereClause = "("
                        + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR "
                        + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND "
                        + sqlFormatter.SqlIdentifier("osmaction") + " = 'delete' AND "
                        + sqlFormatter.SqlIdentifier("osmelementtype") + " = 'node'";

                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        searchCursor = revisionTable.Search(queryFilter, false);
                        comReleaser.ManageLifetime(searchCursor);

                        while ((searchRowToUpdate = searchCursor.NextRow()) != null)
                        {
                            // if the overall number of uploaded elements is too big for a single changeset we do need to split it up
                            // into multiple sets
                            if ((featureUpdateCounter % maxElementsinChangeSet) == 0)
                            {
                                CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter);
                            }

                            long osmID = -1;
                            if (revOldIDFieldIndex != -1)
                            {
                                osmID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex));
                            }
                            int osmVersion = -1;
                            if (revVersionFieldIndex != -1)
                            {
                                osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex));
                            }

                            IPoint deletePoint = null;
                            if (revLongitudeFieldIndex != -1 && revLatitudeFieldIndex != -1)
                            {
                                try
                                {
                                    // let's reconstruct the delete point
                                    deletePoint = new PointClass();
                                    deletePoint.X = Convert.ToDouble(searchRowToUpdate.get_Value(revLongitudeFieldIndex));
                                    deletePoint.Y = Convert.ToDouble(searchRowToUpdate.get_Value(revLatitudeFieldIndex));
                                    deletePoint.SpatialReference = m_wgs84;
                                }
                                catch (Exception ex)
                                {
                                    message.AddWarning(ex.Message);
                                }

                                if (deletePoint == null)
                                {
                                    // inform the about the issue - no successful creation of point and continue on to the next delete instruction
                                    // in the revision table
                                    message.AddWarning(resourceManager.GetString("GPTools_OSMGPUpload_invalidPoint"));
                                    continue;
                                }
                            }

                            osm deleteNode = CreateOSMNodeRepresentation(pointFeatureClass, "delete", osmID, changeSetID, osmVersion, deletePoint, internalExtensionVersion);

                            string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(deleteNode, serializer, Encoding.UTF8, "text/xml");

                            if (String.IsNullOrEmpty(sContent))
                            {
                                continue;
                            }

                            string errorMessage = String.Empty;

                            try
                            {
                                httpResponse = OsmRest.HttpUtils.Delete(baseURLGPString.Value + "/api/0.6/node/" + Convert.ToString(osmID), sContent, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout) as HttpWebResponse;

                                if (revStatusFieldIndex != -1)
                                {
                                    searchRowToUpdate.set_Value(revStatusFieldIndex, (int)httpResponse.StatusCode);
                                }

                                if (revStatusCodeFieldIndex != -1)
                                {
                                    searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode);
                                }

                                if (httpResponse != null)
                                {
                                    httpResponse.Close();
                                }
                            }
                            catch (Exception ex)
                            {
                                message.AddError(120009, ex.Message);

                                if (ex is WebException)
                                {
                                    updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex);
                                }

                                if (httpResponse != null)
                                {
                                    httpResponse.Close();
                                }

                            }

                            // track the update/sync requests against the server
                            featureUpdateCounter = featureUpdateCounter + 1;

                            try
                            {
                                searchRowToUpdate.Store();
                            }
                            catch { }

                            if (TrackCancel.Continue() == false)
                            {
                                closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString);
                                return;
                            }
                        }
                    }

                    #endregion
                    #endregion
                    #endregion
                }
            }
            catch (Exception ex)
            {
                message.AddError(120058, ex.Message);
                message.AddError(120058, ex.StackTrace);
            }
            finally
            {
                closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString);

                if (revisionTable != null)
                {
                    try
                    {
                        ISchemaLock tableSchemaLock = revisionTable as ISchemaLock;

                        if (tableSchemaLock != null)
                        {
                            tableSchemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
                        }
                    }
                    catch (Exception eLock)
                    {
                        message.AddError(120059, resourceManager.GetString("GPTools_OSMGPUpload_LockErrorTitle") + eLock.Message);
                    }
                }

                if (revisionTable != null)
                {
                    Marshal.FinalReleaseComObject(revisionTable);
                }

                // if the searchCursor still has a reference somewhere do release it now - and as a result release any remaining table locks
                if (searchCursor != null)
                {
                    Marshal.FinalReleaseComObject(searchCursor);
                }

                gpUtilities3.RemoveInternalData();
                gpUtilities3.ReleaseInternals();

                //Marshal.ReleaseComObject(gpUtilities3);
            }
        }
コード例 #23
0
        private void buttonOK_Click(object sender, EventArgs e)
        {
            this.Visible = false;
            if (_axmapcontrol != null)
            {
                try
                {
                    IEnvelope penvelope = new EnvelopeClass();
                    penvelope.XMin = Convert.ToDouble(textBoxWest.Text);
                    penvelope.XMax = Convert.ToDouble(textBoxEast.Text);
                    penvelope.YMax = Convert.ToDouble(textBoxNorth.Text);
                    penvelope.YMin = Convert.ToDouble(textBoxSouth.Text);
                    IPoint pmiddle = new PointClass();
                    pmiddle.PutCoords((penvelope.XMax + penvelope.XMin) / 2, (penvelope.YMax + penvelope.YMin) / 2);//中心点
                    /*********************************将Envelope转成Polygon*/
                    IPolygon         pon = new PolygonClass();
                    IPointCollection ptcoll = new PolygonClass();
                    IPoint           a = new PointClass(); IPoint b = new PointClass(); IPoint c = new PointClass(); IPoint d = new PointClass();
                    a.PutCoords(penvelope.XMin, penvelope.YMax);
                    b.PutCoords(penvelope.XMax, penvelope.YMax);
                    c.PutCoords(penvelope.XMax, penvelope.YMin);
                    d.PutCoords(penvelope.XMin, penvelope.YMin);
                    object missing = Type.Missing;
                    ptcoll.AddPoint(a, ref missing, ref missing);
                    ptcoll.AddPoint(b, ref missing, ref missing);
                    ptcoll.AddPoint(c, ref missing, ref missing);
                    ptcoll.AddPoint(d, ref missing, ref missing);
                    pon = ptcoll as IPolygon;
                    /*********************************/
                    IGeometry geo = new PolygonClass();

                    geo = pon as IGeometry;

                    /*-----xisheng 20110802------*/
                    ISpatialReference         earthref    = null;
                    ISpatialReference         flatref     = null;
                    ISpatialReferenceFactory2 pSpatRefFac = new SpatialReferenceEnvironmentClass();
                    earthref = pSpatRefFac.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);
                    if (this.WriteLog)
                    {
                        Plugin.LogTable.Writelog(this.Text);//xisheng 日志记录 0928;
                    }
                    if (_axmapcontrol.MapUnits == esriUnits.esriMeters)
                    {
                        flatref = _axmapcontrol.Map.SpatialReference;
                        geo.SpatialReference = flatref;//yjl20110812
                        //geo.Project(flatref);
                    }
                    /*-----xisheng 20110802------*/


                    //创建Topo对象,简化后统一空间参考
                    ITopologicalOperator pTopo = (ITopologicalOperator)geo;
                    pTopo.Simplify();
                    geo.Project(_axmapcontrol.Map.SpatialReference);


                    if (m_frmQuery == null)
                    {
                        m_frmQuery             = new frmQuery(_axmapcontrol, m_enumQueryMode);
                        m_frmQuery.Owner       = m_mainFrm;
                        m_frmQuery.FormClosed += new FormClosedEventHandler(frmQuery_FormClosed);
                    }

                    //清除上次的所有元素
                    (_axmapcontrol.Map as IGraphicsContainer).DeleteAllElements();
                    m_frmBufferSet             = new frmBufferSet(geo, _axmapcontrol.Map, m_frmQuery);
                    m_frmBufferSet.FormClosed += new FormClosedEventHandler(frmBufferSet_FormClosed);
                    _axmapcontrol.CenterAt(pmiddle);
                    IGeometry pGeometry = m_frmBufferSet.GetBufferGeometry();
                    if (pGeometry == null || m_frmBufferSet.Res == false)
                    {
                        return;
                    }

                    m_frmQuery.Show();
                    ///ZQ 20111119  modify
                    m_frmQuery.FillData(_axmapcontrol.ActiveView.FocusMap, pGeometry, m_frmBufferSet.pesriSpatialRelEnum);
                    this.Close();
                }
                catch (Exception ex)
                {
                    SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "错误:" + ex.Message);
                }
            }
        }
コード例 #24
0
        private void btnCalculate_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            string str = txtLon.Text.Trim();

            if (str == string.Empty)
            {
                errorProvider1.SetError(txtLon, "请输入经度!");
            }
            double lon = 0;

            try
            {
                lon = Convert.ToDouble(str);
            }
            catch
            {
                errorProvider1.SetError(txtLon, "请输入度为单位的经度!");
            }
            string str2 = txtLat.Text.Trim();

            if (str2 == string.Empty)
            {
                errorProvider1.SetError(txtLat, "请输入纬度!");
            }
            double lat = 0;

            try
            {
                lat = Convert.ToDouble(str2);
            }
            catch
            {
                errorProvider1.SetError(txtLat, "请输入度为单位的纬度!");
            }

            string str3 = txtCentre.Text.Trim();

            if (str3 == string.Empty)
            {
                errorProvider1.SetError(txtLat, "请输入中央经线!");
            }
            double longitude0 = 0;

            try
            {
                longitude0 = Convert.ToDouble(str3);
            }
            catch
            {
                errorProvider1.SetError(txtCentre, "请输入度为单位的中央经线!");
            }
            List <ProjectionParameter> pInfo = new List <ProjectionParameter>();

            pInfo.Add(new ProjectionParameter("latitude_of_origin", 0));
            pInfo.Add(new ProjectionParameter("central_meridian", longitude0));
            pInfo.Add(new ProjectionParameter("scale_factor", 1));
            pInfo.Add(new ProjectionParameter("false_easting", 500000));
            pInfo.Add(new ProjectionParameter("false_northing", 0));

            Projection proj = new Projection("Gauss_Kruger", pInfo, "", "EPSG", 0, String.Empty, String.Empty, String.Empty);

            System.Collections.Generic.List <AxisInfo> axes = new List <AxisInfo>();
            axes.Add(new AxisInfo("East", AxisOrientationEnum.East));
            axes.Add(new AxisInfo("North", AxisOrientationEnum.North));
            ISpatialReferenceFactory        srf    = new SpatialReferenceEnvironmentClass();
            IHorizontalDatum                dataum = srf.CreateDatum((int)RgSRDatumType.RgSRDatum_Beijing1954);
            ICoordinateSystem               gauss  = new ProjectedCoordinateSystem(dataum, coord, ProjNet.CoordinateSystems.LinearUnit.Metre, proj, axes, "CustomGauss", "EPSG", 0, String.Empty, "", string.Empty);
            CoordinateTransformationFactory ctfac  = new CoordinateTransformationFactory();
            ICoordinateTransformation       trans  = ctfac.CreateFromCoordinateSystems(coord, gauss);

            double[] pGauss = trans.MathTransform.Transform(new double[] { lon, lat });
            txtX.Text = string.Format("{0}", pGauss[0]);
            txtY.Text = string.Format("{0}", pGauss[1]);
        }
コード例 #25
0
        //创建featureclass
        private IFeatureClass CreateFeatureClass(string name, IWorkspace pWorkspace, UID uidCLSID, UID uidCLSEXT, IGeometry pGeometry)
        {
            try
            {
                if (uidCLSID == null)
                {
                    uidCLSID       = new UIDClass();
                    uidCLSID.Value = "{52353152-891A-11D0-BEC6-00805F7C4268}";
                }

                // 设置 uidCLSEXT (if Null)
                //uidCLSEXT == null;

                IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspace;
                IFields           fields            = new FieldsClass();
                IFieldsEdit       fieldsEdit        = (IFieldsEdit)fields;
                IField            oidField          = new FieldClass();
                IFieldEdit        oidFieldEdit      = (IFieldEdit)oidField; oidFieldEdit.Name_2 = "OID";
                oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
                fieldsEdit.AddField(oidField);


                IGeometryDef     geometryDef     = new GeometryDefClass();
                IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
                geometryDefEdit.GeometryType_2 = pGeometry.GeometryType;
                ISpatialReferenceFactory    spatialReferenceFactory    = new SpatialReferenceEnvironmentClass();
                ISpatialReference           spatialReference           = pGeometry.SpatialReference;
                ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference;
                spatialReferenceResolution.ConstructFromHorizon();
                ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference;
                spatialReferenceTolerance.SetDefaultXYTolerance();
                geometryDefEdit.SpatialReference_2 = spatialReference;


                IField     geometryField     = new FieldClass();
                IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField;
                geometryFieldEdit.Name_2        = "Shape";
                geometryFieldEdit.Type_2        = esriFieldType.esriFieldTypeGeometry;
                geometryFieldEdit.GeometryDef_2 = geometryDef;
                fieldsEdit.AddField(geometryField);

                // Use IFieldChecker to create a validated fields collection.
                IFieldChecker   fieldChecker    = new FieldCheckerClass();
                IEnumFieldError enumFieldError  = null;
                IFields         validatedFields = null;
                fieldChecker.ValidateWorkspace = pWorkspace;
                fieldChecker.Validate(fields, out enumFieldError, out validatedFields);
                IFeatureClass targetFeatureclass = null;
                targetFeatureclass = pFeatureWorkspace.CreateFeatureClass("" + name + "", fields, uidCLSID, uidCLSEXT, esriFeatureType.esriFTSimple, "Shape", "");
                return(targetFeatureclass);
            }
            catch (Exception ex)
            {
                if (ex.Message == "Cannot create a low precision dataset in a high precision database.")
                {
                    MessageBox.Show("数据必须是ArcGis9.3的数据,请将数据处理成ArcGis9.2的数据!");
                }
            }
            IFeatureClass featureclass = null;

            return(featureclass);
        }
コード例 #26
0
        private void OnExecute()
        {
            Console.WriteLine(this.FeatureClassName);
            IWorkspaceFactory workspaceFactory = null;
            IWorkspace        workspace        = null;
            IFeatureClass     featureClass     = null;

            switch (DataSourceType)
            {
            case DataSourceType.Sde:
            {
                workspaceFactory = new SdeWorkspaceFactoryClass();
            }
            break;

            case DataSourceType.Gdb:
            {
                workspaceFactory = new FileGDBWorkspaceFactoryClass();
            }
            break;

            case DataSourceType.Shp:
            {
                workspaceFactory = new ShapefileWorkspaceFactoryClass();
            }
            break;

            default:
                break;
            }
            workspace    = workspaceFactory.OpenFromFile(DataSource, 0);
            featureClass = ((IFeatureWorkspace)workspace).OpenFeatureClass(FeatureClassName);

            IWorkspaceFactory outWorkspaceFactory = null;
            IWorkspace        outWorkspace        = null;
            IFeatureClass     outFeatureClass     = null;

            switch (OutDataSourceType)
            {
            case DataSourceType.Sde:
            {
                outWorkspaceFactory = new SdeWorkspaceFactoryClass();
            }
            break;

            case DataSourceType.Gdb:
            {
                outWorkspaceFactory = new FileGDBWorkspaceFactoryClass();
            }
            break;

            case DataSourceType.Shp:
            {
                outWorkspaceFactory = new ShapefileWorkspaceFactoryClass();
            }
            break;

            default:
                break;
            }
            outWorkspace    = outWorkspaceFactory.OpenFromFile(OutDataSource, 0);
            outFeatureClass = ((IFeatureWorkspace)outWorkspace).OpenFeatureClass(OutFeatureClassName);

            ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            FileInfo          projectionFile   = new FileInfo(ProJectionFile);
            ISpatialReference spatialReference = spatialReferenceFactory.CreateESRISpatialReferenceFromPRJFile(projectionFile.FullName);


            FileInfo scalesFile = new FileInfo(ScalesFile);

            System.IO.FileStream fs = scalesFile.OpenRead();
            StreamReader         sr = new StreamReader(fs);
            string scalesString     = sr.ReadToEnd();
            var    scales           = scalesString.Split('\r').Where(str => double.TryParse(str, out var d)).Select(str => double.Parse(str)).ToArray();

            sr.Close();

            ;
            try
            {
                _indexOfFieldScale = outFeatureClass.FindField(FieldScale);
            }
            catch (Exception)
            {
            }
            try
            {
                _indexOfFieldFrame = outFeatureClass.FindField(FieldFrame);
            }
            catch (Exception)
            {
            }
            switch (Mode)
            {
            case Mode.Data:
                GenerateAnimationLines(
                    featureClass: featureClass,
                    outFeatureClass: outFeatureClass,
                    spatialReference: Get3857Sr(),
                    frameRate: FrameRate,
                    lineLengthInPixel: LineLength,
                    intervalInPixel: Interval);
                break;

            case Mode.Mxd:
                ModifyMxd(outFeatureClass, scales, spatialReference);
                break;

            default:
                break;
            }
        }
コード例 #27
0
        protected override void OnClick()
        {
            #region Get Shapefile
            // Ask user to browse to a shapefile
            IGxObject openedFile = commonFunctions.OpenShapefile("Select your Non-Fissure Waypoint Shapefile");
            if (openedFile == null)
            {
                return;
            }

            // Open the file as an IFeatureClass
            IWorkspaceFactory wsFact = new ShapefileWorkspaceFactoryClass();
            IFeatureWorkspace ws     = wsFact.OpenFromFile(openedFile.Parent.FullName, 0) as IFeatureWorkspace;

            string path = @"C:\tmp\config.txt";
            if (!File.Exists(path))
            {
                MessageBox.Show("Missing the config File !");
                return;
            }

            IFeatureClass nonFissureWaypoints = ws.OpenFeatureClass(openedFile.Name);

            // Make sure user selected a point featureclass
            if (nonFissureWaypoints.ShapeType != esriGeometryType.esriGeometryPoint)
            {
                MessageBox.Show("The shapefile you selected does not contain points. Try again.");
                return;
            }

            // Make sure that the Coordinate System is set
            IGeoDataset                gDs          = nonFissureWaypoints as IGeoDataset;
            IGeoDatasetSchemaEdit      schemaEditor = gDs as IGeoDatasetSchemaEdit;
            ISpatialReferenceFactory2  spaRefFact   = new SpatialReferenceEnvironmentClass();
            IProjectedCoordinateSystem projCs       = spaRefFact.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_NAD1983UTM_12N);
            schemaEditor.AlterSpatialReference(projCs);

            // Put all the points into a cursor
            IFeatureCursor sourcePoints = nonFissureWaypoints.Search(null, false);
            #endregion

            #region Prepare for Loop
            // Get a reference to the Stations featureclass in EarthFissure SDE database
            IWorkspace    sdeWs    = commonFunctions.OpenFissureWorkspace();
            IFeatureClass stations = commonFunctions.OpenFeatureClass(sdeWs, "Stations");

            // Get a reference to the Fissure Info table in the SDE database
            ITable nonFissInfoTable = commonFunctions.OpenTable(sdeWs, "NonFissureStationDescription");

            // Get a reference to the SysInfo table for spinning up IDs
            sysInfo fissDbInfo = new sysInfo(sdeWs);

            // Get field indexes
            Dictionary <string, int> stationIndexes = GetFieldIndexes(stations as ITable);
            Dictionary <string, int> infoIndexes    = GetFieldIndexes(nonFissInfoTable);
            Dictionary <string, int> sourceIndexes  = GetFieldIndexes(nonFissureWaypoints as ITable);

            // Need a geographic coordinate system in the loop
            IGeographicCoordinateSystem geoCs = spaRefFact.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_NAD1983);

            // Setup the ProgressBar
            // setupProgressBar(nonFissureWaypoints.FeatureCount(null));
            #endregion

            // Start an edit session
            IWorkspaceEdit wsEditor = sdeWs as IWorkspaceEdit;
            wsEditor.StartEditing(false);
            wsEditor.StartEditOperation();

            try
            {
                // Get Insert Cursors
                IFeatureCursor stationInsert     = stations.Insert(true);
                ICursor        stationInfoInsert = nonFissInfoTable.Insert(true);

                // Loop through the source points, appending appropriately to both tables.
                IFeature sourcePoint = sourcePoints.NextFeature();

                while (sourcePoint != null)
                {
                    // Get the new station's identifier
                    string stationID = "FIS.StationPoints." + fissDbInfo.GetNextIdValue("StationPoints");

                    // Get the new station description entry's identifier
                    string descriptionID = "FIS.NonFissureStationDescription." + fissDbInfo.GetNextIdValue("NonFissureStationDescription");

                    // Get the Lat/Long values for the new point
                    IGeometry locGeom = sourcePoint.ShapeCopy as IGeometry;
                    locGeom.Project(geoCs);
                    IPoint locPoint = locGeom as IPoint;

                    // Make the new StationPoint
                    IFeatureBuffer newStation = stations.CreateFeatureBuffer();
                    newStation.set_Value(stationIndexes["Stations_ID"], stationID);
                    newStation.set_Value(stationIndexes["FieldID"], "");
                    newStation.set_Value(stationIndexes["Label"], "");
                    newStation.set_Value(stationIndexes["Symbol"], "NonFissure");
                    newStation.set_Value(stationIndexes["PlotAtScale"], 24000);
                    newStation.set_Value(stationIndexes["LocationConfidenceMeters"], sourcePoint.get_Value(sourceIndexes["Horz_Prec"]));
                    newStation.set_Value(stationIndexes["MapY"], locPoint.Y);
                    newStation.set_Value(stationIndexes["MapX"], locPoint.X);
                    newStation.set_Value(stationIndexes["DataSourceID"], "");
                    newStation.Shape = sourcePoint.ShapeCopy;
                    stationInsert.InsertFeature(newStation);

                    // Make the new FissureDescription
                    IRowBuffer newDescription = nonFissInfoTable.CreateRowBuffer();
                    newDescription.set_Value(infoIndexes["stationid"], stationID);
                    newDescription.set_Value(infoIndexes["typeoflineament"], sourcePoint.get_Value(sourceIndexes["Type_of_Li"]));
                    newDescription.set_Value(infoIndexes["datafile"], sourcePoint.get_Value(sourceIndexes["Datafile"]));
                    newDescription.set_Value(infoIndexes["nonfissdescription_id"], descriptionID);
                    stationInfoInsert.InsertRow(newDescription);

                    // Iterate
                    sourcePoint = sourcePoints.NextFeature();
                    // progress.PerformStep();
                }

                // Done. Save edits.
                wsEditor.StopEditOperation();
                wsEditor.StopEditing(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
                wsEditor.StopEditOperation();
                wsEditor.StopEditing(false);
            }
            finally
            {
                //progress.Visible = false;
            }
        }
コード例 #28
0
ファイル: Dataset.cs プロジェクト: zj8487/HyDM
        /// <summary>
        /// 创建空间参考
        /// </summary>
        /// <param name="headNode">VCT头节点</param>
        private ISpatialReference CreateProjection(HeadNode headNode)
        {
            try
            {
                string sPrjInfo = "";
                //根据投影参数中的长半轴值,来判断是什么坐标系统(北京54,西安80,WGS-84,其他地方坐标系)
                //北京54
                double dMajorAxis = headNode.MajorMax.Y;

                //读取参考椭球的名称 (名称,长半轴,扁率的倒数)
                string sProjection = headNode.Spheroid.Split(',')[0];
                dMajorAxis = Math.Abs(dMajorAxis - 6378245);
                //if (fabs( m_dSemiMajorAxis - 6378245) < 0.0001)
                if (dMajorAxis < 0.0001)
                {
                    sPrjInfo = string.Format("PROJCS[\"{0}\",GEOGCS[\"GCS_Beijing_1954\",DATUM[\"D_Beijing_1954\""
                        + ",SPHEROID[\"{1}\",6378140.0,298.257]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],"
                    + "PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",{2}],PARAMETER[\"False_Northing\",0.0],"
                    + "PARAMETER[\"Central_Meridian\",{3}],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],"
                    + "UNIT[\"Meter\",1.0]]", sProjection, "Gauss-Krueger", headNode.Excursion, headNode.Parametetor.OriginLongtitude);

                }
                //西安80
                else
                {
                    // sPrjInfo = string.Format("PROJCS["%s\",GEOGCS[\"GCS_Xian_1980\",DATUM[\"D_Xian_1980\",SPHEROID[\"%s\",6378140.0,298.257]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",%s],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",%f],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]", m_strProjection, m_strSpheroid, sPianYi, m_lMeridian);
                    sPrjInfo = string.Format("PROJCS[\"{0}\",GEOGCS[\"GCS_Xian_1980\",DATUM[\"D_Xian_1980\","
                    + "SPHEROID[\"{1}\",6378140.0,298.257]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],"
                    + "PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",{2}],PARAMETER[\"False_Northing\",0.0],"
                    + "PARAMETER[\"Central_Meridian\",{3}],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],"
                    + "UNIT[\"Meter\",1.0]]", sProjection, "Gauss-Krueger", headNode.Parametetor.EastOffset, headNode.Parametetor.OriginLongtitude);
                }
                //将坐标信息写入到Prj文件
                string sPrjFilename = Application.StartupPath + "tempPrj.prj";
                FileStream fs = File.Create(sPrjFilename);
                StreamWriter sw = new StreamWriter(fs);
                sw.Write(sPrjInfo);
                sw.Close();
                fs.Close();

                //根据Prj文件生成空间参考
                ISpatialReferenceFactory ipSpatialFactory = new SpatialReferenceEnvironmentClass();
                ISpatialReference pSpatialReference = ipSpatialFactory.CreateESRISpatialReferenceFromPRJFile(sPrjFilename);
                pSpatialReference.SetDomain(headNode.MajorMin.X,headNode.MajorMax.X,headNode.MajorMin.Y,headNode.MajorMax.Y);//
                //设置精度,防止cut失败
                //设置六位小数精度。以保证导出时也是六位
                ISpatialReferenceTolerance ipSrTolerance = pSpatialReference as ISpatialReferenceTolerance;

                ipSrTolerance.XYTolerance = 0.000001;
                ipSrTolerance.MTolerance = 0.001;
                ipSrTolerance.ZTolerance = 0.001;

                ISpatialReferenceResolution ipSrResolution = pSpatialReference as ISpatialReferenceResolution;
                ipSrResolution.MResolution = 0.001;
                ipSrResolution.set_XYResolution(true, 0.000001);
                ipSrResolution.set_ZResolution(true, 0.001);

                //删除生成的Prj文件
                File.Delete(sPrjFilename);


                //ISpatialReference pSpatialReference;
                //ISpatialReferenceFactory pSpatialreferenceFactory;
                //pSpatialreferenceFactory = new SpatialReferenceEnvironmentClass();
                //IGeographicCoordinateSystem pGeographicCoordinateSystem;
                //pGeographicCoordinateSystem = pSpatialreferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCS3Type.esriSRGeoCS_Xian1980);
                //pSpatialReference = pGeographicCoordinateSystem as ISpatialReference;
                //pSpatialReference.SetFalseOriginAndUnits(-180, -90, 1000000);//

                return pSpatialReference;
            }
            catch (Exception ex)
            {
                LogAPI.WriteLog("创建空间参考失败,系统默认创建空的空间参考!\r\n");
                LogAPI.WriteErrorLog(ex);
                ISpatialReference pSpatialReference = new UnknownCoordinateSystemClass();
                pSpatialReference.SetDomain(headNode.MajorMin.X, headNode.MajorMax.X, headNode.MajorMin.Y, headNode.MajorMax.Y);//
                return pSpatialReference;
            }
        }
コード例 #29
0
ファイル: frmRangeOutMap.cs プロジェクト: siszoey/geosufan
        private void buttonOK_Click(object sender, EventArgs e)
        {
            this.Visible = false;
            if (_axmapcontrol != null)
            {
                try
                {
                    IEnvelope penvelope = new EnvelopeClass();
                    penvelope.XMin = Convert.ToDouble(textBoxWest.Text);
                    penvelope.XMax = Convert.ToDouble(textBoxEast.Text);
                    penvelope.YMax = Convert.ToDouble(textBoxNorth.Text);
                    penvelope.YMin = Convert.ToDouble(textBoxSouth.Text);
                    IPoint pmiddle = new PointClass();
                    pmiddle.PutCoords((penvelope.XMax + penvelope.XMin) / 2, (penvelope.YMax + penvelope.YMin) / 2);//中心点

                    IGeometry pGeometry = penvelope as IGeometry;

                    /*-----xisheng 20110802------*/
                    ISpatialReference         earthref    = null;
                    ISpatialReference         flatref     = null;
                    ISpatialReferenceFactory2 pSpatRefFac = new SpatialReferenceEnvironmentClass();
                    earthref = pSpatRefFac.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);

                    if (_axmapcontrol.MapUnits == esriUnits.esriMeters)
                    {
                        flatref = _axmapcontrol.Map.SpatialReference;
                        pGeometry.SpatialReference = flatref;//yjl20110812 modify
                        //pGeometry.Project(flatref);
                    }
                    /*-----xisheng 20110802------*/

                    if (pGeometry == null)
                    {
                        return;
                    }
                    if (pGeometry.GeometryType != esriGeometryType.esriGeometryEnvelope)
                    {
                        return;
                    }
                    if (pGeometry.Envelope.Width < 0)
                    {
                        return;
                    }
                    if (this.WriteLog)
                    {
                        Plugin.LogTable.Writelog("坐标范围制图");
                    }
                    drawgeometryXOR(pGeometry as IEnvelope, _axmapcontrol.ActiveView.ScreenDisplay);
                    ESRI.ArcGIS.Carto.IMap pMap = _axmapcontrol.Map;
                    SysCommon.CProgress    pgss = new SysCommon.CProgress("正在加载制图界面,请稍候...");
                    pgss.EnableCancel    = false;
                    pgss.ShowDescription = false;
                    pgss.FakeProgress    = true;
                    pgss.TopMost         = true;
                    pgss.ShowProgress();
                    Application.DoEvents();
                    frm             = new FrmPageLayout(pMap, pGeometry);
                    frm.WriteLog    = WriteLog;//ygc 2012-9-12 是否写日志
                    frm.FormClosed += new FormClosedEventHandler(frm_FormClosed);
                    frm.typeZHT     = 2;
                    frm.Show();
                    pgss.Close();
                    _axmapcontrol.CurrentTool = null;
                    Application.DoEvents();
                }
                catch (Exception ex)
                {
                    SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "错误:" + ex.Message);
                }
            }
        }
コード例 #30
0
        public override void OnClick()
        {
            Exception eError = null;

            //FrmMathematicsCheck mFrmMathematicsCheck = new FrmMathematicsCheck(_AppHk, enumErrorType.数学基础正确性);
            //mFrmMathematicsCheck.ShowDialog();



            FrmMathCheck pFrmMathCheck = new FrmMathCheck();

            if (pFrmMathCheck.ShowDialog() == DialogResult.OK)
            {
                #region 错误日志保存
                //错误日志连接信息
                string logPath = TopologyCheckClass.GeoLogPath + "Log" + System.DateTime.Today.Year.ToString() + System.DateTime.Today.Month.ToString() + System.DateTime.Today.Day.ToString() + System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + ".xls";
                if (File.Exists(logPath))
                {
                    if (SysCommon.Error.ErrorHandle.ShowFrmInformation("是", "否", "日志文件\n'" + logPath + "'\n已经存在,是否替换?"))
                    {
                        File.Delete(logPath);
                    }
                    else
                    {
                        return;
                    }
                }
                //生成日志信息EXCEL格式
                SysCommon.DataBase.SysDataBase pSysLog = new SysCommon.DataBase.SysDataBase();
                pSysLog.SetDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + logPath + "; Extended Properties=Excel 8.0;", SysCommon.enumDBConType.OLEDB, SysCommon.enumDBType.ACCESS, out eError);
                if (eError != null)
                {
                    SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "日志信息表连接失败!");
                    return;
                }
                string strCreateTableSQL = @" CREATE TABLE ";
                strCreateTableSQL += @" 错误日志 ";
                strCreateTableSQL += @" ( ";
                strCreateTableSQL += @" 检查功能名 VARCHAR, ";
                strCreateTableSQL += @" 错误类型 VARCHAR, ";
                strCreateTableSQL += @" 错误描述 VARCHAR, ";
                strCreateTableSQL += @" 数据图层1 VARCHAR, ";
                strCreateTableSQL += @" 数据OID1 VARCHAR, ";
                strCreateTableSQL += @" 数据图层2 VARCHAR, ";
                strCreateTableSQL += @" 数据OID2 VARCHAR, ";
                strCreateTableSQL += @" 定位点X VARCHAR , ";
                strCreateTableSQL += @" 定位点Y VARCHAR , ";
                strCreateTableSQL += @" 检查时间 VARCHAR ,";
                strCreateTableSQL += @" 数据文件路径 VARCHAR ";
                strCreateTableSQL += @" ) ";

                pSysLog.UpdateTable(strCreateTableSQL, out eError);
                if (eError != null)
                {
                    SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "插入表头出错!");
                    pSysLog.CloseDbConnection();
                    return;
                }

                DataCheckClass dataCheckCls = new DataCheckClass(_AppHk);
                //将日志表连接信息和表名保存起来
                dataCheckCls.ErrDbCon     = pSysLog.DbConn;
                dataCheckCls.ErrTableName = "错误日志";
                #endregion

                #region 获得要检查的IFeatureClass的集合
                //将Mapcontrol上所有的图层名保存起来
                List <IFeatureClass> LstFeaClass = new List <IFeatureClass>();
                for (int i = 0; i < _AppHk.MapControl.LayerCount; i++)
                {
                    ILayer player = _AppHk.MapControl.get_Layer(i);
                    if (player is IGroupLayer)
                    {
                        ICompositeLayer pComLayer = player as ICompositeLayer;
                        for (int j = 0; j < pComLayer.Count; j++)
                        {
                            ILayer        mLayer        = pComLayer.get_Layer(j);
                            IFeatureLayer mfeatureLayer = mLayer as IFeatureLayer;
                            if (mfeatureLayer == null)
                            {
                                continue;
                            }
                            IFeatureClass pfeaCls = mfeatureLayer.FeatureClass;
                            if (!LstFeaClass.Contains(pfeaCls))
                            {
                                LstFeaClass.Add(pfeaCls);
                            }
                        }
                    }
                    else
                    {
                        IFeatureLayer pfeatureLayer = player as IFeatureLayer;
                        if (pfeatureLayer == null)
                        {
                            continue;
                        }
                        IFeatureClass mFeaCls = pfeatureLayer.FeatureClass;
                        if (!LstFeaClass.Contains(mFeaCls))
                        {
                            LstFeaClass.Add(mFeaCls);
                        }
                    }
                }
                #endregion

                if (_AppHk.DataTree == null)
                {
                    return;
                }
                _AppHk.DataTree.Nodes.Clear();
                //创建处理树图
                IntialTree(_AppHk.DataTree);
                //设置树节点颜色
                setNodeColor(_AppHk.DataTree);
                _AppHk.DataTree.Tag = false;

                string prjStr = pFrmMathCheck.PRJFNAME;
                if (prjStr == "")
                {
                    return;
                }
                try
                {
                    ISpatialReferenceFactory spatialRefFac      = new SpatialReferenceEnvironmentClass();
                    ISpatialReference        standardSpatialRef = spatialRefFac.CreateESRISpatialReferenceFromPRJFile(prjStr);


                    for (int i = 0; i < LstFeaClass.Count; i++)
                    {
                        IFeatureClass pFeatureClass  = LstFeaClass[i];
                        string        pFeaClsNameStr = "";//图层名
                        pFeaClsNameStr = (pFeatureClass as IDataset).Name.Trim();

                        //创建树图节点(以图层名作为根结点)
                        DevComponents.AdvTree.Node pNode = new DevComponents.AdvTree.Node();
                        pNode = (DevComponents.AdvTree.Node)CreateAdvTreeNode(_AppHk.DataTree.Nodes, pFeaClsNameStr, pFeaClsNameStr, _AppHk.DataTree.ImageList.Images[6], true);//图层名节点
                        //显示进度条
                        ShowProgressBar(true);

                        int tempValue = 0;
                        ChangeProgressBar((_AppHk as Plugin.Application.IAppFormRef).ProgressBar, 0, 1, tempValue);

                        dataCheckCls.MathematicsCheck(pFeatureClass, standardSpatialRef, out eError);
                        if (eError != null)
                        {
                            SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "数学基础性正确检查失败。" + eError.Message);
                            pSysLog.CloseDbConnection();
                            return;
                        }

                        tempValue += 1;//进度条的值加1
                        ChangeProgressBar((_AppHk as Plugin.Application.IAppFormRef).ProgressBar, -1, -1, tempValue);

                        //改变树图运行状态
                        ChangeTreeSelectNode(pNode, "完成图层" + pFeaClsNameStr + "的数据基础性正确检查", false);
                    }
                    SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "数据检查完成!");
                    pSysLog.CloseDbConnection();
                    //隐藏进度条
                    ShowProgressBar(false);
                }
                catch (Exception ex)
                {
                    SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", ex.Message);
                    pSysLog.CloseDbConnection();
                    return;
                }
            }
        }
        public static void TestThumbnailBuilder(string rasterTypeName, string rasterTypeProductFilter,
                                                string rasterTypeProductName, string dataSource, string dataSourceFilter, string fgdbParentFolder,
                                                bool saveToArt, string customTypeFilePath, bool clearGdbDirectory)
        {
            try
            {
                string[] rasterProductNames = rasterTypeProductName.Split(';');
                string   nameString         = rasterTypeName.Replace(" ", "") + rasterTypeProductFilter.Replace(" ", "") +
                                              rasterProductNames[0].Replace(" ", "");

                #region Directory Declarations
                string fgdbName          = nameString + ".gdb";
                string fgdbDir           = fgdbParentFolder + "\\" + fgdbName;
                string MosaicDatasetName = nameString + "MD";
                #endregion

                #region Global Declarations
                IMosaicDataset                  theMosaicDataset          = null;
                IMosaicDatasetOperation         theMosaicDatasetOperation = null;
                IMosaicWorkspaceExtensionHelper mosaicExtHelper           = null;
                IMosaicWorkspaceExtension       mosaicExt = null;
                #endregion

                #region Create File GDB
                Console.WriteLine("Creating File GDB: " + fgdbName);
                if (clearGdbDirectory)
                {
                    try
                    {
                        Console.WriteLine("Emptying Gdb folder.");
                        System.IO.Directory.Delete(fgdbParentFolder, true);
                        System.IO.Directory.CreateDirectory(fgdbParentFolder);
                    }
                    catch (System.IO.IOException EX)
                    {
                        Console.WriteLine(EX.Message);
                        return;
                    }
                }

                // Create a File Gdb
                Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
                IWorkspaceFactory FgdbFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
                FgdbFactory.Create(fgdbParentFolder,
                                   fgdbName, null, 0);
                #endregion

                #region Create Mosaic Dataset
                try
                {
                    Console.WriteLine("Create Mosaic Dataset: " + MosaicDatasetName);
                    // Setup workspaces.
                    IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
                    IWorkspace        fgdbWorkspace    = workspaceFactory.OpenFromFile(fgdbDir, 0);
                    // Create Srs
                    ISpatialReferenceFactory spatialrefFactory = new SpatialReferenceEnvironmentClass();
                    ISpatialReference        mosaicSrs         = spatialrefFactory.CreateProjectedCoordinateSystem(
                        (int)(esriSRProjCSType.esriSRProjCS_World_Mercator));
                    // Create the mosaic dataset creation parameters object.
                    ICreateMosaicDatasetParameters creationPars = new CreateMosaicDatasetParametersClass();
                    // Create the mosaic workspace extension helper class.
                    mosaicExtHelper = new MosaicWorkspaceExtensionHelperClass();
                    // Find the right extension from the workspace.
                    mosaicExt = mosaicExtHelper.FindExtension(fgdbWorkspace);
                    // Use the extension to create a new mosaic dataset, supplying the
                    // spatial reference and the creation parameters object created above.
                    theMosaicDataset = mosaicExt.CreateMosaicDataset(MosaicDatasetName,
                                                                     mosaicSrs, creationPars, "");
                    theMosaicDatasetOperation = (IMosaicDatasetOperation)(theMosaicDataset);
                }
                catch (Exception exc)
                {
                    Console.WriteLine("Error: Failed to create Mosaic Dataset : {0}.",
                                      MosaicDatasetName + " " + exc.Message);
                    return;
                }
                #endregion

                #region Create Custom Raster Type
                Console.WriteLine("Preparing Raster Type");
                // Create a Raster Type Name object.
                IRasterTypeName theRasterTypeName = new RasterTypeNameClass();
                // Assign the name of the Raster Type to the name object.
                // The Name field accepts a path to an .art file as well
                // the name for a built in Raster Type.
                theRasterTypeName.Name = rasterTypeName;
                // Use the Open function from the IName interface to get the Raster Type object.
                IRasterType theRasterType = (IRasterType)(((IName)theRasterTypeName).Open());
                if (theRasterType == null)
                {
                    Console.WriteLine("Error:Raster Type not found " + rasterTypeName);
                    return;
                }
                #endregion

                #region Prepare Raster Type
                // Set the URI Filter on the loaded raster type.
                if (rasterTypeProductFilter != "")
                {
                    // Get the supported URI filters from the raster type object using the
                    // raster type properties interface.
                    IArray         mySuppFilters = ((IRasterTypeProperties)theRasterType).SupportedURIFilters;
                    IItemURIFilter productFilter = null;
                    for (int i = 0; i < mySuppFilters.Count; ++i)
                    {
                        // Set the desired filter from the supported filters.
                        productFilter = (IItemURIFilter)mySuppFilters.get_Element(i);
                        if (productFilter.Name == rasterTypeProductFilter)
                        {
                            theRasterType.URIFilter = productFilter;
                        }
                    }
                }
                // Enable the correct templates in the raster type.
                bool enableTemplate = false;
                if (rasterProductNames.Length >= 1 && (rasterProductNames[0] != ""))
                {
                    // Get the supported item templates from the raster type.
                    IItemTemplateArray templateArray = theRasterType.ItemTemplates;
                    for (int i = 0; i < templateArray.Count; ++i)
                    {
                        // Go through the supported item templates and enable the ones needed.
                        IItemTemplate template = templateArray.get_Element(i);
                        enableTemplate = false;
                        for (int j = 0; j < rasterProductNames.Length; ++j)
                        {
                            if (template.Name == rasterProductNames[j])
                            {
                                enableTemplate = true;
                            }
                        }
                        if (enableTemplate)
                        {
                            template.Enabled = true;
                        }
                        else
                        {
                            template.Enabled = false;
                        }
                    }
                }
                ((IRasterTypeProperties)theRasterType).DataSourceFilter = dataSourceFilter;
                #endregion

                #region Save Custom Raster Type
                if (saveToArt)
                {
                    IRasterTypeProperties  rasterTypeProperties = (IRasterTypeProperties)theRasterType;
                    IRasterTypeEnvironment rasterTypeHelper     = new RasterTypeEnvironmentClass();
                    rasterTypeProperties.Name = customTypeFilePath;

                    IMemoryBlobStream ipBlob = rasterTypeHelper.SaveRasterType(theRasterType);
                    ipBlob.SaveToFile(customTypeFilePath);
                }
                #endregion

                #region Preparing Data Source Crawler
                Console.WriteLine("Preparing Data Source Crawler");
                // Create a new property set to specify crawler properties.
                IPropertySet crawlerProps = new PropertySetClass();
                // Specify a file filter
                crawlerProps.SetProperty("Filter", dataSourceFilter);
                // Specify whether to search subdirectories.
                crawlerProps.SetProperty("Recurse", true);
                // Specify the source path.
                crawlerProps.SetProperty("Source", dataSource);
                // Get the recommended crawler from the raster type based on the specified
                // properties using the IRasterBuilder interface.
                // Pass on the Thumbnailtype to the crawler...
                IDataSourceCrawler theCrawler = ((IRasterBuilder)theRasterType).GetRecommendedCrawler(crawlerProps);
                #endregion

                #region Add Rasters
                try
                {
                    Console.WriteLine("Adding Rasters");
                    // Create a AddRaster parameters object.
                    IAddRastersParameters AddRastersArgs = new AddRastersParametersClass();
                    // Specify the data crawler to be used to crawl the data.
                    AddRastersArgs.Crawler = theCrawler;
                    // Specify the Thumbnail raster type to be used to add the data.
                    AddRastersArgs.RasterType = theRasterType;
                    // Use the mosaic dataset operation interface to add
                    // rasters to the mosaic dataset.
                    theMosaicDatasetOperation.AddRasters(AddRastersArgs, null);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: Add raster Failed." + ex.Message);
                    return;
                }
                #endregion

                #region Compute Pixel Size Ranges
                Console.WriteLine("Computing Pixel Size Ranges.");
                try
                {
                    // Create a calculate cellsize ranges parameters object.
                    ICalculateCellSizeRangesParameters computeArgs = new CalculateCellSizeRangesParametersClass();
                    // Use the mosaic dataset operation interface to calculate cellsize ranges.
                    theMosaicDatasetOperation.CalculateCellSizeRanges(computeArgs, null);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: Compute Pixel Size Failed." + ex.Message);
                    return;
                }
                #endregion

                #region Building Boundary
                Console.WriteLine("Building Boundary");
                try
                {
                    // Create a build boundary parameters object.
                    IBuildBoundaryParameters boundaryArgs = new BuildBoundaryParametersClass();
                    // Set flags that control boundary generation.
                    boundaryArgs.AppendToExistingBoundary = true;
                    // Use the mosaic dataset operation interface to build boundary.
                    theMosaicDatasetOperation.BuildBoundary(boundaryArgs, null);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: Build Boundary Failed." + ex.Message);
                    return;
                }
                #endregion

                #region Report
                Console.WriteLine("Successfully created MD: " + MosaicDatasetName + ". ");
                #endregion
            }
            catch (Exception exc)
            {
                #region Report
                Console.WriteLine("Exception Caught in TestThumbnailBuilder: " + exc.Message);
                Console.WriteLine("Failed.");
                Console.WriteLine("Shutting down.");
                #endregion
            }
        }
コード例 #32
0
        private List<TileInfo> GetTile()
        {
            var schema = _tileSource.Schema;
            IEnvelope pEnvelope = new EnvelopeClass();
            ISpatialReferenceFactory pSpatRefFact = new SpatialReferenceEnvironmentClass();
            pEnvelope.SpatialReference = pSpatRefFact.CreateGeographicCoordinateSystem(4326);
            pEnvelope.XMin = extent[0];
            pEnvelope.XMax = extent[2];
            pEnvelope.YMin = extent[1];
            pEnvelope.YMax = extent[3];

            var env = Projector.ProjectEnvelope(pEnvelope, schema.Srs);

            var mapWidth = 256 * num;
            var mapHeight = 256 * num;
            float resolution = (float)level;

            var centerPoint = env.GetCenterPoint();

            var transform = new Transform(centerPoint, resolution, mapWidth, mapHeight);
            Extent exte = new Extent(pEnvelope.XMin, pEnvelope.YMin, pEnvelope.XMax, pEnvelope.YMax);
            var level1 = Utilities.GetNearestLevel(schema.Resolutions, transform.Resolution);

            var tempExtent = new Extent(12597408.0986328, 2623556.09863281, 12629205.9013672, 2655353.90136719);
            var tiles = schema.GetTilesInView(tempExtent, 10);

            return tiles.ToList();
        }
コード例 #33
0
        /// <summary>
        ///     Handles the incoming rest requests
        /// </summary>
        /// <param name="boundVariables"> The bound variables. </param>
        /// <param name="operationInput"> The operation input. </param>
        /// <param name="outputFormat"> The output format. </param>
        /// <param name="requestProperties"> The request properties. </param>
        /// <param name="responseProperties"> The response properties. </param>
        /// <returns> </returns>
        /// <exception cref="System.ArgumentNullException"></exception>
        public static byte[] Handler(NameValueCollection boundVariables, JsonObject operationInput,
                                     string outputFormat, string requestProperties,
                                     out string responseProperties)
        {
            responseProperties = null;
            var errors = new ErrorContainer(400);
            var wkid   = 26912;

            //pull out all the variables
            var featureClass = operationInput.GetStringValue("featureClass");
            var returnValues = operationInput.GetStringValue("returnValues");
            var predicate    = operationInput.GetStringValue("predicate", nullable: true);
            var geometryJson = operationInput.GetStringValue("geometry", nullable: true);
            var wkidInput    = operationInput.GetNumberValue("wkid", nullable: true);
            var bufferInput  = operationInput.GetNumberValue("buffer", nullable: true);

            if (wkidInput > 0)
            {
                wkid = Convert.ToInt32(wkidInput);
            }

            var isSafeSqlCommand = new IsSafeSqlCommand(new[]
            {
                featureClass, returnValues, predicate
            });

            if (!CommandExecutor.ExecuteCommand(isSafeSqlCommand))
            {
                errors.Add("Input appears to be unsafe. That is all I will tell you.");
            }

            GeometryContainer        container           = null;
            ISpatialReference        newSpatialRefefence = null;
            ISpatialReferenceFactory srFactory           = null;

            //reproject to our data's spatial reference
            if (wkid != 26912)
            {
                srFactory = new SpatialReferenceEnvironmentClass();

                var isProjected = true;
                try
                {
                    newSpatialRefefence = srFactory.CreateProjectedCoordinateSystem(wkid);
                }
                catch (ArgumentException)
                {
                    isProjected = false;
                }

                if (!isProjected)
                {
                    newSpatialRefefence = srFactory.CreateGeographicCoordinateSystem(wkid);
                }
            }

            //input has a geometry - deal with it
            if (!string.IsNullOrEmpty(geometryJson))
            {
                var extractGeometryCommand = new ExtractGeometryCommand(geometryJson, wkid);
                container = CommandExecutor.ExecuteCommand(extractGeometryCommand);

                if (container == null)
                {
                    var message = "Geometry coordinates appear to be invalid.";

                    if (!string.IsNullOrEmpty(extractGeometryCommand.ErrorMessage))
                    {
                        message += " Maybe this information can help: {0}".With(extractGeometryCommand.ErrorMessage);
                    }

                    errors.Add(message);
                }

                //input is in different projection - reproject it
                if (wkid != 26912)
                {
                    if (srFactory == null)
                    {
                        srFactory = new SpatialReferenceEnvironmentClass();
                    }

                    var toUtm = srFactory.CreateProjectedCoordinateSystem(26912);

                    if (container != null)
                    {
                        if ((container.Coordinates == null || container.Coordinates.Count < 1) && container.Geometry != null)
                        {
                            container.Geometry.Project(toUtm);
                        }
                        else
                        {
                            foreach (var points in container.Coordinates)
                            {
                                var point = new PointClass
                                {
                                    X = points[0],
                                    Y = points[1],
                                    SpatialReference = newSpatialRefefence
                                };

                                point.Project(toUtm);

                                if (point.IsEmpty)
                                {
                                    errors.Add("Input geometry is empty. Check your x and y values.");
                                    return(Json(errors));
                                }

                                container.Geometry = point;

                                points[0] = point.X;
                                points[1] = point.Y;
                            }
                        }
                    }
                }

                //buffer point - set container type to polygon
                if (bufferInput > 0 && container != null)
                {
                    container.Geometry = CommandExecutor.ExecuteCommand(new BufferGeometryCommand(container, bufferInput));
                    container.Type     = "POLYGON";
                }
            }

            var sdeConnector = SdeConnectorFactory.Create(featureClass);

            if (sdeConnector == null)
            {
                errors.Add("{0} was not found in our database. ".With(featureClass) +
                           "A valid example would be SGID10.BOUNDARIES.Counties.");
            }

            if (errors.HasErrors)
            {
                return(Json(errors));
            }

// ReSharper disable PossibleNullReferenceException because of returning errors if null
            var workspace = sdeConnector.Connect();

            // ReSharper restore PossibleNullReferenceException


            if (workspace is not IFeatureWorkspace featureWorkspace)
            {
                errors.Add("Error connecting to SDE.");
                return(Json(errors));
            }

            var values = returnValues.Split(',').Select(x => x.Trim()).ToArray();

            var commandToExecute = SpatialCommandFactory.Get(container, featureWorkspace, featureClass, values,
                                                             predicate, newSpatialRefefence);

            var result = CommandExecutor.ExecuteCommand(commandToExecute);

            if (!string.IsNullOrEmpty(commandToExecute.ErrorMessage))
            {
                errors.Add(commandToExecute.ErrorMessage);
                return(Json(errors));
            }

            return(Json(result));
        }
コード例 #34
0
        /// <summary>
        /// Transforms an Point to a different coordinate system.
        /// </summary>
        /// <param name="inPoint">The Point to be Converted</param>
        /// <param name="inDataCoordinateSystem">The Coordinate System the point is currently in</param>
        /// <param name="inReturnCoordinateSystem">The coordinate System the point is to be returned into</param>
        /// <returns>A transformed point or null.</returns>
        public T ConvertToCoordinateSystem <T>(T inputGeometry, int inDataCoordinateSystem, ISpatialReference destSpatialReference) where T : IGeometry2
        {
            // Create source spatial reference

            ISpatialReferenceFactory2 spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            ISpatialReference         sourceSpatialReference  = spatialReferenceFactory.CreateSpatialReference(inDataCoordinateSystem);

            if (destSpatialReference == null)
            {
                return(inputGeometry);
            }

            //cast T as IGeometry2 and project this.
            IGeometry2 geometry = inputGeometry as IGeometry2;

            if ((inDataCoordinateSystem == 27700) && (destSpatialReference.FactoryCode == 4326))
            {
                IGeoTransformation geoTransformation = spatialReferenceFactory.CreateGeoTransformation(1196) as IGeoTransformation;
                geometry.ProjectEx(destSpatialReference as ISpatialReference, esriTransformDirection.esriTransformForward, geoTransformation, false, 0, 0);
            }
            else if ((inDataCoordinateSystem == 4326) && (destSpatialReference.FactoryCode == 27700))
            {
                IGeoTransformation geoTransformation = spatialReferenceFactory.CreateGeoTransformation(1196) as IGeoTransformation;
                geometry.ProjectEx(destSpatialReference as ISpatialReference, esriTransformDirection.esriTransformReverse, geoTransformation, false, 0, 0);
            }
            else if ((inDataCoordinateSystem == 27700) && (destSpatialReference.FactoryCode == 102113))
            {
                IGeoTransformation          geoTransformation  = spatialReferenceFactory.CreateGeoTransformation(1196) as IGeoTransformation;
                IGeoTransformation          pGeoTrans_B        = spatialReferenceFactory.CreateGeoTransformation(108100) as IGeoTransformation; // ' WGS84 Maj Aux Sphere to WGS84
                ICompositeGeoTransformation pGeoTransComposite = new CompositeGeoTransformationClass() as ICompositeGeoTransformation;
                pGeoTransComposite.Add(esriTransformDirection.esriTransformForward, geoTransformation);                                         // National Grid to Wgs84
                pGeoTransComposite.Add(esriTransformDirection.esriTransformReverse, pGeoTrans_B);                                               // reversed sphere to wgs84
                geometry.ProjectEx(destSpatialReference, esriTransformDirection.esriTransformForward, pGeoTransComposite, false, 0, 0);
            }
            else if ((inDataCoordinateSystem == 102113) && (destSpatialReference.FactoryCode == 27700))
            {
                IGeoTransformation          geoTransformation  = spatialReferenceFactory.CreateGeoTransformation(1196) as IGeoTransformation;
                IGeoTransformation          pGeoTrans_B        = spatialReferenceFactory.CreateGeoTransformation(108100) as IGeoTransformation; // ' WGS84 Maj Aux Sphere to WGS84
                ICompositeGeoTransformation pGeoTransComposite = new CompositeGeoTransformationClass() as ICompositeGeoTransformation;
                pGeoTransComposite.Add(esriTransformDirection.esriTransformForward, pGeoTrans_B);                                               // sphere to wgs84
                pGeoTransComposite.Add(esriTransformDirection.esriTransformReverse, geoTransformation);                                         // National Grid to Wgs84
                geometry.ProjectEx(destSpatialReference, esriTransformDirection.esriTransformForward, pGeoTransComposite, false, 0, 0);
            }
            else if ((inDataCoordinateSystem == 27700) && (destSpatialReference.FactoryCode == 102100))
            {
                IGeoTransformation          geoTransformation  = spatialReferenceFactory.CreateGeoTransformation(1196) as IGeoTransformation;
                IGeoTransformation          pGeoTrans_B        = spatialReferenceFactory.CreateGeoTransformation(108100) as IGeoTransformation; // ' WGS84 Maj Aux Sphere to WGS84
                ICompositeGeoTransformation pGeoTransComposite = new CompositeGeoTransformationClass();
                pGeoTransComposite.Add(esriTransformDirection.esriTransformForward, geoTransformation);                                         // National Grid to Wgs84
                pGeoTransComposite.Add(esriTransformDirection.esriTransformReverse, pGeoTrans_B);                                               // reversed sphere to wgs84
                geometry.ProjectEx(destSpatialReference, esriTransformDirection.esriTransformForward, pGeoTransComposite, false, 0, 0);
            }
            else if ((inDataCoordinateSystem == 102100) && (destSpatialReference.FactoryCode == 27700))
            {
                IGeoTransformation          geoTransformation  = spatialReferenceFactory.CreateGeoTransformation(1196) as IGeoTransformation;
                IGeoTransformation          pGeoTrans_B        = spatialReferenceFactory.CreateGeoTransformation(108100) as IGeoTransformation; // ' WGS84 Maj Aux Sphere to WGS84
                ICompositeGeoTransformation pGeoTransComposite = new CompositeGeoTransformationClass();
                pGeoTransComposite.Add(esriTransformDirection.esriTransformForward, pGeoTrans_B);                                               // sphere to wgs84
                pGeoTransComposite.Add(esriTransformDirection.esriTransformReverse, geoTransformation);                                         // National Grid to Wgs84
                geometry.ProjectEx(destSpatialReference, esriTransformDirection.esriTransformForward, pGeoTransComposite, false, 0, 0);
            }

            else if ((inDataCoordinateSystem == 27700) && (destSpatialReference.FactoryCode == 3857))
            {
                IGeoTransformation          geoTransformation  = spatialReferenceFactory.CreateGeoTransformation(1196) as IGeoTransformation;
                IGeoTransformation          pGeoTrans_B        = spatialReferenceFactory.CreateGeoTransformation(108100) as IGeoTransformation; // ' WGS84 Maj Aux Sphere to WGS84
                ICompositeGeoTransformation pGeoTransComposite = new CompositeGeoTransformationClass();
                pGeoTransComposite.Add(esriTransformDirection.esriTransformForward, geoTransformation);                                         // National Grid to Wgs84
                pGeoTransComposite.Add(esriTransformDirection.esriTransformReverse, pGeoTrans_B);                                               // reversed sphere to wgs84
                geometry.ProjectEx(destSpatialReference, esriTransformDirection.esriTransformForward, pGeoTransComposite, false, 0, 0);
            }
            else if ((inDataCoordinateSystem == 3857) && (destSpatialReference.FactoryCode == 27700))
            {
                IGeoTransformation          geoTransformation  = spatialReferenceFactory.CreateGeoTransformation(1196) as IGeoTransformation;
                IGeoTransformation          pGeoTrans_B        = spatialReferenceFactory.CreateGeoTransformation(108100) as IGeoTransformation; // ' WGS84 Maj Aux Sphere to WGS84
                ICompositeGeoTransformation pGeoTransComposite = new CompositeGeoTransformationClass();
                pGeoTransComposite.Add(esriTransformDirection.esriTransformForward, pGeoTrans_B);                                               // sphere to wgs84
                pGeoTransComposite.Add(esriTransformDirection.esriTransformReverse, geoTransformation);                                         // National Grid to Wgs84
                geometry.ProjectEx(destSpatialReference, esriTransformDirection.esriTransformForward, pGeoTransComposite, false, 0, 0);
            }
            else
            {
                geometry.Project(destSpatialReference as ISpatialReference);
            }

            return(inputGeometry);
        }
コード例 #35
0
        private void buttonOK_Click(object sender, EventArgs e)
        {
            this.Visible = false;
            if (_axmapcontrol != null)
            {
                try
                {
                    /*xisheng 20110802 */

                    ISpatialReferenceFactory2 pSpatRefFac = new SpatialReferenceEnvironmentClass();
                    earthref = pSpatRefFac.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);

                    point = new ESRI.ArcGIS.Geometry.PointClass();
                    double x1 = Convert.ToDouble(textBoxX.Text);
                    double y1 = Convert.ToDouble(textBoxY.Text);
                    if (_axmapcontrol.MapUnits == esriUnits.esriMeters)
                    {
                        flatref = _axmapcontrol.Map.SpatialReference;
                        point.PutCoords(x1, y1);//yjl20110812
                    }
                    else if (_axmapcontrol.MapUnits == esriUnits.esriDecimalDegrees)
                    {
                        point.PutCoords(x1, y1);
                    }
                    // ESRI.ArcGIS.Geometry.IPoint pPoint = _axmapcontrol.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(Convert.ToInt32(point.X), Convert.ToInt32(point.Y));
                    //end 0802
                    if (this.WriteLog)
                    {
                        Plugin.LogTable.Writelog(this.Text);//xisheng 日志记录 0928;
                    }
                    if (m_frmQuery == null)
                    {
                        m_frmQuery             = new frmQuery(_axmapcontrol, m_enumQueryMode);
                        m_frmQuery.Owner       = m_mainFrm;
                        m_frmQuery.FormClosed += new FormClosedEventHandler(frmQuery_FormClosed);
                    }
                    if (m_frmBufferSet != null)
                    {
                        m_frmBufferSet.setBufferGeometry(null);
                        m_frmBufferSet = null;
                    }
                    m_frmBufferSet             = new frmBufferSet(point as IGeometry, _axmapcontrol.Map, m_frmQuery);
                    m_frmBufferSet.FormClosed += new FormClosedEventHandler(frmBufferSet_FormClosed);
                    _axmapcontrol.CenterAt(point);
                    IGeometry pGeometry = m_frmBufferSet.GetBufferGeometry();
                    if (pGeometry == null || m_frmBufferSet.Res == false)
                    {
                        return;
                    }

                    //m_frmQuery.Show();
                    ///ZQ 20111119  modify
                    //m_frmQuery.FillData(_axmapcontrol.ActiveView.FocusMap, pGeometry, m_frmBufferSet.pesriSpatialRelEnum);
                    QueryBar.m_pMapControl = _axmapcontrol;
                    QueryBar.EmergeQueryData(_axmapcontrol.ActiveView.FocusMap, pGeometry, m_frmBufferSet.pesriSpatialRelEnum);
                    try
                    {
                        DevComponents.DotNetBar.Bar pBar = QueryBar.Parent.Parent as DevComponents.DotNetBar.Bar;
                        if (pBar != null)
                        {
                            pBar.AutoHide = false;
                            //pBar.SelectedDockTab = 1;
                            int tmpindex = pBar.Items.IndexOf("dockItemDataCheck");
                            pBar.SelectedDockTab = tmpindex;
                        }
                    }
                    catch
                    { }
                    this.Close();
                }
                catch (Exception ex)
                {
                    SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "错误:" + ex.Message);
                }
            }
        }
コード例 #36
0
        /// <summary>
        /// Get current view extent (in geographical coordinate system). 
        /// </summary>
        /// <remarks>
        /// If error occurred, exception would be thrown.
        /// </remarks>
        /// <returns>view extent as an envelope object</returns>
        private esri.gpt.csw.Envelope CurrentMapViewExtent()
        {
            esri.gpt.csw.Envelope envCurrentViewExent;

            IMxDocument mxDoc = (IMxDocument)m_application.Document;
            IMap map = mxDoc.FocusMap;
            IActiveView activeView = (IActiveView)map;
            IEnvelope extent = activeView.Extent;
            if (extent == null) return null;

            ISpatialReference CurrentMapSpatialReference = extent.SpatialReference;
            if (CurrentMapSpatialReference == null) throw new Exception(StringResources.SpatialReferenceNotDefined);

            if (CurrentMapSpatialReference is IUnknownCoordinateSystem)
            {
                // unknown cooridnate system
                throw new Exception(StringResources.UnknownCoordinateSystem);
            }
            else if (CurrentMapSpatialReference is IGeographicCoordinateSystem)
            {
                // already in geographical coordinate system, reuse coordinate values
                envCurrentViewExent = new esri.gpt.csw.Envelope(extent.XMin, extent.YMin, extent.XMax, extent.YMax);
            }
            else if (CurrentMapSpatialReference is IProjectedCoordinateSystem)
            {
                // project to geographical coordinate system
                ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironmentClass();
                IGeographicCoordinateSystem gcs = srFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_NAD1983);
                gcs.SetFalseOriginAndUnits(-180, -90, 1000000);
                extent.Project(gcs);
                envCurrentViewExent = new esri.gpt.csw.Envelope(extent.XMin, extent.YMin, extent.XMax, extent.YMax);
            }
            else
            {
                ShowErrorMessageBox(StringResources.UnsupportedCoordinateSystem);
                envCurrentViewExent = null;
            }

            return envCurrentViewExent;
        }
コード例 #37
0
ファイル: helpers.cs プロジェクト: BGCX261/ziggis-svn-to-git
 public static ISpatialReference setEsriSpatiaReferenceFromSrText(int srid, Connection conn)
 {
     ISpatialReference sr = new UnknownCoordinateSystemClass();
     string srText = "";
     int i = 0;
     try
     {
         //Bill: query srtext associated with srid
         AutoDataReader dr = conn.doQuery("select * from spatial_ref_sys where srid = " + srid.ToString());
         if (dr.Read())
         {
             srText = dr["srtext"] + "";
             ISpatialReferenceFactory2 srf = new SpatialReferenceEnvironmentClass();
             if (srText == "")
             {
                 sr = new UnknownCoordinateSystemClass();
             }
             else
             {
                 //use srText to construct SR.
                 srf.CreateESRISpatialReference(srText, out sr, out i);
             }
         }
         return sr;
     }
     catch
     {
         //PostGis srid is not implemented as an Esri Factory Code
         sr = new UnknownCoordinateSystemClass();
         return sr;
     }
 }
コード例 #38
0
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) {
            //
            if (context == null) { return null; }
            if (context.Instance == null) { return null; }
            if (provider == null) { return null; }

            // Cannot handle multiple objects
            if (context.Instance is object[]) { return null; }

            //
            string wkt = null;
            if (value != null) {
                wkt = value.ToString();
            }
            
            // Do ArcGIS Desktop Test
            object dialog = null;
            try {
                dialog = new SpatialReferenceDialogClass();
            }
            catch { }
            if (dialog == null) {
                MessageBox.Show(
                    "You do not have ArcGIS Desktop Installed",
                    Resources.TEXT_APPLICATION,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Exclamation,
                    MessageBoxDefaultButton.Button1,
                    MessageBoxOptions.DefaultDesktopOnly);
                return null;
            }

            // Variable to hold edited or created spatial reference
            ISpatialReference spatialReferenceOut = null;

            // Use DoModelCreate (if NULL) or DoModelEdit (if not NULL)
            if (string.IsNullOrEmpty(wkt)) {
               
                ISpatialReferenceDialog2 spatialReferenceDialog = (ISpatialReferenceDialog2)dialog;
                spatialReferenceOut = spatialReferenceDialog.DoModalCreate(false, false, false, 0);
            }
            else {
                // Recreate ESRI Spatial Reference from String
                ISpatialReferenceFactory3 spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
                ISpatialReferenceInfo spatialReferenceInfo = null;
                int size;
                spatialReferenceFactory.CreateESRISpatialReferenceInfo(wkt, out spatialReferenceInfo, out size);
                ISpatialReference spatialReference = (ISpatialReference)spatialReferenceInfo;

                // Display Spatial Reference Dialog
                ISpatialReferenceDialog3 spatialReferenceDialog = (ISpatialReferenceDialog3)dialog;
                spatialReferenceOut = spatialReferenceDialog.DoModalEdit3(spatialReference, true, 0);
            }

            // Exit if Output SpatialReference is NULL
            if (spatialReferenceOut == null) { return wkt; }

            // Convert ESRI Spatial Reference to a String
            IESRISpatialReferenceGEN spatialReferenceGEN = (IESRISpatialReferenceGEN)spatialReferenceOut;
            string projection;
            int size2;
            spatialReferenceGEN.ExportToESRISpatialReference(out projection, out size2);
            if (string.IsNullOrEmpty(projection)) { return wkt; }

            // Return Result
            return projection;
        }
コード例 #39
0
        static void Main(string[] args)
        {
            #region Initialize License
            ESRI.ArcGIS.esriSystem.AoInitialize aoInit = null;
            try
            {
                Console.WriteLine("Obtaining license");
                ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);
                aoInit = new AoInitializeClass();
                esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced);
                Console.WriteLine("Ready with license.");
            }
            catch (Exception exc)
            {
                // If it fails at this point, shutdown the test and ignore any subsequent errors.
                Console.WriteLine(exc.Message);
            }
            #endregion

            try
            {
                #region Setup MD Parameters
                MDParameters.gdbParentFolder = @"e:\MD\CustomRasterType\DMCII";
                // Choose which type of gdb to create/open.
                // 0 - Create File Gdb
                // 1 - Create Personal Gdb
                // 2 - Open SDE
                int gdbOption = 0;
                // Provide the proper extension based on the gdb you want to create.
                // e.g. MDParameters.gdbName = "samplePGdb.mdb" to create a personal gdb.
                // To use an SDE, set SDE connection properties below.
                MDParameters.gdbName           = @"CustomTypeGdb.gdb";
                MDParameters.mosaicDatasetName = @"CustomTypeMD";

                // Specify the srs of the mosaic dataset
                ISpatialReferenceFactory spatialrefFactory = new SpatialReferenceEnvironmentClass();
                MDParameters.mosaicDatasetSrs = spatialrefFactory.CreateProjectedCoordinateSystem(
                    (int)(esriSRProjCSType.esriSRProjCS_World_Mercator));

                // 0 and PT_UNKNOWN for bits and bands = use defaults.
                MDParameters.mosaicDatasetBands = 0;
                MDParameters.mosaicDatasetBits  = rstPixelType.PT_UNKNOWN;
                MDParameters.configKeyword      = "";

                // Product Definition key choices:
                // None
                // NATURAL_COLOR_RGB
                // NATURAL_COLOR_RGBI
                // FALSE_COLOR_IRG
                // FORMOSAT-2_4BANDS
                // GEOEYE-1_4BANDS
                // IKONOS_4BANDS
                // KOMPSAT-2_4BANDS
                // LANDSAT_6BANDS
                // LANDSAT_MSS_4BANDS
                // QUICKBIRD_4BANDS
                // RAPIDEYE_5BANDS
                // SPOT-5_4BANDS
                // WORLDVIEW-2_8BANDS

                // Setting this property ensures any data added to the MD with its
                // metadata defined gets added with the correct band combination.
                MDParameters.productDefinitionKey = "FALSE_COLOR_IRG";

                MDParameters.rasterTypeName = "DMCIIRasterType";
                // The next two properties can be left blank for defaults
                // The product filter defines which specific product of the raster
                // type to add, e.g. To specfiy Quickbird Basic use value "Basic"
                MDParameters.rasterTypeProductFilter = "";
                // The product name specifies which template to use when adding data.
                // e.g. "Pansharpen and Multispectral" means both multispectral and
                // pansharpened rasters are added to the mosaic dataset.
                MDParameters.rasterTypeProductName = "Raw";

                // Data source from which to read the data.
                MDParameters.dataSource       = @"F:\Data\DMCii";
                MDParameters.dataSourceFilter = @"";
                // No need to set if data source has an srs or if you want to use the MD srs as data source srs.
                MDParameters.dataSourceSrs = null;

                MDParameters.buildOverviews = false;
                #endregion

                MDParameters.emptyGdbFolder        = false;
                MDParameters.createGdbParentFolder = false;
                #region Empty/Create Output Directory
                if (MDParameters.emptyGdbFolder)
                {
                    try
                    {
                        Console.WriteLine("Emptying Output Directory");
                        Directory.Delete(MDParameters.gdbParentFolder, true);
                        Directory.CreateDirectory(MDParameters.gdbParentFolder);
                    }
                    catch (Exception)
                    {
                    }
                }
                if (MDParameters.createGdbParentFolder && !System.IO.Directory.Exists(MDParameters.gdbParentFolder))
                {
                    Console.WriteLine("Creating Output Directory");
                    Directory.CreateDirectory(MDParameters.gdbParentFolder);
                }
                #endregion

                CreateMD createMD = new CreateMD();

                if (gdbOption == 0)
                {
                    #region Create MD in File GDB
                    Console.WriteLine("Creating File GDB: " + MDParameters.gdbName);
                    IWorkspace fgdbWorkspace = CreateFileGdbWorkspace(MDParameters.gdbParentFolder, MDParameters.gdbName);
                    createMD.CreateMosaicDataset(fgdbWorkspace);
                    #endregion
                }
                else if (gdbOption == 1)
                {
                    #region Create MD in Personal GDB
                    Console.WriteLine("Creating Personal GDB: " + MDParameters.gdbName);
                    IWorkspace pGdbWorkspace = CreateAccessWorkspace(MDParameters.gdbParentFolder, MDParameters.gdbName);
                    createMD.CreateMosaicDataset(pGdbWorkspace);
                    #endregion
                }
                else if (gdbOption == 2)
                {
                    #region Open SDE GDB
                    // Set SDE connection properties.
                    IPropertySet sdeProperties = new PropertySetClass();
                    sdeProperties.SetProperty("SERVER", "barbados");
                    sdeProperties.SetProperty("INSTANCE", "9411");
                    sdeProperties.SetProperty("VERSION", "sde.DEFAULT");
                    sdeProperties.SetProperty("USER", "gdb");
                    sdeProperties.SetProperty("PASSWORD", "gdb");
                    sdeProperties.SetProperty("DATABASE", "VTEST");
                    IWorkspace sdeWorkspace = CreateSdeWorkspace(sdeProperties);
                    if (sdeWorkspace == null)
                    {
                        Console.WriteLine("Could not open SDE workspace: ");
                        return;
                    }

                    #endregion

                    #region Create MD in SDE
                    MDParameters.mosaicDatasetName = @"sampleMD";
                    createMD.CreateMosaicDataset(sdeWorkspace);
                    #endregion
                }

                #region Shutdown
                Console.WriteLine("Press any key...");
                Console.ReadKey();
                // Shutdown License
                aoInit.Shutdown();
                #endregion
            }
            catch (Exception exc)
            {
                #region Report
                Console.WriteLine("Exception Caught in Main: " + exc.Message);
                Console.WriteLine("Shutting down.");
                #endregion

                #region Shutdown
                Console.WriteLine("Press any key...");
                Console.ReadKey();
                // Shutdown License
                aoInit.Shutdown();
                #endregion
            }
        }
コード例 #40
0
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            //
            if (context == null)
            {
                return(null);
            }
            if (context.Instance == null)
            {
                return(null);
            }
            if (provider == null)
            {
                return(null);
            }

            // Cannot handle multiple objects
            if (context.Instance is object[])
            {
                return(null);
            }

            //
            string wkt = null;

            if (value != null)
            {
                wkt = value.ToString();
            }

            // Do ArcGIS Desktop Test
            object dialog = null;

            try {
                dialog = new SpatialReferenceDialogClass();
            }
            catch { }
            if (dialog == null)
            {
                MessageBox.Show(
                    "You do not have ArcGIS Desktop Installed",
                    Resources.TEXT_APPLICATION,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Exclamation,
                    MessageBoxDefaultButton.Button1,
                    MessageBoxOptions.DefaultDesktopOnly);
                return(null);
            }

            // Variable to hold edited or created spatial reference
            ISpatialReference spatialReferenceOut = null;

            // Use DoModelCreate (if NULL) or DoModelEdit (if not NULL)
            if (string.IsNullOrEmpty(wkt))
            {
                ISpatialReferenceDialog2 spatialReferenceDialog = (ISpatialReferenceDialog2)dialog;
                spatialReferenceOut = spatialReferenceDialog.DoModalCreate(false, false, false, 0);
            }
            else
            {
                // Recreate ESRI Spatial Reference from String
                ISpatialReferenceFactory3 spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
                ISpatialReferenceInfo     spatialReferenceInfo    = null;
                int size;
                spatialReferenceFactory.CreateESRISpatialReferenceInfo(wkt, out spatialReferenceInfo, out size);
                ISpatialReference spatialReference = (ISpatialReference)spatialReferenceInfo;

                // Display Spatial Reference Dialog
                ISpatialReferenceDialog3 spatialReferenceDialog = (ISpatialReferenceDialog3)dialog;
                spatialReferenceOut = spatialReferenceDialog.DoModalEdit3(spatialReference, true, 0);
            }

            // Exit if Output SpatialReference is NULL
            if (spatialReferenceOut == null)
            {
                return(wkt);
            }

            // Convert ESRI Spatial Reference to a String
            IESRISpatialReferenceGEN spatialReferenceGEN = (IESRISpatialReferenceGEN)spatialReferenceOut;
            string projection;
            int    size2;

            spatialReferenceGEN.ExportToESRISpatialReference(out projection, out size2);
            if (string.IsNullOrEmpty(projection))
            {
                return(wkt);
            }

            // Return Result
            return(projection);
        }
コード例 #41
0
ファイル: BaseGISTools.cs プロジェクト: BNU-Chen/3DGlobe
 /// <summary>
 /// 坐标系转换-----WGS84转投影坐标系 
 /// </summary>
 /// <param name="point">转换前的IPoint</param>
 /// <returns>转换后的IPoint</returns>
 public static IPoint getProjectPoint(IPoint point)
 {
     try
     {
         ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass();
         point.SpatialReference = pSRF.CreateGeographicCoordinateSystem((int)(esriSRGeoCSType.esriSRGeoCS_WGS1984));
         point.Project(pSRF.CreateProjectedCoordinateSystem((int)(esriSRProjCSType.esriSRProjCS_WGS1984UTM_31N)));
     }
     catch //(Exception e)
     {
         // MessageBox.Show(e.ToString());
     }
     return point;
 }
コード例 #42
0
ファイル: BusinessLogic.cs プロジェクト: VsPun/DPP
        private Tuple <IGeoTransformation, esriTransformDirection> GetPredefinedTransformation(SpatialReferenceEnvironmentClass spatialReferenceFactory, ISpatialReference fromSpatialReference, ISpatialReference toSpatialReference)
        {
            int?fromFactoryCode = GetGCSFactoryCode(fromSpatialReference);
            int?toFactoryCode   = GetGCSFactoryCode(toSpatialReference);

            if (!fromFactoryCode.HasValue || !toFactoryCode.HasValue)
            {
                return(null);
            }

            var geographicTransformationsSet = spatialReferenceFactory.CreatePredefinedGeographicTransformations();

            geographicTransformationsSet.Reset();

            var geoTransformation = geographicTransformationsSet.Next() as IGeoTransformation;

            try
            {
                while (geoTransformation != null)
                {
                    geoTransformation.GetSpatialReferences(out ISpatialReference bufferForFromGeoCoordSystemSR, out ISpatialReference bufferForToGeoCoordSystemSR);

                    if (bufferForFromGeoCoordSystemSR.FactoryCode == fromFactoryCode && bufferForToGeoCoordSystemSR.FactoryCode == toFactoryCode)
                    {
                        return(new Tuple <IGeoTransformation, esriTransformDirection>(geoTransformation, esriTransformDirection.esriTransformForward));
                    }

                    if (bufferForFromGeoCoordSystemSR.FactoryCode == toFactoryCode && bufferForToGeoCoordSystemSR.FactoryCode == fromFactoryCode)
                    {
                        return(new Tuple <IGeoTransformation, esriTransformDirection>(geoTransformation, esriTransformDirection.esriTransformReverse));
                    }
                    geoTransformation = geographicTransformationsSet.Next() as IGeoTransformation;
                }
            }
            finally
            {
                Marshal.ReleaseComObject(geographicTransformationsSet);
            }
            return(null);
        }
        public static void initEditing()
        {
            if (AAState.PerformUpdates == false)
            {
                AAState.WriteLine(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantEditorMess_3a"));
                return;
            }
            // wire events
            if (reInitExt() == false)
            {
                AAState.WriteLine(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantEditorMess_3b"));
                AAState.PerformUpdates = false;

            }
            if (AAState._editor.EditWorkspace != null)
            {
                if (AAState._editor.EditWorkspace.Type == esriWorkspaceType.esriFileSystemWorkspace)
                {
                    AAState.WriteLine(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantEditorMess_3c"));
                    AAState.PerformUpdates = false;

                }
            }
            if (AAState.PerformUpdates)
            {
                AAState.WriteLine(A4LGSharedFunctions.Localizer.GetString("AttributeAssistantEditorMess_3d"));
                if (Debug().ToUpper() == "TRUE")
                {
                    AAState._filePath = Globals.getDebugPath();
                    if (AAState._filePath != "")
                    {
                        AAState._sw = Globals.createTextFile(AAState._filePath, FileMode.Create);

                    }
                    Globals.LogLocations = AAState._filePath;
                }
                else
                {
                    AAState._sw = null;
                    Globals.LogLocations = "";
                }

                // Get user Info

                reInitExt();

                //obtain rotation calculator
                AAState.rCalc = new RotationCalculator(ArcMap.Application);

                //Create WGS_84 SR
                ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironmentClass();
                IGeographicCoordinateSystem gcs = srFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);
                _sr1 = gcs;

                _editEvents.OnChangeFeature += FeatureChange;
                _editEvents.OnCreateFeature += FeatureCreate;
                _editEvents2.BeforeStopOperation += StopOperation; // SG Jan 2013

            }
            else
            {

                AAState.PerformUpdates = false;

                _editEvents.OnChangeFeature -= FeatureChange;
                _editEvents.OnCreateFeature -= FeatureCreate;
                _editEvents2.BeforeStopOperation -= StopOperation; // SG Jan 2013

            }

            ArcMap.Application.StatusBar.set_Message(0, A4LGSharedFunctions.Localizer.GetString("AttributeAssistantEditorDone_3a"));
        }
コード例 #44
0
        // create feature class in file geodatabase
        #region "create feature class in file geodatabase"
        public static ESRI.ArcGIS.Geodatabase.IFeatureClass CreateFeatureClass(String featureClassName, UID classExtensionUID, IFeatureWorkspace featureWorkspace)
        {
            // check if the fc exist, if so rename it



            // Create a fields collection for the feature class.
            IFields     fields     = new FieldsClass();
            IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

            // Add an object ID field to the fields collection. This is mandatory for feature classes.
            IField     oidField     = new FieldClass();
            IFieldEdit oidFieldEdit = (IFieldEdit)oidField;

            oidFieldEdit.Name_2 = "OBJECTID";
            oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
            fieldsEdit.AddField(oidField);

            // Create a geometry definition (and spatial reference) for the feature class.
            IGeometryDef     geometryDef     = new GeometryDefClass();
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;

            geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline;
            ISpatialReferenceFactory    spatialReferenceFactory    = new SpatialReferenceEnvironmentClass();
            ISpatialReference           spatialReference           = spatialReferenceFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_NAD1983UTM_12N);
            ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference;

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

            spatialReferenceTolerance.SetDefaultXYTolerance();
            geometryDefEdit.SpatialReference_2 = spatialReference;

            // Add a geometry field to the fields collection. This is where the geometry definition is applied.
            IField     geometryField     = new FieldClass();
            IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField;

            geometryFieldEdit.Name_2        = "Shape";
            geometryFieldEdit.Type_2        = esriFieldType.esriFieldTypeGeometry;
            geometryFieldEdit.GeometryDef_2 = geometryDef;
            fieldsEdit.AddField(geometryField);

            // Create a text field called "ADDRSYS_L" for the fields collection.
            IField     addrSysLField     = new FieldClass();
            IFieldEdit addrSysLFieldEdit = (IFieldEdit)addrSysLField;

            addrSysLFieldEdit.Name_2   = "ADDRSYS_L";
            addrSysLFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            addrSysLFieldEdit.Length_2 = 30;
            fieldsEdit.AddField(addrSysLField);

            // Create a text field called "ADDRSYS_R" for the fields collection.
            IField     addrSysRField     = new FieldClass();
            IFieldEdit addrSysRFieldEdit = (IFieldEdit)addrSysRField;

            addrSysRFieldEdit.Name_2   = "ADDRSYS_R";
            addrSysRFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            addrSysRFieldEdit.Length_2 = 30;
            fieldsEdit.AddField(addrSysRField);


            // Create a text field called "FROMADDR_L" for the fields collection.
            IField     rangeL_Ffield     = new FieldClass();
            IFieldEdit rangeL_FfieldEdit = (IFieldEdit)rangeL_Ffield;

            rangeL_FfieldEdit.Name_2      = "FROMADDR_L";
            rangeL_FfieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
            rangeL_FfieldEdit.Precision_2 = 38;
            rangeL_FfieldEdit.Scale_2     = 8;
            fieldsEdit.AddField(rangeL_Ffield);

            // Create a text field called "TOADDR_L" for the fields collection.
            IField     rangeL_Tfield     = new FieldClass();
            IFieldEdit rangeL_TfieldEdit = (IFieldEdit)rangeL_Tfield;

            rangeL_TfieldEdit.Name_2      = "TOADDR_L";
            rangeL_TfieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
            rangeL_TfieldEdit.Precision_2 = 38;
            rangeL_TfieldEdit.Scale_2     = 8;
            fieldsEdit.AddField(rangeL_Tfield);

            // Create a text field called "FROMADDR_R" for the fields collection.
            IField     rangeR_Ffield     = new FieldClass();
            IFieldEdit rangeR_FfieldEdit = (IFieldEdit)rangeR_Ffield;

            rangeR_FfieldEdit.Name_2      = "FROMADDR_R";
            rangeR_FfieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
            rangeR_FfieldEdit.Precision_2 = 38;
            rangeR_FfieldEdit.Scale_2     = 8;
            fieldsEdit.AddField(rangeR_Ffield);

            // Create a text field called "TOADDR_R" for the fields collection.
            IField     rangeR_Tfield     = new FieldClass();
            IFieldEdit rangeR_TfieldEdit = (IFieldEdit)rangeR_Tfield;

            rangeR_TfieldEdit.Name_2      = "TOADDR_R";
            rangeR_TfieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
            rangeR_TfieldEdit.Precision_2 = 38;
            rangeR_TfieldEdit.Scale_2     = 8;
            fieldsEdit.AddField(rangeR_Tfield);

            // Create a text field called "PREDIR" for the fields collection.
            IField     predirField     = new FieldClass();
            IFieldEdit predirFieldEdit = (IFieldEdit)predirField;

            predirFieldEdit.Name_2   = "PREDIR";
            predirFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            predirFieldEdit.Length_2 = 1;
            fieldsEdit.AddField(predirField);

            // Create a text field called "NAME" for the fields collection.
            IField     nameField     = new FieldClass();
            IFieldEdit nameFieldEdit = (IFieldEdit)nameField;

            nameFieldEdit.Name_2   = "NAME";
            nameFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            nameFieldEdit.Length_2 = 30;
            fieldsEdit.AddField(nameField);

            // Create a text field called "POSTTYPE" for the fields collection.
            IField     streettypeField     = new FieldClass();
            IFieldEdit streettypeFieldEdit = (IFieldEdit)streettypeField;

            streettypeFieldEdit.Name_2   = "POSTTYPE";
            streettypeFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            streettypeFieldEdit.Length_2 = 4;
            fieldsEdit.AddField(streettypeField);

            // Create a text field called "POSTDIR" for the fields collection.
            IField     sufdirField     = new FieldClass();
            IFieldEdit sufdirFieldEdit = (IFieldEdit)sufdirField;

            sufdirFieldEdit.Name_2   = "POSTDIR";
            sufdirFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            sufdirFieldEdit.Length_2 = 2;
            fieldsEdit.AddField(sufdirField);

            // Create a text field called "ZIPCODE_L" for the fields collection.
            IField     zipleftField     = new FieldClass();
            IFieldEdit zipleftFieldEdit = (IFieldEdit)zipleftField;

            zipleftFieldEdit.Name_2   = "ZIPCODE_L";
            zipleftFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            zipleftFieldEdit.Length_2 = 5;
            fieldsEdit.AddField(zipleftField);

            // Create a text field called "ZIPCODE_R" for the fields collection.
            IField     ziprightField     = new FieldClass();
            IFieldEdit ziprightFieldEdit = (IFieldEdit)ziprightField;

            ziprightFieldEdit.Name_2   = "ZIPCODE_R";
            ziprightFieldEdit.Type_2   = esriFieldType.esriFieldTypeString;
            ziprightFieldEdit.Length_2 = 5;
            fieldsEdit.AddField(ziprightField);

            // Create a text field called "GLOBALID_SGID" for the fields collection - to join to the table or sgid.
            IField     globalidField     = new FieldClass();
            IFieldEdit globalidFieldEdit = (IFieldEdit)globalidField;

            globalidFieldEdit.Name_2   = "GLOBALID_SGID";
            globalidFieldEdit.Type_2   = esriFieldType.esriFieldTypeString; // use string and not the globalid type b/c it might that might assign it's own unique global id and this is for joinging back to sgid
            globalidFieldEdit.Length_2 = 50;
            fieldsEdit.AddField(globalidField);

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

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

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

            // Create the feature class. Note that the CLSID parameter is null - this indicates to use the
            // default CLSID, esriGeodatabase.Feature (acceptable in most cases for feature classes).
            IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(featureClassName, validatedFields, null, classExtensionUID, esriFeatureType.esriFTSimple, "Shape", "");

            return(featureClass);
        }
コード例 #45
0
        private void frmGeographicTransformationConvert_Load(object sender, EventArgs e)
        {
            int num;

            this.btnEdit.Enabled = false;
            this.btnNew.Enabled  = false;
            this.cboTarget.Items.Clear();
            ISpatialReferenceFactory factory   = new SpatialReferenceEnvironmentClass();
            ISpatialReference        reference = null;

            for (num = 0; num < this.int_0.Length; num++)
            {
                reference = factory.CreateGeographicCoordinateSystem(this.int_0[num]);
                this.cboTarget.Items.Add(new ObjectWrap(reference));
            }
            this.cboTarget.SelectedIndex = 0;
            if (this.ibasicMap_0.SpatialReference is IProjectedCoordinateSystem)
            {
                this.list_0.Add(
                    (this.ibasicMap_0.SpatialReference as IProjectedCoordinateSystem).GeographicCoordinateSystem.Name);
                this.listBox1.Items.Add(
                    new ObjectWrap(
                        (this.ibasicMap_0.SpatialReference as IProjectedCoordinateSystem).GeographicCoordinateSystem));
            }
            else if (this.ibasicMap_0.SpatialReference is IGeographicCoordinateSystem)
            {
                this.list_0.Add(this.ibasicMap_0.SpatialReference.Name);
                this.listBox1.Items.Add(new ObjectWrap(this.ibasicMap_0.SpatialReference));
            }
            for (num = 0; num < this.ibasicMap_0.LayerCount; num++)
            {
                ILayer layer = this.ibasicMap_0.get_Layer(num);
                if (layer is IGroupLayer)
                {
                    for (int i = 0; i < (layer as ICompositeLayer).Count; i++)
                    {
                        this.method_0((layer as ICompositeLayer).get_Layer(i));
                    }
                }
                else if (layer is IGeoDataset)
                {
                    string      name;
                    IGeoDataset dataset = layer as IGeoDataset;
                    if (dataset.SpatialReference is IProjectedCoordinateSystem)
                    {
                        name =
                            (this.ibasicMap_0.SpatialReference as IProjectedCoordinateSystem).GeographicCoordinateSystem
                            .Name;
                        if (this.list_0.IndexOf(name) == -1)
                        {
                            this.list_0.Add(
                                (this.ibasicMap_0.SpatialReference as IProjectedCoordinateSystem)
                                .GeographicCoordinateSystem.Name);
                            this.listBox1.Items.Add(
                                new ObjectWrap(
                                    (dataset.SpatialReference as IProjectedCoordinateSystem).GeographicCoordinateSystem));
                        }
                    }
                    else if (dataset.SpatialReference is IGeographicCoordinateSystem)
                    {
                        name = this.ibasicMap_0.SpatialReference.Name;
                        if (this.list_0.IndexOf(name) == -1)
                        {
                            this.list_0.Add(name);
                            this.listBox1.Items.Add(new ObjectWrap(dataset.SpatialReference));
                        }
                    }
                }
            }
            this.bool_0 = true;
            if (this.listBox1.Items.Count > 0)
            {
                this.listBox1.SelectedIndex = 0;
            }
        }
コード例 #46
0
        private void btOK_Click(object sender, EventArgs e)
        {
            try
            {
                string        pPointFileName   = cboBoxPointLayer.SelectedItem.ToString();
                string        pCenterlinName   = comboBoxExCenterlineLinearLayer.SelectedItem.ToString();
                IFeatureLayer pPointLayer      = null;
                IFeatureLayer pCenterlineLayer = null;
                for (int i = 0; i < pMapcontrol.LayerCount; i++)
                {
                    if (pPointFileName == pMapcontrol.get_Layer(i).Name)
                    {
                        pPointLayer = pMapcontrol.get_Layer(i) as IFeatureLayer;
                    }
                    if (pCenterlinName == pMapcontrol.get_Layer(i).Name)
                    {
                        pCenterlineLayer = pMapcontrol.get_Layer(i) as IFeatureLayer;
                    }
                }
                IFeatureClass  pLineFC      = pCenterlineLayer.FeatureClass;
                IFeatureClass  pPointFC     = pPointLayer.FeatureClass;
                IFeatureCursor pLineCursor  = pLineFC.Search(null, false);
                IFeature       pLineFeature = pLineCursor.NextFeature();
                IQueryFilter   qf1          = null;
                DataTable      ptable;

                if (radioButtonLayer.Checked)
                {
                    ptable = AOFunctions.GDB.ITableUtil.GetDataTableFromITable(pPointFC as ITable, qf1);
                }
                else
                {
                    string          strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + this.textBoxFile.Text + ";Extended Properties=Excel 8.0";
                    OleDbConnection conn   = new OleDbConnection(strCon);
                    string          sql1   = "select * from [Sheet1$]";
                    conn.Open();
                    OleDbDataAdapter myCommand = new OleDbDataAdapter(sql1, strCon);
                    DataSet          ds        = new DataSet();
                    myCommand.Fill(ds);
                    conn.Close();
                    ptable = ds.Tables[0];
                    if (ptable.Columns.Contains(EvConfig.IMUMoveDistanceField))
                    {
                        ptable.Columns[EvConfig.IMUMoveDistanceField].DataType = System.Type.GetType("System.Double");
                    }
                }


                if (!ptable.Columns.Contains("X"))
                {
                    ptable.Columns.Add("X", System.Type.GetType("System.Double"));
                }
                if (!ptable.Columns.Contains("Y"))
                {
                    ptable.Columns.Add("Y", System.Type.GetType("System.Double"));
                }
                if (!ptable.Columns.Contains("Z"))
                {
                    ptable.Columns.Add("Z", System.Type.GetType("System.Double"));
                }
                if (!ptable.Columns.Contains("对齐里程"))
                {
                    ptable.Columns.Add("对齐里程", System.Type.GetType("System.Double"));
                }
                if (!ptable.Columns.Contains("距离偏移"))
                {
                    ptable.Columns.Add("距离偏移", System.Type.GetType("System.Double"));
                }
                ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
                //wgs 84
                IGeographicCoordinateSystem wgs84 = spatialReferenceFactory.CreateGeographicCoordinateSystem(4326) as IGeographicCoordinateSystem;
                IUnit meterUnit = spatialReferenceFactory.CreateUnit((int)ESRI.ArcGIS.Geometry.esriSRUnitType.esriSRUnit_Meter);

                IPolyline pline = pLineFeature.Shape as IPolyline;
                pline.SpatialReference = wgs84;

                IProximityOperator pPO = pline as IProximityOperator;

                int idx = 0;
                for (int i = 0; i < ptable.Rows.Count; i++)
                {
                    try
                    {
                        DataRow r  = ptable.Rows[i];
                        IPoint  pt = new PointClass();
                        pt.X = Convert.ToDouble(r[EvConfig.WeldXField]);
                        pt.Y = Convert.ToDouble(r[EvConfig.WeldYField]);
                        pt.SpatialReference = wgs84;
                        IPoint ptInLine = pPO.ReturnNearestPoint(pt, esriSegmentExtension.esriNoExtension);
                        r["X"]    = ptInLine.X;
                        r["Y"]    = ptInLine.Y;
                        r["对齐里程"] = ptInLine.M;
                        r["Z"]    = ptInLine.Z;

                        r["距离偏移"] = Math.Round(DataAlignment.DataAlignment.CalculateDistanceBetween84TwoPoints(pt, ptInLine), 2);
                    }
                    catch
                    {
                    }
                }
                System.Runtime.InteropServices.Marshal.ReleaseComObject(spatialReferenceFactory);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pLineCursor);


                FrmIMUAlignmentresult frm = new FrmIMUAlignmentresult(ptable);
                frm.setResultType("焊缝对齐报告");
                frm.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
コード例 #47
0
        /// <summary>
        /// draw footprints on the map
        /// </summary>
        /// <param name="record">Record for which the footprint needs to be drwan</param>
        /// <param name="refreshview">Indicates if the view is refreshed or not after the element is drawn</param>
        /// <param name="deleteelements">Indicates if the element can be deleted or not</param>
        private void drawfootprint(CswRecord record, bool refreshview, bool deleteelements)
        {
            //create the triangle outline symbol
            ISimpleLineSymbol lineSymbol = new SimpleLineSymbolClass();
            lineSymbol.Style = esriSimpleLineStyle.esriSLSSolid;
            lineSymbol.Width = 2.0;

            //create the triangle's fill symbol
             ISimpleFillSymbol simpleFillSymbol = new SimpleFillSymbolClass();
            simpleFillSymbol.Outline = (ILineSymbol)lineSymbol;
            simpleFillSymbol.Style = esriSimpleFillStyle.esriSFSDiagonalCross;

            IMxDocument mxDoc;
            mxDoc = (IMxDocument)m_application.Document;

            //the original projection system
            ISpatialReference spatialReference;
            IGeographicCoordinateSystem geographicCoordinateSystem;
            SpatialReferenceEnvironmentClass spatialReferenceEnviorment = new SpatialReferenceEnvironmentClass();
            geographicCoordinateSystem = spatialReferenceEnviorment.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);
            spatialReference = (ISpatialReference)geographicCoordinateSystem;

            //set the geometry of the element
            IPoint point = new ESRI.ArcGIS.Geometry.PointClass();
            point.SpatialReference = spatialReference;
            point.PutCoords(record.BoundingBox.Minx, record.BoundingBox.Miny);

            IPoint point1 = new ESRI.ArcGIS.Geometry.PointClass();
            point1.SpatialReference = spatialReference;
            point1.PutCoords(record.BoundingBox.Minx, record.BoundingBox.Maxy);

            IPoint point2 = new ESRI.ArcGIS.Geometry.PointClass();
            point2.SpatialReference = spatialReference;
            point2.PutCoords(record.BoundingBox.Maxx, record.BoundingBox.Maxy);

            IPoint point3 = new ESRI.ArcGIS.Geometry.PointClass();

               point3.SpatialReference = spatialReference;
               point3.PutCoords(record.BoundingBox.Maxx, record.BoundingBox.Miny);

            IPointCollection pointCollection;
            pointCollection = new ESRI.ArcGIS.Geometry.PolygonClass();

            object x = Type.Missing;
            object y = Type.Missing;

            pointCollection.AddPoint(point, ref x, ref y);
            pointCollection.AddPoint(point1, ref x, ref y);
            pointCollection.AddPoint(point2, ref x, ref y);
            pointCollection.AddPoint(point3, ref x, ref y);

            PolygonElementClass element = new PolygonElementClass();
            element.Symbol = simpleFillSymbol;
            element.SpatialReference = spatialReference;
            element.Geometry.SpatialReference = spatialReference;
            element.Geometry = (IGeometry)pointCollection;
            element.Geometry.Project(mxDoc.ActiveView.Extent.SpatialReference);

            //add the graphics element to the map
            IGraphicsContainer graphicsContainer;
            graphicsContainer = (IGraphicsContainer)mxDoc.FocusMap;
            if (deleteelements) {
                graphicsContainer.DeleteAllElements();
            }
            graphicsContainer.AddElement(element, 0);
            if (refreshview) {
                mxDoc.ActiveView.Extent = element.Geometry.Envelope;
                mxDoc.ActiveView.Refresh();
            }
        }
コード例 #48
0
        /// <summary>
        /// 文本地理坐标文件加载
        /// </summary>
        /// <param name="mapControl">要加载的地图控件</param>
        /// <param name="InputTxt">要加载的地图控件</param>
        /// <param name="OutputShp">要加载的地图控件</param>
        public void AddTxt(AxMapControl mapControl, string InputTxt, string OutputShp)
        {
            List <string> columns = new List <string>();

            char[] splChar = new char[] { ',', ' ', '\t' };
            // 1.将文本文件转换为CPoint集合
            List <CPoint> pointList    = new List <CPoint>();
            FileStream    fileStream   = new FileStream(InputTxt, FileMode.Open);
            StreamReader  streamReader = new StreamReader(fileStream, Encoding.Default);
            string        strLine      = streamReader.ReadLine();

            if (strLine != null)
            {
                string[] strArray = strLine.Split(splChar);
                if (strArray.Length > 0)
                {
                    foreach (string item in strArray)
                    {
                        columns.Add(item);
                    }
                }
                while ((strLine = streamReader.ReadLine()) != null)
                {
                    strArray = strLine.Split(splChar);
                    CPoint cPoint = new CPoint();
                    cPoint.Name = strArray[0];
                    cPoint.x    = Convert.ToDouble(strArray[1]);
                    cPoint.y    = Convert.ToDouble(strArray[2]);
                    pointList.Add(cPoint);
                }
            }
            streamReader.Close();
            // 2.将CPoint集合转换为FeatureClass
            if (pointList.Count > 0)
            {
                int    splIndex = OutputShp.LastIndexOf("\\");
                string filePath = OutputShp.Substring(0, splIndex);
                string fileName = OutputShp.Substring(splIndex + 1);
                //字段集
                IFields     fields     = new FieldsClass();
                IFieldsEdit fieldsEdit = (IFieldsEdit)fields;
                //单个字段
                IField     field     = new FieldClass();
                IFieldEdit fieldEdit = (IFieldEdit)field;
                //几何定义
                IGeometryDef     geometryDef     = new GeometryDefClass();
                IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;

                //赋值-几何定义
                ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
                ISpatialReference        spatialReference        = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_Beijing1954);
                geometryDefEdit.GeometryType_2     = esriGeometryType.esriGeometryPoint;
                geometryDefEdit.SpatialReference_2 = spatialReference;
                //赋值-字段
                fieldEdit.Name_2        = "Shape";
                fieldEdit.Type_2        = esriFieldType.esriFieldTypeGeometry;
                fieldEdit.GeometryDef_2 = geometryDef;
                //赋值-字段集和
                fieldsEdit.AddField(field);

                //再来一遍
                field     = new FieldClass();
                fieldEdit = (IFieldEdit)field;

                fieldEdit.Name_2 = "Test";
                fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;

                fieldsEdit.AddField(field);

                //创建图层
                IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass();
                IFeatureWorkspace workspace        = (IFeatureWorkspace)workspaceFactory.OpenFromFile(filePath, 0);
                IFeatureClass     featureClass     = workspace.CreateFeatureClass(fileName, fields, null, null, esriFeatureType.esriFTSimple, "Shape", "");
                //添加图斑
                IPoint point = new PointClass();
                foreach (CPoint item in pointList)
                {
                    point.X = item.x;
                    point.Y = item.y;
                    IFeature feature = featureClass.CreateFeature();
                    feature.Shape = point;
                    feature.Store();
                }
                // 3.将FeatureClass加入控件
                IFeatureLayer featureLayer = new FeatureLayerClass();
                featureLayer.FeatureClass = featureClass;
                featureLayer.Name         = featureClass.AliasName;
                mapControl.AddLayer(featureLayer);
            }
        }
コード例 #49
0
        private Envelope GetCurrentExtent()
        {
            Envelope currentExtent;

            IEnvelope extent = ArcMap.Document.ActiveView.Extent;
            if (extent == null) return null;

            ISpatialReference CurrentMapSpatialReference = extent.SpatialReference;
            if (CurrentMapSpatialReference == null)
            {
                //MessageBox.Show("Spatial Reference is Not Defined");
                currentExtent = null;
            }
            if (CurrentMapSpatialReference is IUnknownCoordinateSystem)
            {
                // unknown cooridnate system
                MessageBox.Show("Unknown Coordinate System\n\nNo extent will be used for search");
                currentExtent = null;
            }
            else if (CurrentMapSpatialReference is IGeographicCoordinateSystem)
            {
                // already in geographical coordinate system, reuse coordinate values
                currentExtent = new Envelope(extent.XMin, extent.YMin, extent.XMax, extent.YMax);
            }
            else if (CurrentMapSpatialReference is IProjectedCoordinateSystem)
            {
                // project to geographical coordinate system
                ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironmentClass();
                IGeographicCoordinateSystem gcs = srFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);
                gcs.SetFalseOriginAndUnits(-180, -90, 1000000);
                extent.Project(gcs);
                currentExtent = new Envelope(extent.XMin, extent.YMin, extent.XMax, extent.YMax);
            }
            else
            {
                MessageBox.Show("Unsupported Coordinate System\n\nNo extent will be used for search");
                currentExtent = null;
            }

            return currentExtent;
        }
コード例 #50
0
ファイル: Program.cs プロジェクト: SuYiChi/OperateFCInMemory
        /// <summary>
        /// 建立featureclass
        /// </summary>
        /// <param name="featureClassName"></param>
        /// <returns></returns>
        public IFeatureClass CreateFC(string featureClassName)
        {
            if (pWorkspace == null)
            {
                throw new NullReferenceException("尚未建立Wokspace, " + nameof(pWorkspace) + " NullReference");
            }

            IFeatureClass pFC    = null;
            UID           pCLSID = null;

            if (pCLSID == null)
            {
                pCLSID       = new UID();
                pCLSID.Value = "esriGeoDatabase.Feature";
            }

            IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspace;

            IObjectClassDescription objectClassDescription = new FeatureClassDescriptionClass();

            // create the fields using the required fields method
            IFields     fields     = objectClassDescription.RequiredFields;
            IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

            // Create a geometry definition (and spatial reference) for the feature class.
            // GeometryType=point and SpatialReference=WGS84
            IGeometryDef     geometryDef     = new GeometryDefClass();
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;

            geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
            ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            ISpatialReference        spatialReference        =
                spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);
            ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference;

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

            spatialReferenceTolerance.SetDefaultXYTolerance();
            geometryDefEdit.SpatialReference_2 = spatialReference;

            // Set spatialReference
            for (int i = 0; i < fields.FieldCount; i++)
            {
                var pfield = fields.get_Field(i);
                if (pfield.Type == esriFieldType.esriFieldTypeGeometry)
                {
                    var geometryField = pfield as IFieldEdit;
                    geometryField.GeometryDef_2 = geometryDef;
                    Console.WriteLine(pfield.GeometryDef.SpatialReference.Name);
                    break;
                }
            }

            // create a user defined text field
            IField     field     = new FieldClass();
            IFieldEdit fieldEdit = (IFieldEdit)field;

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

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

            String strShapeField = "";

            // locate the shape field
            for (int j = 0; j < fields.FieldCount; j++)
            {
                if (fields.get_Field(j).Type == esriFieldType.esriFieldTypeGeometry)
                {
                    strShapeField = fields.get_Field(j).Name;
                }
            }

            //create feature class in memory workspace
            pFC = pFeatureWorkspace.CreateFeatureClass(featureClassName, fields, pCLSID, null, esriFeatureType.esriFTSimple, strShapeField, null);

            return(pFC);
        }
コード例 #51
0
        // build the actual point feature and store it
        private void CreateWellsiteFeature()
        {
            IFeatureCursor pFeatureCursor = null;

            try
            {
                IFeatureClass pFeatureClass;
                IFields pFields;

                pFeatureClass = m_pFeatureLayerWellsOSDB.FeatureClass;

                // first deal with point creation
                IPoint pPoint = new PointClass();
                ISpatialReferenceFactory2 pSRF = new SpatialReferenceEnvironmentClass();

                double xcoord, ycoord;
                ISpatialReference pSR = null;

                if (txtUTMnorthing.ReadOnly == false)  //we'll use the UTM coordinates to validate the BCGS
                {
                    // create the correct UTM projected coordinate system (based on zone) - NAD 83 datum
                    pSR = pSRF.CreateSpatialReference(26900 + Convert.ToInt32(txtUTMzone.Text));

                    xcoord = Convert.ToDouble(txtUTMeasting.Text);
                    ycoord = Convert.ToDouble(txtUTMnorthing.Text);
                }
                else // we'll use the lat/lon coordinates to validate the BCGS
                {
                    pSR = pSRF.CreateSpatialReference(4269); //esriSRGeoCS_NAD1983

                    xcoord = Convert.ToDouble(txtLongitude.Text);
                    ycoord = Convert.ToDouble(txtLatitude.Text);

                    // make sure our xcoord is negative even if the user entered positive (for western hem)
                    if (xcoord > 0)
                        xcoord *= -1;

                    // make sure our ycoord is positive for northern hemisphere
                    if (ycoord < 0)
                        ycoord *= -1;

                }

                // assign coordinate info and SR
                pPoint.SpatialReference = pSR;
                pPoint.X = xcoord;
                pPoint.Y = ycoord;

                Debug.WriteLine("before project -> x,y = " + pPoint.X.ToString() + "," + pPoint.Y.ToString());

                // get SR of destination featureclass
                IGeoDataset pGeodataset = (IGeoDataset)pFeatureClass;

                // project point
                pPoint.Project(pGeodataset.SpatialReference);

                if (pPoint.IsEmpty == true)
                {
                    MessageBox.Show("The point coordinate failed to project.\n" +
                                    "Check that your coordinates are correct.", "SUITT Error");
                    return;
                }
                else
                {
                    Debug.WriteLine("after  project -> x,y = " + pPoint.X.ToString() + "," + pPoint.Y.ToString());
                }

                string correctMapSheet;
                if (BCGSCheck(txtBCGSMap.Text, pPoint, out correctMapSheet) == false)
                {
                    if (correctMapSheet.Length == 0)
                    {
                        // no result.. either a major error or the point does not fall inside
                        // any mapsheet polygon
                        MessageBox.Show("The point coordinate does not fall inside any BCGS map sheet", "SUITT");
                        return;
                    }
                    else
                    {
                        // point was not in the specified mapsheet polygon
                        MessageBox.Show("The point coordinate does not exist\n" +
                                        "within the specified BCGS map sheet.\n" +
                                        "The point cannot be added.\n\n" +
                                        "The correct sheet should be: " + correctMapSheet, "SUITT");
                        return;
                    }
                }

                // now do the insertion
                pFeatureCursor = pFeatureClass.Insert(false);

                IFeatureBuffer pFeatureBuffer = pFeatureClass.CreateFeatureBuffer();
                pFields = pFeatureCursor.Fields;

                pFeatureBuffer.set_Value(pFields.FindField("WELLSITE_SID"), Convert.ToDouble(txtWellsiteSID.Text));

                // write point
                pFeatureBuffer.Shape = pPoint;

                int fieldInd = pFields.FindField("CCOG_CHR");
                if (fieldInd != -1)
                    pFeatureBuffer.set_Value(fieldInd, FCODE_WELLSITEPOINT);

                // insert and release cursor
                pFeatureCursor.InsertFeature(pFeatureBuffer);

                // Display message that well site point was successfully created
                MessageBox.Show("Well Site Point was successfully created", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);

                // cleanup... clear all textboxes and set the focus back to the wellsite sid textbox
                ClearTextBoxes();
                txtWellsiteSID.Focus();

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message + "\n" + ex.StackTrace);
                util.Logger.Write(" Descrip  : Creating a wellsite point feature. " +
                    "\n Message  : " + ex.Message +
                    "\n StackTrc : " + ex.StackTrace, util.Logger.LogLevel.Debug);

            }
            finally
            {
                util.Utils.Release(pFeatureCursor);
            }
        }
コード例 #52
0
 public static IPoint XY2JWD(double x, double y, int gcsType, int pcsType)
 {
     try
     {
         IPoint point = new PointClass();
         point.PutCoords(x, y);
         ISpatialReferenceFactory factory = new SpatialReferenceEnvironmentClass();
         point.SpatialReference = factory.CreateProjectedCoordinateSystem(pcsType);
         point.Project(factory.CreateGeographicCoordinateSystem(gcsType));
         return point;
     }
     catch
     {
         return null;
     }
 }
コード例 #53
0
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            _message = message;

            IFeatureClass osmPointFeatureClass = null;
            IFeatureClass osmLineFeatureClass = null;
            IFeatureClass osmPolygonFeatureClass = null;

            try
            {
                DateTime syncTime = DateTime.Now;

                IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

                if (TrackCancel == null)
                {
                    TrackCancel = new CancelTrackerClass();
                }

                IGPParameter baseURLParameter = paramvalues.get_Element(in_downloadURLNumber) as IGPParameter;
                IGPString baseURLString = gpUtilities3.UnpackGPValue(baseURLParameter) as IGPString;

                if (baseURLString == null)
                {
                    message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), baseURLParameter.Name));
                }

                IGPParameter downloadExtentParameter = paramvalues.get_Element(in_downloadExtentNumber) as IGPParameter;
                IGPValue downloadExtentGPValue = gpUtilities3.UnpackGPValue(downloadExtentParameter);

                esriGPExtentEnum gpExtent;
                IEnvelope downloadEnvelope = gpUtilities3.GetExtent(downloadExtentGPValue, out gpExtent);

                IGPParameter includeAllReferences = paramvalues.get_Element(in_includeReferencesNumber) as IGPParameter;
                IGPBoolean includeAllReferencesGPValue = gpUtilities3.UnpackGPValue(includeAllReferences) as IGPBoolean;

                if (includeAllReferencesGPValue == null)
                {
                    message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), includeAllReferences.Name));
                }

                IEnvelope newExtent = null;

                ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass() as ISpatialReferenceFactory;
                ISpatialReference wgs84 = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984) as ISpatialReference;

                // this determines the spatial reference as defined from the gp environment settings and the initial wgs84 SR
                ISpatialReference downloadSpatialReference = gpUtilities3.GetGPSpRefEnv(envMgr, wgs84, newExtent, 0, 0, 0, 0, null);

                downloadEnvelope.Project(wgs84);

                Marshal.ReleaseComObject(wgs84);
                Marshal.ReleaseComObject(spatialReferenceFactory);

                HttpWebRequest httpClient;
                System.Xml.Serialization.XmlSerializer serializer = null;
                serializer = new XmlSerializer(typeof(osm));

                // get the capabilities from the server
                HttpWebResponse httpResponse = null;

                api apiCapabilities = null;
                CultureInfo enUSCultureInfo = new CultureInfo("en-US");

#if DEBUG
                Console.WriteLine("Debbuging");
                message.AddMessage("Debugging...");
#endif

                message.AddMessage(resourceManager.GetString("GPTools_OSMGPDownload_startingDownloadRequest"));

                try
                {
                    httpClient = HttpWebRequest.Create(baseURLString.Value + "/api/capabilities") as HttpWebRequest;
                    httpClient = AssignProxyandCredentials(httpClient);

                    httpResponse = httpClient.GetResponse() as HttpWebResponse;

                    osm osmCapabilities = null;

                    Stream stream = httpResponse.GetResponseStream();

                    XmlTextReader xmlReader = new XmlTextReader(stream);
                    osmCapabilities = serializer.Deserialize(xmlReader) as osm;
                    xmlReader.Close();

                    apiCapabilities = osmCapabilities.Items[0] as api;

                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    message.AddError(120009, ex.Message);

                    if (ex is WebException)
                    {
                        WebException webException = ex as WebException;
                        string serverErrorMessage = webException.Response.Headers["Error"];
                        if (!String.IsNullOrEmpty(serverErrorMessage))
                        {
                            message.AddError(120009, serverErrorMessage);
                        }
                    }

                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Close();
                    }
                    httpClient = null;
                }

                if (apiCapabilities != null)
                {
                    // check for the extent
                    double roiArea = ((IArea)downloadEnvelope).Area;
                    double capabilitiyArea = Convert.ToDouble(apiCapabilities.area.maximum, new CultureInfo("en-US"));

                    if (roiArea > capabilitiyArea)
                    {
                        message.AddAbort(resourceManager.GetString("GPTools_OSMGPDownload_exceedDownloadROI"));
                        return;
                    }
                }

                // check for user interruption
                if (TrackCancel.Continue() == false)
                {
                    return;
                }

                // list containing either only one document for a single bbox request or multiple if relation references need to be resolved
                List<string> downloadedOSMDocuments = new List<string>();

                string requestURL = baseURLString.Value + "/api/0.6/map?bbox=" + downloadEnvelope.XMin.ToString("f5", enUSCultureInfo) + "," + downloadEnvelope.YMin.ToString("f5", enUSCultureInfo) + "," + downloadEnvelope.XMax.ToString("f5", enUSCultureInfo) + "," + downloadEnvelope.YMax.ToString("f5", enUSCultureInfo);
                string osmMasterDocument = downloadOSMDocument(ref message, requestURL, apiCapabilities);

                // check if the initial request was successfull
                // it might have failed at this point because too many nodes were requested or because of something else
                if (String.IsNullOrEmpty(osmMasterDocument))
                {
                    message.AddAbort(resourceManager.GetString("GPTools_OSMGPDownload_noValidOSMResponse"));
                    return;
                }

                // add the "master document" ) original bbox request to the list
                downloadedOSMDocuments.Add(osmMasterDocument);

                if (includeAllReferencesGPValue.Value)
                {
                    List<string> nodeList = new List<string>();
                    List<string> wayList = new List<string>();
                    List<string> relationList = new List<string>();
                    // check for user interruption
                    if (TrackCancel.Continue() == false)
                    {
                        return;
                    }

                    parseOSMDocument(osmMasterDocument, ref message, ref nodeList, ref wayList, ref relationList, ref downloadedOSMDocuments, baseURLString.Value, apiCapabilities);
                }

                string metadataAbstract = resourceManager.GetString("GPTools_OSMGPDownload_metadata_abstract");
                string metadataPurpose = resourceManager.GetString("GPTools_OSMGPDownload_metadata_purpose");

                IGPParameter targetDatasetParameter = paramvalues.get_Element(out_targetDatasetNumber) as IGPParameter;
                IDEDataset2 targetDEDataset2 = gpUtilities3.UnpackGPValue(targetDatasetParameter) as IDEDataset2;
                IGPValue targetDatasetGPValue = gpUtilities3.UnpackGPValue(targetDatasetParameter);
                string targetDatasetName = ((IGPValue)targetDEDataset2).GetAsText();

                IDataElement targetDataElement = targetDEDataset2 as IDataElement;
                IDataset targetDataset = gpUtilities3.OpenDatasetFromLocation(targetDataElement.CatalogPath);

                IName parentName = null;

                try
                {
                    parentName = gpUtilities3.CreateParentFromCatalogPath(targetDataElement.CatalogPath);
                }
                catch
                {
                    message.AddError(120033, resourceManager.GetString("GPTools_OSMGPFileReader_unable_to_create_fd"));
                    return;
                }

                // test if the feature classes already exists, 
                // if they do and the environments settings are such that an overwrite is not allowed we need to abort at this point
                IGeoProcessorSettings gpSettings = (IGeoProcessorSettings)envMgr;
                if (gpSettings.OverwriteOutput == true)
                {
                }

                else
                {
                    if (gpUtilities3.Exists((IGPValue)targetDEDataset2) == true)
                    {
                        message.AddError(120010, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_basenamealreadyexists"), targetDataElement.Name));
                        return;
                    }
                }

                string Container = "";
                IDEUtilities deUtilities = new DEUtilitiesClass();
                deUtilities.ParseContainer(targetDataElement.CatalogPath, ref Container);

                IFeatureWorkspace featureWorkspace = gpUtilities3.OpenFromString(Container) as IFeatureWorkspace;

                if (featureWorkspace == null)
                {
                    message.AddError(120011, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nofeatureworkspace"), Container));
                    return;
                }

                // load the descriptions from which to derive the domain values
                OSMDomains availableDomains = null;

                System.Xml.XmlTextReader reader = null;
                try
                {
                    if (File.Exists(m_editorConfigurationSettings["osmdomainsfilepath"]))
                    {
                        reader = new System.Xml.XmlTextReader(m_editorConfigurationSettings["osmdomainsfilepath"]);
                    }
                }
                // If is in the server and hasn't been install all the configuration files
                catch
                {
                    if (File.Exists(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(OSMGPDownload)).Location), "osm_domains.xml")))
                    {
                        reader = new System.Xml.XmlTextReader(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(OSMGPDownload)).Location), "osm_domains.xml"));
                    }
                }

                if (reader == null)
                {
                    message.AddError(120012, resourceManager.GetString("GPTools_OSMGPDownload_NoDomainConfigFile"));
                    return;
                }

                try
                {
                    serializer = new XmlSerializer(typeof(OSMDomains));
                    availableDomains = serializer.Deserialize(reader) as OSMDomains;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    System.Diagnostics.Debug.WriteLine(ex.StackTrace);
                    message.AddError(120013, ex.Message);
                    return;
                }

                #region define and add domains to the workspace
                // we are using domains to guide the edit templates in the editor for ArcGIS desktop
                Dictionary<string, IDomain> codedValueDomains = new Dictionary<string, IDomain>();

                foreach (var domain in availableDomains.domain)
                {
                    ICodedValueDomain pointCodedValueDomain = new CodedValueDomainClass();
                    ((IDomain)pointCodedValueDomain).Name = domain.name + "_pt";
                    ((IDomain)pointCodedValueDomain).FieldType = esriFieldType.esriFieldTypeString;

                    ICodedValueDomain lineCodedValueDomain = new CodedValueDomainClass();
                    ((IDomain)lineCodedValueDomain).Name = domain.name + "_ln";
                    ((IDomain)lineCodedValueDomain).FieldType = esriFieldType.esriFieldTypeString;

                    ICodedValueDomain polygonCodedValueDomain = new CodedValueDomainClass();
                    ((IDomain)polygonCodedValueDomain).Name = domain.name + "_ply";
                    ((IDomain)polygonCodedValueDomain).FieldType = esriFieldType.esriFieldTypeString;

                    for (int i = 0; i < domain.domainvalue.Length; i++)
                    {
                        for (int domainGeometryIndex = 0; domainGeometryIndex < domain.domainvalue[i].geometrytype.Length; domainGeometryIndex++)
                        {
                            switch (domain.domainvalue[i].geometrytype[domainGeometryIndex])
                            {
                                case geometrytype.point:
                                    pointCodedValueDomain.AddCode(domain.domainvalue[i].value, domain.domainvalue[i].value);
                                    break;
                                case geometrytype.line:
                                    lineCodedValueDomain.AddCode(domain.domainvalue[i].value, domain.domainvalue[i].value);
                                    break;
                                case geometrytype.polygon:
                                    polygonCodedValueDomain.AddCode(domain.domainvalue[i].value, domain.domainvalue[i].value);
                                    break;
                                default:
                                    break;
                            }
                        }
                    }

                    // add the domain tables to the domains collection
                    codedValueDomains.Add(((IDomain)pointCodedValueDomain).Name, (IDomain)pointCodedValueDomain);
                    codedValueDomains.Add(((IDomain)lineCodedValueDomain).Name, (IDomain)lineCodedValueDomain);
                    codedValueDomains.Add(((IDomain)polygonCodedValueDomain).Name, (IDomain)polygonCodedValueDomain);
                }

                IWorkspaceDomains workspaceDomain = featureWorkspace as IWorkspaceDomains;
                foreach (var domain in codedValueDomains.Values)
                {
                    IDomain testDomain = null;
                    try
                    {
                        testDomain = workspaceDomain.get_DomainByName(domain.Name);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                        System.Diagnostics.Debug.WriteLine(ex.StackTrace);
                    }

                    if (testDomain == null)
                    {
                        workspaceDomain.AddDomain(domain);
                    }
                }
                #endregion

                IGPEnvironment configKeyword = getEnvironment(envMgr, "configKeyword");
                IGPString gpString = null;
                if (configKeyword != null)
                    gpString = configKeyword.Value as IGPString;

                string storageKeyword = String.Empty;

                if (gpString != null)
                {
                    storageKeyword = gpString.Value;
                }

                IFeatureDataset targetFeatureDataset = null;
                if (gpUtilities3.Exists((IGPValue)targetDEDataset2))
                {
                    targetFeatureDataset = gpUtilities3.OpenDataset((IGPValue)targetDEDataset2) as IFeatureDataset;
                }
                else
                {
                    targetFeatureDataset = featureWorkspace.CreateFeatureDataset(targetDataElement.Name, downloadSpatialReference);
                }


                ESRI.ArcGIS.esriSystem.UID osmClassExtensionUID = new ESRI.ArcGIS.esriSystem.UIDClass();
                //GUID for the OSM feature class extension
                osmClassExtensionUID.Value = "{65CA4847-8661-45eb-8E1E-B2985CA17C78}";


                downloadSpatialReference = ((IGeoDataset)targetFeatureDataset).SpatialReference;
                OSMToolHelper osmToolHelper = new OSMToolHelper();

                #region create point/line/polygon feature classes and tables
                // points
                try
                {
                    osmPointFeatureClass = osmToolHelper.CreatePointFeatureClass((IWorkspace2)featureWorkspace, targetFeatureDataset, targetDataElement.Name + "_osm_pt", null, null, osmClassExtensionUID, storageKeyword, availableDomains, metadataAbstract, metadataPurpose);
                }
                catch (Exception ex)
                {
                    message.AddError(120014, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message));
                    return;
                }

                if (osmPointFeatureClass == null)
                {
                    return;
                }

                // change the property set of the osm class extension to skip any change detection during the initial data load
                osmPointFeatureClass.RemoveOSMClassExtension();

                // lines
                try
                {
                    osmLineFeatureClass = osmToolHelper.CreateLineFeatureClass((IWorkspace2)featureWorkspace, targetFeatureDataset, targetDataElement.Name + "_osm_ln", null, null, osmClassExtensionUID, storageKeyword, availableDomains, metadataAbstract, metadataPurpose);
                }
                catch (Exception ex)
                {
                    message.AddError(120015, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nulllinefeatureclass"), ex.Message));
                    return;
                }

                if (osmLineFeatureClass == null)
                {
                    return;
                }

                // change the property set of the osm class extension to skip any change detection during the initial data load
                osmLineFeatureClass.RemoveOSMClassExtension();

                // polygons
                try
                {
                    osmPolygonFeatureClass = osmToolHelper.CreatePolygonFeatureClass((IWorkspace2)featureWorkspace, targetFeatureDataset, targetDataElement.Name + "_osm_ply", null, null, osmClassExtensionUID, storageKeyword, availableDomains, metadataAbstract, metadataPurpose);
                }
                catch (Exception ex)
                {
                    message.AddError(120016, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpolygonfeatureclass"), ex.Message));
                    return;
                }

                if (osmPolygonFeatureClass == null)
                {
                    return;
                }

                // change the property set of the osm class extension to skip any change detection during the initial data load
                osmPolygonFeatureClass.RemoveOSMClassExtension();

                // relation table
                ITable relationTable = null;

                try
                {
                    relationTable = osmToolHelper.CreateRelationTable((IWorkspace2)featureWorkspace, targetDataElement.Name + "_osm_relation", null, storageKeyword, metadataAbstract, metadataPurpose);
                }
                catch (Exception ex)
                {
                    message.AddError(120017, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullrelationtable"), ex.Message));
                    return;
                }

                if (relationTable == null)
                {
                    return;
                }

                // revision table 
                ITable revisionTable = null;

                try
                {
                    revisionTable = osmToolHelper.CreateRevisionTable((IWorkspace2)featureWorkspace, targetDataElement.Name + "_osm_revision", null, storageKeyword);
                }
                catch (Exception ex)
                {
                    message.AddError(120018, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullrelationtable"), ex.Message));
                    return;
                }

                if (revisionTable == null)
                {
                    return;
                }

                // check for user interruption
                if (TrackCancel.Continue() == false)
                {
                    return;
                }
                #endregion

                #region clean any existing data from loading targets
                ESRI.ArcGIS.Geoprocessing.IGeoProcessor2 gp = new ESRI.ArcGIS.Geoprocessing.GeoProcessorClass();
                IGeoProcessorResult gpResult = new GeoProcessorResultClass();

                try
                {
                    IVariantArray truncateParameters = new VarArrayClass();
                    truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "\\" + targetDataElement.Name + "_osm_pt");
                    gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel);

                    truncateParameters = new VarArrayClass();
                    truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "\\" + targetDataElement.Name + "_osm_ln");
                    gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel);

                    truncateParameters = new VarArrayClass();
                    truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "\\" + targetDataElement.Name + "_osm_ply");
                    gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel);

                    truncateParameters = new VarArrayClass();
                    truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "_osm_relation");
                    gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel);

                    truncateParameters = new VarArrayClass();
                    truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "_osm_revision");
                    gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel);
                }
                catch (Exception ex)
                {
                    message.AddWarning(ex.Message);
                }
                #endregion

                Dictionary<string, OSMToolHelper.simplePointRef> osmNodeDictionary = null;

                foreach (string osmDownloadDocument in downloadedOSMDocuments.Reverse<string>())
                {
                    long nodeCapacity = 0;
                    long wayCapacity = 0;
                    long relationCapacity = 0;

                    message.AddMessage(resourceManager.GetString("GPTools_OSMGPFileReader_countingNodes"));

                    osmToolHelper.countOSMStuff(osmDownloadDocument, ref nodeCapacity, ref wayCapacity, ref relationCapacity, ref TrackCancel);
                    message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_countedElements"), nodeCapacity, wayCapacity, relationCapacity));

                    if (osmNodeDictionary == null)
                        osmNodeDictionary = new Dictionary<string, OSMToolHelper.simplePointRef>(Convert.ToInt32(nodeCapacity));

                    #region load points
                    osmToolHelper.loadOSMNodes(osmDownloadDocument, ref TrackCancel, ref message, targetDatasetGPValue, osmPointFeatureClass, false, false, Convert.ToInt32(nodeCapacity), ref osmNodeDictionary, featureWorkspace, downloadSpatialReference, availableDomains, false);
                    #endregion

                    if (TrackCancel.Continue() == false)
                    {
                        return;
                    }

                    #region load ways
                    if (wayCapacity > 0)
                    {
                        List<string> missingWays = null;
                        missingWays = osmToolHelper.loadOSMWays(osmDownloadDocument, ref TrackCancel, ref message, targetDatasetGPValue, osmPointFeatureClass, osmLineFeatureClass, osmPolygonFeatureClass, false, false, Convert.ToInt32(wayCapacity), ref osmNodeDictionary, featureWorkspace, downloadSpatialReference, availableDomains, false);
                    }
                    #endregion

                    if (TrackCancel.Continue() == false)
                    {
                        return;
                    }

                    # region for conserve memory condition, update refcount
                    int refCounterFieldIndex = osmPointFeatureClass.Fields.FindField("wayRefCount");
                    if (refCounterFieldIndex > -1)
                    {
                        foreach (var refNode in osmNodeDictionary)
                        {
                            try
                            {
                                IFeature updateFeature = osmPointFeatureClass.GetFeature(refNode.Value.pointObjectID);

                                int refCount = refNode.Value.RefCounter;
                                if (refCount == 0)
                                {
                                    refCount = 1;
                                }

                                updateFeature.set_Value(refCounterFieldIndex, refCount);
                                updateFeature.Store();
                            }
                            catch { }
                        }
                    }

                    #endregion

                    // check for user interruption
                    if (TrackCancel.Continue() == false)
                    {
                        return;
                    }
                    ESRI.ArcGIS.Geoprocessor.Geoprocessor geoProcessor = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();

                    #region for local geodatabases enforce spatial integrity
                    bool storedOriginal = geoProcessor.AddOutputsToMap;
                    geoProcessor.AddOutputsToMap = false;

                    try
                    {
                        if (osmLineFeatureClass != null)
                        {
                            if (((IDataset)osmLineFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace)
                            {
                                IVariantArray lineRepairParameters = new VarArrayClass();
                                lineRepairParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "\\" + targetDataElement.Name + "_osm_ln");
                                lineRepairParameters.Add("DELETE_NULL");

                                IGeoProcessorResult2 gpResults = gp.Execute("RepairGeometry_management", lineRepairParameters, TrackCancel) as IGeoProcessorResult2;
                                message.AddMessages(gpResults.GetResultMessages());
                            }
                        }

                        if (osmPolygonFeatureClass != null)
                        {
                            if (((IDataset)osmPolygonFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace)
                            {
                                IVariantArray polygonRepairParameters = new VarArrayClass();
                                polygonRepairParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "\\" + targetDataElement.Name + "_osm_ply");
                                polygonRepairParameters.Add("DELETE_NULL");

                                IGeoProcessorResult2 gpResults = gp.Execute("RepairGeometry_management", polygonRepairParameters, TrackCancel) as IGeoProcessorResult2;
                                message.AddMessages(gpResults.GetResultMessages());
                            }
                        }
                    }
                    catch
                    {
                        message.AddWarning(resourceManager.GetString("GPTools_OSMGPDownload_repairgeometryfailure"));
                    }
                    geoProcessor.AddOutputsToMap = storedOriginal;
                    #endregion



                    #region load relations
                    if (relationCapacity > 0)
                    {
                        List<string> missingRelations = null;
                        missingRelations = osmToolHelper.loadOSMRelations(osmDownloadDocument, ref TrackCancel, ref message, targetDatasetGPValue, osmPointFeatureClass, osmLineFeatureClass, osmPolygonFeatureClass, Convert.ToInt32(relationCapacity), relationTable, availableDomains, false, false);
                    }
                    #endregion
                }

                #region update the references counts and member lists for nodes
                message.AddMessage(resourceManager.GetString("GPTools_OSMGPFileReader_updatereferences"));
                IFeatureCursor pointUpdateCursor = null;

                using (SchemaLockManager ptLockManager = new SchemaLockManager(osmPointFeatureClass as ITable))
                {
                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        int updateCount = 0;
                        pointUpdateCursor = osmPointFeatureClass.Update(null, false);
                        updateCount = ((ITable)osmPointFeatureClass).RowCount(null);

                        IStepProgressor stepProgressor = TrackCancel as IStepProgressor;

                        if (stepProgressor != null)
                        {
                            stepProgressor.MinRange = 0;
                            stepProgressor.MaxRange = updateCount;
                            stepProgressor.Position = 0;
                            stepProgressor.Message = resourceManager.GetString("GPTools_OSMGPFileReader_updatepointrefcount");
                            stepProgressor.StepValue = 1;
                            stepProgressor.Show();
                        }

                        comReleaser.ManageLifetime(pointUpdateCursor);

                        IFeature pointFeature = pointUpdateCursor.NextFeature();

                        int osmPointIDFieldIndex = osmPointFeatureClass.FindField("OSMID");
                        int osmWayRefCountFieldIndex = osmPointFeatureClass.FindField("wayRefCount");
                        int positionCounter = 0;
                        while (pointFeature != null)
                        {
                            positionCounter++;
                            string nodeID = Convert.ToString(pointFeature.get_Value(osmPointIDFieldIndex));

                            // let get the reference counter from the internal node dictionary
                            if (osmNodeDictionary[nodeID].RefCounter == 0)
                            {
                                pointFeature.set_Value(osmWayRefCountFieldIndex, 1);
                            }
                            else
                            {
                                pointFeature.set_Value(osmWayRefCountFieldIndex, osmNodeDictionary[nodeID].RefCounter);
                            }

                            pointUpdateCursor.UpdateFeature(pointFeature);

                            if (pointFeature != null)
                                Marshal.ReleaseComObject(pointFeature);

                            pointFeature = pointUpdateCursor.NextFeature();

                            if (stepProgressor != null)
                            {
                                stepProgressor.Position = positionCounter;
                            }
                        }

                        if (stepProgressor != null)
                        {
                            stepProgressor.Hide();
                        }
                    }
                }
                #endregion

                // clean all the downloaded OSM files
                foreach (string osmFile in downloadedOSMDocuments)
                {
                    if (File.Exists(osmFile))
                    {
                        try
                        {
                            File.Delete(osmFile);
                        }
                        catch { }
                    }
                }

                SyncState.StoreLastSyncTime(targetDatasetName, syncTime);

                gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3;

                // repackage the feature class into their respective gp values
                IGPParameter pointFeatureClassParameter = paramvalues.get_Element(out_osmPointsNumber) as IGPParameter;
                IGPValue pointFeatureClassPackGPValue = gpUtilities3.UnpackGPValue(pointFeatureClassParameter);
                gpUtilities3.PackGPValue(pointFeatureClassPackGPValue, pointFeatureClassParameter);

                IGPParameter lineFeatureClassParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter;
                IGPValue lineFeatureClassPackGPValue = gpUtilities3.UnpackGPValue(lineFeatureClassParameter);
                gpUtilities3.PackGPValue(lineFeatureClassPackGPValue, lineFeatureClassParameter);

                IGPParameter polygonFeatureClassParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter;
                IGPValue polygon1FeatureClassPackGPValue = gpUtilities3.UnpackGPValue(polygonFeatureClassParameter);
                gpUtilities3.PackGPValue(polygon1FeatureClassPackGPValue, polygonFeatureClassParameter);

                gpUtilities3.ReleaseInternals();
                Marshal.ReleaseComObject(gpUtilities3);

                Marshal.ReleaseComObject(baseURLString);
                Marshal.ReleaseComObject(downloadExtentGPValue);
                Marshal.ReleaseComObject(downloadEnvelope);
                Marshal.ReleaseComObject(includeAllReferences);
                Marshal.ReleaseComObject(downloadSpatialReference);

                if (osmToolHelper != null)
                    osmToolHelper = null;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                System.Diagnostics.Debug.WriteLine(ex.StackTrace);
                message.AddError(120019, ex.Message);
            }
            finally
            {
                try
                {
                    if (osmPointFeatureClass != null)
                    {
                        osmPointFeatureClass.ApplyOSMClassExtension();
                        Marshal.ReleaseComObject(osmPointFeatureClass);
                    }

                    if (osmLineFeatureClass != null)
                    {
                        osmLineFeatureClass.ApplyOSMClassExtension();
                        Marshal.ReleaseComObject(osmLineFeatureClass);
                    }

                    if (osmPolygonFeatureClass != null)
                    {
                        osmPolygonFeatureClass.ApplyOSMClassExtension();
                        Marshal.ReleaseComObject(osmPolygonFeatureClass);
                    }
                }
                catch (Exception ex)
                {
                    message.AddError(120020, ex.ToString());
                }
            }
        }
コード例 #54
0
        private void btOK_Click(object sender, EventArgs e)
        {
            string        pPointFileName   = cboBoxPointLayer.SelectedItem.ToString();
            string        pCenterlinName   = comboBoxExCenterlineLayer.SelectedItem.ToString();
            IFeatureLayer pPointLayer      = null;
            IFeatureLayer pCenterlineLayer = null;

            for (int i = 0; i < pMapcontrol.LayerCount; i++)
            {
                if (pPointFileName == pMapcontrol.get_Layer(i).Name)
                {
                    pPointLayer = pMapcontrol.get_Layer(i) as IFeatureLayer;
                }
                if (pCenterlinName == pMapcontrol.get_Layer(i).Name)
                {
                    pCenterlineLayer = pMapcontrol.get_Layer(i) as IFeatureLayer;
                }
            }
            IFeatureClass  pLineFC      = pCenterlineLayer.FeatureClass;
            IFeatureClass  pPointFC     = pPointLayer.FeatureClass;
            IQueryFilter   pQF          = null;
            IFeatureCursor pLineCursor  = pLineFC.Search(null, false);
            IFeatureCursor pPointCursor = pPointFC.Search(null, false);
            IFeature       pLineFeature = pLineCursor.NextFeature();
            DataTable      ptTable      = AOFunctions.GDB.ITableUtil.GetDataTableFromITable(pPointFC as ITable, pQF);

            ptTable.Columns.Add("长度");
            ptTable.Columns.Add("距离");
            ptTable.Columns.Add("中间点坐标");
            if (pLineFeature != null)
            {
                ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
                //wgs 84
                IGeographicCoordinateSystem wgs84 = spatialReferenceFactory.CreateGeographicCoordinateSystem(4326) as IGeographicCoordinateSystem;
                IUnit     meterUnit = spatialReferenceFactory.CreateUnit((int)ESRI.ArcGIS.Geometry.esriSRUnitType.esriSRUnit_Meter);
                IPolyline pline     = pLineFeature.Shape as IPolyline;
                pline.SpatialReference = wgs84;

                IProximityOperator pPO       = pline as IProximityOperator;
                IFeature           ptFeature = pPointCursor.NextFeature();
                int idx = 0;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(spatialReferenceFactory);
                while (ptFeature != null)
                {
                    DataRow row = ptTable.Rows[idx];
                    IPoint  pt  = ptFeature.Shape as IPoint;
                    pt.SpatialReference = wgs84;
                    IPoint nearestpt = pPO.ReturnNearestPoint(pt, esriSegmentExtension.esriNoExtension);
                    double distance  = DataAlignment.DataAlignment.CalculateDistanceBetween84TwoPoints(pt, nearestpt);
                    // = pPO.ReturnDistance(pt);

                    row["距离"] = distance;
                    if (idx == 0)
                    {
                        row["长度"] = 0;
                    }
                    else
                    {
                        DataRow preRow = ptTable.Rows[idx - 1];
                        row["长度"] = Convert.ToDouble(row[EvConfig.IMUMoveDistanceField]) - Convert.ToDouble(preRow[EvConfig.IMUMoveDistanceField]);
                    }
                    ptFeature = pPointCursor.NextFeature();
                    idx++;
                }
                System.Runtime.InteropServices.Marshal.ReleaseComObject(spatialReferenceFactory);
            }


            DataTable dt2 = new DataTable();

            dt2.Columns.Add("名称");
            dt2.Columns.Add("长度");
            dt2.Columns.Add("比例");

            //  List<DataRow> rowlist = (dt2.Rows.Where(e => Convert.ToDouble(e["距离"]) <= 2)).ToList();

            List <DataRow> less1 = (from DataRow r in ptTable.Rows
                                    where Convert.ToDouble(r["距离"]) <= 1
                                    select r).ToList();
            double length1 = less1.Sum(x => Convert.ToDouble(x["长度"]));
            int    sum1    = less1.Count;

            List <DataRow> Great2 = (from DataRow r in ptTable.Rows
                                     where Convert.ToDouble(r["距离"]) > 2
                                     select r).ToList();
            double length2 = Great2.Sum(x => Convert.ToDouble(x["长度"]));
            int    sum2    = Great2.Count;

            List <DataRow> Medium2 = (from DataRow r in ptTable.Rows
                                      where Convert.ToDouble(r["距离"]) > 1 && Convert.ToDouble(r["距离"]) <= 2
                                      select r).ToList();
            double length3 = Medium2.Sum(x => Convert.ToDouble(x["长度"]));
            int    sum3    = Medium2.Count;

            DataRow r1;

            r1    = dt2.Rows.Add();
            r1[0] = "≤1米";
            r1[1] = length1;
            r1[2] = 1.0 * sum1 / (sum1 + sum2 + sum3);

            r1    = dt2.Rows.Add();
            r1[0] = ">1米且≤2米";
            r1[1] = length3;
            r1[2] = 1.0 * sum3 / (sum1 + sum2 + sum3);


            r1    = dt2.Rows.Add();
            r1[0] = "大于2米";
            r1[1] = length2;
            r1[2] = 1.0 * sum2 / (sum1 + sum2 + sum3);


            List <DataTable> tablelist = new List <DataTable>();

            tablelist.Add(ptTable);
            tablelist.Add(dt2);

            FRMInsideInspectionReport frm = new FRMInsideInspectionReport(tablelist);

            frm.ShowDialog();
        }
コード例 #55
0
 public static IPoint JWD2XY(IPoint pJWDPoint, int gcsType, int pcsType)
 {
     try
     {
         ISpatialReferenceFactory factory = new SpatialReferenceEnvironmentClass();
         pJWDPoint.SpatialReference = factory.CreateGeographicCoordinateSystem(gcsType);
         pJWDPoint.Project(factory.CreateProjectedCoordinateSystem(pcsType));
         return pJWDPoint;
     }
     catch
     {
         return null;
     }
 }
コード例 #56
0
        private void frmGaphicTransformation_Load(object sender, EventArgs e)
        {
            int num;

            for (num = 0; num < this.igeoTransformation_0.Length; num++)
            {
                this.cboHCSTransformMethod.Items.Add(new Class1(this.igeoTransformation_0[num], this.string_0[num]));
            }
            this.cboTargetGCS.Items.Clear();
            ISpatialReferenceFactory factory   = new SpatialReferenceEnvironmentClass();
            ISpatialReference        reference = null;

            for (num = 0; num < this.int_0.Length; num++)
            {
                reference = factory.CreateGeographicCoordinateSystem(this.int_0[num]);
                this.cboTargetGCS.Items.Add(new ObjectWrap(reference));
            }
            if (this.ispatialReference_1 != null)
            {
                this.cboTargetGCS.Text    = this.ispatialReference_1.Name;
                this.cboTargetGCS.Enabled = false;
            }
            else
            {
                this.cboTargetGCS.SelectedIndex = 0;
            }
            this.txtName.Text = "新装换";
            this.paramlistView.ValueChanged += new ValueChangedHandler(this.method_0);
            if (this.ispatialReference_0 is IProjectedCoordinateSystem)
            {
                this.txtSourGCS.Text =
                    (this.ispatialReference_0 as IProjectedCoordinateSystem).GeographicCoordinateSystem.Name;
                this.txtSourGCS.Tag =
                    (this.ispatialReference_0 as IProjectedCoordinateSystem).GeographicCoordinateSystem;
            }
            else if (this.ispatialReference_0 is IGeographicCoordinateSystem)
            {
                this.txtSourGCS.Text = this.ispatialReference_0.Name;
                this.txtSourGCS.Tag  = this.ispatialReference_0;
            }
            this.bool_0 = true;
            if (this.igeoTransformation_1 != null)
            {
                this.txtName.Text = this.igeoTransformation_1.Name;
                if (this.igeoTransformation_1 is ICoordinateFrameTransformation)
                {
                    this.cboHCSTransformMethod.SelectedIndex = 4;
                }
                else if (this.igeoTransformation_1 is IMolodenskyTransformation)
                {
                    if (this.igeoTransformation_1 is MolodenskyTransformationClass)
                    {
                        this.cboHCSTransformMethod.SelectedIndex = 1;
                    }
                    else if (this.igeoTransformation_1 is AbridgedMolodenskyTransformationClass)
                    {
                        this.cboHCSTransformMethod.SelectedIndex = 2;
                    }
                }
                else if (this.igeoTransformation_1 is IGeocentricTranslation)
                {
                    this.cboHCSTransformMethod.SelectedIndex = 0;
                }
                else if (this.igeoTransformation_1 is IPositionVectorTransformation)
                {
                    this.cboHCSTransformMethod.SelectedIndex = 3;
                }
                else if (this.igeoTransformation_1 is IGridTransformation)
                {
                    if (this.igeoTransformation_1 is NADCONTransformationClass)
                    {
                        this.cboHCSTransformMethod.SelectedIndex = 5;
                    }
                    else if (this.igeoTransformation_1 is HARNTransformationClass)
                    {
                        this.cboHCSTransformMethod.SelectedIndex = 6;
                    }
                }
                else if (this.igeoTransformation_1 is ILongitudeRotationTransformation)
                {
                    this.cboHCSTransformMethod.SelectedIndex = 7;
                }
                this.cboHCSTransformMethod.Enabled = false;
            }
            else
            {
                this.cboHCSTransformMethod.SelectedIndex = 0;
            }
        }
コード例 #57
0
        public void Startup(ref object initializationData)
        {
            try
            {
                m_application = initializationData as IApplication;
                if (m_application == null)
                    return;

                ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass() as ISpatialReferenceFactory;
                m_wgs84 = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984) as ISpatialReference;

                //Get the editor.
                UID editorUid = new UID();
                editorUid.Value = "esriEditor.Editor";
                m_editor3 = m_application.FindExtensionByCLSID(editorUid) as IEditor3;
                m_editEvents2 = m_editor3 as IEditEvents2_Event;
                m_editEvents = m_editor3 as IEditEvents_Event;

                m_editEvents.OnCreateFeature += new IEditEvents_OnCreateFeatureEventHandler(m_editEvents_OnCreateFeature);
                m_editEvents.OnChangeFeature += new IEditEvents_OnChangeFeatureEventHandler(m_editEvents_OnChangeFeature);
                m_editEvents.OnDeleteFeature += new IEditEvents_OnDeleteFeatureEventHandler(m_editEvents_OnDeleteFeature);
                m_editEvents.OnStartEditing += new IEditEvents_OnStartEditingEventHandler(m_editEvents_OnStartEditing);

                resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.Editor.OSMFeatureInspectorStrings", this.GetType().Assembly);
                _osmUtility = new OSMClassExtension.OSMUtility();

                // retrtrieve osm editor specfic information
                m_editorConfigurationSettings = OSMGPFactory.ReadOSMEditorSettings();
            }
            catch { }
        }
コード例 #58
0
        /// <summary>
        /// shape图层入库
        /// </summary>
        /// <param name="sourceworkspace"></param>
        /// <param name="targetworkspace"></param>
        /// <param name="nameOfsourceFeatureClass"></param>
        /// <param name="nameOftargetFeatureClass"></param>
        /// <returns></returns>
        public IFeatureClass ShapeFileIntoGDB(IWorkspace sourceworkspace, IWorkspace targetworkspace,
                                              string nameOfsourceFeatureClass, string nameOftargetFeatureClass)
        {
            try
            {
                //创建源工作空间
                IDataset       sourceWorkspaceDataset = (IDataset)sourceworkspace;
                IWorkspaceName sourceWorkspaceName    = (IWorkspaceName)sourceWorkspaceDataset.FullName;

                //创建源数据集
                IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass();
                IDatasetName      sourceDatasetName      = (IDatasetName)sourceFeatureClassName;
                sourceDatasetName.WorkspaceName = sourceWorkspaceName;
                sourceDatasetName.Name          = nameOfsourceFeatureClass;

                //创建目标工作空间
                IDataset       targetWorkspaceDataset = (IDataset)targetworkspace;
                IWorkspaceName targetWorkspaceName    = (IWorkspaceName)targetWorkspaceDataset.FullName;

                //创建目标数据集
                IFeatureClassName targetFeatureClassName = new FeatureClassNameClass();
                IDatasetName      targetDatasetName      = (IDatasetName)targetFeatureClassName;
                targetDatasetName.WorkspaceName = targetWorkspaceName;
                targetDatasetName.Name          = nameOftargetFeatureClass;

                //源数据集的字段集
                IName         sourceName         = (IName)sourceFeatureClassName;
                IFeatureClass sourceFeatureClass = (IFeatureClass)sourceName.Open();

                //验证字段
                IFieldChecker   fieldChecker = new FieldCheckerClass();
                IFields         targetFeatureClassFields;
                IFields         sourceFeatureClassFields = sourceFeatureClass.Fields;
                IEnumFieldError enumFieldError;

                //设置验证的对象
                fieldChecker.InputWorkspace    = sourceworkspace;
                fieldChecker.ValidateWorkspace = targetworkspace;
                fieldChecker.Validate(sourceFeatureClassFields, out enumFieldError, out targetFeatureClassFields);

                //找到空间对象字段
                IField geometryField;
                for (int i = 0; i < targetFeatureClassFields.FieldCount; i++)
                {
                    if (targetFeatureClassFields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        geometryField = targetFeatureClassFields.get_Field(i);

                        //得到空间字段的定义
                        IGeometryDef geometryDef = geometryField.GeometryDef;

                        //得到空间字段的索引
                        IGeometryDefEdit targetFCGeometryDefEdit = (IGeometryDefEdit)geometryDef;
                        targetFCGeometryDefEdit.GridCount_2 = 1;
                        targetFCGeometryDefEdit.set_GridSize(0, 0);
                        //targetFCGeometryDefEdit.SpatialReference_2 = geometryField.GeometryDef.SpatialReference;

                        ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
                        ISpatialReference        spatialReference        = DataEditCommon.g_pMap.SpatialReference;
                        //spatialReferenceFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_NAD1983UTM_20N);
                        ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference;
                        spatialReferenceResolution.ConstructFromHorizon();
                        spatialReferenceResolution.SetDefaultXYResolution();
                        spatialReferenceResolution.SetDefaultZResolution();
                        ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference;
                        spatialReferenceTolerance.SetMinimumXYTolerance();
                        spatialReferenceTolerance.SetMinimumZTolerance();

                        double XMin, XMax, YMin, YMax, ZMin, ZMax, MinXYTolerance, MinZTolerance;
                        XMin = 4054.3603997438;
                        XMax = 78088.6926632544;
                        YMin = 14424.8510028409;
                        YMax = 59609.4812606697;
                        ZMin = 30330.1483519995;
                        ZMax = 38389.3283520005;
                        //spatialReference.SetDomain(XMin, XMax, YMin, YMax);
                        //spatialReference.SetZDomain(ZMin, ZMax);

                        MinXYTolerance = 0.000000000008219;
                        MinZTolerance  = 0.000000000007629;
                        //spatialReferenceTolerance.SetMinimumZTolerance( MinXYTolerance);

                        //spatialReference.GetDomain(out XMin, out XMax, out YMin, out YMax);
                        //spatialReference.GetZDomain(out ZMin, out ZMax);


                        targetFCGeometryDefEdit.SpatialReference_2 = spatialReference;


                        //开始导入
                        IQueryFilter queryFilter = new QueryFilterClass();
                        queryFilter.WhereClause = "";

                        //导入所有的输入对象
                        IFeatureDataConverter featureDataConverter = new FeatureDataConverterClass();
                        IEnumInvalidObject    enumInvalidObject    = featureDataConverter.ConvertFeatureClass(sourceFeatureClassName,
                                                                                                              queryFilter, null, targetFeatureClassName, geometryDef, targetFeatureClassFields, "", 1000, 0);
                        break;
                    }
                }

                //导入后数据集的字段集
                IName         targetName         = (IName)targetFeatureClassName;
                IFeatureClass targetFeatureClass = (IFeatureClass)targetName.Open();

                return(targetFeatureClass);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
コード例 #59
0
        public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
        {
            IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

            // check for a valid download url
            IGPParameter downloadURLParameter = paramvalues.get_Element(in_downloadURLNumber) as IGPParameter;

            if (downloadURLParameter.HasBeenValidated == false)
            {
                IGPString downloadURLGPString = downloadURLParameter.Value as IGPString;


                if (downloadURLGPString != null)
                {
                    if (String.IsNullOrEmpty(downloadURLGPString.Value) == false)
                    {
                        try
                        {
                            Uri downloadURI = new Uri(downloadURLGPString.Value);


                            // attempt a download request from the given URL to get the server capabilities
                            m_osmAPICapabilities = CheckValidServerURL(downloadURLGPString.Value);

                            // if we can construct a valid URI  class then we are accepting the value and store it in the user settings as well
                            if (m_editorConfigurationSettings != null)
                            {
                                if (m_editorConfigurationSettings.ContainsKey("osmbaseurl"))
                                {
                                    m_editorConfigurationSettings["osmbaseurl"] = downloadURLGPString.Value;
                                }
                                else
                                {
                                    m_editorConfigurationSettings.Add("osmbaseurl", downloadURLGPString.Value);
                                }

                                OSMGPFactory.StoreOSMEditorSettings(m_editorConfigurationSettings);
                            }
                        }
                        catch (Exception ex)
                        {
                            StringBuilder errorMessage = new StringBuilder();
                            errorMessage.AppendLine(resourceManager.GetString("GPTools_OSMGPDownload_invaliddownloadurl"));
                            errorMessage.AppendLine(ex.Message);
                            Messages.ReplaceError(in_downloadURLNumber, -3, errorMessage.ToString());
                            m_osmAPICapabilities = null;
                        }
                    }
                }
            }


            if (m_osmAPICapabilities == null)
            {
                return;
            }

            // check for extent
            IGPParameter downloadExtentParameter = paramvalues.get_Element(in_downloadExtentNumber) as IGPParameter;

            if (downloadExtentParameter.HasBeenValidated == false)
            {
                IGPValue downloadExtent = gpUtilities3.UnpackGPValue(downloadExtentParameter);

                if (downloadExtent != null)
                {
                    esriGPExtentEnum gpExtent;
                    IEnvelope downloadEnvelope = gpUtilities3.GetExtent(downloadExtent, out gpExtent);

                    if (downloadEnvelope == null)
                        return;

                    if (downloadEnvelope.IsEmpty == true)
                        return;

                    ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass() as ISpatialReferenceFactory;
                    ISpatialReference wgs84 = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984) as ISpatialReference;

                    downloadEnvelope.Project(wgs84);

                    Marshal.ReleaseComObject(wgs84);
                    Marshal.ReleaseComObject(spatialReferenceFactory);

                    IArea downloadArea = downloadEnvelope as IArea;
                    double maximumAcceptableOSMArea = Convert.ToDouble(m_osmAPICapabilities.area.maximum, new CultureInfo("en-US"));

                    if (downloadArea.Area > maximumAcceptableOSMArea)
                    {
                        Messages.ReplaceError(in_downloadExtentNumber, -3, resourceManager.GetString("GPTools_OSMGPDownload_exceedDownloadROI"));
                    }
                }
            }

            // check for valid geodatabase path
            // if the user is pointing to a valid directory on disk, flag it as an error
            IGPParameter targetDatasetParameter = paramvalues.get_Element(out_targetDatasetNumber) as IGPParameter;
            IGPValue targetDatasetGPValue = gpUtilities3.UnpackGPValue(targetDatasetParameter);

            if (targetDatasetGPValue == null)
            {
                Messages.ReplaceError(out_targetDatasetNumber, -98, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), targetDatasetParameter.Name));
            }


            if (targetDatasetGPValue.IsEmpty() == false)
            {
                if (System.IO.Directory.Exists(targetDatasetGPValue.GetAsText()))
                {
                    Messages.ReplaceError(out_targetDatasetNumber, -4, resourceManager.GetString("GPTools_OSMGPDownload_directory_is_not_target_dataset"));
                }
            }

            // check one of the output feature classes for version compatibility
            IGPParameter pointFeatureClassParameter = paramvalues.get_Element(out_osmPointsNumber) as IGPParameter;
            IDEFeatureClass pointDEFeatureClass = gpUtilities3.UnpackGPValue(pointFeatureClassParameter) as IDEFeatureClass;

            if (pointDEFeatureClass != null)
            {
                if (((IGPValue)pointDEFeatureClass).IsEmpty() == false)
                {
                    if (gpUtilities3.Exists((IGPValue)pointDEFeatureClass))
                    {
                        IFeatureClass ptfc = gpUtilities3.Open(gpUtilities3.UnpackGPValue(pointFeatureClassParameter)) as IFeatureClass;
                        IPropertySet osmExtensionPropertySet = ptfc.ExtensionProperties;

                        if (osmExtensionPropertySet == null)
                        {
                            Messages.ReplaceError(out_targetDatasetNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), 1, OSMClassExtensionManager.Version));
                            Messages.ReplaceError(out_osmPointsNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), 1, OSMClassExtensionManager.Version));
                            Messages.ReplaceError(out_osmLinesNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), 1, OSMClassExtensionManager.Version));
                            Messages.ReplaceError(out_osmPolygonsNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), 1, OSMClassExtensionManager.Version));
                        }
                        else
                        {
                            try
                            {
                                int extensionVersion = Convert.ToInt32(osmExtensionPropertySet.GetProperty("VERSION"));

                                object names;
                                object values;
                                osmExtensionPropertySet.GetAllProperties(out names, out values);

                                if (extensionVersion != OSMClassExtensionManager.Version)
                                {
                                    Messages.ReplaceError(out_targetDatasetNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), extensionVersion, OSMClassExtensionManager.Version));
                                    Messages.ReplaceError(out_osmPointsNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), extensionVersion, OSMClassExtensionManager.Version));
                                    Messages.ReplaceError(out_osmLinesNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), extensionVersion, OSMClassExtensionManager.Version));
                                    Messages.ReplaceError(out_osmPolygonsNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), extensionVersion, OSMClassExtensionManager.Version));
                                }
                            }
                            catch
                            {
                                Messages.ReplaceError(out_targetDatasetNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), 1, OSMClassExtensionManager.Version));
                                Messages.ReplaceError(out_osmPointsNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), 1, OSMClassExtensionManager.Version));
                                Messages.ReplaceError(out_osmLinesNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), 1, OSMClassExtensionManager.Version));
                                Messages.ReplaceError(out_osmPolygonsNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), 1, OSMClassExtensionManager.Version));
                            }
                        }
                    }
                }
            }
        }
コード例 #60
0
        /// <summary>
        /// 从srid获取投影坐标系统
        /// </summary>
        /// <param name="srid"></param>
        /// <returns></returns>
        public static IProjectedCoordinateSystem getPcsById(int srid)
        {
            ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();

            return(spatialReferenceFactory.CreateProjectedCoordinateSystem(SRID));
        }