Пример #1
0
        public override bool Work()
        {
            base.Work();
            if (!Init())
            {
                Finish();
                return(false);
            }
            var current = 1;

            foreach (var item in _files)
            {
                try
                {
                    StepProgressor.Message = string.Format("{0}/{1}——正在分析文件:{2}", current++, _files.Count, System.IO.Path.GetFileNameWithoutExtension(item));
                    CanContinue            = TrackCancel.Continue();
                    if (!CanContinue)
                    {
                        break;
                    }
                    Analyze(item);
                }catch (Exception ex)
                {
                    _errors.Add(string.Format("分析文件:{0}发生错误,错误详情:{1}", item, ex.ToString()));
                }
            }

            Finish();
            return(true);
        }
Пример #2
0
        public override bool Work()
        {
            base.Work();
            if (!Init())
            {
                ProgressDialog.HideDialog();
                return(false);
            }
            foreach (var item in _files)
            {
                Count++;
                StepProgressor.Message = string.Format("正在分析{0},进度{1}/{2}", System.IO.Path.GetFileNameWithoutExtension(item), Count, _files.Count);
                CanContinue            = TrackCancel.Continue();
                if (!CanContinue)
                {
                    break;
                }


                try
                {
                    var tables = GetTableNames(item);
                    if (tables.Count > 0)
                    {
                        foreach (var tableName in tables)
                        {
                            var fields    = GainField(item, tableName);
                            var fieldList = new List <string>();
                            foreach (var a in _fields)
                            {
                                if (fields.Contains(a))
                                {
                                    fieldList.Add(a);
                                }
                            }
                            var temp = Prgram(item, tableName, fieldList.ToArray());
                            if (temp.Count > 0)
                            {
                                Save(temp, tableName, _saveFilePath);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Copy(item, _folder);
                }

                StepProgressor.Step();
            }
            ProgressDialog.HideDialog();
            return(true);
        }
        public override bool Work()
        {
            base.Work();
            if (!Init())
            {
                ProgressDialog.HideDialog();
                Error = string.Format("初始化错误:{0}", Error);
                return(false);
            }
            var list = new List <int>();
            var shps = new List <string>();

            for (var i = 0; i < Layers.Count; i++)
            {
                StepProgressor.Message = string.Format("正在对图层:{0}进行分析", Layers[i]);
                CanContinue            = TrackCancel.Continue();
                if (!CanContinue)
                {
                    break;
                }
                try
                {
                    // ConstructPolygon(System.IO.Path.GetDirectoryName(CADFilePath), System.IO.Path.GetFileNameWithoutExtension(CADFilePath), i, LayerField, Layers[i]);
                    var result          = SelectPolyline(System.IO.Path.GetDirectoryName(CADFilePath), System.IO.Path.GetFileNameWithoutExtension(CADFilePath), i, LayerField, Layers[i]);
                    var polygonfilepath = string.Format("{0}\\{1}_1.shp", System.IO.Path.GetDirectoryName(result), System.IO.Path.GetFileNameWithoutExtension(result));
                    if (TranslatePolylineToPolygon(result, polygonfilepath, Layers[i]))
                    {
                        shps.Add(polygonfilepath);
                    }
                    list.Add(i);
                } catch (Exception ex)
                {
                }
                StepProgressor.Step();
            }
            if (shps.Count > 0)
            {
                Merge(shps, SaveFilePath);
            }

            // ContractPolygon(shps, SaveFilePath);
            // Merge(System.IO.Path.GetDirectoryName(CADFilePath), list, System.IO.Path.GetFileNameWithoutExtension(CADFilePath));
            ProgressDialog.HideDialog();
            return(true);
        }
Пример #4
0
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            try
            {
                IGPUtilities3 execute_Utilities = new GPUtilitiesClass();

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

                IGPParameter inputOSMParameter = paramvalues.get_Element(in_osmFeatureClass) as IGPParameter;
                IGPValue     inputOSMGPValue   = execute_Utilities.UnpackGPValue(inputOSMParameter);

                IGPParameter  tagCollectionParameter = paramvalues.get_Element(in_attributeSelector) as IGPParameter;
                IGPMultiValue tagCollectionGPValue   = execute_Utilities.UnpackGPValue(tagCollectionParameter) as IGPMultiValue;

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

                bool useUpdateCursor = false;

                IFeatureClass osmFeatureClass = null;
                ITable        osmInputTable   = null;
                IQueryFilter  osmQueryFilter  = null;

                try
                {
                    execute_Utilities.DecodeFeatureLayer(inputOSMGPValue, out osmFeatureClass, out osmQueryFilter);
                    if (osmFeatureClass != null)
                    {
                        if (osmFeatureClass.Extension is IOSMClassExtension)
                        {
                            useUpdateCursor = false;
                        }
                        else
                        {
                            useUpdateCursor = true;
                        }
                    }

                    osmInputTable = osmFeatureClass as ITable;
                }
                catch { }

                try
                {
                    if (osmInputTable == null)
                    {
                        execute_Utilities.DecodeTableView(inputOSMGPValue, out osmInputTable, out osmQueryFilter);
                    }
                }
                catch { }

                if (osmInputTable == null)
                {
                    string errorMessage = String.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelecto_unableopentable"), inputOSMGPValue.GetAsText());
                    message.AddError(120053, errorMessage);
                    return;
                }

                // find the field that holds tag binary/xml field
                int osmTagCollectionFieldIndex = osmInputTable.FindField("osmTags");


                // if the Field doesn't exist - wasn't found (index = -1) get out
                if (osmTagCollectionFieldIndex == -1)
                {
                    message.AddError(120005, resourceManager.GetString("GPTools_OSMGPAttributeSelector_notagfieldfound"));
                    return;
                }

                // check if the tag collection includes the keyword "ALL", if does then we'll need to extract all tags
                bool extractAll = false;
                for (int valueIndex = 0; valueIndex < tagCollectionGPValue.Count; valueIndex++)
                {
                    if (tagCollectionGPValue.get_Value(valueIndex).GetAsText().Equals("ALL"))
                    {
                        extractAll = true;
                        break;
                    }
                }
                //if (extractAll)
                //{
                //    if (osmTagKeyCodedValues == null)
                //        extractAllTags(ref osmTagKeyCodedValues, osmInputTable, osmQueryFilter, osmTagCollectionFieldIndex, false);

                //    if (osmTagKeyCodedValues == null)
                //    {
                //        message.AddAbort(resourceManager.GetString("GPTools_OSMGPAttributeSelector_Unable2RetrieveTags"));
                //        return;
                //    }

                //    // empty the existing gp multivalue object
                //    tagCollectionGPValue = new GPMultiValueClass();

                //    // fill the coded domain in gp multivalue object
                //    for (int valueIndex = 0; valueIndex < osmTagKeyCodedValues.CodeCount; valueIndex++)
                //    {
                //        tagCollectionGPValue.AddValue(osmTagKeyCodedValues.get_Value(valueIndex));
                //    }
                //}

                // get an overall feature count as that determines the progress indicator
                int featureCount = osmInputTable.RowCount(osmQueryFilter);

                // set up the progress indicator
                IStepProgressor stepProgressor = TrackCancel as IStepProgressor;

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

                // let's get all the indices of the desired fields
                // if the field already exists get the index and if it doesn't exist create it
                Dictionary <string, int> tagsAttributesIndices = new Dictionary <string, int>();
                Dictionary <int, int>    attributeFieldLength  = new Dictionary <int, int>();

                IFeatureWorkspaceManage featureWorkspaceManage = ((IDataset)osmInputTable).Workspace as IFeatureWorkspaceManage;

                String illegalCharacters = String.Empty;

                ISQLSyntax sqlSyntax = ((IDataset)osmInputTable).Workspace as ISQLSyntax;
                if (sqlSyntax != null)
                {
                    illegalCharacters = sqlSyntax.GetInvalidCharacters();
                }

                IFieldsEdit fieldsEdit = osmInputTable.Fields as IFieldsEdit;


                using (SchemaLockManager lockMgr = new SchemaLockManager(osmInputTable))
                {
                    try
                    {
                        string tagKey = String.Empty;
                        ESRI.ArcGIS.Geoprocessing.IGeoProcessor2 gp = new ESRI.ArcGIS.Geoprocessing.GeoProcessorClass();

                        // if we have explicitly defined tags to extract then go through the list of values now
                        if (extractAll == false)
                        {
                            for (int valueIndex = 0; valueIndex < tagCollectionGPValue.Count; valueIndex++)
                            {
                                if (TrackCancel.Continue() == false)
                                {
                                    return;
                                }

                                try
                                {
                                    // Check if the input field already exists.
                                    string nameofTag = tagCollectionGPValue.get_Value(valueIndex).GetAsText();
                                    tagKey = convert2AttributeFieldName(nameofTag, illegalCharacters);

                                    int fieldIndex = osmInputTable.FindField(tagKey);

                                    if (fieldIndex < 0)
                                    {
                                        // generate a new attribute field
                                        IFieldEdit fieldEdit = new FieldClass();
                                        fieldEdit.Name_2      = tagKey;
                                        fieldEdit.AliasName_2 = nameofTag + resourceManager.GetString("GPTools_OSMGPAttributeSelector_aliasaddition");
                                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                                        fieldEdit.Length_2    = 100;

                                        osmInputTable.AddField(fieldEdit);

                                        message.AddMessage(string.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelector_addField"), tagKey, nameofTag));

                                        // re-generate the attribute index
                                        fieldIndex = osmInputTable.FindField(tagKey);
                                    }

                                    if (fieldIndex > 0)
                                    {
                                        tagsAttributesIndices.Add(nameofTag, fieldIndex);
                                        attributeFieldLength.Add(fieldIndex, osmInputTable.Fields.get_Field(fieldIndex).Length);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    // the key is already there, this might result because from multiple upper and lower-case combinations of the same key
                                    message.AddWarning(ex.Message + " (" + convert2OSMKey(tagKey, illegalCharacters) + ")");
                                }
                            }
                        }
                        else
                        {
                            List <string> listofAllTags = extractAllTags(osmInputTable, osmQueryFilter, osmTagCollectionFieldIndex);

                            foreach (string nameOfTag in listofAllTags)
                            {
                                if (TrackCancel.Continue() == false)
                                {
                                    return;
                                }

                                try
                                {
                                    // Check if the input field already exists.
                                    tagKey = convert2AttributeFieldName(nameOfTag, illegalCharacters);

                                    int fieldIndex = osmInputTable.FindField(tagKey);

                                    if (fieldIndex < 0)
                                    {
                                        // generate a new attribute field
                                        IFieldEdit fieldEdit = new FieldClass();
                                        fieldEdit.Name_2      = tagKey;
                                        fieldEdit.AliasName_2 = nameOfTag + resourceManager.GetString("GPTools_OSMGPAttributeSelector_aliasaddition");
                                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                                        fieldEdit.Length_2    = 100;

                                        osmInputTable.AddField(fieldEdit);

                                        message.AddMessage(string.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelector_addField"), tagKey, nameOfTag));

                                        // re-generate the attribute index
                                        fieldIndex = osmInputTable.FindField(tagKey);
                                    }

                                    if (fieldIndex > 0)
                                    {
                                        tagsAttributesIndices.Add(nameOfTag, fieldIndex);
                                        attributeFieldLength.Add(fieldIndex, osmInputTable.Fields.get_Field(fieldIndex).Length);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    // the key is already there, this might result because from multiple upper and lower-case combinations of the same key
                                    message.AddWarning(ex.Message + " (" + convert2OSMKey(tagKey, illegalCharacters) + ")");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        message.AddWarning(ex.Message);
                    }
                }

                try
                {
                    execute_Utilities.DecodeFeatureLayer(inputOSMGPValue, out osmFeatureClass, out osmQueryFilter);
                    if (osmFeatureClass != null)
                    {
                        if (osmFeatureClass.Extension is IOSMClassExtension)
                        {
                            useUpdateCursor = false;
                        }
                        else
                        {
                            useUpdateCursor = true;
                        }
                    }

                    osmInputTable = osmFeatureClass as ITable;
                }
                catch { }

                try
                {
                    if (osmInputTable == null)
                    {
                        execute_Utilities.DecodeTableView(inputOSMGPValue, out osmInputTable, out osmQueryFilter);
                    }
                }
                catch { }

                if (osmInputTable == null)
                {
                    string errorMessage = String.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelecto_unableopentable"), inputOSMGPValue.GetAsText());
                    message.AddError(120053, errorMessage);
                    return;
                }

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    using (SchemaLockManager lockMgr = new SchemaLockManager(osmInputTable))
                    {
                        // get an update cursor for all the features to process
                        ICursor rowCursor = null;
                        if (useUpdateCursor)
                        {
                            rowCursor = osmInputTable.Update(osmQueryFilter, false);
                        }
                        else
                        {
                            rowCursor = osmInputTable.Search(osmQueryFilter, false);
                        }

                        comReleaser.ManageLifetime(rowCursor);

                        IRow osmRow = null;


                        Dictionary <string, string> tagKeys = new Dictionary <string, string>();
                        int progessIndex = 0;
#if DEBUG
                        message.AddMessage("useUpdateCursor: " + useUpdateCursor.ToString());
#endif

                        // as long as there are features....
                        while ((osmRow = rowCursor.NextRow()) != null)
                        {
                            // retrieve the tags of the current feature
                            tag[] storedTags = _osmUtility.retrieveOSMTags(osmRow, osmTagCollectionFieldIndex, ((IDataset)osmInputTable).Workspace);

                            bool rowChanged = false;
                            if (storedTags != null)
                            {
                                foreach (tag tagItem in storedTags)
                                {
                                    // Check for matching values so we only change a minimum number of rows
                                    if (tagsAttributesIndices.ContainsKey(tagItem.k))
                                    {
                                        int fieldIndex = tagsAttributesIndices[tagItem.k];

                                        //...then stored the value in the attribute field
                                        // ensure that the content of the tag actually does fit into the field length...otherwise do truncate it
                                        string tagValue = tagItem.v;

                                        int fieldLength = attributeFieldLength[fieldIndex];

                                        if (tagValue.Length > fieldLength)
                                        {
                                            tagValue = tagValue.Substring(0, fieldLength);
                                        }

                                        osmRow.set_Value(fieldIndex, tagValue);
                                        rowChanged = true;
                                    }
                                    else
                                    {
#if DEBUG
                                        //message.AddWarning(tagItem.k);
#endif
                                    }
                                }
                            }

                            storedTags = null;

                            try
                            {
                                if (rowChanged)
                                {
                                    if (useUpdateCursor)
                                    {
                                        rowCursor.UpdateRow(osmRow);
                                    }
                                    else
                                    {
                                        // update the feature through the cursor
                                        osmRow.Store();
                                    }
                                }
                                progessIndex++;
                            }
                            catch (Exception ex)
                            {
                                System.Diagnostics.Debug.WriteLine(ex.Message);
                                message.AddWarning(ex.Message);
                            }

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

                            if (stepProgressor != null)
                            {
                                // update the progress UI
                                stepProgressor.Position = progessIndex;
                            }

                            // check for user cancellation (every 100 rows)
                            if ((progessIndex % 100 == 0) && (TrackCancel.Continue() == false))
                            {
                                return;
                            }
                        }

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

                execute_Utilities.ReleaseInternals();
                Marshal.ReleaseComObject(execute_Utilities);
            }
            catch (Exception ex)
            {
                message.AddError(120054, ex.Message);
            }
        }
Пример #5
0
        public override bool Work()
        {
            base.Work();
            if (!Init())
            {
                //System.Runtime.InteropServices.Marshal.ReleaseComObject(InsertFeatureCursor);
                ProgressDialog.HideDialog();
                return(false);
            }
            foreach (var file in Files)
            {
                Count++;
                var tcmc = System.IO.Path.GetFileNameWithoutExtension(file);
                StepProgressor.Message = string.Format("正在分析{0},进度{1}/{2}", tcmc, Count, MaxValue);
                CanContinue            = TrackCancel.Continue();
                if (!CanContinue)
                {
                    break;
                }
                var inputfeatureClass = file.GetShpFeatureClass();
                if (inputfeatureClass != null)
                {
                    if (FeatureClass == null)
                    {
                        IGeoDataset geodataset = inputfeatureClass as IGeoDataset;
                        FeatureClass = FeatureClassManager.CreateFeatrueClass(this.SavaFilePath, geodataset.SpatialReference, inputfeatureClass.ShapeType);
                    }
                    if (FeatureClass != null)
                    {
                        CheckField(FeatureClass, inputfeatureClass);
                        var            insertfeaturecursor = FeatureClass.Insert(true);
                        IFeatureBuffer featureBuffer       = null;
                        IFeatureCursor featureCursor       = inputfeatureClass.Search(null, false);
                        IFeature       feature             = featureCursor.NextFeature();
                        while (feature != null)
                        {
                            #region

                            featureBuffer = FeatureClass.CreateFeatureBuffer();
                            var copy = feature.ShapeCopy;
                            var aw   = copy as IZAware;
                            if (aw.ZAware == true)
                            {
                                aw.ZAware = false;
                            }
                            featureBuffer.Shape = copy;
                            foreach (var field in Fields)
                            {
                                if (field.Name == "TCMC")
                                {
                                    featureBuffer.set_Value(field.Index, tcmc);
                                    continue;
                                }
                                var a = feature.Fields.FindField(field.Name);
                                if (a != -1)
                                {
                                    featureBuffer.set_Value(field.Index, feature.get_Value(a));
                                }
                            }
                            try
                            {
                                object featureOID = insertfeaturecursor.InsertFeature(featureBuffer);
                                insertfeaturecursor.Flush();
                            }
                            catch (Exception ex)
                            {
                                Error += string.Format("在读取{0}时,合并错误,错误信息:{1};", tcmc, ex.Message);
                                break;
                            }
                            #endregion
                            feature = featureCursor.NextFeature();
                        }
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(insertfeaturecursor);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(featureCursor);
                    }
                }
                else
                {
                    Error += string.Format("无法打开文件:{0};", tcmc);
                }
                StepProgressor.Step();
            }
            // System.Runtime.InteropServices.Marshal.ReleaseComObject(InsertFeatureCursor);
            ProgressDialog.HideDialog();
            return(true);
        }
Пример #6
0
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            try
            {
                IGPUtilities3 execute_Utilities = new GPUtilitiesClass();

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

                IGPParameter inputFeatureDatasetParameter = paramvalues.get_Element(in_featureDatasetParameterNumber) as IGPParameter;
                IGPValue inputFeatureDatasetGPValue = execute_Utilities.UnpackGPValue(inputFeatureDatasetParameter);
                IGPValue outputOSMFileGPValue = execute_Utilities.UnpackGPValue(paramvalues.get_Element(out_osmFileLocationParameterNumber));

                // get the name of the feature dataset
                int fdDemlimiterPosition = inputFeatureDatasetGPValue.GetAsText().LastIndexOf("\\");

                string nameOfFeatureDataset = inputFeatureDatasetGPValue.GetAsText().Substring(fdDemlimiterPosition + 1);


                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;

                System.Xml.XmlWriter xmlWriter = null;

                try
                {
                    xmlWriter = XmlWriter.Create(outputOSMFileGPValue.GetAsText(), settings);
                }
                catch (Exception ex)
                {
                    message.AddError(120021, ex.Message);
                    return;
                }

                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("osm"); // start the osm root node
                xmlWriter.WriteAttributeString("version", "0.6"); // add the version attribute
                xmlWriter.WriteAttributeString("generator", "ArcGIS Editor for OpenStreetMap"); // add the generator attribute

                // write all the nodes
                // use a feature search cursor to loop through all the known points and write them out as osm node

                IFeatureClassContainer osmFeatureClasses = execute_Utilities.OpenDataset(inputFeatureDatasetGPValue) as IFeatureClassContainer;

                if (osmFeatureClasses == null)
                {
                    message.AddError(120022, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), inputFeatureDatasetParameter.Name));
                    return;
                }

                IFeatureClass osmPointFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_pt");

                if (osmPointFeatureClass == null)
                {
                    message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_pointfeatureclass"), nameOfFeatureDataset + "_osm_pt"));
                    return;
                }

                // check the extension of the point feature class to determine its version
                int internalOSMExtensionVersion = osmPointFeatureClass.OSMExtensionVersion();

                IFeatureCursor searchCursor = null;

                System.Xml.Serialization.XmlSerializerNamespaces xmlnsEmpty = new System.Xml.Serialization.XmlSerializerNamespaces();
                xmlnsEmpty.Add("", "");

                message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_pts_msg"));
                int pointCounter = 0;

                string nodesExportedMessage = String.Empty;

                // collect the indices for the point feature class once
                int pointOSMIDFieldIndex = osmPointFeatureClass.Fields.FindField("OSMID");
                int pointChangesetFieldIndex = osmPointFeatureClass.Fields.FindField("osmchangeset");
                int pointVersionFieldIndex = osmPointFeatureClass.Fields.FindField("osmversion");
                int pointUIDFieldIndex = osmPointFeatureClass.Fields.FindField("osmuid");
                int pointUserFieldIndex = osmPointFeatureClass.Fields.FindField("osmuser");
                int pointTimeStampFieldIndex = osmPointFeatureClass.Fields.FindField("osmtimestamp");
                int pointVisibleFieldIndex = osmPointFeatureClass.Fields.FindField("osmvisible");
                int pointTagsFieldIndex = osmPointFeatureClass.Fields.FindField("osmTags");

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    searchCursor = osmPointFeatureClass.Search(null, false);
                    comReleaser.ManageLifetime(searchCursor);

                    System.Xml.Serialization.XmlSerializer pointSerializer = new System.Xml.Serialization.XmlSerializer(typeof(node));

                    IFeature currentFeature = searchCursor.NextFeature();

                    IWorkspace pointWorkspace = ((IDataset)osmPointFeatureClass).Workspace;

                    while (currentFeature != null)
                    {
                        if (TrackCancel.Continue() == true)
                        {
                            // convert the found point feature into a osm node representation to store into the OSM XML file
                            node osmNode = ConvertPointFeatureToOSMNode(currentFeature, pointWorkspace, pointTagsFieldIndex, pointOSMIDFieldIndex, pointChangesetFieldIndex, pointVersionFieldIndex, pointUIDFieldIndex, pointUserFieldIndex, pointTimeStampFieldIndex, pointVisibleFieldIndex, internalOSMExtensionVersion);

                            pointSerializer.Serialize(xmlWriter, osmNode, xmlnsEmpty);

                            // increase the point counter to later status report
                            pointCounter++;

                            currentFeature = searchCursor.NextFeature();
                        }
                        else
                        {
                            // properly close the document
                            xmlWriter.WriteEndElement(); // closing the osm root element
                            xmlWriter.WriteEndDocument(); // finishing the document

                            xmlWriter.Close(); // closing the document

                            // report the number of elements loader so far
                            nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter);
                            message.AddMessage(nodesExportedMessage);

                            return;
                        }
                    }
                }

                nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter);
                message.AddMessage(nodesExportedMessage);

                // next loop through the line and polygon feature classes to export those features as ways
                // in case we encounter a multi-part geometry, store it in a relation collection that will be serialized when exporting the relations table
                IFeatureClass osmLineFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ln");

                if (osmLineFeatureClass == null)
                {
                    message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_linefeatureclass"), nameOfFeatureDataset + "_osm_ln"));
                    return;
                }

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

                // as we are looping through the line and polygon feature classes let's collect the multi-part features separately 
                // as they are considered relations in the OSM world
                List<relation> multiPartElements = new List<relation>();

                System.Xml.Serialization.XmlSerializer waySerializer = new System.Xml.Serialization.XmlSerializer(typeof(way));
                int lineCounter = 0;
                int relationCounter = 0;
                string waysExportedMessage = String.Empty;

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    searchCursor = osmLineFeatureClass.Search(null, false);
                    comReleaser.ManageLifetime(searchCursor);

                    IFeature currentFeature = searchCursor.NextFeature();

                    // collect the indices for the point feature class once
                    int lineOSMIDFieldIndex = osmLineFeatureClass.Fields.FindField("OSMID");
                    int lineChangesetFieldIndex = osmLineFeatureClass.Fields.FindField("osmchangeset");
                    int lineVersionFieldIndex = osmLineFeatureClass.Fields.FindField("osmversion");
                    int lineUIDFieldIndex = osmLineFeatureClass.Fields.FindField("osmuid");
                    int lineUserFieldIndex = osmLineFeatureClass.Fields.FindField("osmuser");
                    int lineTimeStampFieldIndex = osmLineFeatureClass.Fields.FindField("osmtimestamp");
                    int lineVisibleFieldIndex = osmLineFeatureClass.Fields.FindField("osmvisible");
                    int lineTagsFieldIndex = osmLineFeatureClass.Fields.FindField("osmTags");
                    int lineMembersFieldIndex = osmLineFeatureClass.Fields.FindField("osmMembers");

                    IWorkspace lineWorkspace = ((IDataset)osmLineFeatureClass).Workspace;

                    while (currentFeature != null)
                    {
                        if (TrackCancel.Continue() == false)
                        {
                            // properly close the document
                            xmlWriter.WriteEndElement(); // closing the osm root element
                            xmlWriter.WriteEndDocument(); // finishing the document

                            xmlWriter.Close(); // closing the document

                            // report the number of elements loaded so far
                            waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter);
                            message.AddMessage(waysExportedMessage);

                            return;
                        }

                        //test if the feature geometry has multiple parts
                        IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection;

                        if (geometryCollection != null)
                        {
                            if (geometryCollection.GeometryCount == 1)
                            {
                                // convert the found polyline feature into a osm way representation to store into the OSM XML file
                                way osmWay = ConvertFeatureToOSMWay(currentFeature, lineWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, internalOSMExtensionVersion);
                                waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty);

                                // increase the line counter for later status report
                                lineCounter++;
                            }
                            else
                            {
                                relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, lineWorkspace, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, lineMembersFieldIndex, internalOSMExtensionVersion);
                                multiPartElements.Add(osmRelation);

                                // increase the line counter for later status report
                                relationCounter++;
                            }
                        }

                        currentFeature = searchCursor.NextFeature();
                    }
                }


                IFeatureClass osmPolygonFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ply");
                IFeatureWorkspace commonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace as IFeatureWorkspace;

                if (osmPolygonFeatureClass == null)
                {
                    message.AddError(120024, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_polygonfeatureclass"), nameOfFeatureDataset + "_osm_ply"));
                    return;
                }

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    searchCursor = osmPolygonFeatureClass.Search(null, false);
                    comReleaser.ManageLifetime(searchCursor);

                    IFeature currentFeature = searchCursor.NextFeature();

                    // collect the indices for the point feature class once
                    int polygonOSMIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("OSMID");
                    int polygonChangesetFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmchangeset");
                    int polygonVersionFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmversion");
                    int polygonUIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuid");
                    int polygonUserFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuser");
                    int polygonTimeStampFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmtimestamp");
                    int polygonVisibleFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmvisible");
                    int polygonTagsFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmTags");
                    int polygonMembersFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmMembers");

                    IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace;

                    while (currentFeature != null)
                    {
                        if (TrackCancel.Continue() == false)
                        {
                            // properly close the document
                            xmlWriter.WriteEndElement(); // closing the osm root element
                            xmlWriter.WriteEndDocument(); // finishing the document

                            xmlWriter.Close(); // closing the document

                            // report the number of elements loaded so far
                            waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter);
                            message.AddMessage(waysExportedMessage);

                            message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
                            return;
                        }

                        //test if the feature geometry has multiple parts
                        IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection;

                        if (geometryCollection != null)
                        {
                            if (geometryCollection.GeometryCount == 1)
                            {
                                // convert the found polyline feature into a osm way representation to store into the OSM XML file
                                way osmWay = ConvertFeatureToOSMWay(currentFeature, polygonWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, internalOSMExtensionVersion);
                                waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty);

                                // increase the line counter for later status report
                                lineCounter++;
                            }
                            else
                            {
                                relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, polygonWorkspace, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, polygonMembersFieldIndex, internalOSMExtensionVersion);
                                multiPartElements.Add(osmRelation);

                                // increase the line counter for later status report
                                relationCounter++;
                            }
                        }

                        currentFeature = searchCursor.NextFeature();
                    }
                }

                waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter);
                message.AddMessage(waysExportedMessage);


                // now let's go through the relation table 
                message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_relations_msg"));
                ITable relationTable = commonWorkspace.OpenTable(nameOfFeatureDataset + "_osm_relation");

                if (relationTable == null)
                {
                    message.AddError(120025, String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_relationTable"), nameOfFeatureDataset + "_osm_relation"));
                    return;
                }


                System.Xml.Serialization.XmlSerializer relationSerializer = new System.Xml.Serialization.XmlSerializer(typeof(relation));
                string relationsExportedMessage = String.Empty;

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    ICursor rowCursor = relationTable.Search(null, false);
                    comReleaser.ManageLifetime(rowCursor);

                    IRow currentRow = rowCursor.NextRow();

                    // collect the indices for the relation table once
                    int relationOSMIDFieldIndex = relationTable.Fields.FindField("OSMID");
                    int relationChangesetFieldIndex = relationTable.Fields.FindField("osmchangeset");
                    int relationVersionFieldIndex = relationTable.Fields.FindField("osmversion");
                    int relationUIDFieldIndex = relationTable.Fields.FindField("osmuid");
                    int relationUserFieldIndex = relationTable.Fields.FindField("osmuser");
                    int relationTimeStampFieldIndex = relationTable.Fields.FindField("osmtimestamp");
                    int relationVisibleFieldIndex = relationTable.Fields.FindField("osmvisible");
                    int relationTagsFieldIndex = relationTable.Fields.FindField("osmTags");
                    int relationMembersFieldIndex = relationTable.Fields.FindField("osmMembers");

                    IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace;


                    while (currentRow != null)
                    {
                        if (TrackCancel.Continue() == false)
                        {
                            // properly close the document
                            xmlWriter.WriteEndElement(); // closing the osm root element
                            xmlWriter.WriteEndDocument(); // finishing the document

                            xmlWriter.Close(); // closing the document

                            // report the number of elements loaded so far
                            relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter);
                            message.AddMessage(relationsExportedMessage);

                            message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
                            return;
                        }

                        relation osmRelation = ConvertRowToOSMRelation(currentRow, (IWorkspace)commonWorkspace, relationTagsFieldIndex, relationOSMIDFieldIndex, relationChangesetFieldIndex, relationVersionFieldIndex, relationUIDFieldIndex, relationUserFieldIndex, relationTimeStampFieldIndex, relationVisibleFieldIndex, relationMembersFieldIndex, internalOSMExtensionVersion);
                        relationSerializer.Serialize(xmlWriter, osmRelation, xmlnsEmpty);

                        // increase the line counter for later status report
                        relationCounter++;

                        currentRow = rowCursor.NextRow();
                    }
                }

                // lastly let's serialize the collected multipart-geometries back into relation elements
                foreach (relation currentRelation in multiPartElements)
                {
                    if (TrackCancel.Continue() == false)
                    {
                        // properly close the document
                        xmlWriter.WriteEndElement(); // closing the osm root element
                        xmlWriter.WriteEndDocument(); // finishing the document

                        xmlWriter.Close(); // closing the document

                        // report the number of elements loaded so far
                        relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter);
                        message.AddMessage(relationsExportedMessage);

                        return;
                    }

                    relationSerializer.Serialize(xmlWriter, currentRelation, xmlnsEmpty);
                    relationCounter++;
                }

                relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter);
                message.AddMessage(relationsExportedMessage);


                xmlWriter.WriteEndElement(); // closing the osm root element
                xmlWriter.WriteEndDocument(); // finishing the document

                xmlWriter.Close(); // closing the document
            }
            catch (Exception ex)
            {
                message.AddError(11111, ex.StackTrace);
                message.AddError(120026, ex.Message);
            }
        }
Пример #7
0
        private void ExportTool()
        {
            IExport pExport = null;
            //  IExportJPEG pExportFormat;
            IWorldFileSettings pWorldFile = null;
            IExportImage       pExportType;
            IEnvelope          pEnv = new Envelope() as IEnvelope;
            int lResolution;

            lResolution = Convert.ToInt32(this.numericUpDown1.Value);
            switch (this.saveFileDialog1.Filter.ToString().Trim().Substring(0, 3))
            {
            case "jpg":
                pExport = new ExportJPEG() as IExport;
                break;

            case "bmp":
                pExport = new ExportBMP() as IExport;
                break;

            case "gif":
                pExport = new ExportGIF() as IExport;
                break;

            case "tif":
                pExport = new ExportTIFF() as IExport;
                break;

            case "png":
                pExport = new ExportPNG() as IExport;
                break;

            case "emf":
                pExport = new ExportEMF() as IExport;
                break;

            case "pdf":
                pExport = new ExportPDF() as IExport;
                break;

            case ".ai":
                pExport = new ExportAI() as IExport;
                break;

            case "svg":
                pExport = new ExportSVG() as IExport;
                break;

            case "ps":
                pExport = new ExportPS() as IExport;
                break;

            default:
                pExport = new ExportJPEG() as IExport;
                break;
            }

            if (this.textBox1.Text.ToString().Trim() != "")
            {
                if (System.IO.File.Exists(this.textBox1.Text.ToString()) == true)
                {
                    MessageBox.Show("该文件已经存在,请重新命名!");
                    this.textBox1.Text = "";
                    this.textBox1.Focus();
                }
                else
                {
                    pExport.ExportFileName = this.textBox1.Text;
                    pExport.Resolution     = lResolution;
                    pExportType            = pExport as IExportImage;
                    pExportType.ImageType  = esriExportImageType.esriExportImageTypeTrueColor;
                    pEnv                       = pActiveView.Extent;
                    pWorldFile                 = (IWorldFileSettings)pExport;
                    pWorldFile.MapExtent       = pEnv;
                    pWorldFile.OutputWorldFile = false;

                    tagRECT deviceRECT;
                    deviceRECT = Form1.m_mapControl.ActiveView.ScreenDisplay.DisplayTransformation.get_DeviceFrame();

                    IEnvelope pDriverBounds;
                    pDriverBounds = new Envelope() as IEnvelope;
                    pDriverBounds.PutCoords(deviceRECT.left, deviceRECT.bottom, deviceRECT.right, deviceRECT.top);
                    pExport.PixelBounds = pDriverBounds;

                    ITrackCancel pTrackCancel = new TrackCancel();
                    Form1.m_mapControl.ActiveView.Output(pExport.StartExporting(), lResolution, ref deviceRECT, pActiveView.Extent, pTrackCancel);

                    pExport.FinishExporting();
                    MessageBox.Show("打印图片保存成功!", "保存", MessageBoxButtons.OK);
                    this.Close();
                }
            }
            else
            {
                MessageBox.Show("请保存文件!");
            }
        }
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            try
            {
                IGPUtilities3 gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3;

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

                // decode in the input layers
                IGPParameter in_SourceFeatureClassParameter = paramvalues.get_Element(in_sourceFeatureClassNumber) as IGPParameter;
                IGPValue     in_SourceFeatureGPValue        = gpUtilities3.UnpackGPValue(in_SourceFeatureClassParameter) as IGPValue;

                IFeatureClass sourceFeatureClass = null;
                IQueryFilter  queryFilter        = null;

                gpUtilities3.DecodeFeatureLayer((IGPValue)in_SourceFeatureGPValue, out sourceFeatureClass, out queryFilter);

                if (sourceFeatureClass == null)
                {
                    message.AddError(120027, resourceManager.GetString("GPTools_OSMGPFeatureComparison_source_nullpointer"));
                    return;
                }

                IGPParameter in_NumberOfIntersectionsFieldParameter = paramvalues.get_Element(in_sourceIntersectionFieldNumber) as IGPParameter;
                IGPValue     in_NumberOfIntersectionsFieldGPValue   = gpUtilities3.UnpackGPValue(in_NumberOfIntersectionsFieldParameter) as IGPValue;

                IGPParameter in_SourceRefIDFieldParameter = paramvalues.get_Element(in_sourceRefIDsFieldNumber) as IGPParameter;
                IGPValue     in_SourceRefIDFieldGPValue   = gpUtilities3.UnpackGPValue(in_SourceRefIDFieldParameter) as IGPValue;

                IGPParameter in_MatchFeatureClassParameter = paramvalues.get_Element(in_MatchFeatureClassNumber) as IGPParameter;
                IGPValue     in_MatchFeatureGPValue        = gpUtilities3.UnpackGPValue(in_MatchFeatureClassParameter) as IGPValue;

                IFeatureClass matchFeatureClass = null;
                IQueryFilter  matchQueryFilter  = null;

                gpUtilities3.DecodeFeatureLayer((IGPValue)in_MatchFeatureGPValue, out matchFeatureClass, out matchQueryFilter);


                if (matchFeatureClass == null)
                {
                    message.AddError(120028, resourceManager.GetString("GPTools_OSMGPFeatureComparison_match_nullpointer"));
                    return;
                }

                if (queryFilter != null)
                {
                    if (((IGeoDataset)matchFeatureClass).SpatialReference != null)
                    {
                        queryFilter.set_OutputSpatialReference(sourceFeatureClass.ShapeFieldName, ((IGeoDataset)matchFeatureClass).SpatialReference);
                    }
                }


                IWorkspace     sourceWorkspace     = ((IDataset)sourceFeatureClass).Workspace;
                IWorkspaceEdit sourceWorkspaceEdit = sourceWorkspace as IWorkspaceEdit;

                if (sourceWorkspace.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace)
                {
                    sourceWorkspaceEdit = sourceWorkspace as IWorkspaceEdit;
                    sourceWorkspaceEdit.StartEditing(false);
                    sourceWorkspaceEdit.StartEditOperation();
                }

                // get an overall feature count as that determines the progress indicator
                int featureCount = ((ITable)sourceFeatureClass).RowCount(queryFilter);

                // set up the progress indicator
                IStepProgressor stepProgressor = TrackCancel as IStepProgressor;

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

                int numberOfIntersectionsFieldIndex = sourceFeatureClass.FindField(in_NumberOfIntersectionsFieldGPValue.GetAsText());
                int sourceRefIDFieldIndex           = sourceFeatureClass.FindField(in_SourceRefIDFieldGPValue.GetAsText());

                ISpatialFilter matchFCSpatialFilter = new SpatialFilter();
                matchFCSpatialFilter.GeometryField = matchFeatureClass.ShapeFieldName;
                matchFCSpatialFilter.SpatialRel    = esriSpatialRelEnum.esriSpatialRelIntersects;
                matchFCSpatialFilter.WhereClause   = matchQueryFilter.WhereClause;

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    IFeatureCursor sourceFeatureCursor = sourceFeatureClass.Search(queryFilter, false);
                    comReleaser.ManageLifetime(sourceFeatureCursor);

                    IFeature sourceFeature = null;

                    while ((sourceFeature = sourceFeatureCursor.NextFeature()) != null)
                    {
                        int    numberOfIntersections = 0;
                        string intersectedFeatures   = String.Empty;

                        IPolyline sourceLine = sourceFeature.Shape as IPolyline;

                        matchFCSpatialFilter.Geometry = sourceLine;

                        using (ComReleaser innerReleaser = new ComReleaser())
                        {
                            IFeatureCursor matchFeatureCursor = matchFeatureClass.Search(matchFCSpatialFilter, false);
                            innerReleaser.ManageLifetime(matchFeatureCursor);

                            IFeature matchFeature = null;

                            while ((matchFeature = matchFeatureCursor.NextFeature()) != null)
                            {
                                IPointCollection intersectionPointCollection = null;
                                try
                                {
                                    ITopologicalOperator topoOperator = sourceLine as ITopologicalOperator;

                                    if (topoOperator.IsSimple == false)
                                    {
                                        ((ITopologicalOperator2)topoOperator).IsKnownSimple_2 = false;
                                        topoOperator.Simplify();
                                    }

                                    IPolyline matchPolyline = matchFeature.Shape as IPolyline;

                                    if (queryFilter != null)
                                    {
                                        matchPolyline.Project(sourceLine.SpatialReference);
                                    }

                                    if (((ITopologicalOperator)matchPolyline).IsSimple == false)
                                    {
                                        ((ITopologicalOperator2)matchPolyline).IsKnownSimple_2 = false;
                                        ((ITopologicalOperator)matchPolyline).Simplify();
                                    }

                                    intersectionPointCollection = topoOperator.Intersect(matchPolyline, esriGeometryDimension.esriGeometry0Dimension) as IPointCollection;
                                }
                                catch (Exception ex)
                                {
                                    message.AddWarning(ex.Message);
                                    continue;
                                }

                                if (intersectionPointCollection != null && intersectionPointCollection.PointCount > 0)
                                {
                                    numberOfIntersections = numberOfIntersections + intersectionPointCollection.PointCount;

                                    if (String.IsNullOrEmpty(intersectedFeatures))
                                    {
                                        intersectedFeatures = matchFeature.OID.ToString();
                                    }
                                    else
                                    {
                                        intersectedFeatures = intersectedFeatures + "," + matchFeature.OID.ToString();
                                    }
                                }
                            }

                            if (numberOfIntersectionsFieldIndex > -1)
                            {
                                sourceFeature.set_Value(numberOfIntersectionsFieldIndex, numberOfIntersections);
                            }

                            if (sourceRefIDFieldIndex > -1)
                            {
                                if (intersectedFeatures.Length > sourceFeatureClass.Fields.get_Field(sourceRefIDFieldIndex).Length)
                                {
                                    sourceFeature.set_Value(sourceRefIDFieldIndex, intersectedFeatures.Substring(0, sourceFeatureClass.Fields.get_Field(sourceRefIDFieldIndex).Length));
                                }
                                else
                                {
                                    sourceFeature.set_Value(sourceRefIDFieldIndex, intersectedFeatures);
                                }
                            }
                        }

                        try
                        {
                            sourceFeature.Store();
                        }
                        catch (Exception ex)
                        {
                            message.AddWarning(ex.Message);
                        }

                        if (stepProgressor != null)
                        {
                            // update the progress UI
                            stepProgressor.Step();
                        }

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

                if (sourceWorkspaceEdit != null)
                {
                    sourceWorkspaceEdit.StopEditOperation();
                    sourceWorkspaceEdit.StopEditing(true);
                }

                if (stepProgressor != null)
                {
                    stepProgressor.Hide();
                }
            }
            catch (Exception ex)
            {
                message.AddAbort(ex.Message);
            }
        }
        public override bool Work()
        {
            base.Work();
            if (!Init())
            {
                ProgressDialog.HideDialog();
                return(false);
            }
            ParallelLoopResult result = Parallel.ForEach <string>(Files, s => { Analyze(s); });


            //foreach(var file in Files)
            //{
            //    Count++;
            //    StepProgressor.Message = string.Format("正在分析{0},进度{1}/{2}", file, Count,MaxValue);
            //    CanContinue = TrackCancel.Continue();
            //    if (!CanContinue)
            //    {
            //        break;
            //    }
            //    Application.DoEvents();
            //    Analyze(file);
            //    StepProgressor.Step();
            //}

            foreach (var file in Files)
            {
                Count++;
                StepProgressor.Message = string.Format("正在分析{0},进度{1}/{2}", file, Count, MaxValue);
                CanContinue            = TrackCancel.Continue();
                if (!CanContinue)
                {
                    break;
                }
                Application.DoEvents();
                Judge(file);
                StepProgressor.Step();
            }
            StepProgressor.Message = string.Format("正在保存中");
            if (PointFiles.Count > 0)
            {
                var savePoint = string.Format("{0}\\{1}_点.shp", System.IO.Path.GetDirectoryName(this.SaveFilePath), System.IO.Path.GetFileNameWithoutExtension(this.SaveFilePath));
                StepProgressor.Message = string.Format("正在生成文件{0}", savePoint);
                Merge(string.Join(";", PointFiles.ToArray()), savePoint);
            }
            if (PolylineFiles.Count > 0)
            {
                var savePolyline = string.Format("{0}\\{1}_线.shp", System.IO.Path.GetDirectoryName(this.SaveFilePath), System.IO.Path.GetFileNameWithoutExtension(this.SaveFilePath));
                StepProgressor.Message = string.Format("正在生成文件{0}", savePolyline);
                Merge(string.Join(";", PolylineFiles.ToArray()), savePolyline);
            }

            if (PolygonFiles.Count > 0)
            {
                var savePolygon = string.Format("{0}\\{1}_点.shp", System.IO.Path.GetDirectoryName(this.SaveFilePath), System.IO.Path.GetFileNameWithoutExtension(this.SaveFilePath));
                StepProgressor.Message = string.Format("正在生成文件{0}", savePolygon);
                Merge(string.Join(";", PolygonFiles.ToArray()), savePolygon);
            }
            ProgressDialog.HideDialog();
            return(true);
        }
        public override bool Work()
        {
            base.Work();
            if (!Init())
            {
                Finish();
                return(false);
            }

            var current = 1;

            foreach (var item in _txtFiles)
            {
                StepProgressor.Message = string.Format("{0}/{1}——正在分析读取文件:{2}", current++, _txtFiles.Count, System.IO.Path.GetFileNameWithoutExtension(item));
                CanContinue            = TrackCancel.Continue();
                if (!CanContinue)
                {
                    break;
                }
                //#region  方法二
                //using (var reader = new StreamReader(item, Encoding.GetEncoding("GB2312")))
                //{
                //    var line = reader.ReadLine();
                //    var begin = false;
                //    var polygon = new PolygonClass();
                //    var ring = new RingClass();
                //    var pc = ring as IPointCollection;
                //    var ringId = string.Empty;
                //    var lastTokens = new[] { "", "", "", "", "", "", "", "", "" };
                //    var row = 1;
                //    var pgCount = 0;
                //    var ext = false;
                //    var list = new List<IPoint>();
                //    while (line != null)
                //    {
                //        line = line.Trim();
                //        if (line == "[地块坐标]")
                //        {
                //            begin = true;
                //            line = reader.ReadLine();
                //            row++;
                //            ext = true;
                //            continue;
                //        }

                //        if (begin && !string.IsNullOrEmpty(line))
                //        {
                //            string[] tokens = line.Split(',');
                //            if (tokens[tokens.Length - 1] == "@")
                //            {
                //                #region
                //                if (tokens.Length != 9)
                //                {
                //                    _errors.Add(string.Format("文件第{0}行的格式有误,字段数量应为9", row));
                //                    break;
                //                }
                //                if (pc.PointCount > 0)
                //                {
                //                    if (pc.PointCount < 4)
                //                    {
                //                        _errors.Add(string.Format("文件第{0}行之前的坐标串有误,多边形顶点数不应少于4个", row));
                //                        ring = new RingClass();
                //                        pc = ring as IPointCollection;
                //                        break;
                //                    }
                //                    else
                //                    {
                //                        polygon.AddGeometry(ring, ref missing, ref missing);

                //                    }
                //                }

                //                //if (polygon.GeometryCount > 0)
                //                //{
                //                //    var buffer = FeatureClass.CreateFeatureBuffer();
                //                //    polygon.ITopologicalOperator2_IsKnownSimple_2 = false;
                //                //    (polygon as ITopologicalOperator2).Simplify();
                //                //    polygon.GeometriesChanged();
                //                //    buffer.Shape = polygon;
                //                //    buffer.set_Value(buffer.Fields.FindField("FILENAME"), System.IO.Path.GetFileName(item));
                //                //    buffer.set_Value(buffer.Fields.FindField("DKBH"), lastTokens[2]);
                //                //    buffer.set_Value(buffer.Fields.FindField("DKMC"), lastTokens[3]);
                //                //    buffer.set_Value(buffer.Fields.FindField("JLTXSX"), lastTokens[4]);
                //                //    buffer.set_Value(buffer.Fields.FindField("TFH"), lastTokens[5]);
                //                //    buffer.set_Value(buffer.Fields.FindField("DKYT"), lastTokens[6]);
                //                //    buffer.set_Value(buffer.Fields.FindField("DLBM"), lastTokens[7]);
                //                //    // FeatureCursor.InsertFeature(buffer);
                //                //    _featureCursor.InsertFeature(buffer);
                //                //    pgCount++;
                //                //}
                //                #endregion
                //                lastTokens = tokens;
                //            }
                //            else
                //            {
                //                #region
                //                if (tokens.Length == 4)
                //                {
                //                    IPoint pt = new PointClass();
                //                    double x, y;
                //                    if ((!double.TryParse(tokens[2], out y) || !double.TryParse(tokens[3], out x)) || x < 40000000 || x > 41000000 || y < 2000000 || y > 4000000)
                //                    {
                //                        _errors.Add(string.Format("文件第{0}行的格式有误,坐标应为数字类型", row));
                //                        polygon = new PolygonClass();
                //                        pc = polygon as IPointCollection;
                //                        break;
                //                    }
                //                    pt.X = x;
                //                    pt.Y = y;
                //                    pc.AddPoint(pt, ref missing, ref missing);
                //                    list.Add(pt);
                //                }
                //                else
                //                {
                //                    _errors.Add(string.Format("文件第{0}行的格式有误,字段数量应为4", row));
                //                    polygon = new PolygonClass();
                //                    ring = new RingClass();
                //                    pc = ring as IPointCollection;
                //                    break;
                //                }
                //                #endregion
                //            }
                //        }
                //        line = reader.ReadLine();
                //        row++;
                //    }

                //    try
                //    {
                //        IGeometryBridge2 geometryBridge2 = new GeometryEnvironmentClass();
                //        IPointCollection4 pcollection = new PolygonClass();
                //        WKSPoint[] wksPoint = new WKSPoint[list.Count];
                //        for (var i = 0; i < list.Count; i++)
                //        {
                //            var temp = list[i];
                //            wksPoint[i].X = temp.X;
                //            wksPoint[i].Y = temp.Y;
                //        }

                //        geometryBridge2.SetWKSPoints(pcollection, ref wksPoint);
                //        IPolygon poly = pcollection as IPolygon;
                //        poly.Close();

                //        var buffer = FeatureClass.CreateFeatureBuffer();
                //        buffer.Shape = poly;
                //        buffer.set_Value(buffer.Fields.FindField("FILENAME"), System.IO.Path.GetFileName(item));
                //        buffer.set_Value(buffer.Fields.FindField("DKBH"), lastTokens[2]);
                //        buffer.set_Value(buffer.Fields.FindField("DKMC"), lastTokens[3]);
                //        buffer.set_Value(buffer.Fields.FindField("JLTXSX"), lastTokens[4]);
                //        buffer.set_Value(buffer.Fields.FindField("TFH"), lastTokens[5]);
                //        buffer.set_Value(buffer.Fields.FindField("DKYT"), lastTokens[6]);
                //        buffer.set_Value(buffer.Fields.FindField("DLBM"), lastTokens[7]);
                //        _featureCursor.InsertFeature(buffer);

                //    }
                //    catch(Exception ex)
                //    {
                //        System.Diagnostics.Trace.WriteLine(ex);
                //    }



                //    //if (pc.PointCount > 0)
                //    //{
                //    //    if (pc.PointCount < 4)
                //    //    {
                //    //        _errors.Add(string.Format("文件第{0}行之前的坐标串有误,多边形顶点不应少于4个", row));
                //    //    }
                //    //    else
                //    //    {
                //    //        polygon.AddGeometry(ring, ref missing, ref missing);
                //    //    }
                //    //}
                //    //if (polygon.GeometryCount > 0)
                //    //{
                //    //    #region
                //    //    try
                //    //    {
                //    //        var buffer = FeatureClass.CreateFeatureBuffer();
                //    //        polygon.ITopologicalOperator2_IsKnownSimple_2 = false;
                //    //        (polygon as ITopologicalOperator2).Simplify();
                //    //        polygon.GeometriesChanged();
                //    //        buffer.Shape = polygon;
                //    //        buffer.set_Value(buffer.Fields.FindField("FILENAME"), System.IO.Path.GetFileName(item));
                //    //        buffer.set_Value(buffer.Fields.FindField("DKBH"), lastTokens[2]);
                //    //        buffer.set_Value(buffer.Fields.FindField("DKMC"), lastTokens[3]);
                //    //        buffer.set_Value(buffer.Fields.FindField("JLTXSX"), lastTokens[4]);
                //    //        buffer.set_Value(buffer.Fields.FindField("TFH"), lastTokens[5]);
                //    //        buffer.set_Value(buffer.Fields.FindField("DKYT"), lastTokens[6]);
                //    //        buffer.set_Value(buffer.Fields.FindField("DLBM"), lastTokens[7]);
                //    //        _featureCursor.InsertFeature(buffer);
                //    //        pgCount++;
                //    //    }
                //    //    catch (Exception ex)
                //    //    {
                //    //        _errors.Add(string.Format("导入第{0}个地块时发生错误:{1}", pgCount, ex.Message));
                //    //    }
                //    //    #endregion
                //    //}
                //}
                //#endregion

                #region  方法一


                using (var reader = new StreamReader(item, Encoding.GetEncoding("GB2312")))
                {
                    var line    = reader.ReadLine();
                    var begin   = false;
                    var polygon = new PolygonClass();
                    IGeometryCollection resultPolygon = new PolygonClass();
                    var ring       = new RingClass();
                    var pc         = ring as IPointCollection;
                    var ringId     = string.Empty;
                    var lastTokens = new[] { "", "", "", "", "", "", "", "", "" };
                    var row        = 1;
                    var pgCount    = 0;
                    var ext        = false;
                    while (line != null)
                    {
                        line = line.Trim();
                        if (line == "[地块坐标]")
                        {
                            begin = true;
                            line  = reader.ReadLine();
                            row++;
                            ext = true;
                            continue;
                        }

                        if (begin && !string.IsNullOrEmpty(line))
                        {
                            string[] tokens = line.Split(',');
                            if (tokens[tokens.Length - 1] == "@")
                            {
                                #region
                                if (tokens.Length != 9)
                                {
                                    _errors.Add(string.Format("文件第{0}行的格式有误,字段数量应为9", row));
                                    break;
                                }
                                if (pc.PointCount > 0)
                                {
                                    if (pc.PointCount < 4)
                                    {
                                        _errors.Add(string.Format("文件第{0}行之前的坐标串有误,多边形顶点数不应少于4个", row));
                                        ring = new RingClass();
                                        pc   = ring as IPointCollection;
                                        break;
                                    }
                                    else
                                    {
                                        polygon.AddGeometry(ring, ref missing, ref missing);
                                        ring = new RingClass();
                                        pc   = ring as IPointCollection;
                                    }
                                }
                                if (polygon.GeometryCount > 0)
                                {
                                    polygon.ITopologicalOperator2_IsKnownSimple_2 = false;
                                    (polygon as ITopologicalOperator2).Simplify();
                                    polygon.GeometriesChanged();
                                    resultPolygon.AddGeometryCollection(polygon as IGeometryCollection);
                                }

                                //if (polygon.GeometryCount > 0)
                                //{
                                //    var buffer = FeatureClass.CreateFeatureBuffer();
                                //    polygon.ITopologicalOperator2_IsKnownSimple_2 = false;
                                //    (polygon as ITopologicalOperator2).Simplify();
                                //    polygon.GeometriesChanged();
                                //    buffer.Shape = polygon;
                                //    buffer.set_Value(buffer.Fields.FindField("FILENAME"), System.IO.Path.GetFileName(item));
                                //    buffer.set_Value(buffer.Fields.FindField("DKBH"), lastTokens[2]);
                                //    buffer.set_Value(buffer.Fields.FindField("DKMC"), lastTokens[3]);
                                //    buffer.set_Value(buffer.Fields.FindField("JLTXSX"), lastTokens[4]);
                                //    buffer.set_Value(buffer.Fields.FindField("TFH"), lastTokens[5]);
                                //    buffer.set_Value(buffer.Fields.FindField("DKYT"), lastTokens[6]);
                                //    buffer.set_Value(buffer.Fields.FindField("DLBM"), lastTokens[7]);
                                //    // FeatureCursor.InsertFeature(buffer);
                                //    _featureCursor.InsertFeature(buffer);
                                //    pgCount++;
                                //}
                                #endregion
                                lastTokens = tokens;
                            }
                            else
                            {
                                #region
                                if (tokens.Length == 4)
                                {
                                    IPoint pt = new PointClass();
                                    double x, y;
                                    if (tokens[1] != ringId)
                                    {
                                        if (pc.PointCount > 0)
                                        {
                                            polygon.AddGeometry(ring, ref missing, ref missing);
                                            //resultPolygon.AddGeometryCollection(ring as IGeometryCollection);
                                        }
                                        ring   = new RingClass();
                                        pc     = ring as IPointCollection;
                                        ringId = tokens[1];
                                    }

                                    if ((!double.TryParse(tokens[2], out y) || !double.TryParse(tokens[3], out x)) || x < 40000000 || x > 41000000 || y < 2000000 || y > 4000000)
                                    {
                                        _errors.Add(string.Format("文件第{0}行的格式有误,坐标应为数字类型", row));
                                        polygon = new PolygonClass();
                                        pc      = polygon as IPointCollection;
                                        break;
                                    }
                                    pt.X = x;
                                    pt.Y = y;
                                    pc.AddPoint(pt, ref missing, ref missing);
                                }
                                else
                                {
                                    _errors.Add(string.Format("文件第{0}行的格式有误,字段数量应为4", row));
                                    polygon = new PolygonClass();
                                    ring    = new RingClass();
                                    pc      = ring as IPointCollection;
                                    break;
                                }
                                #endregion
                            }
                        }
                        line = reader.ReadLine();
                        row++;
                    }
                    if (pc.PointCount > 0)
                    {
                        if (pc.PointCount < 4)
                        {
                            _errors.Add(string.Format("文件第{0}行之前的坐标串有误,多边形顶点不应少于4个", row));
                        }
                        else
                        {
                            polygon.AddGeometry(ring, ref missing, ref missing);
                            ring = new RingClass();
                            pc   = ring as IPointCollection;
                            //resultPolygon.AddGeometryCollection(ring as IGeometryCollection);
                        }
                    }
                    if (polygon.GeometryCount > 0)
                    {
                        #region
                        try
                        {
                            var buffer = FeatureClass.CreateFeatureBuffer();
                            polygon.ITopologicalOperator2_IsKnownSimple_2 = false;
                            (polygon as ITopologicalOperator2).Simplify();
                            polygon.GeometriesChanged();

                            resultPolygon.AddGeometryCollection(polygon as IGeometryCollection);
                            ITopologicalOperator top = resultPolygon as ITopologicalOperator;
                            top.Simplify();
                            // buffer.Shape = resultPolygon as IPolygon;
                            buffer.Shape = resultPolygon as IPolygon;
                            buffer.set_Value(buffer.Fields.FindField("FILENAME"), System.IO.Path.GetFileName(item));
                            buffer.set_Value(buffer.Fields.FindField("DKBH"), lastTokens[2]);
                            buffer.set_Value(buffer.Fields.FindField("DKMC"), lastTokens[3]);
                            buffer.set_Value(buffer.Fields.FindField("JLTXSX"), lastTokens[4]);
                            buffer.set_Value(buffer.Fields.FindField("TFH"), lastTokens[5]);
                            buffer.set_Value(buffer.Fields.FindField("DKYT"), lastTokens[6]);
                            buffer.set_Value(buffer.Fields.FindField("DLBM"), lastTokens[7]);
                            _featureCursor.InsertFeature(buffer);
                            pgCount++;
                        }
                        catch (Exception ex)
                        {
                            _errors.Add(string.Format("导入第{0}个地块时发生错误:{1}", pgCount, ex.Message));
                        }
                        #endregion
                    }
                }
                #endregion
            }

            Finish();
            return(true);
        }