public static void BufferAnalysis(IFeatureClass feacls,string dist) { IGeoProcessor2 gp = new GeoProcessorClass(); gp.OverwriteOutput = true; IGeoProcessorResult result = new GeoProcessorResultClass(); //gp.SetEnvironmentValue("workspace", @"e:\data"); IVariantArray vararr = new VarArrayClass(); object sev = null; try { vararr.Add(feacls); vararr.Add(@"e:\data\wwwwwww.shp"); vararr.Add(dist); result = gp.Execute("Buffer_analysis", vararr, null); while (result.Status == esriJobStatus.esriJobExecuting) Thread.Sleep(1000); MessageBox.Show(gp.GetMessages(ref sev)); } catch (System.Exception ex) { MessageBox.Show(ex.Message); MessageBox.Show(gp.GetMessages(ref sev)); } }
static void Main(string[] args) { // Load the product code and version to the version manager ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); //ESRI License Initializer generated code. m_AOLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeAdvanced }, new esriLicenseExtensionCode[] { }); // Create geoprocessor. Overwrite true will replace existing output IGeoProcessor2 gp = new GeoProcessorClass(); gp.OverwriteOutput = true; // Get the workspace from the user Console.WriteLine("Enter the path to folder where you copied the data folder."); Console.WriteLine("Example: C:\\AirportsAndGolf\\data"); Console.Write(">"); string wks = Console.ReadLine(); // set the workspace to the value user entered gp.SetEnvironmentValue("workspace", wks + "\\" + "golf.gdb"); // Add the custom toolbox to geoprocessor gp.AddToolbox(wks + "\\" + "Find Golf Courses.tbx"); // Create a variant - data are in the workspace IVariantArray parameters = new VarArrayClass(); parameters.Add("Airports"); parameters.Add("8 Miles"); parameters.Add("Golf"); parameters.Add("GolfNearAirports"); object sev = null; try { gp.Execute("GolfFinder", parameters, null); Console.WriteLine(gp.GetMessages(ref sev)); } catch (Exception ex) { Console.WriteLine(ex.Message); string errorMsgs = gp.GetMessages(ref sev); Console.WriteLine(errorMsgs); } finally { Console.WriteLine("Hit Enter to quit"); Console.ReadLine(); // pause the console to see messages } //ESRI License Initializer generated code. //Do not make any call to ArcObjects after ShutDownApplication() m_AOLicenseInitializer.ShutdownApplication(); }
public static void CopyFeatures(IFeatureClass feaCls) { IGeoProcessor2 geoProcessor2 = new GeoProcessorClass(); geoProcessor2.OverwriteOutput = true; geoProcessor2.SetEnvironmentValue("workspace", @"e:\GP\California.gdb"); IVariantArray parameters = new VarArrayClass(); parameters.Add("Lakes"); parameters.Add("origin_copy"); geoProcessor2.Execute("CopyFeatures_management", parameters, null); }
public bool ConvertLayerToKML(string kmzOutputPath, string tmpShapefilePath, ESRI.ArcGIS.Carto.IMap map) { try { string kmzName = System.IO.Path.GetFileName(kmzOutputPath); string folderName = System.IO.Path.GetDirectoryName(kmzOutputPath); IGeoProcessor2 gp = new GeoProcessorClass(); IVariantArray parameters = new VarArrayClass(); parameters.Add(tmpShapefilePath); parameters.Add(kmzName); gp.Execute("MakeFeatureLayer_management", parameters, null); IVariantArray parameters1 = new VarArrayClass(); // assign parameters parameters1.Add(kmzName); parameters1.Add(kmzOutputPath); gp.Execute("LayerToKML_conversion", parameters1, null); // Remove the temporary layer from the TOC for (int i = 0; i < map.LayerCount; i++ ) { ILayer layer = map.get_Layer(i); if (layer.Name == "featureLayer") { map.DeleteLayer(layer); break; } } return true; } catch(Exception ex) { return false; } }
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { IFeatureClass osmPointFeatureClass = null; IFeatureClass osmLineFeatureClass = null; IFeatureClass osmPolygonFeatureClass = null; OSMToolHelper osmToolHelper = null; try { DateTime syncTime = DateTime.Now; IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); osmToolHelper = new OSMToolHelper(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter osmFileParameter = paramvalues.get_Element(in_osmFileNumber) as IGPParameter; IGPValue osmFileLocationString = gpUtilities3.UnpackGPValue(osmFileParameter) as IGPValue; // ensure that the specified file does exist bool osmFileExists = false; try { osmFileExists = System.IO.File.Exists(osmFileLocationString.GetAsText()); } catch (Exception ex) { message.AddError(120029, String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_problemaccessingfile"), ex.Message)); return; } if (osmFileExists == false) { message.AddError(120030, String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_osmfiledoesnotexist"), osmFileLocationString.GetAsText())); return; } IGPParameter conserveMemoryParameter = paramvalues.get_Element(in_conserveMemoryNumber) as IGPParameter; IGPBoolean conserveMemoryGPValue = gpUtilities3.UnpackGPValue(conserveMemoryParameter) as IGPBoolean; if (conserveMemoryGPValue == null) { message.AddError(120031, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), conserveMemoryParameter.Name)); return; } message.AddMessage(resourceManager.GetString("GPTools_OSMGPFileReader_countingNodes")); long nodeCapacity = 0; long wayCapacity = 0; long relationCapacity = 0; Dictionary<esriGeometryType, List<string>> attributeTags = new Dictionary<esriGeometryType, List<string>>(); IGPParameter tagCollectionParameter = paramvalues.get_Element(in_attributeSelector) as IGPParameter; IGPMultiValue tagCollectionGPValue = gpUtilities3.UnpackGPValue(tagCollectionParameter) as IGPMultiValue; List<String> tagstoExtract = null; if (tagCollectionGPValue.Count > 0) { tagstoExtract = new List<string>(); for (int valueIndex = 0; valueIndex < tagCollectionGPValue.Count; valueIndex++) { string nameOfTag = tagCollectionGPValue.get_Value(valueIndex).GetAsText(); if (nameOfTag.ToUpper().Equals("ALL")) { tagstoExtract = new List<string>(); break; } else { tagstoExtract.Add(nameOfTag); } } } // if there is an "ALL" keyword then we scan for all tags, otherwise we only add the desired tags to the feature classes and do a 'quick' // count scan if (tagstoExtract != null) { if (tagstoExtract.Count > 0) { // if the number of tags is > 0 then do a simple feature count and take name tags names from the gp value osmToolHelper.countOSMStuff(osmFileLocationString.GetAsText(), ref nodeCapacity, ref wayCapacity, ref relationCapacity, ref TrackCancel); attributeTags.Add(esriGeometryType.esriGeometryPoint, tagstoExtract); attributeTags.Add(esriGeometryType.esriGeometryPolyline, tagstoExtract); attributeTags.Add(esriGeometryType.esriGeometryPolygon, tagstoExtract); } else { // the count should be zero if we encountered the "ALL" keyword // in this case count the features and create a list of unique tags attributeTags = osmToolHelper.countOSMCapacityAndTags(osmFileLocationString.GetAsText(), ref nodeCapacity, ref wayCapacity, ref relationCapacity, ref TrackCancel); } } else { // no tags we defined, hence we do a simple count and create an empty list indicating that no additional fields // need to be created osmToolHelper.countOSMStuff(osmFileLocationString.GetAsText(), ref nodeCapacity, ref wayCapacity, ref relationCapacity, ref TrackCancel); attributeTags.Add(esriGeometryType.esriGeometryPoint, new List<string>()); attributeTags.Add(esriGeometryType.esriGeometryPolyline, new List<string>()); attributeTags.Add(esriGeometryType.esriGeometryPolygon, new List<string>()); } if (nodeCapacity == 0 && wayCapacity == 0 && relationCapacity == 0) { return; } if (conserveMemoryGPValue.Value == false) { osmNodeDictionary = new Dictionary<string, OSMToolHelper.simplePointRef>(Convert.ToInt32(nodeCapacity)); } message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_countedElements"), nodeCapacity, wayCapacity, relationCapacity)); // prepare the feature dataset and classes IGPParameter targetDatasetParameter = paramvalues.get_Element(out_targetDatasetNumber) as IGPParameter; IGPValue targetDatasetGPValue = gpUtilities3.UnpackGPValue(targetDatasetParameter); IDEDataset2 targetDEDataset2 = targetDatasetGPValue as IDEDataset2; if (targetDEDataset2 == null) { message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), targetDatasetParameter.Name)); return; } 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(120032, String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_basenamealreadyexists"), targetDataElement.Name)); return; } } // load the descriptions from which to derive the domain values OSMDomains availableDomains = null; // Reading the XML document requires a FileStream. System.Xml.XmlTextReader reader = null; string xmlDomainFile = ""; m_editorConfigurationSettings.TryGetValue("osmdomainsfilepath", out xmlDomainFile); if (System.IO.File.Exists(xmlDomainFile)) { reader = new System.Xml.XmlTextReader(xmlDomainFile); } if (reader == null) { message.AddError(120033, resourceManager.GetString("GPTools_OSMGPDownload_NoDomainConfigFile")); return; } System.Xml.Serialization.XmlSerializer domainSerializer = null; try { domainSerializer = new XmlSerializer(typeof(OSMDomains)); availableDomains = domainSerializer.Deserialize(reader) as OSMDomains; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); System.Diagnostics.Debug.WriteLine(ex.StackTrace); message.AddError(120034, ex.Message); return; } reader.Close(); message.AddMessage(resourceManager.GetString("GPTools_preparedb")); 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 = null; IFeatureWorkspace featureWorkspace = null; // if the target dataset already exists we can go ahead and QI to it directly if (targetDataset != null) { workspaceDomain = targetDataset.Workspace as IWorkspaceDomains; featureWorkspace = targetDataset.Workspace as IFeatureWorkspace; } else { // in case it doesn't exist yet we will open the parent (the workspace - geodatabase- itself) and // use it as a reference to create the feature dataset and the feature classes in it. IWorkspace newWorkspace = ((IName)parentName).Open() as IWorkspace; workspaceDomain = newWorkspace as IWorkspaceDomains; featureWorkspace = newWorkspace as IFeatureWorkspace; } foreach (var domain in codedValueDomains.Values) { IDomain testDomain = null; try { testDomain = workspaceDomain.get_DomainByName(domain.Name); } catch { } if (testDomain == null) { workspaceDomain.AddDomain(domain); } } // this determines the spatial reference as defined from the gp environment settings and the initial wgs84 SR ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass() as ISpatialReferenceFactory; ISpatialReference wgs84 = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984) as ISpatialReference; ISpatialReference downloadSpatialReference = gpUtilities3.GetGPSpRefEnv(envMgr, wgs84, null, 0, 0, 0, 0, null); Marshal.ReleaseComObject(wgs84); Marshal.ReleaseComObject(spatialReferenceFactory); IGPEnvironment configKeyword = OSMGPDownload.getEnvironment(envMgr, "configKeyword"); IGPString 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); } downloadSpatialReference = ((IGeoDataset)targetFeatureDataset).SpatialReference; string metadataAbstract = resourceManager.GetString("GPTools_OSMGPFileReader_metadata_abstract"); string metadataPurpose = resourceManager.GetString("GPTools_OSMGPFileReader_metadata_purpose"); // assign the custom class extension for use with the OSM feature inspector UID osmClassUID = new UIDClass(); osmClassUID.Value = "{65CA4847-8661-45eb-8E1E-B2985CA17C78}"; // points try { osmPointFeatureClass = osmToolHelper.CreatePointFeatureClass((IWorkspace2)featureWorkspace, targetFeatureDataset, targetDataElement.Name + "_osm_pt", null, null, null, storageKeyword, availableDomains, metadataAbstract, metadataPurpose, attributeTags[esriGeometryType.esriGeometryPoint]); } catch (Exception ex) { message.AddError(120035, 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(); int osmPointIDFieldIndex = osmPointFeatureClass.FindField("OSMID"); Dictionary<string, int> osmPointDomainAttributeFieldIndices = new Dictionary<string, int>(); foreach (var domains in availableDomains.domain) { int currentFieldIndex = osmPointFeatureClass.FindField(domains.name); if (currentFieldIndex != -1) { osmPointDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex); } } int tagCollectionPointFieldIndex = osmPointFeatureClass.FindField("osmTags"); int osmUserPointFieldIndex = osmPointFeatureClass.FindField("osmuser"); int osmUIDPointFieldIndex = osmPointFeatureClass.FindField("osmuid"); int osmVisiblePointFieldIndex = osmPointFeatureClass.FindField("osmvisible"); int osmVersionPointFieldIndex = osmPointFeatureClass.FindField("osmversion"); int osmChangesetPointFieldIndex = osmPointFeatureClass.FindField("osmchangeset"); int osmTimeStampPointFieldIndex = osmPointFeatureClass.FindField("osmtimestamp"); int osmMemberOfPointFieldIndex = osmPointFeatureClass.FindField("osmMemberOf"); int osmSupportingElementPointFieldIndex = osmPointFeatureClass.FindField("osmSupportingElement"); int osmWayRefCountFieldIndex = osmPointFeatureClass.FindField("wayRefCount"); // lines try { osmLineFeatureClass = osmToolHelper.CreateLineFeatureClass((IWorkspace2)featureWorkspace, targetFeatureDataset, targetDataElement.Name + "_osm_ln", null, null, null, storageKeyword, availableDomains, metadataAbstract, metadataPurpose, attributeTags[esriGeometryType.esriGeometryPolyline]); } catch (Exception ex) { message.AddError(120036, 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(); int osmLineIDFieldIndex = osmLineFeatureClass.FindField("OSMID"); Dictionary<string, int> osmLineDomainAttributeFieldIndices = new Dictionary<string, int>(); foreach (var domains in availableDomains.domain) { int currentFieldIndex = osmLineFeatureClass.FindField(domains.name); if (currentFieldIndex != -1) { osmLineDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex); } } int tagCollectionPolylineFieldIndex = osmLineFeatureClass.FindField("osmTags"); int osmUserPolylineFieldIndex = osmLineFeatureClass.FindField("osmuser"); int osmUIDPolylineFieldIndex = osmLineFeatureClass.FindField("osmuid"); int osmVisiblePolylineFieldIndex = osmLineFeatureClass.FindField("osmvisible"); int osmVersionPolylineFieldIndex = osmLineFeatureClass.FindField("osmversion"); int osmChangesetPolylineFieldIndex = osmLineFeatureClass.FindField("osmchangeset"); int osmTimeStampPolylineFieldIndex = osmLineFeatureClass.FindField("osmtimestamp"); int osmMemberOfPolylineFieldIndex = osmLineFeatureClass.FindField("osmMemberOf"); int osmMembersPolylineFieldIndex = osmLineFeatureClass.FindField("osmMembers"); int osmSupportingElementPolylineFieldIndex = osmLineFeatureClass.FindField("osmSupportingElement"); // polygons try { osmPolygonFeatureClass = osmToolHelper.CreatePolygonFeatureClass((IWorkspace2)featureWorkspace, targetFeatureDataset, targetDataElement.Name + "_osm_ply", null, null, null, storageKeyword, availableDomains, metadataAbstract, metadataPurpose, attributeTags[esriGeometryType.esriGeometryPolygon]); } catch (Exception ex) { message.AddError(120037, 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(); int osmPolygonIDFieldIndex = osmPolygonFeatureClass.FindField("OSMID"); Dictionary<string, int> osmPolygonDomainAttributeFieldIndices = new Dictionary<string, int>(); foreach (var domains in availableDomains.domain) { int currentFieldIndex = osmPolygonFeatureClass.FindField(domains.name); if (currentFieldIndex != -1) { osmPolygonDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex); } } int tagCollectionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmTags"); int osmUserPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuser"); int osmUIDPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuid"); int osmVisiblePolygonFieldIndex = osmPolygonFeatureClass.FindField("osmvisible"); int osmVersionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmversion"); int osmChangesetPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmchangeset"); int osmTimeStampPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmtimestamp"); int osmMemberOfPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMemberOf"); int osmMembersPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMembers"); int osmSupportingElementPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmSupportingElement"); // relation table ITable relationTable = null; try { relationTable = osmToolHelper.CreateRelationTable((IWorkspace2)featureWorkspace, targetDataElement.Name + "_osm_relation", null, storageKeyword, metadataAbstract, metadataPurpose); } catch (Exception ex) { message.AddError(120038, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullrelationtable"), ex.Message)); return; } if (relationTable == null) { return; } int osmRelationIDFieldIndex = relationTable.FindField("OSMID"); int tagCollectionRelationFieldIndex = relationTable.FindField("osmTags"); int osmUserRelationFieldIndex = relationTable.FindField("osmuser"); int osmUIDRelationFieldIndex = relationTable.FindField("osmuid"); int osmVisibleRelationFieldIndex = relationTable.FindField("osmvisible"); int osmVersionRelationFieldIndex = relationTable.FindField("osmversion"); int osmChangesetRelationFieldIndex = relationTable.FindField("osmchangeset"); int osmTimeStampRelationFieldIndex = relationTable.FindField("osmtimestamp"); int osmMemberOfRelationFieldIndex = relationTable.FindField("osmMemberOf"); int osmMembersRelationFieldIndex = relationTable.FindField("osmMembers"); int osmSupportingElementRelationFieldIndex = relationTable.FindField("osmSupportingElement"); // revision table ITable revisionTable = null; try { revisionTable = osmToolHelper.CreateRevisionTable((IWorkspace2)featureWorkspace, targetDataElement.Name + "_osm_revision", null, storageKeyword); } catch (Exception ex) { message.AddError(120039, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullrevisiontable"), ex.Message)); return; } if (revisionTable == null) { return; } #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 bool fastLoad = false; //// check for user interruption //if (TrackCancel.Continue() == false) //{ // message.AddAbort(resourceManager.GetString("GPTools_toolabort")); // return; //} //IFeatureCursor deleteCursor = null; //using (ComReleaser comReleaser = new ComReleaser()) //{ // // let's make sure that we clean out any old data that might have existed in the feature classes // deleteCursor = osmPointFeatureClass.Update(null, false); // comReleaser.ManageLifetime(deleteCursor); // for (IFeature feature = deleteCursor.NextFeature(); feature != null; feature = deleteCursor.NextFeature()) // { // feature.Delete(); // // check for user interruption // if (TrackCancel.Continue() == false) // { // message.AddAbort(resourceManager.GetString("GPTools_toolabort")); // return; // } // } //} //using (ComReleaser comReleaser = new ComReleaser()) //{ // deleteCursor = osmLineFeatureClass.Update(null, false); // comReleaser.ManageLifetime(deleteCursor); // for (IFeature feature = deleteCursor.NextFeature(); feature != null; feature = deleteCursor.NextFeature()) // { // feature.Delete(); // // check for user interruption // if (TrackCancel.Continue() == false) // { // message.AddAbort(resourceManager.GetString("GPTools_toolabort")); // return; // } // } //} //using (ComReleaser comReleaser = new ComReleaser()) //{ // deleteCursor = osmPolygonFeatureClass.Update(null, false); // comReleaser.ManageLifetime(deleteCursor); // for (IFeature feature = deleteCursor.NextFeature(); feature != null; feature = deleteCursor.NextFeature()) // { // feature.Delete(); // // check for user interruption // if (TrackCancel.Continue() == false) // { // message.AddAbort(resourceManager.GetString("GPTools_toolabort")); // return; // } // } //} //ICursor tableCursor = null; //using (ComReleaser comReleaser = new ComReleaser()) //{ // tableCursor = relationTable.Update(null, false); // comReleaser.ManageLifetime(tableCursor); // for (IRow row = tableCursor.NextRow(); row != null; row = tableCursor.NextRow()) // { // row.Delete(); // // check for user interruption // if (TrackCancel.Continue() == false) // { // message.AddAbort(resourceManager.GetString("GPTools_toolabort")); // return; // } // } //} //using (ComReleaser comReleaser = new ComReleaser()) //{ // tableCursor = revisionTable.Update(null, false); // comReleaser.ManageLifetime(tableCursor); // for (IRow row = tableCursor.NextRow(); row != null; row = tableCursor.NextRow()) // { // row.Delete(); // // check for user interruption // if (TrackCancel.Continue() == false) // { // message.AddAbort(resourceManager.GetString("GPTools_toolabort")); // return; // } // } //} // define variables helping to invoke core tools for data management IGeoProcessorResult2 gpResults2 = null; IGeoProcessor2 geoProcessor = new GeoProcessorClass(); #region load points osmToolHelper.loadOSMNodes(osmFileLocationString.GetAsText(), ref TrackCancel, ref message, targetDatasetGPValue, osmPointFeatureClass, conserveMemoryGPValue.Value, fastLoad, Convert.ToInt32(nodeCapacity), ref osmNodeDictionary, featureWorkspace, downloadSpatialReference, availableDomains, false); #endregion if (TrackCancel.Continue() == false) { return; } #region load ways List<string> missingWays = osmToolHelper.loadOSMWays(osmFileLocationString.GetAsText(), ref TrackCancel, ref message, targetDatasetGPValue, osmPointFeatureClass, osmLineFeatureClass, osmPolygonFeatureClass, conserveMemoryGPValue.Value, fastLoad, Convert.ToInt32(wayCapacity), ref osmNodeDictionary, featureWorkspace, downloadSpatialReference, availableDomains, false); #endregion if (downloadSpatialReference != null) Marshal.ReleaseComObject(downloadSpatialReference); #region for local geodatabases enforce spatial integrity bool storedOriginalLocal = geoProcessor.AddOutputsToMap; geoProcessor.AddOutputsToMap = false; if (osmLineFeatureClass != null) { if (((IDataset)osmLineFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace) { gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3; IGPParameter outLinesParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter; IGPValue lineFeatureClass = gpUtilities3.UnpackGPValue(outLinesParameter); DataManagementTools.RepairGeometry repairlineGeometry = new DataManagementTools.RepairGeometry(osmLineFeatureClass); IVariantArray repairGeometryParameterArray = new VarArrayClass(); repairGeometryParameterArray.Add(lineFeatureClass.GetAsText()); repairGeometryParameterArray.Add("DELETE_NULL"); gpResults2 = geoProcessor.Execute(repairlineGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2; message.AddMessages(gpResults2.GetResultMessages()); ComReleaser.ReleaseCOMObject(gpUtilities3); } } if (osmPolygonFeatureClass != null) { if (((IDataset)osmPolygonFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace) { gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3; IGPParameter outPolygonParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter; IGPValue polygonFeatureClass = gpUtilities3.UnpackGPValue(outPolygonParameter); DataManagementTools.RepairGeometry repairpolygonGeometry = new DataManagementTools.RepairGeometry(osmPolygonFeatureClass); IVariantArray repairGeometryParameterArray = new VarArrayClass(); repairGeometryParameterArray.Add(polygonFeatureClass.GetAsText()); repairGeometryParameterArray.Add("DELETE_NULL"); gpResults2 = geoProcessor.Execute(repairpolygonGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2; message.AddMessages(gpResults2.GetResultMessages()); ComReleaser.ReleaseCOMObject(gpUtilities3); } } geoProcessor.AddOutputsToMap = storedOriginalLocal; #endregion if (TrackCancel.Continue() == false) { return; } #region load relations List<string> missingRelations = osmToolHelper.loadOSMRelations(osmFileLocationString.GetAsText(), ref TrackCancel, ref message, targetDatasetGPValue, osmPointFeatureClass, osmLineFeatureClass, osmPolygonFeatureClass, Convert.ToInt32(relationCapacity), relationTable, availableDomains, fastLoad, false); #endregion // check for user interruption if (TrackCancel.Continue() == false) { return; } //storedOriginalLocal = geoProcessor.AddOutputsToMap; //try //{ // geoProcessor.AddOutputsToMap = false; // // add indexes for revisions // //IGPValue revisionTableGPValue = gpUtilities3.MakeGPValueFromObject(revisionTable); // string revisionTableString = targetDatasetGPValue.GetAsText() + System.IO.Path.DirectorySeparatorChar + ((IDataset)revisionTable).BrowseName; // IVariantArray parameterArrary2 = osmToolHelper.CreateAddIndexParameterArray(revisionTableString, "osmoldid;osmnewid", "osmID_IDX", "", ""); // gpResults2 = geoProcessor.Execute("AddIndex_management", parameterArrary2, TrackCancel) as IGeoProcessorResult2; // message.AddMessages(gpResults2.GetResultMessages()); //} //catch (Exception ex) //{ // message.AddWarning(ex.Message); //} //finally //{ // geoProcessor.AddOutputsToMap = storedOriginalLocal; //} #region update the references counts and member lists for nodes message.AddMessage(resourceManager.GetString("GPTools_OSMGPFileReader_updatereferences")); IFeatureCursor pointUpdateCursor = null; IQueryFilter pointQueryFilter = new QueryFilterClass(); // adjust of number of all other reference counter from 0 to 1 if (conserveMemoryGPValue.Value == true) { pointQueryFilter.WhereClause = osmPointFeatureClass.SqlIdentifier("wayRefCount") + " = 0"; pointQueryFilter.SubFields = osmPointFeatureClass.OIDFieldName + ",wayRefCount"; } using (SchemaLockManager ptLockManager = new SchemaLockManager(osmPointFeatureClass as ITable)) { using (ComReleaser comReleaser = new ComReleaser()) { int updateCount = 0; if (conserveMemoryGPValue.Value == true) { pointUpdateCursor = osmPointFeatureClass.Update(pointQueryFilter, false); updateCount = ((ITable)osmPointFeatureClass).RowCount(pointQueryFilter); } else { 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 positionCounter = 0; while (pointFeature != null) { positionCounter++; string nodeID = Convert.ToString(pointFeature.get_Value(osmPointIDFieldIndex)); if (conserveMemoryGPValue.Value == false) { // 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); } } else { // in the case of memory conservation let's go change the 0s to 1s pointFeature.set_Value(osmWayRefCountFieldIndex, 1); } pointUpdateCursor.UpdateFeature(pointFeature); if (pointFeature != null) Marshal.ReleaseComObject(pointFeature); pointFeature = pointUpdateCursor.NextFeature(); if (stepProgressor != null) { stepProgressor.Position = positionCounter; } } if (stepProgressor != null) { stepProgressor.Hide(); } Marshal.ReleaseComObject(pointQueryFilter); } } #endregion if (osmNodeDictionary != null) { // clear outstanding resources potentially holding points osmNodeDictionary = null; System.GC.Collect(2, GCCollectionMode.Forced); } if (missingRelations.Count > 0) { missingRelations.Clear(); missingRelations = null; } if (missingWays.Count > 0) { missingWays.Clear(); missingWays = null; } 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 pointFeatureClassGPValue = gpUtilities3.UnpackGPValue(pointFeatureClassParameter); gpUtilities3.PackGPValue(pointFeatureClassGPValue, pointFeatureClassParameter); IGPParameter lineFeatureClassParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter; IGPValue line1FeatureClassGPValue = gpUtilities3.UnpackGPValue(lineFeatureClassParameter); gpUtilities3.PackGPValue(line1FeatureClassGPValue, lineFeatureClassParameter); IGPParameter polygonFeatureClassParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter; IGPValue polygon1FeatureClassGPValue = gpUtilities3.UnpackGPValue(polygonFeatureClassParameter); gpUtilities3.PackGPValue(polygon1FeatureClassGPValue, polygonFeatureClassParameter); ComReleaser.ReleaseCOMObject(relationTable); ComReleaser.ReleaseCOMObject(revisionTable); ComReleaser.ReleaseCOMObject(targetFeatureDataset); ComReleaser.ReleaseCOMObject(featureWorkspace); ComReleaser.ReleaseCOMObject(osmFileLocationString); ComReleaser.ReleaseCOMObject(conserveMemoryGPValue); ComReleaser.ReleaseCOMObject(targetDataset); gpUtilities3.ReleaseInternals(); ComReleaser.ReleaseCOMObject(gpUtilities3); } catch (Exception ex) { message.AddError(120055, ex.Message); message.AddError(120055, ex.StackTrace); } finally { try { // TE -- 1/7/2015 // this is a 'breaking' change as the default loader won't no longer enable the edit extension // the reasoning here is that most users would like the OSM in a 'read-only' fashion, and don't need to track // changes to be properly transmitted back to the OSM server //if (osmPointFeatureClass != null) //{ // osmPointFeatureClass.ApplyOSMClassExtension(); // ComReleaser.ReleaseCOMObject(osmPointFeatureClass); //} //if (osmLineFeatureClass != null) //{ // osmLineFeatureClass.ApplyOSMClassExtension(); // ComReleaser.ReleaseCOMObject(osmLineFeatureClass); //} //if (osmPolygonFeatureClass != null) //{ // osmPolygonFeatureClass.ApplyOSMClassExtension(); // ComReleaser.ReleaseCOMObject(osmPolygonFeatureClass); //} osmToolHelper = null; System.GC.Collect(); System.GC.WaitForPendingFinalizers(); } catch (Exception ex) { message.AddError(120056, ex.ToString()); } } }
//执行GP的数据修复功能 //田晶添加20080916 //修改,提高效率 //靳军杰2011-11-30 /// <summary> /// 修复面图层自相交错误 /// </summary> /// <param name="sPath"></param> /// <returns></returns> public bool FeatureRepair(string sPath) { if (string.IsNullOrEmpty(sPath)) { return false; } IGeoProcessor pGP = new GeoProcessorClass(); try { //GT_CARTO.XApplication.ProgressBar.ShowGifProgress(null); //GT_CARTO.XApplication.ProgressBar.ShowHint("正在预处理地类图斑数据..."); //string sPath = pWks.PathName; pGP.OverwriteOutput = true; pGP.SetEnvironmentValue("workspace", (object)sPath); IGpEnumList pfds = pGP.ListFeatureClasses("", "Polygon", "Dataset"); string sFeatClsName = pfds.Next(); //IGeoProcessorResult pResult; while (!string.IsNullOrEmpty(sFeatClsName)) { if (!sFeatClsName.Contains("_Standard") && !sFeatClsName.Equals("TK", StringComparison.OrdinalIgnoreCase)) { //要修复的FeatureClass路径 string sInFeatureClassPath = string.Format("{0}\\dataset\\{1}", sPath, sFeatClsName); IVariantArray pValues = new VarArrayClass(); pValues.Add(sInFeatureClassPath); pGP.Execute("RepairGeometry", pValues, null); object obj = 2; //GT_CONST.LogAPI.CheckLog.AppendErrLogs(pGP.GetMessages(ref obj)); } sFeatClsName = pfds.Next(); } return true; } catch (Exception exp) { Hy.Common.Utility.Log.OperationalLogManager.AppendMessage(exp.ToString()); //GT_CARTO.XApplication.ProgressBar.Hide(); return false; } finally { //GT_CARTO.XApplication.ProgressBar.Hide(); Marshal.ReleaseComObject(pGP); } }
/// <summary> /// Called when a step of this type is executed in the workflow. /// </summary> /// <param name="JobID">ID of the job being executed</param> /// <param name="StepID">ID of the step being executed</param> /// <param name="argv">Array of arguments passed into the step's execution</param> /// <param name="ipFeedback">Feedback object to return status messages and files</param> /// <returns>Return code of execution for workflow path traversal</returns> public int Execute(int jobID, int stepID, ref object[] argv, ref IJTXCustomStepFeedback ipFeedback) { #if (!SERVER) StatusForm sfd = null; #endif bool success = true; // Reset the message logging this.ClearCachedLogMessages(); try { Log("ExecuteGPTool.Execute beginning.."); // Define variables string strToolboxPath = ""; string strTool = ""; string strToolboxRoot = ""; string strToolboxName = ""; // Get the toolbox name (check for errors) if (!StepUtilities.GetArgument(ref argv, "toolboxpath", true, out strToolboxPath) || strToolboxPath.Equals(String.Empty)) { success = false; Log("Error getting 'toolboxpath' argument"); #if (!SERVER) MessageBox.Show("Missing toolbox argument."); #endif } // Get the tool name (check for errors) else if (!StepUtilities.GetArgument(ref argv, "tool", true, out strTool) || strTool.Equals(String.Empty)) { success = false; Log("Error getting 'tool' argument"); #if (!SERVER) MessageBox.Show("Missing tool argument."); #endif } else { #if (!SERVER) // Display status dialog sfd = new StatusForm(); sfd.ToolName = strTool; sfd.Show(); sfd.Refresh(); #endif // Get directory of toolbox strToolboxRoot = Path.GetDirectoryName(strToolboxPath); // Get toolbox name without .tbx extension strToolboxName = Path.GetFileNameWithoutExtension(strToolboxPath); // Open toolbox and tool IWorkspaceFactory pToolboxWorkspaceFactory = new ToolboxWorkspaceFactoryClass(); IToolboxWorkspace pToolboxWorkspace = pToolboxWorkspaceFactory.OpenFromFile(strToolboxRoot, 0) as IToolboxWorkspace; IGPToolbox pGPToolbox = pToolboxWorkspace.OpenToolbox(strToolboxName); IGPTool pGPTool = pGPToolbox.OpenTool(strTool); Log("ExecuteGPTool.Execute successfully opened Tool " + strTool + " in Toolbox " + strToolboxPath + ".."); // Generate the arrays for parameters IVariantArray parameters = new VarArrayClass(); // For Execute method ESRI.ArcGIS.esriSystem.IArray pParameterArray = pGPTool.ParameterInfo; // For Validate and InvokeModal methods // Get parameter "pairs"; "GetDoubleArguments" supports the GP-style, // two-colon argument strings, like "/param:tool_param_name:tool_param_value" string[] argNames; string[] argValues; if (StepUtilities.GetDoubleArguments(ref argv, "param", true, out argNames, out argValues)) { // Stash away the variables that were passed in Dictionary<string, string> argTable = new Dictionary<string, string>(); for (int i = 0; i < argNames.Length; i++) { string uppercaseName = argNames[i].ToUpper(); argTable[uppercaseName] = argValues[i]; } // The GP tool's parameter list may include parameters that weren't specified in the // JTX step arguments. So iterate through the tool's parameters, setting the values // from the input where you can. Where no value was passed in, just skip the // parameter and go with the default. for (int i = 0; i < pParameterArray.Count; i++) { IGPParameter pGPParam = (IGPParameter)pParameterArray.get_Element(i); IGPParameterEdit pGPParamEdit = (IGPParameterEdit)pGPParam; string uppercaseName = pGPParam.Name.ToUpper(); // Override the default value, if something was passed in if (argTable.ContainsKey(uppercaseName)) { IGPDataType pGPType = pGPParam.DataType; string strValue = argTable[uppercaseName]; pGPParamEdit.Value = pGPType.CreateValue(strValue); Log("ExecuteGPTool.Execute Tool Parameter = " + uppercaseName + ", Value = " + strValue + ".."); } // Always stash away the current parameter value, since we need the complete list // for "Execute" below. parameters.Add(pGPParam.Value); } } Log("ExecuteGPTool.Execute successfully setup parameter values.."); // Initialize the geoprocessor IGeoProcessor pGP = new GeoProcessorClass(); // Create callback object for GP messages JTXGPCallback pCallback = new JTXGPCallback(); // Set up the geoprocessor pGP.AddToolbox(strToolboxPath); pGP.RegisterGeoProcessorEvents(pCallback); Log("ExecuteGPTool.Execute created and registered GeoProcessor.."); // Create the messages object and a bool to pass to InvokeModal method IGPMessages pGPMessages = pGPTool.Validate(pParameterArray, true, null); IGPMessages pInvokeMessages = new GPMessagesClass(); string strMessage = ""; // Check for error messages if (pGPMessages.MaxSeverity == esriGPMessageSeverity.esriGPMessageSeverityError) { #if (!SERVER) // Only want to invoke a modal dialog if we're running on a workstation // Set a reference to IGPCommandHelper2 interface IGPToolCommandHelper2 pToolHelper = new GPToolCommandHelperClass() as IGPToolCommandHelper2; pToolHelper.SetTool(pGPTool); bool pOK = true; // Open tool GUI pToolHelper.InvokeModal(0, pParameterArray, out pOK, out pInvokeMessages); if (pOK == true) { bool bFailureMessages; strMessage = ConvertGPMessagesToString(pInvokeMessages, out bFailureMessages); success = !bFailureMessages; } else { success = false; } #else Log("ExecuteGPTool.Execute Tool Validate failed.."); // If we're running on a server, then just indicate a failure. (Someone will // have to use the JTX application to fix the step arguments, if they can be // fixed.) success = false; #endif } else // If there are no error messages, execute the tool { Log("ExecuteGPTool.Execute successfully validated parameter values, About to Execute.."); IGPMessages ipMessages = new GPMessagesClass(); try { pGPTool.Execute(pParameterArray, null, new GPEnvironmentManagerClass(), ipMessages); Log("ExecuteGPTool.Execute completed call to pGPTool.Execute()"); } catch (System.Runtime.InteropServices.COMException ex) { success = false; Log("ExecuteGPTool.Execute Tool Execute failed, Message = " + ex.Message + ", DataCode = " + ex.ErrorCode + ", Data = " + ex.StackTrace); } // Get Messages bool bFailureMessages = false; strMessage += this.ConvertGPMessagesToString(ipMessages, out bFailureMessages); Log("ExecuteGPTool.Execute got messages from tool"); Log("*** GP MESSAGES ***" + System.Environment.NewLine + strMessage + System.Environment.NewLine); Log("*** END GP MESSAGES ***"); // If tool failed during execution, indicate a failure if (pGP.MaxSeverity == (int)esriGPMessageSeverity.esriGPMessageSeverityError) { success = false; Log("ExecuteGPTool.Execute Found Error messages from the tool.."); } } // Call AttachMsg try { IJTXJobManager ipJobManager = m_ipDatabase.JobManager; IJTXJob ipJob = ipJobManager.GetJob(jobID); AttachMsg(ipJob, strTool, this.GetCachedLogMessages()); this.ClearCachedLogMessages(); } catch (Exception ex) { string strEx = ex.Message; Log("Caught exception: " + ex.Message); } pGP.UnRegisterGeoProcessorEvents(pCallback); } } catch (Exception ex2) { success = false; Log("Caught exception: " + ex2.Message); #if (!SERVER) string msg = ""; if (ex2.InnerException == null) { msg = "Inner Exception is null"; } else { msg = "Inner Exception is not null"; } MessageBox.Show("Stack Trace: " + ex2.StackTrace + Environment.NewLine + "Message: " + ex2.Message + Environment.NewLine + "Source: " + ex2.Source + Environment.NewLine + msg); #endif } // Clean up #if (!SERVER) if (sfd != null) { sfd.Close(); } #endif // Indicate success or failure if (success == true) { return 1; } else { return 0; } }
public IGeoProcessor getGP() { IGeoProcessor gp2 = new GeoProcessorClass(); return(gp2); }
/// <summary> /// Where all of the work is done. Override from TabBaseViewModel /// </summary> internal override void CreateMapElement() { if (!CanCreateElement || ArcMap.Document == null || ArcMap.Document.FocusMap == null || string.IsNullOrWhiteSpace(SelectedSurfaceName)) return; //base.CreateMapElement(); var surface = GetSurfaceFromMapByName(ArcMap.Document.FocusMap, SelectedSurfaceName); if (surface == null) return; using (ComReleaser oComReleaser = new ComReleaser()) { // Create feature workspace IFeatureWorkspace workspace = CreateFeatureWorkspace("tempWorkspace"); StartEditOperation((IWorkspace)workspace); // Create feature class IFeatureClass pointFc = CreateObserversFeatureClass(workspace, "Output" + RunCount.ToString()); double finalObserverOffset = GetOffsetInZUnits(ArcMap.Document.FocusMap, ObserverOffset.Value, surface.ZFactor, OffsetUnitType); double finalSurfaceOffset = GetOffsetInZUnits(ArcMap.Document.FocusMap, SurfaceOffset, surface.ZFactor, OffsetUnitType); double conversionFactor = GetConversionFactor(ArcMap.Document.FocusMap.SpatialReference); double convertedMinDistance = MinDistance * conversionFactor; double convertedMaxDistance = MaxDistance * conversionFactor; double finalMinDistance = GetLinearDistance(ArcMap.Document.FocusMap, convertedMinDistance, OffsetUnitType); double finalMaxDistance = GetLinearDistance(ArcMap.Document.FocusMap, convertedMaxDistance, OffsetUnitType); double finalLeftHorizontalFOV = GetAngularDistance(ArcMap.Document.FocusMap, LeftHorizontalFOV, AngularUnitType); double finalRightHorizontalFOV = GetAngularDistance(ArcMap.Document.FocusMap, RightHorizontalFOV, AngularUnitType); double finalBottomVerticalFOV = GetAngularDistance(ArcMap.Document.FocusMap, BottomVerticalFOV, AngularUnitType); double finalTopVerticalFOV = GetAngularDistance(ArcMap.Document.FocusMap, TopVerticalFOV, AngularUnitType); // Out radius geometries List<IGeometry> radius2GeomList = new List<IGeometry>(); List<IGeometry> radius1_2GeomList = new List<IGeometry>(); List<IGeometry> donutGeomList = new List<IGeometry>(); foreach (var observerPoint in ObserverAddInPoints) { // Create buffer geometries for final Min/Max distance ITopologicalOperator topologicalOperator = observerPoint.Point as ITopologicalOperator; IGeometry geom = topologicalOperator.Buffer(finalMaxDistance); radius2GeomList.Add(geom); radius1_2GeomList.Add(geom); if (finalMinDistance > 0) { IGeometry geom2 = topologicalOperator.Buffer(finalMinDistance); ITopologicalOperator eraseTopo = geom as ITopologicalOperator; IGeometry erasedGeom = eraseTopo.Difference(geom2); donutGeomList.Add(erasedGeom); } else { radius1_2GeomList.Add(geom); } double z1 = surface.GetElevation(observerPoint.Point) + finalObserverOffset; //create a new point feature IFeature ipFeature = pointFc.CreateFeature(); // Set the field values for the feature SetFieldValues(finalObserverOffset, finalSurfaceOffset, finalMinDistance, finalMaxDistance, finalLeftHorizontalFOV, finalRightHorizontalFOV, finalBottomVerticalFOV, finalTopVerticalFOV, ipFeature); //Create shape IPoint point = new PointClass() { Z = z1, X = observerPoint.Point.X, Y = observerPoint.Point.Y, ZAware = true }; ipFeature.Shape = point; ipFeature.Store(); } IFeatureClassDescriptor fd = new FeatureClassDescriptorClass(); fd.Create(pointFc, null, "OBJECTID"); StopEditOperation((IWorkspace)workspace); try { ILayer layer = GetLayerFromMapByName(ArcMap.Document.FocusMap, SelectedSurfaceName); string layerPath = GetLayerPath(layer); IFeatureLayer ipFeatureLayer = new FeatureLayerClass(); ipFeatureLayer.FeatureClass = pointFc; IDataset ipDataset = (IDataset)pointFc; string outputFcName = ipDataset.BrowseName + "_output"; string strPath = ipDataset.Workspace.PathName + "\\" + ipDataset.BrowseName; string outPath = ipDataset.Workspace.PathName + "\\" + outputFcName; IVariantArray parameters = new VarArrayClass(); parameters.Add(layerPath); parameters.Add(strPath); parameters.Add(outPath); esriLicenseStatus status = GetSpatialAnalystLicense(); IGeoProcessor2 gp = new GeoProcessorClass(); gp.AddOutputsToMap = false; // Add a mask to buffer the output to selected distance SetGPMask(workspace, radius2GeomList, gp, "radiusMask"); object oResult = gp.Execute("Visibility_sa", parameters, null); IGeoProcessorResult ipResult = (IGeoProcessorResult)oResult; ComReleaser.ReleaseCOMObject(gp); gp = null; GC.Collect(); // Add buffer geometries to the map foreach (IGeometry geom in radius1_2GeomList) { var color = new RgbColorClass() { Blue = 255 } as IColor; AddGraphicToMap(geom, color, true); } IRasterLayer outputRasterLayer = new RasterLayerClass(); outputRasterLayer.CreateFromFilePath(outPath); string fcName = IntersectOutput(outputRasterLayer, ipDataset, workspace, donutGeomList); IFeatureClass finalFc = workspace.OpenFeatureClass(fcName); IFeatureLayer outputFeatureLayer = new FeatureLayerClass(); outputFeatureLayer.FeatureClass = finalFc; //Add it to a map if the layer is valid. if (outputFeatureLayer != null) { // set the renderer IFeatureRenderer featRend = UnqueValueRenderer(workspace, finalFc); IGeoFeatureLayer geoLayer = outputFeatureLayer as IGeoFeatureLayer; geoLayer.Renderer = featRend; geoLayer.Name = "VisibilityLayer_" + RunCount.ToString(); // Set the layer transparency IDisplayFilterManager filterManager = (IDisplayFilterManager)outputFeatureLayer; ITransparencyDisplayFilter filter = new TransparencyDisplayFilter(); filter.Transparency = 80; filterManager.DisplayFilter = filter; ESRI.ArcGIS.Carto.IMap map = ArcMap.Document.FocusMap; map.AddLayer((ILayer)outputFeatureLayer); } RunCount += 1; } catch (Exception ex) { string exception = ex.ToString(); System.Windows.MessageBox.Show(VisibilityLibrary.Properties.Resources.MsgTryAgain, VisibilityLibrary.Properties.Resources.MsgCalcCancelled); } //Reset(true); } }
internal List<string> loadOSMRelations(string osmFileLocation, ref ITrackCancel TrackCancel, ref IGPMessages message, IGPValue targetGPValue, IFeatureClass osmPointFeatureClass, IFeatureClass osmLineFeatureClass, IFeatureClass osmPolygonFeatureClass, int relationCapacity, ITable relationTable, OSMDomains availableDomains, bool fastLoad, bool checkForExisting) { List<string> missingRelations = null; XmlReader osmFileXmlReader = null; XmlSerializer relationSerializer = null; try { missingRelations = new List<string>(); if (osmLineFeatureClass == null) { throw new ArgumentNullException("osmLineFeatureClass"); } if (osmPolygonFeatureClass == null) { throw new ArgumentNullException("osmPolygonFeatureClass"); } if (relationTable == null) { throw new ArgumentNullException("relationTable"); } int osmPointIDFieldIndex = osmPointFeatureClass.FindField("OSMID"); Dictionary<string, int> osmPointDomainAttributeFieldIndices = new Dictionary<string, int>(); foreach (var domains in availableDomains.domain) { int currentFieldIndex = osmPointFeatureClass.FindField(domains.name); if (currentFieldIndex != -1) { osmPointDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex); } } int tagCollectionPointFieldIndex = osmPointFeatureClass.FindField("osmTags"); int osmUserPointFieldIndex = osmPointFeatureClass.FindField("osmuser"); int osmUIDPointFieldIndex = osmPointFeatureClass.FindField("osmuid"); int osmVisiblePointFieldIndex = osmPointFeatureClass.FindField("osmvisible"); int osmVersionPointFieldIndex = osmPointFeatureClass.FindField("osmversion"); int osmChangesetPointFieldIndex = osmPointFeatureClass.FindField("osmchangeset"); int osmTimeStampPointFieldIndex = osmPointFeatureClass.FindField("osmtimestamp"); int osmMemberOfPointFieldIndex = osmPointFeatureClass.FindField("osmMemberOf"); int osmSupportingElementPointFieldIndex = osmPointFeatureClass.FindField("osmSupportingElement"); int osmWayRefCountFieldIndex = osmPointFeatureClass.FindField("wayRefCount"); int osmLineIDFieldIndex = osmLineFeatureClass.FindField("OSMID"); Dictionary<string, int> osmLineDomainAttributeFieldIndices = new Dictionary<string, int>(); Dictionary<string, int> osmLineDomainAttributeFieldLength = new Dictionary<string, int>(); foreach (var domains in availableDomains.domain) { int currentFieldIndex = osmLineFeatureClass.FindField(domains.name); if (currentFieldIndex != -1) { osmLineDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex); osmLineDomainAttributeFieldLength.Add(domains.name, osmLineFeatureClass.Fields.get_Field(currentFieldIndex).Length); } } int tagCollectionPolylineFieldIndex = osmLineFeatureClass.FindField("osmTags"); int osmUserPolylineFieldIndex = osmLineFeatureClass.FindField("osmuser"); int osmUIDPolylineFieldIndex = osmLineFeatureClass.FindField("osmuid"); int osmVisiblePolylineFieldIndex = osmLineFeatureClass.FindField("osmvisible"); int osmVersionPolylineFieldIndex = osmLineFeatureClass.FindField("osmversion"); int osmChangesetPolylineFieldIndex = osmLineFeatureClass.FindField("osmchangeset"); int osmTimeStampPolylineFieldIndex = osmLineFeatureClass.FindField("osmtimestamp"); int osmMemberOfPolylineFieldIndex = osmLineFeatureClass.FindField("osmMemberOf"); int osmMembersPolylineFieldIndex = osmLineFeatureClass.FindField("osmMembers"); int osmSupportingElementPolylineFieldIndex = osmLineFeatureClass.FindField("osmSupportingElement"); int osmPolygonIDFieldIndex = osmPolygonFeatureClass.FindField("OSMID"); Dictionary<string, int> osmPolygonDomainAttributeFieldIndices = new Dictionary<string, int>(); Dictionary<string, int> osmPolygonDomainAttributeFieldLength = new Dictionary<string, int>(); foreach (var domains in availableDomains.domain) { int currentFieldIndex = osmPolygonFeatureClass.FindField(domains.name); if (currentFieldIndex != -1) { osmPolygonDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex); osmPolygonDomainAttributeFieldLength.Add(domains.name, osmPolygonFeatureClass.Fields.get_Field(currentFieldIndex).Length); } } int tagCollectionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmTags"); int osmUserPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuser"); int osmUIDPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuid"); int osmVisiblePolygonFieldIndex = osmPolygonFeatureClass.FindField("osmvisible"); int osmVersionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmversion"); int osmChangesetPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmchangeset"); int osmTimeStampPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmtimestamp"); int osmMemberOfPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMemberOf"); int osmMembersPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMembers"); int osmSupportingElementPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmSupportingElement"); int osmRelationIDFieldIndex = relationTable.FindField("OSMID"); int tagCollectionRelationFieldIndex = relationTable.FindField("osmTags"); int osmUserRelationFieldIndex = relationTable.FindField("osmuser"); int osmUIDRelationFieldIndex = relationTable.FindField("osmuid"); int osmVisibleRelationFieldIndex = relationTable.FindField("osmvisible"); int osmVersionRelationFieldIndex = relationTable.FindField("osmversion"); int osmChangesetRelationFieldIndex = relationTable.FindField("osmchangeset"); int osmTimeStampRelationFieldIndex = relationTable.FindField("osmtimestamp"); int osmMemberOfRelationFieldIndex = relationTable.FindField("osmMemberOf"); int osmMembersRelationFieldIndex = relationTable.FindField("osmMembers"); int osmSupportingElementRelationFieldIndex = relationTable.FindField("osmSupportingElement"); // list for reference count and relation list for lines/polygons/relations // set up the progress indicator IStepProgressor stepProgressor = TrackCancel as IStepProgressor; if (stepProgressor != null) { stepProgressor.MinRange = 0; stepProgressor.MaxRange = relationCapacity; stepProgressor.Position = 0; stepProgressor.Message = _resourceManager.GetString("GPTools_OSMGPFileReader_loadingRelations"); stepProgressor.StepValue = 1; stepProgressor.Show(); } bool relationIndexRebuildRequired = false; if (relationTable != null) { osmFileXmlReader = System.Xml.XmlReader.Create(osmFileLocation); relationSerializer = new XmlSerializer(typeof(relation)); using (ComReleaser comReleaser = new ComReleaser()) { using (SchemaLockManager linelock = new SchemaLockManager(osmLineFeatureClass as ITable), polygonLock = new SchemaLockManager(osmPolygonFeatureClass as ITable), relationLock = new SchemaLockManager(relationTable)) { ICursor rowCursor = relationTable.Insert(true); comReleaser.ManageLifetime(rowCursor); IRowBuffer rowBuffer = relationTable.CreateRowBuffer(); comReleaser.ManageLifetime(rowBuffer); IFeatureCursor lineFeatureInsertCursor = osmLineFeatureClass.Insert(true); comReleaser.ManageLifetime(lineFeatureInsertCursor); IFeatureBuffer lineFeatureBuffer = osmLineFeatureClass.CreateFeatureBuffer(); comReleaser.ManageLifetime(lineFeatureBuffer); IFeatureCursor polygonFeatureInsertCursor = osmPolygonFeatureClass.Insert(true); comReleaser.ManageLifetime(polygonFeatureInsertCursor); IFeatureBuffer polygonFeatureBuffer = osmPolygonFeatureClass.CreateFeatureBuffer(); comReleaser.ManageLifetime(polygonFeatureBuffer); int relationCount = 1; int relationDebugCount = 1; string lineSQLIdentifier = osmLineFeatureClass.SqlIdentifier("OSMID"); string polygonSQLIdentifier = osmPolygonFeatureClass.SqlIdentifier("OSMID"); message.AddMessage(_resourceManager.GetString("GPTools_OSMGPFileReader_resolvegeometries")); osmFileXmlReader.MoveToContent(); while (osmFileXmlReader.Read()) { if (osmFileXmlReader.IsStartElement()) { if (osmFileXmlReader.Name == "relation") { relation currentRelation = null; try { // read the full relation node string currentrelationString = osmFileXmlReader.ReadOuterXml(); using (StringReader relationReader = new System.IO.StringReader(currentrelationString)) { // de-serialize the xml into to the class instance currentRelation = relationSerializer.Deserialize(relationReader) as relation; } if (currentRelation == null) continue; relationDebugCount = relationDebugCount + 1; esriGeometryType detectedGeometryType = determineRelationGeometryType(osmLineFeatureClass, osmPolygonFeatureClass, relationTable, currentRelation); if (checkForExisting) { switch (detectedGeometryType) { case esriGeometryType.esriGeometryAny: if (CheckIfExists(relationTable, currentRelation.id)) continue; break; case esriGeometryType.esriGeometryBag: if (CheckIfExists(relationTable, currentRelation.id)) continue; break; case esriGeometryType.esriGeometryBezier3Curve: break; case esriGeometryType.esriGeometryCircularArc: break; case esriGeometryType.esriGeometryEllipticArc: break; case esriGeometryType.esriGeometryEnvelope: break; case esriGeometryType.esriGeometryLine: if (CheckIfExists(osmLineFeatureClass as ITable, currentRelation.id)) continue; break; case esriGeometryType.esriGeometryMultiPatch: break; case esriGeometryType.esriGeometryMultipoint: break; case esriGeometryType.esriGeometryNull: if (CheckIfExists(relationTable, currentRelation.id)) continue; break; case esriGeometryType.esriGeometryPath: break; case esriGeometryType.esriGeometryPoint: break; case esriGeometryType.esriGeometryPolygon: if (CheckIfExists(osmPolygonFeatureClass as ITable, currentRelation.id)) continue; break; case esriGeometryType.esriGeometryPolyline: if (CheckIfExists(osmLineFeatureClass as ITable, currentRelation.id)) continue; break; case esriGeometryType.esriGeometryRay: break; case esriGeometryType.esriGeometryRing: break; case esriGeometryType.esriGeometrySphere: break; case esriGeometryType.esriGeometryTriangleFan: break; case esriGeometryType.esriGeometryTriangleStrip: break; case esriGeometryType.esriGeometryTriangles: break; default: break; } } List<tag> relationTagList = new List<tag>(); List<member> relationMemberList = new List<member>(); Dictionary<string, string> wayList = new Dictionary<string, string>(); // sanity check that the overall relation notation contains at least something if (currentRelation.Items == null) continue; List<OSMNodeFeature> osmPointList = null; List<OSMLineFeature> osmLineList = null; List<OSMPolygonFeature> osmPolygonList = null; List<OSMRelation> osmRelationList = null; rowBuffer = relationTable.CreateRowBuffer(); comReleaser.ManageLifetime(rowBuffer); lineFeatureBuffer = osmLineFeatureClass.CreateFeatureBuffer(); comReleaser.ManageLifetime(lineFeatureBuffer); polygonFeatureBuffer = osmPolygonFeatureClass.CreateFeatureBuffer(); comReleaser.ManageLifetime(polygonFeatureBuffer); foreach (var item in currentRelation.Items) { if (item is member) { member memberItem = item as member; relationMemberList.Add(memberItem); switch (memberItem.type) { case memberType.way: if (!wayList.ContainsKey(memberItem.@ref)) wayList.Add(memberItem.@ref, memberItem.role); if (IsThisWayALine(memberItem.@ref, osmLineFeatureClass, lineSQLIdentifier, osmPolygonFeatureClass, polygonSQLIdentifier)) { if (osmLineList == null) { osmLineList = new List<OSMLineFeature>(); } OSMLineFeature lineFeature = new OSMLineFeature(); lineFeature.relationList = new List<string>(); lineFeature.lineID = memberItem.@ref; if (detectedGeometryType == esriGeometryType.esriGeometryPolygon) { lineFeature.relationList.Add(currentRelation.id + "_ply"); } else if (detectedGeometryType == esriGeometryType.esriGeometryPolyline) { lineFeature.relationList.Add(currentRelation.id + "_ln"); } else { lineFeature.relationList.Add(currentRelation.id + "_rel"); } osmLineList.Add(lineFeature); } else { if (osmPolygonList == null) { osmPolygonList = new List<OSMPolygonFeature>(); } OSMPolygonFeature polygonFeature = new OSMPolygonFeature(); polygonFeature.relationList = new List<string>(); polygonFeature.polygonID = memberItem.@ref; if (detectedGeometryType == esriGeometryType.esriGeometryPolygon) { polygonFeature.relationList.Add(currentRelation.id + "_ply"); } else if (detectedGeometryType == esriGeometryType.esriGeometryPolyline) { polygonFeature.relationList.Add(currentRelation.id + "_ln"); } else { polygonFeature.relationList.Add(currentRelation.id + "_rel"); } osmPolygonList.Add(polygonFeature); } break; case memberType.node: if (osmPointList == null) { osmPointList = new List<OSMNodeFeature>(); } OSMNodeFeature nodeFeature = new OSMNodeFeature(); nodeFeature.relationList = new List<string>(); nodeFeature.nodeID = memberItem.@ref; nodeFeature.relationList.Add(currentRelation.id + "_rel"); osmPointList.Add(nodeFeature); break; case memberType.relation: if (osmRelationList == null) { osmRelationList = new List<OSMRelation>(); } OSMRelation relation = new OSMRelation(); relation.relationList = new List<string>(); relation.relationID = memberItem.@ref; relation.relationList.Add(currentRelation.id + "_rel"); break; default: break; } } else if (item is tag) { relationTagList.Add((tag)item); } } // if there is a defined geometry type use it to generate a multipart geometry if (detectedGeometryType == esriGeometryType.esriGeometryPolygon) { #region create multipart polygon geometry //IFeature mpFeature = osmPolygonFeatureClass.CreateFeature(); IPolygon relationMPPolygon = new PolygonClass(); relationMPPolygon.SpatialReference = ((IGeoDataset)osmPolygonFeatureClass).SpatialReference; ISegmentCollection relationPolygonGeometryCollection = relationMPPolygon as ISegmentCollection; IQueryFilter osmIDQueryFilter = new QueryFilterClass(); string sqlPolyOSMID = osmPolygonFeatureClass.SqlIdentifier("OSMID"); object missing = Type.Missing; bool relationComplete = true; // loop through the list of referenced ways that are listed in a relation // for each of the items we need to make a decision if they have merit to qualify as stand-alone features // due to the presence of meaningful attributes (tags) foreach (KeyValuePair<string, string> wayKey in wayList) { if (relationComplete == false) break; if (TrackCancel.Continue() == false) { return missingRelations; } osmIDQueryFilter.WhereClause = sqlPolyOSMID + " = '" + wayKey.Key + "'"; System.Diagnostics.Debug.WriteLine("Relation (Polygon) #: " + relationDebugCount + " :___: " + currentRelation.id + " :___: " + wayKey.Key); using (ComReleaser relationComReleaser = new ComReleaser()) { IFeatureCursor featureCursor = osmPolygonFeatureClass.Search(osmIDQueryFilter, false); relationComReleaser.ManageLifetime(featureCursor); IFeature partFeature = featureCursor.NextFeature(); // set the appropriate field attribute to become invisible as a standalone features if (partFeature != null) { IGeometryCollection ringCollection = partFeature.Shape as IGeometryCollection; // test for available content in the geometry collection if (ringCollection.GeometryCount > 0) { // test if we dealing with a valid geometry if (ringCollection.get_Geometry(0).IsEmpty == false) { // add it to the new geometry and mark the added geometry as a supporting element relationPolygonGeometryCollection.AddSegmentCollection((ISegmentCollection)ringCollection.get_Geometry(0)); if (osmSupportingElementPolygonFieldIndex > -1) { // if the member of a relation has the role of "inner" and it has tags, then let's keep it // as a standalone feature as well // the geometry is then a hole in the relation but due to the tags it also has merits to be // considered a stand-alone feature if (wayKey.Value.ToLower().Equals("inner")) { if (!_osmUtility.DoesHaveKeys(partFeature, tagCollectionPolygonFieldIndex, null)) { partFeature.set_Value(osmSupportingElementPolygonFieldIndex, "yes"); } } else { // relation member without an explicit role or the role of "outer" are turned into // supporting features if they don't have relevant attribute if (!_osmUtility.DoesHaveKeys(partFeature, tagCollectionPolylineFieldIndex, null)) { partFeature.set_Value(osmSupportingElementPolygonFieldIndex, "yes"); } } } partFeature.Store(); } } } else { // it still can be a line geometry that will be pieced together into a polygon IFeatureCursor lineFeatureCursor = osmLineFeatureClass.Search(osmIDQueryFilter, false); relationComReleaser.ManageLifetime(lineFeatureCursor); partFeature = lineFeatureCursor.NextFeature(); if (partFeature != null) { IGeometryCollection ringCollection = partFeature.Shape as IGeometryCollection; // test for available content in the geometry collection if (ringCollection.GeometryCount > 0) { // test if we dealing with a valid geometry if (ringCollection.get_Geometry(0).IsEmpty == false) { // add it to the new geometry and mark the added geometry as a supporting element relationPolygonGeometryCollection.AddSegmentCollection((ISegmentCollection)ringCollection.get_Geometry(0)); if (osmSupportingElementPolylineFieldIndex > -1) { // if the member of a relation has the role of "inner" and it has tags, then let's keep it // as a standalone feature as well // the geometry is then a hole in the relation but due to the tags it also has merits to be // considered a stand-alone feature if (wayKey.Value.ToLower().Equals("inner")) { if (!_osmUtility.DoesHaveKeys(partFeature, tagCollectionPolylineFieldIndex, null)) { partFeature.set_Value(osmSupportingElementPolylineFieldIndex, "yes"); } } else { // relation member without an explicit role or the role of "outer" are turned into // supporting features if they don't have relevant attribute if (!_osmUtility.DoesHaveKeys(partFeature, tagCollectionPolylineFieldIndex, null)) { partFeature.set_Value(osmSupportingElementPolylineFieldIndex, "yes"); } } } partFeature.Store(); } } } else { relationComplete = false; continue; } } } } // mark the relation as incomplete if (relationComplete == false) { missingRelations.Add(currentRelation.id); continue; } // transform the added collections for geometries into a topological correct geometry representation ((IPolygon4)relationMPPolygon).SimplifyEx(true, false, true); polygonFeatureBuffer.Shape = relationMPPolygon; if (_osmUtility.DoesHaveKeys(currentRelation)) { } else { relationTagList = MergeTagsFromOuterPolygonToRelation(currentRelation, osmPolygonFeatureClass); } insertTags(osmPolygonDomainAttributeFieldIndices, osmPolygonDomainAttributeFieldLength, tagCollectionPolygonFieldIndex, polygonFeatureBuffer, relationTagList.ToArray()); if (fastLoad == false) { if (osmMembersPolygonFieldIndex > -1) { _osmUtility.insertMembers(osmMembersPolygonFieldIndex, (IFeature)polygonFeatureBuffer, relationMemberList.ToArray()); } // store the administrative attributes // user, uid, version, changeset, timestamp, visible if (osmUserPolygonFieldIndex != -1) { if (!String.IsNullOrEmpty(currentRelation.user)) { polygonFeatureBuffer.set_Value(osmUserPolygonFieldIndex, currentRelation.user); } } if (osmUIDPolygonFieldIndex != -1) { if (!String.IsNullOrEmpty(currentRelation.uid)) { polygonFeatureBuffer.set_Value(osmUIDPolygonFieldIndex, Convert.ToInt32(currentRelation.uid)); } } if (osmVisiblePolygonFieldIndex != -1) { if (String.IsNullOrEmpty(currentRelation.visible) == false) { polygonFeatureBuffer.set_Value(osmVisiblePolygonFieldIndex, currentRelation.visible.ToString()); } else { polygonFeatureBuffer.set_Value(osmVisiblePolygonFieldIndex, "unknown"); } } if (osmVersionPolygonFieldIndex != -1) { if (!String.IsNullOrEmpty(currentRelation.version)) { polygonFeatureBuffer.set_Value(osmVersionPolygonFieldIndex, Convert.ToInt32(currentRelation.version)); } } if (osmChangesetPolygonFieldIndex != -1) { if (!String.IsNullOrEmpty(currentRelation.changeset)) { polygonFeatureBuffer.set_Value(osmChangesetPolygonFieldIndex, Convert.ToInt32(currentRelation.changeset)); } } if (osmTimeStampPolygonFieldIndex != -1) { if (!String.IsNullOrEmpty(currentRelation.timestamp)) { polygonFeatureBuffer.set_Value(osmTimeStampPolygonFieldIndex, Convert.ToDateTime(currentRelation.timestamp)); } } if (osmPolygonIDFieldIndex != -1) { polygonFeatureBuffer.set_Value(osmPolygonIDFieldIndex, currentRelation.id); } if (osmSupportingElementPolygonFieldIndex > -1) { polygonFeatureBuffer.set_Value(osmSupportingElementPolygonFieldIndex, "no"); } } try { //mpFeature.Store(); polygonFeatureInsertCursor.InsertFeature(polygonFeatureBuffer); } catch (Exception ex) { message.AddWarning(ex.Message); } #endregion } else if (detectedGeometryType == esriGeometryType.esriGeometryPolyline) { #region create multipart polyline geometry //IFeature mpFeature = osmLineFeatureClass.CreateFeature(); IPolyline relationMPPolyline = new PolylineClass(); relationMPPolyline.SpatialReference = ((IGeoDataset)osmLineFeatureClass).SpatialReference; IGeometryCollection relationPolylineGeometryCollection = relationMPPolyline as IGeometryCollection; IQueryFilter osmIDQueryFilter = new QueryFilterClass(); object missing = Type.Missing; // loop through the foreach (KeyValuePair<string, string> wayKey in wayList) { if (TrackCancel.Continue() == false) { return missingRelations; } osmIDQueryFilter.WhereClause = osmLineFeatureClass.WhereClauseByExtensionVersion(wayKey.Key, "OSMID", 2); System.Diagnostics.Debug.WriteLine("Relation (Polyline) #: " + relationDebugCount + " :___: " + currentRelation.id + " :___: " + wayKey); using (ComReleaser relationComReleaser = new ComReleaser()) { IFeatureCursor featureCursor = osmLineFeatureClass.Search(osmIDQueryFilter, false); relationComReleaser.ManageLifetime(featureCursor); IFeature partFeature = featureCursor.NextFeature(); // set the appropriate field attribute to become invisible as a standalone features if (partFeature != null) { if (partFeature.Shape.IsEmpty == false) { IGeometryCollection pathCollection = partFeature.Shape as IGeometryCollection; relationPolylineGeometryCollection.AddGeometry(pathCollection.get_Geometry(0), ref missing, ref missing); if (osmSupportingElementPolylineFieldIndex > -1) { if (!_osmUtility.DoesHaveKeys(partFeature, tagCollectionPolylineFieldIndex, null)) { partFeature.set_Value(osmSupportingElementPolylineFieldIndex, "yes"); } } partFeature.Store(); } } } } lineFeatureBuffer.Shape = relationMPPolyline; insertTags(osmLineDomainAttributeFieldIndices, osmLineDomainAttributeFieldLength, tagCollectionPolylineFieldIndex, lineFeatureBuffer, relationTagList.ToArray()); if (fastLoad == false) { if (osmMembersPolylineFieldIndex > -1) { _osmUtility.insertMembers(osmMembersPolylineFieldIndex, (IFeature)lineFeatureBuffer, relationMemberList.ToArray()); } // store the administrative attributes // user, uid, version, changeset, timestamp, visible if (osmUserPolylineFieldIndex != -1) { if (!String.IsNullOrEmpty(currentRelation.user)) { lineFeatureBuffer.set_Value(osmUserPolylineFieldIndex, currentRelation.user); } } if (osmUIDPolylineFieldIndex != -1) { if (!String.IsNullOrEmpty(currentRelation.uid)) { lineFeatureBuffer.set_Value(osmUIDPolylineFieldIndex, Convert.ToInt32(currentRelation.uid)); } } if (osmVisiblePolylineFieldIndex != -1) { if (String.IsNullOrEmpty(currentRelation.visible) == false) { lineFeatureBuffer.set_Value(osmVisiblePolylineFieldIndex, currentRelation.visible.ToString()); } else { lineFeatureBuffer.set_Value(osmVisiblePolylineFieldIndex, "unknown"); } } if (osmVersionPolylineFieldIndex != -1) { if (!String.IsNullOrEmpty(currentRelation.version)) { lineFeatureBuffer.set_Value(osmVersionPolylineFieldIndex, Convert.ToInt32(currentRelation.version)); } } if (osmChangesetPolylineFieldIndex != -1) { if (!String.IsNullOrEmpty(currentRelation.changeset)) { lineFeatureBuffer.set_Value(osmChangesetPolylineFieldIndex, Convert.ToInt32(currentRelation.changeset)); } } if (osmTimeStampPolylineFieldIndex != -1) { if (!String.IsNullOrEmpty(currentRelation.timestamp)) { lineFeatureBuffer.set_Value(osmTimeStampPolylineFieldIndex, Convert.ToDateTime(currentRelation.timestamp)); } } if (osmLineIDFieldIndex != -1) { lineFeatureBuffer.set_Value(osmLineIDFieldIndex, currentRelation.id); } if (osmSupportingElementPolylineFieldIndex > -1) { lineFeatureBuffer.set_Value(osmSupportingElementPolylineFieldIndex, "no"); } } try { lineFeatureInsertCursor.InsertFeature(lineFeatureBuffer); } catch (Exception ex) { message.AddWarning(ex.Message); } #endregion } else if (detectedGeometryType == esriGeometryType.esriGeometryPoint) { System.Diagnostics.Debug.WriteLine("Relation #: " + relationDebugCount + " :____: POINT!!!"); if (TrackCancel.Continue() == false) { return missingRelations; } } else // otherwise it is relation that needs to be dealt with separately { if (TrackCancel.Continue() == false) { return missingRelations; } System.Diagnostics.Debug.WriteLine("Relation #: " + relationDebugCount + " :____: Kept as relation"); if (tagCollectionRelationFieldIndex != -1) { _osmUtility.insertOSMTags(tagCollectionRelationFieldIndex, rowBuffer, relationTagList.ToArray()); } if (fastLoad == false) { if (osmMembersRelationFieldIndex != -1) { _osmUtility.insertMembers(osmMembersRelationFieldIndex, rowBuffer, relationMemberList.ToArray()); } // store the administrative attributes // user, uid, version, changeset, timestamp, visible if (osmUserRelationFieldIndex != -1) { if (!String.IsNullOrEmpty(currentRelation.user)) { rowBuffer.set_Value(osmUserRelationFieldIndex, currentRelation.user); } } if (osmUIDRelationFieldIndex != -1) { if (!String.IsNullOrEmpty(currentRelation.uid)) { rowBuffer.set_Value(osmUIDRelationFieldIndex, Convert.ToInt64(currentRelation.uid)); } } if (osmVisibleRelationFieldIndex != -1) { if (currentRelation.visible != null) { rowBuffer.set_Value(osmVisibleRelationFieldIndex, currentRelation.visible.ToString()); } } if (osmVersionRelationFieldIndex != -1) { if (!String.IsNullOrEmpty(currentRelation.version)) { rowBuffer.set_Value(osmVersionRelationFieldIndex, Convert.ToInt32(currentRelation.version)); } } if (osmChangesetRelationFieldIndex != -1) { if (!String.IsNullOrEmpty(currentRelation.changeset)) { rowBuffer.set_Value(osmChangesetRelationFieldIndex, Convert.ToInt32(currentRelation.changeset)); } } if (osmTimeStampRelationFieldIndex != -1) { if (!String.IsNullOrEmpty(currentRelation.timestamp)) { try { rowBuffer.set_Value(osmTimeStampRelationFieldIndex, Convert.ToDateTime(currentRelation.timestamp)); } catch (Exception ex) { message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_invalidTimeFormat"), ex.Message)); } } } if (osmRelationIDFieldIndex != -1) { rowBuffer.set_Value(osmRelationIDFieldIndex, currentRelation.id); } } try { rowCursor.InsertRow(rowBuffer); relationCount = relationCount + 1; relationIndexRebuildRequired = true; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } // check for user interruption if (TrackCancel.Continue() == false) { return missingRelations; } } // update the isMemberOf fields of the attached features if (osmPointList != null) { foreach (OSMNodeFeature nodeFeature in osmPointList) { updateIsMemberOf(osmLineFeatureClass, osmMemberOfPolylineFieldIndex, nodeFeature.nodeID, nodeFeature.relationList); } } if (osmLineList != null) { foreach (OSMLineFeature lineFeature in osmLineList) { updateIsMemberOf(osmLineFeatureClass, osmMemberOfPolylineFieldIndex, lineFeature.lineID, lineFeature.relationList); } } if (osmPolygonList != null) { foreach (OSMPolygonFeature polygonFeature in osmPolygonList) { updateIsMemberOf(osmLineFeatureClass, osmMemberOfPolylineFieldIndex, polygonFeature.polygonID, polygonFeature.relationList); } } if (stepProgressor != null) { stepProgressor.Position = relationCount; } if ((relationCount % 50000) == 0) { message.AddMessage(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_relationsloaded"), relationCount)); } } catch (Exception ex) { message.AddWarning(ex.Message); } finally { if (rowBuffer != null) { Marshal.ReleaseComObject(rowBuffer); if (rowBuffer != null) rowBuffer = null; } if (lineFeatureBuffer != null) { Marshal.ReleaseComObject(lineFeatureBuffer); if (lineFeatureBuffer != null) lineFeatureBuffer = null; } if (polygonFeatureBuffer != null) { Marshal.ReleaseComObject(polygonFeatureBuffer); if (polygonFeatureBuffer != null) polygonFeatureBuffer = null; } currentRelation = null; } } } } // close the OSM file osmFileXmlReader.Close(); // flush any remaining entities from the cursor rowCursor.Flush(); polygonFeatureInsertCursor.Flush(); lineFeatureInsertCursor.Flush(); // force a garbage collection System.GC.Collect(); // let the user know that we are done dealing with the relations message.AddMessage(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_relationsloaded"), relationCount)); } } if (stepProgressor != null) { stepProgressor.Hide(); } // Addd index for osmid column as well IGeoProcessor2 geoProcessor = new GeoProcessorClass(); bool storedOriginalLocal = geoProcessor.AddOutputsToMap; IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); try { geoProcessor.AddOutputsToMap = false; if (relationIndexRebuildRequired) { IIndexes tableIndexes = relationTable.Indexes; int indexPosition = -1; tableIndexes.FindIndex("osmID_IDX", out indexPosition); if (indexPosition == -1) { IGPValue relationTableGPValue = gpUtilities3.MakeGPValueFromObject(relationTable); string sddd = targetGPValue.GetAsText(); string tableLocation = GetLocationString(targetGPValue, relationTable); IVariantArray parameterArrary = CreateAddIndexParameterArray(tableLocation, "OSMID", "osmID_IDX", "UNIQUE", ""); IGeoProcessorResult2 gpResults2 = geoProcessor.Execute("AddIndex_management", parameterArrary, TrackCancel) as IGeoProcessorResult2; } } } catch (Exception ex) { message.AddWarning(ex.Message); } finally { geoProcessor.AddOutputsToMap = storedOriginalLocal; Marshal.FinalReleaseComObject(gpUtilities3); Marshal.FinalReleaseComObject(geoProcessor); } } } catch (Exception ex) { } finally { if (relationSerializer != null) relationSerializer = null; if (osmFileXmlReader != null) osmFileXmlReader = null; System.GC.Collect(); System.GC.WaitForPendingFinalizers(); } return missingRelations; }
internal void loadOSMNodes(string osmFileLocation, ref ITrackCancel TrackCancel, ref IGPMessages message,IGPValue targetGPValue, IFeatureClass osmPointFeatureClass, bool conserveMemory, bool fastLoad, int nodeCapacity, ref Dictionary<string, simplePointRef> osmNodeDictionary, IFeatureWorkspace featureWorkspace, ISpatialReference downloadSpatialReference, OSMDomains availableDomains, bool checkForExisting) { XmlReader osmFileXmlReader = null; XmlSerializer nodeSerializer = null; try { osmFileXmlReader = System.Xml.XmlReader.Create(osmFileLocation); nodeSerializer = new XmlSerializer(typeof(node)); ISpatialReferenceFactory spatialRef = new SpatialReferenceEnvironmentClass(); ISpatialReference wgs84 = spatialRef.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); bool shouldProject = !((IClone)wgs84).IsEqual((IClone)downloadSpatialReference); int osmPointIDFieldIndex = osmPointFeatureClass.FindField("OSMID"); Dictionary<string, int> osmPointDomainAttributeFieldIndices = new Dictionary<string, int>(); Dictionary<string, int> osmPointDomainAttributeFieldLength = new Dictionary<string, int>(); foreach (var domains in availableDomains.domain) { int currentFieldIndex = osmPointFeatureClass.FindField(domains.name); if (currentFieldIndex != -1) { osmPointDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex); osmPointDomainAttributeFieldLength.Add(domains.name, osmPointFeatureClass.Fields.get_Field(currentFieldIndex).Length); } } int tagCollectionPointFieldIndex = osmPointFeatureClass.FindField("osmTags"); int osmUserPointFieldIndex = osmPointFeatureClass.FindField("osmuser"); int osmUIDPointFieldIndex = osmPointFeatureClass.FindField("osmuid"); int osmVisiblePointFieldIndex = osmPointFeatureClass.FindField("osmvisible"); int osmVersionPointFieldIndex = osmPointFeatureClass.FindField("osmversion"); int osmChangesetPointFieldIndex = osmPointFeatureClass.FindField("osmchangeset"); int osmTimeStampPointFieldIndex = osmPointFeatureClass.FindField("osmtimestamp"); int osmMemberOfPointFieldIndex = osmPointFeatureClass.FindField("osmMemberOf"); int osmSupportingElementPointFieldIndex = osmPointFeatureClass.FindField("osmSupportingElement"); int osmWayRefCountFieldIndex = osmPointFeatureClass.FindField("wayRefCount"); // set up the progress indicator IStepProgressor stepProgressor = TrackCancel as IStepProgressor; if (stepProgressor != null) { stepProgressor.MinRange = 0; stepProgressor.MaxRange = nodeCapacity; stepProgressor.StepValue = (1); stepProgressor.Message = _resourceManager.GetString("GPTools_OSMGPFileReader_loadingNodes"); stepProgressor.Position = 0; stepProgressor.Show(); } // flag to determine if a computation of indices is required bool indexBuildRequired = false; if (nodeCapacity > 0) indexBuildRequired = true; int pointCount = 0; // let's insert all the points first if (osmPointFeatureClass != null) { IFeatureBuffer pointFeature = null; IFeatureClassLoad pointFeatureLoad = null; using (ComReleaser comReleaser = new ComReleaser()) { using (SchemaLockManager schemaLockManager = new SchemaLockManager(osmPointFeatureClass as ITable)) { if (((IWorkspace)featureWorkspace).WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace) { pointFeatureLoad = osmPointFeatureClass as IFeatureClassLoad; } IFeatureCursor pointInsertCursor = osmPointFeatureClass.Insert(true); comReleaser.ManageLifetime(pointInsertCursor); pointFeature = osmPointFeatureClass.CreateFeatureBuffer(); comReleaser.ManageLifetime(pointFeature); if (pointFeatureLoad != null) { pointFeatureLoad.LoadOnlyMode = true; } osmFileXmlReader.MoveToContent(); while (osmFileXmlReader.Read()) { if (osmFileXmlReader.IsStartElement()) { if (osmFileXmlReader.Name == "node") { string currentNodeString = osmFileXmlReader.ReadOuterXml(); // turn the xml node representation into a node class representation ESRI.ArcGIS.OSM.OSMClassExtension.node currentNode = null; using (StringReader nodeReader = new System.IO.StringReader(currentNodeString)) { currentNode = nodeSerializer.Deserialize(nodeReader) as ESRI.ArcGIS.OSM.OSMClassExtension.node; } // check if a feature with the same OSMID already exists, because the can only be one if (checkForExisting == true) { if (CheckIfExists(osmPointFeatureClass as ITable, currentNode.id)) { continue; } } try { //if (pointFeature == null) //{ pointFeature = osmPointFeatureClass.CreateFeatureBuffer(); comReleaser.ManageLifetime(pointFeature); //} IPoint pointGeometry = new PointClass(); comReleaser.ManageLifetime(pointGeometry); pointGeometry.X = Convert.ToDouble(currentNode.lon, new CultureInfo("en-US")); pointGeometry.Y = Convert.ToDouble(currentNode.lat, new CultureInfo("en-US")); pointGeometry.SpatialReference = wgs84; if (shouldProject) { pointGeometry.Project(downloadSpatialReference); } pointFeature.Shape = pointGeometry; pointFeature.set_Value(osmPointIDFieldIndex, currentNode.id); string isSupportingNode = ""; if (_osmUtility.DoesHaveKeys(currentNode)) { // if case it has tags I assume that the node presents an entity of it own, // hence it is not a supporting node in the context of supporting a way or relation isSupportingNode = "no"; if (conserveMemory == false) { osmNodeDictionary[currentNode.id] = new simplePointRef(Convert.ToSingle(currentNode.lon, new CultureInfo("en-US")), Convert.ToSingle(currentNode.lat, new CultureInfo("en-US")), 0, 0); } } else { // node has no tags -- at this point I assume that the absence of tags indicates that it is a supporting node // for a way or a relation isSupportingNode = "yes"; if (conserveMemory == false) { osmNodeDictionary[currentNode.id] = new simplePointRef(Convert.ToSingle(currentNode.lon, new CultureInfo("en-US")), Convert.ToSingle(currentNode.lat, new CultureInfo("en-US")), 0, 0); } } insertTags(osmPointDomainAttributeFieldIndices, osmPointDomainAttributeFieldLength, tagCollectionPointFieldIndex, pointFeature, currentNode.tag); if (fastLoad == false) { if (osmSupportingElementPointFieldIndex > -1) { pointFeature.set_Value(osmSupportingElementPointFieldIndex, isSupportingNode); } if (osmWayRefCountFieldIndex > -1) { pointFeature.set_Value(osmWayRefCountFieldIndex, 0); } // store the administrative attributes // user, uid, version, changeset, timestamp, visible if (osmUserPointFieldIndex > -1) { if (!String.IsNullOrEmpty(currentNode.user)) { pointFeature.set_Value(osmUserPointFieldIndex, currentNode.user); } } if (osmUIDPointFieldIndex > -1) { if (!String.IsNullOrEmpty(currentNode.uid)) { pointFeature.set_Value(osmUIDPointFieldIndex, Convert.ToInt32(currentNode.uid)); } } if (osmVisiblePointFieldIndex > -1) { pointFeature.set_Value(osmVisiblePointFieldIndex, currentNode.visible.ToString()); } if (osmVersionPointFieldIndex > -1) { if (!String.IsNullOrEmpty(currentNode.version)) { pointFeature.set_Value(osmVersionPointFieldIndex, Convert.ToInt32(currentNode.version)); } } if (osmChangesetPointFieldIndex > -1) { if (!String.IsNullOrEmpty(currentNode.changeset)) { pointFeature.set_Value(osmChangesetPointFieldIndex, Convert.ToInt32(currentNode.changeset)); } } if (osmTimeStampPointFieldIndex > -1) { if (!String.IsNullOrEmpty(currentNode.timestamp)) { try { pointFeature.set_Value(osmTimeStampPointFieldIndex, Convert.ToDateTime(currentNode.timestamp)); } catch (Exception ex) { message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_invalidTimeFormat"), ex.Message)); } } } } try { pointInsertCursor.InsertFeature(pointFeature); pointCount = pointCount + 1; if (stepProgressor != null) { stepProgressor.Position = pointCount; } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); message.AddWarning(ex.Message); } if (TrackCancel.Continue() == false) { return; } if ((pointCount % 50000) == 0) { message.AddMessage(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_pointsloaded"), pointCount)); pointInsertCursor.Flush(); System.GC.Collect(); } if (pointGeometry != null) Marshal.ReleaseComObject(pointGeometry); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); message.AddWarning(ex.Message); } finally { if (pointFeature != null) { Marshal.ReleaseComObject(pointFeature); if (pointFeature != null) pointFeature = null; } } currentNode = null; } } } if (stepProgressor != null) { stepProgressor.Hide(); } pointInsertCursor.Flush(); osmFileXmlReader.Close(); message.AddMessage(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_pointsloaded"), pointCount)); message.AddMessage(_resourceManager.GetString("GPTools_buildingpointidx")); if (pointFeatureLoad != null) { pointFeatureLoad.LoadOnlyMode = false; } } } if (TrackCancel.Continue() == false) { return; } using (ComReleaser comReleaser = new ComReleaser()) { IFeatureCursor updatePoints = osmPointFeatureClass.Update(null, false); comReleaser.ManageLifetime(updatePoints); IFeature feature2Update = updatePoints.NextFeature(); while (feature2Update != null) { IPoint pointGeometry = feature2Update.Shape as IPoint; pointGeometry.ID = feature2Update.OID; feature2Update.Shape = pointGeometry; if (conserveMemory == false) { string osmid = Convert.ToString(feature2Update.get_Value(osmPointIDFieldIndex)); if (osmNodeDictionary.ContainsKey(osmid)) osmNodeDictionary[osmid].pointObjectID = feature2Update.OID; } updatePoints.UpdateFeature(feature2Update); if (TrackCancel.Continue() == false) { return; } if (feature2Update != null) Marshal.ReleaseComObject(feature2Update); if (pointGeometry != null) Marshal.ReleaseComObject(pointGeometry); feature2Update = updatePoints.NextFeature(); } } if (indexBuildRequired) { IGeoProcessor2 geoProcessor = new GeoProcessorClass(); bool storedOriginal = geoProcessor.AddOutputsToMap; try { IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); IGPValue pointFeatureClass = gpUtilities3.MakeGPValueFromObject(osmPointFeatureClass); string fcLocation = GetLocationString(targetGPValue, osmPointFeatureClass); IIndexes featureClassIndexes = osmPointFeatureClass.Indexes; int indexPosition = -1; featureClassIndexes.FindIndex("osmID_IDX", out indexPosition); if (indexPosition == -1) { { geoProcessor.AddOutputsToMap = false; IVariantArray parameterArrary = CreateAddIndexParameterArray(fcLocation, "OSMID", "osmID_IDX", "UNIQUE", ""); IGeoProcessorResult2 gpResults2 = geoProcessor.Execute("AddIndex_management", parameterArrary, TrackCancel) as IGeoProcessorResult2; } } if (pointCount > 500) { if (pointFeatureLoad == null) { UpdateSpatialGridIndex(TrackCancel, message, geoProcessor, fcLocation); } } } catch (COMException comEx) { message.AddWarning(comEx.Message); } catch (Exception ex) { message.AddWarning(ex.Message); } finally { geoProcessor.AddOutputsToMap = storedOriginal; } } } } catch (Exception ex) { message.AddError(120100, String.Format(_resourceManager.GetString("GPTools_Utility_NodeLoadError"), ex.Message)); } finally { if (osmFileXmlReader != null) osmFileXmlReader = null; if (nodeSerializer != null) nodeSerializer = null; } }
private void simpleButton4_Click(object sender, EventArgs e) { if (this.comboBoxInputRaster.Text.ToString() == "" || this.comboBoxContrastRaster.Text.ToString() == "" || this.comboBoxOutputRaster.Text.ToString() == "") { MessageBox.Show("请输入参数!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; }//有任意一个空为空则弹出对话框提示:请输入参数。 string strResultsDBPath = m_pGDBHelper.GetResultsDBPath();//声明变量获取数据库结果路径 //string ToolName = "变化向量角5"; if (Utilities.GDBUtilites.CheckNameExist(strResultsDBPath, this.comboBoxOutputRaster.Text.ToString()) == false)//如果没有同名文件 { //执行光谱角分析 ILayer pInputLayer1 = null; ILayer pInputLayer2 = null; for (int i = 0; i < m_pMapCtrl.LayerCount; i++) { if (m_pMapCtrl.get_Layer(i).Name == this.comboBoxInputRaster.Text.ToString()) { pInputLayer1 = m_pMapCtrl.get_Layer(i); } else if (m_pMapCtrl.get_Layer(i).Name == this.comboBoxContrastRaster.Text.ToString()) { pInputLayer2 = m_pMapCtrl.get_Layer(i); } } if (pInputLayer1 != null && pInputLayer2 != null) { IRasterLayer pRasterLayer1 = pInputLayer1 as IRasterLayer; IRasterLayer pRasterLayer2 = pInputLayer2 as IRasterLayer; string rasterpath1 = pRasterLayer1.FilePath; string rasterpath2 = pRasterLayer2.FilePath; IGeoProcessor2 pGP = new GeoProcessorClass(); string GPPath = m_pGDBHelper.GetToolboxPath(); pGP.AddToolbox(GPPath); IVariantArray gpParameters = new VarArrayClass(); //gpParameters.Add(pRasterLayer1.Raster); //gpParameters.Add(pRasterLayer2.Raster); gpParameters.Add(rasterpath1); gpParameters.Add(rasterpath2); gpParameters.Add(strResultsDBPath + "\\" + this.comboBoxOutputRaster.Text); IGeoProcessorResult pGeoProcessorResult = null; pGeoProcessorResult = pGP.Execute("changevector", gpParameters, null); if (pGeoProcessorResult.Status == esriJobStatus.esriJobSucceeded) { if (this.checkBox1.Checked) { IWorkspaceFactory2 pWKF = new FileGDBWorkspaceFactoryClass(); IRasterWorkspaceEx pRasterWKEx = (IRasterWorkspaceEx)pWKF.OpenFromFile(m_pGDBHelper.GetResultsDBPath(), 0); IRasterDataset3 pRasterDataset = pRasterWKEx.OpenRasterDataset(this.comboBoxOutputRaster.Text.ToString()) as IRasterDataset3; Utilities.MapUtilites.AddRasterLayer(m_pMapCtrl.ActiveView, pRasterDataset, null); } MessageBox.Show("变化向量分析完成!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } } this.DialogResult = DialogResult.OK; this.Close(); } else { MessageBox.Show("已存在同名数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } }
private void btOk_Click(object sender, EventArgs e) { int sExcute = 0; int sIsNul = 0; int sIsThan = 0; double sAll = 0; for (int i = 0; i < this.dataGridView1.Rows.Count - 1; i++) { if (this.dataGridView1.Rows[i].Cells[1].Value == null) { sIsNul = 1; //如果权重存在空值,sIsNul=1 } else { double ssRow = double.Parse(this.dataGridView1.Rows[i].Cells[1].Value.ToString()); sAll = sAll + ssRow; } } if ((sAll != 1.0) && (sIsNul == 0)) { sIsThan = 1; //如果权重之和不为1,sIsThan=1 } //判断权重是否为空 if (sIsNul == 1) { MessageBox.Show("请您输入数据权重!"); } //判断权重之和是否等于1 if (sIsThan == 1) { MessageBox.Show("请您确保输入的权重之和等于1"); } if (txtSavePath.Equals("")) { MessageBox.Show("请选择输出路径!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //准备后续执行 if ((sIsNul == 0) && (sIsThan == 0) && (Onebt == 1)) { //现创建一个存放临时文件的临时文件夹 string newPath = System.IO.Path.Combine(Temfile, ""); System.IO.Directory.CreateDirectory(newPath); this.rtxtState.AppendText("正在执行,请您耐心等待...\n"); this.rtxtState.ScrollToCaret(); this.rtxtState.AppendText("准备调用GP工具箱...\n"); this.rtxtState.ScrollToCaret(); IVariantArray parameters = new VarArrayClass(); Geoprocessor GP = new Geoprocessor(); ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator sCalR = new ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator(); this.rtxtState.AppendText("开始遍历读取表中数据...\n"); this.rtxtState.ScrollToCaret(); this.rtxtState.AppendText("开始对栅格数据重分类...\n"); this.rtxtState.ScrollToCaret(); for (int m = 0; m < this.dataGridView1.Rows.Count - 1; m++) { string sFileName; sFileName = Temfile + "\\重分类" + (m + 1).ToString() + ".tif"; //计算栅格最小值 double dMin0 = 0; IGeoProcessor2 gp = new GeoProcessorClass(); gp.OverwriteOutput = true; // Create a variant array to hold the parameter values. IVariantArray parameters2 = new VarArrayClass(); IGeoProcessorResult result = new GeoProcessorResultClass(); // Set parameter values. parameters2.Add(this.dataGridView1.Rows[m].Cells[0].Value.ToString()); parameters2.Add("MINIMUM"); result = gp.Execute("GetRasterProperties_management", parameters2, null); dMin0 = (double)result.ReturnValue; int dMin = (int)dMin0; //计算栅格最大值 double dMax0 = 0; IGeoProcessor2 gp2 = new GeoProcessorClass(); gp2.OverwriteOutput = true; // Create a variant array to hold the parameter values. IVariantArray parameters3 = new VarArrayClass(); IGeoProcessorResult result3 = new GeoProcessorResultClass(); // Set parameter values. parameters3.Add(this.dataGridView1.Rows[m].Cells[0].Value.ToString()); parameters3.Add("MAXIMUM"); result3 = gp2.Execute("GetRasterProperties_management", parameters3, null); dMax0 = (double)result3.ReturnValue; int dMax = (int)dMax0; //计算分类区间 int Avera = (dMax - dMin) / 4; int interval1 = dMin + Avera; int interval2 = dMin + 2 * Avera; int interval3 = dMin + 3 * Avera; //开始对数据进行重分类 ESRI.ArcGIS.SpatialAnalystTools.Reclassify tReclass = new ESRI.ArcGIS.SpatialAnalystTools.Reclassify(); tReclass.in_raster = this.dataGridView1.Rows[m].Cells[0].Value.ToString(); tReclass.missing_values = "NODATA"; tReclass.out_raster = sFileName; tReclass.reclass_field = "VALUE"; //tReclass.remap = "1400 2176 1;2176 2538 2;2538 3040 3;3040 4073 4"; tReclass.remap = dMin.ToString() + " " + interval1.ToString() + " " + "1;" + interval1.ToString() + " " + interval2.ToString() + " " + "2;" + interval2.ToString() + " " + interval3.ToString() + " " + "3;" + interval3.ToString() + " " + dMax.ToString() + " " + "4;"; // ScrollToBottom("Reclassify"); //tGeoResult = (IGeoProcessorResult)tGp.Execute(tReclass, null); GP.Execute(tReclass, null); } this.rtxtState.AppendText("输入数据重分类完成...\n"); this.rtxtState.ScrollToCaret(); //开始进行栅格计算 this.rtxtState.AppendText("开始准备进行栅格加权运算...\n"); this.rtxtState.ScrollToCaret(); string sFileName2 = "重分类"; string sRoad = Temfile + "\\重分类"; for (int n = 1; n < this.dataGridView1.Rows.Count; n++) { sFileName2 = sRoad + n.ToString() + "." + "tif"; strExp = "\"" + sFileName2 + "\"" + "*" + double.Parse(this.dataGridView1.Rows[n - 1].Cells[1].Value.ToString()); if (n < this.dataGridView1.Rows.Count - 1) { sR2 = sR2 + strExp + "+"; } else { sR2 = sR2 + strExp; } } sR3 = sR2; sCalR.expression = sR3; sR = Temfile + "\\地质灾害.tif"; sCalR.output_raster = sR; GP.Execute(sCalR, null); this.rtxtState.AppendText("栅格计算成功,得到地质灾害分布栅格影像...\n"); this.rtxtState.ScrollToCaret(); this.rtxtState.AppendText("开始对地质灾害影像进行重分类...\n"); this.rtxtState.ScrollToCaret(); //开始准备对生成的地质灾害.tif进行分类 //计算栅格最小值 double dMin02 = 0; IGeoProcessor2 gp3 = new GeoProcessorClass(); gp3.OverwriteOutput = true; // Create a variant array to hold the parameter values. IVariantArray parameters22 = new VarArrayClass(); IGeoProcessorResult result22 = new GeoProcessorResultClass(); // Set parameter values. parameters22.Add(sR); parameters22.Add("MINIMUM"); result22 = gp3.Execute("GetRasterProperties_management", parameters22, null); dMin02 = (double)result22.ReturnValue; //计算栅格最大值 double dMax02 = 0; IGeoProcessor2 gp4 = new GeoProcessorClass(); gp4.OverwriteOutput = true; // Create a variant array to hold the parameter values. IVariantArray parameters33 = new VarArrayClass(); IGeoProcessorResult result33 = new GeoProcessorResultClass(); // Set parameter values. parameters33.Add(sR); parameters33.Add("MAXIMUM"); result33 = gp4.Execute("GetRasterProperties_management", parameters33, null); dMax02 = (double)result33.ReturnValue; //计算分类区间 double Avera2 = (dMax02 - dMin02) / 4; double interval12 = dMin02 + Avera2; double interval22 = dMin02 + 2 * Avera2; double interval32 = dMin02 + 3 * Avera2; //开始对地质灾害.tif重分类 ESRI.ArcGIS.SpatialAnalystTools.Reclassify tReclass2 = new ESRI.ArcGIS.SpatialAnalystTools.Reclassify(); tReclass2.in_raster = Temfile + "\\地质灾害.tif"; tReclass2.missing_values = "NODATA"; tReclass2.out_raster = txtSavePath.Text; tReclass2.reclass_field = "VALUE"; //tReclass.remap = "1400 2176 1;2176 2538 2;2538 3040 3;3040 4073 4"; tReclass2.remap = dMin02.ToString() + " " + interval12.ToString() + " " + "1;" + interval12.ToString() + " " + interval22.ToString() + " " + "2;" + interval22.ToString() + " " + interval32.ToString() + " " + "3;" + interval32.ToString() + " " + dMax02.ToString() + " " + "4;"; // ScrollToBottom("Reclassify"); //tGeoResult = (IGeoProcessorResult)tGp.Execute(tReclass, null); GP.Execute(tReclass2, null); //删除临时文件夹 string deleteFile = Temfile; DeleteFolder(deleteFile); this.rtxtState.AppendText("完成地质灾害生态红线的划分,已将结果成功保存...\n"); this.rtxtState.ScrollToCaret(); } }
/// <summary> /// Run RasterToPoly tool to convert input raster to poly's. Then run Intersect if input geomList has features /// </summary> /// <param name="rasterLayer"></param> /// <param name="ipDataset"></param> /// <param name="workspace"></param> /// <param name="geomList"></param> /// <returns>Featureclass name</returns> private string IntersectOutput(IRasterLayer rasterLayer, IDataset ipDataset, IFeatureWorkspace workspace, List<IGeometry> geomList) { IGeoProcessor2 gp = new GeoProcessorClass(); gp.AddOutputsToMap = false; // Run RasterToPolygon string inRaster = rasterLayer.FilePath; string outRasterToPolyFcName = ipDataset.BrowseName + "_rasterToPoly"; string outRasterToPolyPath = ipDataset.Workspace.PathName + "\\" + outRasterToPolyFcName; string field = "VALUE"; IVariantArray rasterToPolyParams = new VarArrayClass(); rasterToPolyParams.Add(inRaster); rasterToPolyParams.Add(outRasterToPolyPath); rasterToPolyParams.Add("NO_SIMPLIFY"); rasterToPolyParams.Add(field); try { object oResult = gp.Execute("RasterToPolygon_conversion", rasterToPolyParams, null); IGeoProcessorResult ipResult = (IGeoProcessorResult)oResult; if (geomList.Count == 0) return outRasterToPolyFcName; if (ipResult.Status == esriJobStatus.esriJobSucceeded) { string outFcName = ipDataset.BrowseName + "_intersectRaster"; string outPath = ipDataset.Workspace.PathName + "\\" + outFcName; // Add a mask to buffer the output to selected distance string fcPath = SetGPMask(workspace, geomList, gp, "intersectMask"); string pathParam = outRasterToPolyPath + ";" + fcPath; IVariantArray parameters = new VarArrayClass(); parameters.Add(pathParam); parameters.Add(outPath); object oResult2 = gp.Execute("Intersect_analysis", parameters, null); IGeoProcessorResult ipResult2 = (IGeoProcessorResult)oResult2; return outFcName; } else { return null; } } catch (Exception ex) { return null; } }
public IGeoProcessor getGP() { IGeoProcessor gp2 = new GeoProcessorClass(); return gp2; }
internal List<string> loadOSMWays(string osmFileLocation, ref ITrackCancel TrackCancel, ref IGPMessages message, IGPValue targetGPValue, IFeatureClass osmPointFeatureClass, IFeatureClass osmLineFeatureClass, IFeatureClass osmPolygonFeatureClass, bool conserveMemory, bool fastLoad, int wayCapacity, ref Dictionary<string, simplePointRef> osmNodeDictionary, IFeatureWorkspace featureWorkspace, ISpatialReference downloadSpatialReference, OSMDomains availableDomains, bool checkForExisting) { if (osmLineFeatureClass == null) { throw new ArgumentNullException("osmLineFeatureClass"); } if (osmPolygonFeatureClass == null) { throw new ArgumentNullException("osmPolygonFeatureClass"); } XmlReader osmFileXmlReader = null; XmlSerializer waySerializer = null; List<string> missingWays = null; try { missingWays = new List<string>(); int osmPointIDFieldIndex = osmPointFeatureClass.FindField("OSMID"); int osmWayRefCountFieldIndex = osmPointFeatureClass.FindField("wayRefCount"); int osmLineIDFieldIndex = osmLineFeatureClass.FindField("OSMID"); Dictionary<string, int> osmLineDomainAttributeFieldIndices = new Dictionary<string, int>(); Dictionary<string, int> osmLineDomainAttributeFieldLength = new Dictionary<string, int>(); foreach (var domains in availableDomains.domain) { int currentFieldIndex = osmLineFeatureClass.FindField(domains.name); if (currentFieldIndex != -1) { osmLineDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex); osmLineDomainAttributeFieldLength.Add(domains.name, osmLineFeatureClass.Fields.get_Field(currentFieldIndex).Length); } } int tagCollectionPolylineFieldIndex = osmLineFeatureClass.FindField("osmTags"); int osmUserPolylineFieldIndex = osmLineFeatureClass.FindField("osmuser"); int osmUIDPolylineFieldIndex = osmLineFeatureClass.FindField("osmuid"); int osmVisiblePolylineFieldIndex = osmLineFeatureClass.FindField("osmvisible"); int osmVersionPolylineFieldIndex = osmLineFeatureClass.FindField("osmversion"); int osmChangesetPolylineFieldIndex = osmLineFeatureClass.FindField("osmchangeset"); int osmTimeStampPolylineFieldIndex = osmLineFeatureClass.FindField("osmtimestamp"); int osmMemberOfPolylineFieldIndex = osmLineFeatureClass.FindField("osmMemberOf"); int osmMembersPolylineFieldIndex = osmLineFeatureClass.FindField("osmMembers"); int osmSupportingElementPolylineFieldIndex = osmLineFeatureClass.FindField("osmSupportingElement"); int osmPolygonIDFieldIndex = osmPolygonFeatureClass.FindField("OSMID"); Dictionary<string, int> osmPolygonDomainAttributeFieldIndices = new Dictionary<string, int>(); Dictionary<string, int> osmPolygonDomainAttributeFieldLength = new Dictionary<string, int>(); foreach (var domains in availableDomains.domain) { int currentFieldIndex = osmPolygonFeatureClass.FindField(domains.name); if (currentFieldIndex != -1) { osmPolygonDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex); osmPolygonDomainAttributeFieldLength.Add(domains.name, osmPolygonFeatureClass.Fields.get_Field(currentFieldIndex).Length); } } int tagCollectionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmTags"); int osmUserPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuser"); int osmUIDPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuid"); int osmVisiblePolygonFieldIndex = osmPolygonFeatureClass.FindField("osmvisible"); int osmVersionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmversion"); int osmChangesetPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmchangeset"); int osmTimeStampPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmtimestamp"); int osmMemberOfPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMemberOf"); int osmMembersPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMembers"); int osmSupportingElementPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmSupportingElement"); ISpatialReferenceFactory spatialRef = new SpatialReferenceEnvironmentClass(); ISpatialReference wgs84 = spatialRef.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); bool shouldProject = !((IClone)wgs84).IsEqual((IClone)downloadSpatialReference); // set up the progress indicator IStepProgressor stepProgressor = TrackCancel as IStepProgressor; if (stepProgressor != null) { stepProgressor.MinRange = 0; stepProgressor.MaxRange = wayCapacity; stepProgressor.Position = 0; stepProgressor.Message = _resourceManager.GetString("GPTools_OSMGPFileReader_loadingWays"); stepProgressor.StepValue = 1; stepProgressor.Show(); } bool lineIndexRebuildRequired = false; bool polygonIndexRebuildRequired = false; int wayCount = 0; object missingValue = System.Reflection.Missing.Value; // enterprise GDB indicator -- supporting load only mode IFeatureClassLoad lineFeatureLoad = null; IFeatureClassLoad polygonFeatureLoad = null; using (SchemaLockManager lineLock = new SchemaLockManager(osmLineFeatureClass as ITable), polygonLock = new SchemaLockManager(osmPolygonFeatureClass as ITable)) { using (ComReleaser comReleaser = new ComReleaser()) { IFeatureCursor insertLineCursor = osmLineFeatureClass.Insert(true); comReleaser.ManageLifetime(insertLineCursor); IFeatureBuffer featureLineBuffer = osmLineFeatureClass.CreateFeatureBuffer(); comReleaser.ManageLifetime(featureLineBuffer); IFeatureCursor insertPolygonCursor = osmPolygonFeatureClass.Insert(true); comReleaser.ManageLifetime(insertPolygonCursor); IFeatureBuffer featurePolygonBuffer = osmPolygonFeatureClass.CreateFeatureBuffer(); comReleaser.ManageLifetime(featurePolygonBuffer); if (((IWorkspace)featureWorkspace).WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace) { lineFeatureLoad = osmLineFeatureClass as IFeatureClassLoad; polygonFeatureLoad = osmPolygonFeatureClass as IFeatureClassLoad; } if (lineFeatureLoad != null) { lineFeatureLoad.LoadOnlyMode = true; } if (polygonFeatureLoad != null) { polygonFeatureLoad.LoadOnlyMode = true; } ISpatialReference nativeLineSpatialReference = ((IGeoDataset)osmLineFeatureClass).SpatialReference; ISpatialReference nativePolygonSpatialReference = ((IGeoDataset)osmPolygonFeatureClass).SpatialReference; IQueryFilter osmIDQueryFilter = new QueryFilterClass(); string sqlPointOSMID = osmPointFeatureClass.SqlIdentifier("OSMID"); IFeatureCursor updatePointCursor = null; osmFileXmlReader = System.Xml.XmlReader.Create(osmFileLocation); waySerializer = new XmlSerializer(typeof(way)); // the point query filter for updates will not changes, so let's do that ahead of time try { osmIDQueryFilter.SubFields = osmPointFeatureClass.ShapeFieldName + "," + osmPointFeatureClass.Fields.get_Field(osmPointIDFieldIndex).Name + "," + osmPointFeatureClass.Fields.get_Field(osmWayRefCountFieldIndex).Name; } catch { } osmFileXmlReader.MoveToContent(); while (osmFileXmlReader.Read()) { if (osmFileXmlReader.IsStartElement()) { if (osmFileXmlReader.Name == "way") { string currentwayString = osmFileXmlReader.ReadOuterXml(); // assuming the way to be a polyline is sort of a safe assumption // and won't cause any topology problem due to orientation and closeness bool wayIsLine = true; bool wayIsComplete = true; way currentWay = null; try { using (StringReader wayReader = new System.IO.StringReader(currentwayString)) { currentWay = waySerializer.Deserialize(wayReader) as way; } // if the deserialization fails then go ahead and read the next xml element if (currentWay == null) { continue; } // and we are expecting at least some nodes on the way itself if (currentWay.nd == null) { continue; } featureLineBuffer = osmLineFeatureClass.CreateFeatureBuffer(); featurePolygonBuffer = osmPolygonFeatureClass.CreateFeatureBuffer(); IPointCollection wayPointCollection = null; wayIsLine = IsThisWayALine(currentWay); if (wayIsLine) { // check if a feature with the same OSMID already exists, because the can only be one if (checkForExisting == true) { if (CheckIfExists(osmLineFeatureClass as ITable, currentWay.id)) { continue; } } IPolyline wayPolyline = new PolylineClass(); comReleaser.ManageLifetime(wayPointCollection); wayPolyline.SpatialReference = downloadSpatialReference; IPointIDAware polylineIDAware = wayPolyline as IPointIDAware; polylineIDAware.PointIDAware = true; wayPointCollection = wayPolyline as IPointCollection; # region generate line geometry if (conserveMemory == false) { for (int ndIndex = 0; ndIndex < currentWay.nd.Length; ndIndex++) { string ndID = currentWay.nd[ndIndex].@ref; if (osmNodeDictionary.ContainsKey(ndID)) { IPoint newPoint = new PointClass(); newPoint.X = osmNodeDictionary[ndID].Longitude; newPoint.Y = osmNodeDictionary[ndID].Latitude; newPoint.SpatialReference = wgs84; if (shouldProject) { newPoint.Project(((IGeoDataset)osmLineFeatureClass).SpatialReference); } IPointIDAware idAware = newPoint as IPointIDAware; idAware.PointIDAware = true; newPoint.ID = osmNodeDictionary[ndID].pointObjectID; wayPointCollection.AddPoint(newPoint, ref missingValue, ref missingValue); osmNodeDictionary[ndID].RefCounter = osmNodeDictionary[ndID].RefCounter + 1; } else { message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_undeterminedline_node"), currentWay.id, ndID)); // set the flag that the way is complete due to a missing node wayIsComplete = false; break; } } } else { for (int pointIndex = 0; pointIndex < currentWay.nd.Length; pointIndex++) { wayPointCollection.AddPoint(new PointClass()); } List<string> idRequests = SplitOSMIDRequests(currentWay, 2); // build a list of node ids we can use to determine the point index in the line geometry // as well as a dictionary to determine the position in the list in case of duplicates nodes Dictionary<string, int> nodePositionDictionary = new Dictionary<string, int>(currentWay.nd.Length); List<string> nodeIDs = new List<string>(currentWay.nd.Length); foreach (nd wayNode in currentWay.nd) { nodeIDs.Add(wayNode.@ref); if (nodePositionDictionary.ContainsKey(wayNode.@ref) == false) { nodePositionDictionary.Add(wayNode.@ref, 0); } } try { osmIDQueryFilter.SubFields = osmPointFeatureClass.ShapeFieldName + "," + osmPointFeatureClass.Fields.get_Field(osmPointIDFieldIndex).Name + "," + osmPointFeatureClass.Fields.get_Field(osmWayRefCountFieldIndex).Name; } catch { } foreach (string request in idRequests) { string idCompareString = request; osmIDQueryFilter.WhereClause = sqlPointOSMID + " IN " + request; using (ComReleaser innerComReleaser = new ComReleaser()) { updatePointCursor = osmPointFeatureClass.Update(osmIDQueryFilter, true); innerComReleaser.ManageLifetime(updatePointCursor); IFeature nodeFeature = updatePointCursor.NextFeature(); while (nodeFeature != null) { // determine the index of the point in with respect to the node position string nodeOSMIDString = Convert.ToString(nodeFeature.get_Value(osmPointIDFieldIndex)); // remove the ID from the request string idCompareString = idCompareString.Replace(nodeOSMIDString, String.Empty); int nodePositionIndex = -1; while ((nodePositionIndex = nodeIDs.IndexOf(nodeOSMIDString, nodePositionDictionary[nodeOSMIDString])) != -1) { //// update the new position start search index nodePositionDictionary[nodeOSMIDString] = nodePositionIndex + 1; wayPointCollection.UpdatePoint(nodePositionIndex, (IPoint)nodeFeature.Shape); // increase the reference counter if (osmWayRefCountFieldIndex != -1) { nodeFeature.set_Value(osmWayRefCountFieldIndex, ((int)nodeFeature.get_Value(osmWayRefCountFieldIndex)) + 1); updatePointCursor.UpdateFeature(nodeFeature); } } if (nodeFeature != null) Marshal.ReleaseComObject(nodeFeature); nodeFeature = updatePointCursor.NextFeature(); } idCompareString = CleanReportedNodes(idCompareString); // after removing the commas we should be left with only paranthesis left, meaning a string of length 2 // if we have more then we have found a missing node, resulting in an incomplete way geometry if (idCompareString.Length > 2) { message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_undeterminedline_node"), currentWay.id, idCompareString)); wayIsComplete = false; } } } } #endregion if (wayIsComplete == false) { // if the way geometry is incomplete due to a missing node let's continue to the next way element missingWays.Add(currentWay.id); continue; } featureLineBuffer.Shape = wayPolyline; featureLineBuffer.set_Value(osmLineIDFieldIndex, currentWay.id); } else { // check if a feature with the same OSMID already exists, because the can only be one if (checkForExisting == true) { if (CheckIfExists(osmPolygonFeatureClass as ITable, currentWay.id)) { continue; } } IPolygon wayPolygon = new PolygonClass(); comReleaser.ManageLifetime(wayPointCollection); wayPolygon.SpatialReference = downloadSpatialReference; IPointIDAware polygonIDAware = wayPolygon as IPointIDAware; polygonIDAware.PointIDAware = true; wayPointCollection = wayPolygon as IPointCollection; #region generate polygon geometry if (conserveMemory == false) { for (int ndIndex = 0; ndIndex < currentWay.nd.Length; ndIndex++) { string ndID = currentWay.nd[ndIndex].@ref; if (osmNodeDictionary.ContainsKey(ndID)) { IPoint newPoint = new PointClass(); newPoint.X = osmNodeDictionary[ndID].Longitude; newPoint.Y = osmNodeDictionary[ndID].Latitude; newPoint.SpatialReference = wgs84; if (shouldProject) { newPoint.Project(nativePolygonSpatialReference); } IPointIDAware idAware = newPoint as IPointIDAware; idAware.PointIDAware = true; newPoint.ID = osmNodeDictionary[ndID].pointObjectID; wayPointCollection.AddPoint(newPoint, ref missingValue, ref missingValue); } else { message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_undeterminedpolygon_node"), currentWay.id, ndID)); wayIsComplete = false; break; } } } else { for (int pointIndex = 0; pointIndex < currentWay.nd.Length; pointIndex++) { wayPointCollection.AddPoint(new PointClass()); } List<string> idRequests = SplitOSMIDRequests(currentWay, 2); // build a list of node ids we can use to determine the point index in the line geometry // as well as a dictionary to determine the position in the list in case of duplicates nodes Dictionary<string, int> nodePositionDictionary = new Dictionary<string, int>(currentWay.nd.Length); List<string> nodeIDs = new List<string>(currentWay.nd.Length); foreach (nd wayNode in currentWay.nd) { nodeIDs.Add(wayNode.@ref); if (nodePositionDictionary.ContainsKey(wayNode.@ref) == false) { nodePositionDictionary.Add(wayNode.@ref, 0); } } try { osmIDQueryFilter.SubFields = osmPointFeatureClass.ShapeFieldName + "," + osmPointFeatureClass.Fields.get_Field(osmPointIDFieldIndex).Name + "," + osmPointFeatureClass.Fields.get_Field(osmWayRefCountFieldIndex).Name; } catch { } foreach (string osmIDRequest in idRequests) { string idCompareString = osmIDRequest; using (ComReleaser innercomReleaser = new ComReleaser()) { osmIDQueryFilter.WhereClause = sqlPointOSMID + " IN " + osmIDRequest; updatePointCursor = osmPointFeatureClass.Update(osmIDQueryFilter, false); innercomReleaser.ManageLifetime(updatePointCursor); IFeature nodeFeature = updatePointCursor.NextFeature(); while (nodeFeature != null) { // determine the index of the point in with respect to the node position string nodeOSMIDString = Convert.ToString(nodeFeature.get_Value(osmPointIDFieldIndex)); idCompareString = idCompareString.Replace(nodeOSMIDString, String.Empty); int nodePositionIndex = nodeIDs.IndexOf(nodeOSMIDString, nodePositionDictionary[nodeOSMIDString]); // update the new position start search index nodePositionDictionary[nodeOSMIDString] = nodePositionIndex + 1; wayPointCollection.UpdatePoint(nodePositionIndex, (IPoint)nodeFeature.Shape); // increase the reference counter if (osmWayRefCountFieldIndex != -1) { nodeFeature.set_Value(osmWayRefCountFieldIndex, ((int)nodeFeature.get_Value(osmWayRefCountFieldIndex)) + 1); updatePointCursor.UpdateFeature(nodeFeature); } if (nodeFeature != null) Marshal.ReleaseComObject(nodeFeature); nodeFeature = updatePointCursor.NextFeature(); } idCompareString = CleanReportedNodes(idCompareString); if (idCompareString.Length > 2) { message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_undeterminedpolygon_node"), currentWay.id, idCompareString)); wayIsComplete = false; } } } } #endregion if (wayIsComplete == false) { continue; } // remove the last point as OSM considers them to be coincident wayPointCollection.RemovePoints(wayPointCollection.PointCount - 1, 1); ((IPolygon)wayPointCollection).Close(); featurePolygonBuffer.Shape = (IPolygon)wayPointCollection; featurePolygonBuffer.set_Value(osmPolygonIDFieldIndex, currentWay.id); } if (wayIsLine) { insertTags(osmLineDomainAttributeFieldIndices, osmLineDomainAttributeFieldLength, tagCollectionPolylineFieldIndex, featureLineBuffer, currentWay.tag); } else { insertTags(osmPolygonDomainAttributeFieldIndices, osmPolygonDomainAttributeFieldLength, tagCollectionPolygonFieldIndex, featurePolygonBuffer, currentWay.tag); } // store the administrative attributes // user, uid, version, changeset, timestamp, visible if (fastLoad == false) { if (!String.IsNullOrEmpty(currentWay.user)) { if (wayIsLine) { if (osmUserPolylineFieldIndex != -1) { featureLineBuffer.set_Value(osmUserPolylineFieldIndex, currentWay.user); } } else { if (osmUserPolygonFieldIndex != -1) { featurePolygonBuffer.set_Value(osmUserPolygonFieldIndex, currentWay.user); } } } if (!String.IsNullOrEmpty(currentWay.uid)) { if (wayIsLine) { if (osmUIDPolylineFieldIndex != -1) { featureLineBuffer.set_Value(osmUIDPolylineFieldIndex, Convert.ToInt32(currentWay.uid)); } } else { if (osmUIDPolygonFieldIndex != -1) { featurePolygonBuffer.set_Value(osmUIDPolygonFieldIndex, Convert.ToInt32(currentWay.uid)); } } } if (wayIsLine) { if (osmVisiblePolylineFieldIndex != -1) { featureLineBuffer.set_Value(osmVisiblePolylineFieldIndex, currentWay.visible.ToString()); } } else { if (osmVisiblePolygonFieldIndex != -1) { featurePolygonBuffer.set_Value(osmVisiblePolygonFieldIndex, currentWay.visible.ToString()); } } if (!String.IsNullOrEmpty(currentWay.version)) { if (wayIsLine) { if (osmVersionPolylineFieldIndex != -1) { featureLineBuffer.set_Value(osmVersionPolylineFieldIndex, Convert.ToInt32(currentWay.version)); } } else { if (osmVersionPolygonFieldIndex != -1) { featurePolygonBuffer.set_Value(osmVersionPolygonFieldIndex, Convert.ToInt32(currentWay.version)); } } } if (!String.IsNullOrEmpty(currentWay.changeset)) { if (wayIsLine) { if (osmChangesetPolylineFieldIndex != -1) { featureLineBuffer.set_Value(osmChangesetPolylineFieldIndex, Convert.ToInt32(currentWay.changeset)); } } else { if (osmChangesetPolygonFieldIndex != -1) { featurePolygonBuffer.set_Value(osmChangesetPolygonFieldIndex, Convert.ToInt32(currentWay.changeset)); } } } if (!String.IsNullOrEmpty(currentWay.timestamp)) { try { if (wayIsLine) { if (osmTimeStampPolylineFieldIndex != -1) { featureLineBuffer.set_Value(osmTimeStampPolylineFieldIndex, Convert.ToDateTime(currentWay.timestamp)); } } else { if (osmTimeStampPolygonFieldIndex != -1) { featurePolygonBuffer.set_Value(osmTimeStampPolygonFieldIndex, Convert.ToDateTime(currentWay.timestamp)); } } } catch (Exception ex) { message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_invalidTimeFormat"), ex.Message)); } } if (wayIsLine) { if (osmSupportingElementPolylineFieldIndex > -1) { if (currentWay.tag == null) { featureLineBuffer.set_Value(osmSupportingElementPolylineFieldIndex, "yes"); } else { featureLineBuffer.set_Value(osmSupportingElementPolylineFieldIndex, "no"); } } } else { if (osmSupportingElementPolygonFieldIndex > -1) { if (currentWay.tag == null) { featurePolygonBuffer.set_Value(osmSupportingElementPolygonFieldIndex, "yes"); } else { featurePolygonBuffer.set_Value(osmSupportingElementPolygonFieldIndex, "no"); } } } } // fast load try { if (wayIsLine) { insertLineCursor.InsertFeature(featureLineBuffer); lineIndexRebuildRequired = true; } else { insertPolygonCursor.InsertFeature(featurePolygonBuffer); polygonIndexRebuildRequired = true; } wayCount = wayCount + 1; if (stepProgressor != null) { stepProgressor.Position = wayCount; } if ((wayCount % 50000) == 0) { message.AddMessage(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_waysloaded"), wayCount)); } } catch (Exception ex) { message.AddWarning(ex.Message); message.AddWarning(currentwayString); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); System.Diagnostics.Debug.WriteLine(ex.StackTrace); } finally { if (featureLineBuffer != null) { Marshal.ReleaseComObject(featureLineBuffer); if (featureLineBuffer != null) featureLineBuffer = null; } if (featurePolygonBuffer != null) { Marshal.ReleaseComObject(featurePolygonBuffer); if (featurePolygonBuffer != null) featurePolygonBuffer = null; } currentWay = null; } if (TrackCancel.Continue() == false) { insertPolygonCursor.Flush(); if (polygonFeatureLoad != null) { polygonFeatureLoad.LoadOnlyMode = false; } insertLineCursor.Flush(); if (lineFeatureLoad != null) { lineFeatureLoad.LoadOnlyMode = false; } return missingWays; } } } } osmFileXmlReader.Close(); if (stepProgressor != null) { stepProgressor.Hide(); } message.AddMessage(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_waysloaded"), wayCount)); insertPolygonCursor.Flush(); if (polygonFeatureLoad != null) { polygonFeatureLoad.LoadOnlyMode = false; } insertLineCursor.Flush(); if (lineFeatureLoad != null) { lineFeatureLoad.LoadOnlyMode = false; } } } IGeoProcessor2 geoProcessor = new GeoProcessorClass(); IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); bool storedOriginal = geoProcessor.AddOutputsToMap; IVariantArray parameterArrary = null; IGeoProcessorResult2 gpResults2 = null; try { geoProcessor.AddOutputsToMap = false; if (lineIndexRebuildRequired) { IIndexes featureClassIndexes = osmLineFeatureClass.Indexes; int indexPosition = -1; featureClassIndexes.FindIndex("osmID_IDX", out indexPosition); string fcLocation = GetLocationString(targetGPValue, osmLineFeatureClass); if (indexPosition == -1) { message.AddMessage(_resourceManager.GetString("GPTools_buildinglineidx")); // Addd index for osmid column parameterArrary = CreateAddIndexParameterArray(fcLocation, "OSMID", "osmID_IDX", "UNIQUE", ""); gpResults2 = geoProcessor.Execute("AddIndex_management", parameterArrary, TrackCancel) as IGeoProcessorResult2; } if (wayCount > 100) { // in this case we are dealing with a file geodatabase if (lineFeatureLoad == null) { UpdateSpatialGridIndex(TrackCancel, message, geoProcessor, fcLocation); } } } if (polygonIndexRebuildRequired) { IIndexes featureClassIndexes = osmPolygonFeatureClass.Indexes; int indexPosition = -1; featureClassIndexes.FindIndex("osmID_IDX", out indexPosition); string fcLocation = GetLocationString(targetGPValue, osmPolygonFeatureClass); if (indexPosition == -1) { message.AddMessage(_resourceManager.GetString("GPTools_buildingpolygonidx")); IGPValue polygonFeatureClassGPValue = gpUtilities3.MakeGPValueFromObject(osmPolygonFeatureClass); if (polygonFeatureClassGPValue != null) { // Addd index for osmid column parameterArrary = CreateAddIndexParameterArray(fcLocation, "OSMID", "osmID_IDX", "UNIQUE", ""); gpResults2 = geoProcessor.Execute("AddIndex_management", parameterArrary, TrackCancel) as IGeoProcessorResult2; } } if (wayCount > 100) { if (polygonFeatureLoad == null) { UpdateSpatialGridIndex(TrackCancel, message, geoProcessor, fcLocation); } } } } catch (Exception ex) { message.AddWarning(ex.Message); } finally { geoProcessor.AddOutputsToMap = storedOriginal; Marshal.FinalReleaseComObject(gpUtilities3); Marshal.FinalReleaseComObject(geoProcessor); } } catch (Exception ex) { message.AddWarning(ex.Message); } finally { if (waySerializer != null) waySerializer = null; if (osmFileXmlReader != null) osmFileXmlReader = null; System.GC.Collect(); System.GC.WaitForPendingFinalizers(); } return missingWays; }
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { IFeatureClass osmPointFeatureClass = null; IFeatureClass osmLineFeatureClass = null; IFeatureClass osmPolygonFeatureClass = null; OSMToolHelper osmToolHelper = null; try { DateTime syncTime = DateTime.Now; IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); osmToolHelper = new OSMToolHelper(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter osmFileParameter = paramvalues.get_Element(in_osmFileNumber) as IGPParameter; IGPValue osmFileLocationString = gpUtilities3.UnpackGPValue(osmFileParameter) as IGPValue; // ensure that the specified file does exist bool osmFileExists = false; try { osmFileExists = System.IO.File.Exists(osmFileLocationString.GetAsText()); } catch (Exception ex) { message.AddError(120029, String.Format(resourceManager.GetString("GPTools_OSMGPMultiLoader_problemaccessingfile"), ex.Message)); return; } if (osmFileExists == false) { message.AddError(120030, String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_osmfiledoesnotexist"), osmFileLocationString.GetAsText())); return; } long nodeCapacity = 0; long wayCapacity = 0; long relationCapacity = 0; // this assume a clean, tidy XML file - if this is not the case, there will by sync issues later on osmToolHelper.countOSMStuffFast(osmFileLocationString.GetAsText(), ref nodeCapacity, ref wayCapacity, ref relationCapacity, ref TrackCancel); if (nodeCapacity == 0 && wayCapacity == 0 && relationCapacity == 0) { return; } message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPMultiLoader_countedElements"), nodeCapacity, wayCapacity, relationCapacity)); // determine the number of threads to be used IGPEnvironment parallelProcessingFactorEnvironment = OSMToolHelper.getEnvironment(envMgr, "parallelProcessingFactor"); IGPString parallelProcessingFactorString = parallelProcessingFactorEnvironment.Value as IGPString; // the default value is to use half the cores for additional threads - I am aware that we are comparing apples and oranges but I need a number int numberOfThreads = Convert.ToInt32(System.Environment.ProcessorCount / 2); if (!(parallelProcessingFactorEnvironment.Value.IsEmpty())) { if (!Int32.TryParse(parallelProcessingFactorString.Value, out numberOfThreads)) { // this case we have a percent string string resultString = Regex.Match(parallelProcessingFactorString.Value, @"\d+").Value; numberOfThreads = Convert.ToInt32(Int32.Parse(resultString) / 100 * System.Environment.ProcessorCount); } } // tread the special case of 0 if (numberOfThreads <= 0) numberOfThreads = 1; IGPEnvironment configKeyword = OSMToolHelper.getEnvironment(envMgr, "configKeyword"); IGPString gpString = configKeyword.Value as IGPString; string storageKeyword = String.Empty; if (gpString != null) { storageKeyword = gpString.Value; } // determine the temp folder to be use for the intermediate files IGPEnvironment scratchWorkspaceEnvironment = OSMToolHelper.getEnvironment(envMgr, "scratchWorkspace"); IDEWorkspace deWorkspace = scratchWorkspaceEnvironment.Value as IDEWorkspace; String scratchWorkspaceFolder = String.Empty; if (deWorkspace != null) { if (scratchWorkspaceEnvironment.Value.IsEmpty()) { scratchWorkspaceFolder = (new System.IO.FileInfo(osmFileLocationString.GetAsText())).DirectoryName; } else { if (deWorkspace.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace) { scratchWorkspaceFolder = System.IO.Path.GetTempPath(); } else if (deWorkspace.WorkspaceType == esriWorkspaceType.esriFileSystemWorkspace) { scratchWorkspaceFolder = ((IDataElement)deWorkspace).CatalogPath; } else { scratchWorkspaceFolder = (new System.IO.FileInfo(((IDataElement)deWorkspace).CatalogPath)).DirectoryName; } } } else { scratchWorkspaceFolder = (new System.IO.FileInfo(osmFileLocationString.GetAsText())).DirectoryName; } string metadataAbstract = resourceManager.GetString("GPTools_OSMGPFileReader_metadata_abstract"); string metadataPurpose = resourceManager.GetString("GPTools_OSMGPFileReader_metadata_purpose"); IGPParameter osmPointsFeatureClassParameter = paramvalues.get_Element(out_osmPointsNumber) as IGPParameter; IGPValue osmPointsFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmPointsFeatureClassParameter) as IGPValue; IName workspaceName = gpUtilities3.CreateParentFromCatalogPath(osmPointsFeatureClassGPValue.GetAsText()); IWorkspace2 pointFeatureWorkspace = workspaceName.Open() as IWorkspace2; string[] pointFCNameElements = osmPointsFeatureClassGPValue.GetAsText().Split(System.IO.Path.DirectorySeparatorChar); IGPParameter tagPointCollectionParameter = paramvalues.get_Element(in_pointFieldNamesNumber) as IGPParameter; IGPMultiValue tagPointCollectionGPValue = gpUtilities3.UnpackGPValue(tagPointCollectionParameter) as IGPMultiValue; List<String> pointTagstoExtract = null; if (tagPointCollectionGPValue.Count > 0) { pointTagstoExtract = new List<string>(); for (int valueIndex = 0; valueIndex < tagPointCollectionGPValue.Count; valueIndex++) { string nameOfTag = tagPointCollectionGPValue.get_Value(valueIndex).GetAsText(); pointTagstoExtract.Add(nameOfTag); } } else { pointTagstoExtract = OSMToolHelper.OSMSmallFeatureClassFields(); } // points try { osmPointFeatureClass = osmToolHelper.CreateSmallPointFeatureClass(pointFeatureWorkspace, pointFCNameElements[pointFCNameElements.Length - 1], storageKeyword, metadataAbstract, metadataPurpose, pointTagstoExtract); } catch (Exception ex) { message.AddError(120035, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message)); return; } if (osmPointFeatureClass == null) { return; } int osmPointIDFieldIndex = osmPointFeatureClass.FindField("OSMID"); Dictionary<string, int> mainPointAttributeFieldIndices = new Dictionary<string, int>(); foreach (string fieldName in OSMToolHelper.OSMSmallFeatureClassFields()) { int currentFieldIndex = osmPointFeatureClass.FindField(fieldName); if (currentFieldIndex != -1) { mainPointAttributeFieldIndices.Add(fieldName, currentFieldIndex); } } int tagCollectionPointFieldIndex = osmPointFeatureClass.FindField("osmTags"); int osmSupportingElementPointFieldIndex = osmPointFeatureClass.FindField("osmSupportingElement"); IGPParameter osmLineFeatureClassParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter; IGPValue osmLineFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmLineFeatureClassParameter) as IGPValue; IName lineWorkspaceName = gpUtilities3.CreateParentFromCatalogPath(osmLineFeatureClassGPValue.GetAsText()); IWorkspace2 lineFeatureWorkspace = lineWorkspaceName.Open() as IWorkspace2; string[] lineFCNameElements = osmLineFeatureClassGPValue.GetAsText().Split(System.IO.Path.DirectorySeparatorChar); IGPParameter tagLineCollectionParameter = paramvalues.get_Element(in_lineFieldNamesNumber) as IGPParameter; IGPMultiValue tagLineCollectionGPValue = gpUtilities3.UnpackGPValue(tagLineCollectionParameter) as IGPMultiValue; List<String> lineTagstoExtract = null; if (tagLineCollectionGPValue.Count > 0) { lineTagstoExtract = new List<string>(); for (int valueIndex = 0; valueIndex < tagLineCollectionGPValue.Count; valueIndex++) { string nameOfTag = tagLineCollectionGPValue.get_Value(valueIndex).GetAsText(); lineTagstoExtract.Add(nameOfTag); } } else { lineTagstoExtract = OSMToolHelper.OSMSmallFeatureClassFields(); } // lines try { osmLineFeatureClass = osmToolHelper.CreateSmallLineFeatureClass(lineFeatureWorkspace, lineFCNameElements[lineFCNameElements.Length -1], storageKeyword, metadataAbstract, metadataPurpose, lineTagstoExtract); } catch (Exception ex) { message.AddError(120036, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nulllinefeatureclass"), ex.Message)); return; } if (osmLineFeatureClass == null) { return; } int osmLineIDFieldIndex = osmLineFeatureClass.FindField("OSMID"); Dictionary<string, int> mainLineAttributeFieldIndices = new Dictionary<string, int>(); foreach (string fieldName in OSMToolHelper.OSMSmallFeatureClassFields()) { int currentFieldIndex = osmLineFeatureClass.FindField(fieldName); if (currentFieldIndex != -1) { mainLineAttributeFieldIndices.Add(fieldName, currentFieldIndex); } } int tagCollectionPolylineFieldIndex = osmLineFeatureClass.FindField("osmTags"); int osmSupportingElementPolylineFieldIndex = osmLineFeatureClass.FindField("osmSupportingElement"); IGPParameter osmPolygonFeatureClassParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter; IGPValue osmPolygonFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmPolygonFeatureClassParameter) as IGPValue; IName polygonWorkspaceName = gpUtilities3.CreateParentFromCatalogPath(osmPolygonFeatureClassGPValue.GetAsText()); IWorkspace2 polygonFeatureWorkspace = polygonWorkspaceName.Open() as IWorkspace2; string[] polygonFCNameElements = osmPolygonFeatureClassGPValue.GetAsText().Split(System.IO.Path.DirectorySeparatorChar); IGPParameter tagPolygonCollectionParameter = paramvalues.get_Element(in_polygonFieldNamesNumber) as IGPParameter; IGPMultiValue tagPolygonCollectionGPValue = gpUtilities3.UnpackGPValue(tagPolygonCollectionParameter) as IGPMultiValue; List<String> polygonTagstoExtract = null; if (tagPolygonCollectionGPValue.Count > 0) { polygonTagstoExtract = new List<string>(); for (int valueIndex = 0; valueIndex < tagPolygonCollectionGPValue.Count; valueIndex++) { string nameOfTag = tagPolygonCollectionGPValue.get_Value(valueIndex).GetAsText(); polygonTagstoExtract.Add(nameOfTag); } } else { polygonTagstoExtract = OSMToolHelper.OSMSmallFeatureClassFields(); } // polygons try { osmPolygonFeatureClass = osmToolHelper.CreateSmallPolygonFeatureClass(polygonFeatureWorkspace, polygonFCNameElements[polygonFCNameElements.Length -1], storageKeyword, metadataAbstract, metadataPurpose, polygonTagstoExtract); } catch (Exception ex) { message.AddError(120037, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpolygonfeatureclass"), ex.Message)); return; } if (osmPolygonFeatureClass == null) { return; } int osmPolygonIDFieldIndex = osmPolygonFeatureClass.FindField("OSMID"); Dictionary<string, int> mainPolygonAttributeFieldIndices = new Dictionary<string, int>(); foreach (var fieldName in OSMToolHelper.OSMSmallFeatureClassFields()) { int currentFieldIndex = osmPolygonFeatureClass.FindField(fieldName); if (currentFieldIndex != -1) { mainPolygonAttributeFieldIndices.Add(fieldName, currentFieldIndex); } } int tagCollectionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmTags"); int osmSupportingElementPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmSupportingElement"); ComReleaser.ReleaseCOMObject(osmPointFeatureClass); osmPointFeatureClass = null; ComReleaser.ReleaseCOMObject(osmLineFeatureClass); osmLineFeatureClass = null; ComReleaser.ReleaseCOMObject(osmPolygonFeatureClass); osmPolygonFeatureClass = null; List<string> nodeOSMFileNames = new List<string>(numberOfThreads); List<string> nodeGDBFileNames = new List<string>(numberOfThreads); List<string> wayOSMFileNames = new List<string>(numberOfThreads); List<string> wayGDBFileNames = new List<string>(numberOfThreads); List<string> relationOSMFileNames = new List<string>(numberOfThreads); List<string> relationGDBFileNames = new List<string>(numberOfThreads); if (TrackCancel.Continue() == false) { return; } // split the original OSM xml file into smaller pieces for the python processes osmToolHelper.splitOSMFile(osmFileLocationString.GetAsText(), scratchWorkspaceFolder, nodeCapacity, wayCapacity, relationCapacity, numberOfThreads, out nodeOSMFileNames, out nodeGDBFileNames, out wayOSMFileNames, out wayGDBFileNames, out relationOSMFileNames, out relationGDBFileNames); IGPParameter deleteSourceOSMFileParameter = paramvalues.get_Element(in_deleteOSMSourceFileNumber) as IGPParameter; IGPBoolean deleteSourceOSMFileGPValue = gpUtilities3.UnpackGPValue(deleteSourceOSMFileParameter) as IGPBoolean; if (deleteSourceOSMFileGPValue.Value) { try { System.IO.File.Delete(osmFileLocationString.GetAsText()); } catch (Exception ex) { message.AddWarning(ex.Message); } } if (TrackCancel.Continue() == false) { return; } if (nodeOSMFileNames.Count == 0) { nodeOSMFileNames.Add(osmFileLocationString.GetAsText()); nodeGDBFileNames.Add(osmPointsFeatureClassGPValue.GetAsText()); wayOSMFileNames.Add(osmFileLocationString.GetAsText()); wayGDBFileNames.Add(osmLineFeatureClassGPValue.GetAsText()); relationOSMFileNames.Add(osmFileLocationString.GetAsText()); relationGDBFileNames.Add(osmPolygonFeatureClassGPValue.GetAsText()); } else { // for the nodes let's load one of the parts directly into the target file geodatabase nodeGDBFileNames[0] = ((IWorkspace)pointFeatureWorkspace).PathName; } // define variables helping to invoke core tools for data management IGeoProcessorResult2 gpResults2 = null; IGeoProcessor2 geoProcessor = new GeoProcessorClass(); IGPParameter deleteSupportingNodesParameter = paramvalues.get_Element(in_deleteSupportNodesNumber) as IGPParameter; IGPBoolean deleteSupportingNodesGPValue = gpUtilities3.UnpackGPValue(deleteSupportingNodesParameter) as IGPBoolean; #region load points osmToolHelper.loadOSMNodes(nodeOSMFileNames, nodeGDBFileNames, pointFCNameElements[pointFCNameElements.Length - 1], osmPointsFeatureClassGPValue.GetAsText(), pointTagstoExtract, deleteSupportingNodesGPValue.Value, ref message, ref TrackCancel); #endregion if (TrackCancel.Continue() == false) { return; } #region load ways osmToolHelper.loadOSMWays(wayOSMFileNames, osmPointsFeatureClassGPValue.GetAsText(), wayGDBFileNames, lineFCNameElements[lineFCNameElements.Length - 1], polygonFCNameElements[polygonFCNameElements.Length - 1], lineTagstoExtract, polygonTagstoExtract, ref message, ref TrackCancel); #endregion #region for local geodatabases enforce spatial integrity bool storedOriginalLocal = geoProcessor.AddOutputsToMap; geoProcessor.AddOutputsToMap = false; try { osmLineFeatureClass = ((IFeatureWorkspace)lineFeatureWorkspace).OpenFeatureClass(lineFCNameElements[lineFCNameElements.Length - 1]); if (osmLineFeatureClass != null) { if (((IDataset)osmLineFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace) { gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3; IGPParameter outLinesParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter; IGPValue lineFeatureClass = gpUtilities3.UnpackGPValue(outLinesParameter); DataManagementTools.RepairGeometry repairlineGeometry = new DataManagementTools.RepairGeometry(osmLineFeatureClass); IVariantArray repairGeometryParameterArray = new VarArrayClass(); repairGeometryParameterArray.Add(lineFeatureClass.GetAsText()); repairGeometryParameterArray.Add("DELETE_NULL"); gpResults2 = geoProcessor.Execute(repairlineGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2; message.AddMessages(gpResults2.GetResultMessages()); ComReleaser.ReleaseCOMObject(gpUtilities3); } } } catch { } finally { ComReleaser.ReleaseCOMObject(osmLineFeatureClass); } try { osmPolygonFeatureClass = ((IFeatureWorkspace)polygonFeatureWorkspace).OpenFeatureClass(polygonFCNameElements[polygonFCNameElements.Length - 1]); if (osmPolygonFeatureClass != null) { if (((IDataset)osmPolygonFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace) { gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3; IGPParameter outPolygonParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter; IGPValue polygonFeatureClass = gpUtilities3.UnpackGPValue(outPolygonParameter); DataManagementTools.RepairGeometry repairpolygonGeometry = new DataManagementTools.RepairGeometry(osmPolygonFeatureClass); IVariantArray repairGeometryParameterArray = new VarArrayClass(); repairGeometryParameterArray.Add(polygonFeatureClass.GetAsText()); repairGeometryParameterArray.Add("DELETE_NULL"); gpResults2 = geoProcessor.Execute(repairpolygonGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2; message.AddMessages(gpResults2.GetResultMessages()); ComReleaser.ReleaseCOMObject(gpUtilities3); } } } catch { } finally { ComReleaser.ReleaseCOMObject(osmPolygonFeatureClass); } geoProcessor.AddOutputsToMap = storedOriginalLocal; #endregion if (TrackCancel.Continue() == false) { return; } #region load relations osmToolHelper.loadOSMRelations(relationOSMFileNames, osmLineFeatureClassGPValue.GetAsText(), osmPolygonFeatureClassGPValue.GetAsText(), relationGDBFileNames, lineTagstoExtract, polygonTagstoExtract, ref TrackCancel, ref message); #endregion // check for user interruption if (TrackCancel.Continue() == false) { return; } #region for local geodatabases enforce spatial integrity //storedOriginalLocal = geoProcessor.AddOutputsToMap; //geoProcessor.AddOutputsToMap = false; //try //{ // osmLineFeatureClass = ((IFeatureWorkspace)lineFeatureWorkspace).OpenFeatureClass(lineFCNameElements[lineFCNameElements.Length - 1]); // if (osmLineFeatureClass != null) // { // if (((IDataset)osmLineFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace) // { // gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3; // IGPParameter outLinesParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter; // IGPValue lineFeatureClass = gpUtilities3.UnpackGPValue(outLinesParameter); // DataManagementTools.RepairGeometry repairlineGeometry = new DataManagementTools.RepairGeometry(osmLineFeatureClass); // IVariantArray repairGeometryParameterArray = new VarArrayClass(); // repairGeometryParameterArray.Add(lineFeatureClass.GetAsText()); // repairGeometryParameterArray.Add("DELETE_NULL"); // gpResults2 = geoProcessor.Execute(repairlineGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2; // message.AddMessages(gpResults2.GetResultMessages()); // ComReleaser.ReleaseCOMObject(gpUtilities3); // } // } //} //catch { } //finally //{ // ComReleaser.ReleaseCOMObject(osmLineFeatureClass); //} //try //{ // osmPolygonFeatureClass = ((IFeatureWorkspace)polygonFeatureWorkspace).OpenFeatureClass(polygonFCNameElements[polygonFCNameElements.Length - 1]); // if (osmPolygonFeatureClass != null) // { // if (((IDataset)osmPolygonFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace) // { // gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3; // IGPParameter outPolygonParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter; // IGPValue polygonFeatureClass = gpUtilities3.UnpackGPValue(outPolygonParameter); // DataManagementTools.RepairGeometry repairpolygonGeometry = new DataManagementTools.RepairGeometry(osmPolygonFeatureClass); // IVariantArray repairGeometryParameterArray = new VarArrayClass(); // repairGeometryParameterArray.Add(polygonFeatureClass.GetAsText()); // repairGeometryParameterArray.Add("DELETE_NULL"); // gpResults2 = geoProcessor.Execute(repairpolygonGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2; // message.AddMessages(gpResults2.GetResultMessages()); // ComReleaser.ReleaseCOMObject(gpUtilities3); // } // } //} //catch { } //finally //{ // ComReleaser.ReleaseCOMObject(osmPolygonFeatureClass); //} //geoProcessor.AddOutputsToMap = storedOriginalLocal; #endregion if (TrackCancel.Continue() == false) { return; } if (deleteSupportingNodesGPValue.Value) { message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPMultiLoader_remove_supportNodes"))); storedOriginalLocal = geoProcessor.AddOutputsToMap; geoProcessor.AddOutputsToMap = false; // create a layer file to select the points that have attributes osmPointFeatureClass = ((IFeatureWorkspace)pointFeatureWorkspace).OpenFeatureClass(pointFCNameElements[pointFCNameElements.Length - 1]); IVariantArray makeFeatureLayerParameterArray = new VarArrayClass(); makeFeatureLayerParameterArray.Add(osmPointsFeatureClassGPValue.GetAsText()); string tempLayerFile = System.IO.Path.GetTempFileName(); makeFeatureLayerParameterArray.Add(tempLayerFile); makeFeatureLayerParameterArray.Add(String.Format("{0} = 'no'", osmPointFeatureClass.SqlIdentifier("osmSupportingElement"))); geoProcessor.Execute("MakeFeatureLayer_management", makeFeatureLayerParameterArray, TrackCancel); // copy the features into its own feature class IVariantArray copyFeatureParametersArray = new VarArrayClass(); copyFeatureParametersArray.Add(tempLayerFile); string tempFeatureClass = String.Join("\\", new string[] { ((IWorkspace)pointFeatureWorkspace).PathName, "t_" + pointFCNameElements[pointFCNameElements.Length - 1] }); copyFeatureParametersArray.Add(tempFeatureClass); geoProcessor.Execute("CopyFeatures_management", copyFeatureParametersArray, TrackCancel); // delete the temp file System.IO.File.Delete(tempLayerFile); // delete the original feature class IVariantArray deleteParameterArray = new VarArrayClass(); deleteParameterArray.Add(osmPointsFeatureClassGPValue.GetAsText()); geoProcessor.Execute("Delete_management", deleteParameterArray, TrackCancel); // rename the temp feature class back to the original IVariantArray renameParameterArray = new VarArrayClass(); renameParameterArray.Add(tempFeatureClass); renameParameterArray.Add(osmPointsFeatureClassGPValue.GetAsText()); geoProcessor.Execute("Rename_management", renameParameterArray, TrackCancel); geoProcessor.AddOutputsToMap = storedOriginalLocal; ComReleaser.ReleaseCOMObject(osmPointFeatureClass); ComReleaser.ReleaseCOMObject(geoProcessor); } gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3; // repackage the feature class into their respective gp values IGPParameter pointFeatureClassParameter = paramvalues.get_Element(out_osmPointsNumber) as IGPParameter; IGPValue pointFeatureClassGPValue = gpUtilities3.UnpackGPValue(pointFeatureClassParameter); gpUtilities3.PackGPValue(pointFeatureClassGPValue, pointFeatureClassParameter); IGPParameter lineFeatureClassParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter; IGPValue line1FeatureClassGPValue = gpUtilities3.UnpackGPValue(lineFeatureClassParameter); gpUtilities3.PackGPValue(line1FeatureClassGPValue, lineFeatureClassParameter); IGPParameter polygonFeatureClassParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter; IGPValue polygon1FeatureClassGPValue = gpUtilities3.UnpackGPValue(polygonFeatureClassParameter); gpUtilities3.PackGPValue(polygon1FeatureClassGPValue, polygonFeatureClassParameter); ComReleaser.ReleaseCOMObject(osmFileLocationString); gpUtilities3.ReleaseInternals(); ComReleaser.ReleaseCOMObject(gpUtilities3); } catch (Exception ex) { message.AddError(120055, ex.Message); message.AddError(120055, ex.StackTrace); } finally { try { osmToolHelper = null; System.GC.Collect(); System.GC.WaitForPendingFinalizers(); } catch (Exception ex) { message.AddError(120056, ex.ToString()); } } }
private void btnOK_Click(object sender, EventArgs e) { if (txtSoilClay.Text.Equals("")) { MessageBox.Show("请选择输入土壤黏粒含量(%)数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (txtSoilSlit.Text.Equals("")) { MessageBox.Show("请选择输入土壤粉粒含量(%)数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (txtSoilSand.Text.Equals("")) { MessageBox.Show("请选择输入土壤砂粒含量(%)数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (txtSoilOrganic.Text.Equals("")) { MessageBox.Show("请选择输入土壤有机物含量(%)数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (txtDem.Text.Equals("")) { MessageBox.Show("请选择输入DEM数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (txtC.Text.Equals("")) { MessageBox.Show("请选择输入地表覆被因子相关数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (txtP.Text.Equals("")) { MessageBox.Show("请选择输入水土保持措施因子数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (txtSavePath.Text.Equals("")) { MessageBox.Show("请选择结果输出路径!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (rbtnR.Checked && txtR.Text.Equals("")) { MessageBox.Show("请选择输入降雨侵蚀力因子R相关数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if ((!rbtnR.Checked) && txtPcpPath.Text.Equals("")) { MessageBox.Show("请选择输入多年平均各月降雨量数据所在路径!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if ((!rbtnR.Checked) && txtPcpPrefix.Text.Equals("")) { MessageBox.Show("请输入数据前缀(如:pcp_*)!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if ((!rbtnR.Checked) && txtPcpSuffix.Text.Equals("")) { MessageBox.Show("请输入数据后缀(如:tif)!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if ((!rbtnR.Checked) && txtYear.Text.Equals("")) { MessageBox.Show("请输入年平均降水量!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //现创建一个存放临时文件的临时文件夹 string newPath = System.IO.Path.Combine(Temfile, ""); System.IO.Directory.CreateDirectory(newPath); this.rtxtState.AppendText("正在执行,请您耐心等待...\n"); this.rtxtState.ScrollToCaret(); this.rtxtState.AppendText("开始准备配置文件...\n"); this.rtxtState.ScrollToCaret(); IVariantArray parameters = new VarArrayClass(); Geoprocessor GP = new Geoprocessor(); this.rtxtState.AppendText("准备调用GP工具箱...\n"); this.rtxtState.ScrollToCaret(); //ESRI.ArcGIS.DataManagementTools.GetRasterProperties NDVIMin = new ESRI.ArcGIS.DataManagementTools.GetRasterProperties(); //ESRI.ArcGIS.DataManagementTools.GetRasterProperties NDVIMax = new ESRI.ArcGIS.DataManagementTools.GetRasterProperties(); ESRI.ArcGIS.SpatialAnalystTools.Slope slo = new ESRI.ArcGIS.SpatialAnalystTools.Slope();//计算坡度 ESRI.ArcGIS.SpatialAnalystTools.Fill demFill = new ESRI.ArcGIS.SpatialAnalystTools.Fill(); ESRI.ArcGIS.SpatialAnalystTools.FlowDirection Filldec = new ESRI.ArcGIS.SpatialAnalystTools.FlowDirection(); ESRI.ArcGIS.SpatialAnalystTools.FlowAccumulation DecAcc = new ESRI.ArcGIS.SpatialAnalystTools.FlowAccumulation(); ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator sCals = new ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator(); ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator sCalm = new ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator(); ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator sCalLS = new ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator(); ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator sCalR = new ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator(); ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator sCalK = new ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator(); ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator sCalA = new ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator(); ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator sCalC = new ESRI.ArcGIS.SpatialAnalystTools.RasterCalculator(); //1计算参数R if (rbtnR.Checked) { sR = txtR.Text; this.rtxtState.AppendText("降水侵蚀因子R读取成功,准备计算参数K...\n"); this.rtxtState.ScrollToCaret(); } else { this.rtxtState.AppendText("开始计算参数R...\n"); this.rtxtState.ScrollToCaret(); string sFileName = ""; string sYear = txtYear.Text; for (int i = 1; i < 13; i++) { sFileName = txtPcpPath.Text + "\\" + this.txtPcpPrefix.Text + i.ToString() + "." + this.txtPcpSuffix.Text; strExp = "(1.735 * Power(10,1.5 * Log10((" + "\"" + sFileName + "\"" + " * " + "\"" + sFileName + "\"" + ") /" + "\"" + txtYear.Text + "\")" + " - 0.08188))"; if (i < 12) { sR2 = sR2 + strExp + "+"; } else { sR2 = sR2 + strExp; } } sR3 = sR2; sCalR.expression = sR3; sR = Temfile + "\\CalR.tif"; sCalR.output_raster = sR; GP.Execute(sCalR, null); this.rtxtState.AppendText("降水侵蚀因子R计算成功,准备计算参数K...\n"); this.rtxtState.ScrollToCaret(); } //2计算参数K sK = "(0.2 + 0.3 * Exp(-0.0256 *" + "\"" + txtSoilSand.Text + "\"" + "* (1.0 - " + "\"" + txtSoilSlit.Text + "\"" + " / 100.0))) * Power((" + "\"" + txtSoilSlit.Text + "\"" + " * 1.0 / (" + "\"" + txtSoilClay.Text + "\"" + " * 1.0 + " + "\"" + txtSoilSlit.Text + "\"" + " * 1.0)), 0.3) * (1.0 - 0.25 * " + "\"" + txtSoilOrganic.Text + "\"" + " * 0.58 / (" + "\"" + txtSoilOrganic.Text + "\"" + " * 0.58 + Exp(3.72 - 2.95 * " + "\"" + txtSoilOrganic.Text + "\"" + " * 0.58))) * (1.0 - (0.7 * (1.0 - " + "\"" + txtSoilSand.Text + "\"" + " / 100.0)) / ((1.0 - " + "\"" + txtSoilSand.Text + "\"" + " / 100.0) + Exp(-5.51 + 22.9 * (1.0 - " + "\"" + txtSoilSand.Text + "\"" + " / 100.0))))"; sCalK.expression = sK; CalKpath = Temfile + "\\CalK.tif"; sCalK.output_raster = CalKpath; GP.Execute(sCalK, null); this.rtxtState.AppendText("土壤可蚀性因子K计算成功...\n"); this.rtxtState.ScrollToCaret(); this.rtxtState.AppendText("准备计算地形因子LS...\n"); this.rtxtState.ScrollToCaret(); //3计算参数LS //Fill Dem this.rtxtState.AppendText("开始填充洼地...\n"); this.rtxtState.ScrollToCaret(); demFill.in_surface_raster = txtDem.Text; demFill.out_surface_raster = Temfile + "\\demFill.tif"; GP.Execute(demFill, null); // cal FlowDirection this.rtxtState.AppendText("开始计算流向...\n"); this.rtxtState.ScrollToCaret(); Filldec.in_surface_raster = Temfile + "\\demFill.tif"; Filldec.out_flow_direction_raster = Temfile + "\\FillDec.tif"; GP.Execute(Filldec, null); //cal FlowAccumulation this.rtxtState.AppendText("开始计算流量...\n"); this.rtxtState.ScrollToCaret(); Filldec.in_surface_raster = Temfile + "\\FillDec.tif"; FlowAcc = Temfile + "\\FlowAcc.tif"; Filldec.out_flow_direction_raster = FlowAcc; GP.Execute(Filldec, null); //先计算坡度 this.rtxtState.AppendText("开始计算坡度...\n"); this.rtxtState.ScrollToCaret(); slo.in_raster = txtDem.Text; slo.output_measurement = "DEGREE"; slo.z_factor = 1; string sRoad1 = Temfile + "\\Slope.tif"; slo.out_raster = sRoad1; GP.Execute(slo, null);//坡度计算 //cal S sS = "Con(" + "\"" + sRoad1 + "\"" + " < 5,10.8 * Sin(" + "\"" + sRoad1 + "\"" + " * 3.14 / 180) + 0.03,Con(" + "\"" + sRoad1 + "\"" + " >= 10,21.9 * Sin(" + "\"" + sRoad1 + "\"" + " * 3.14 / 180) - 0.96,16.8 * Sin(" + "\"" + sRoad1 + "\"" + " * 3.14 / 180) - 0.5))"; sCals.expression = sS; Calspath = Temfile + "\\CalS.tif"; sCals.output_raster = Calspath; GP.Execute(sCals, null); //cal m sM = "Con(" + "\"" + sRoad1 + "\"" + " <= 1,0.2,Con(" + "\"" + sRoad1 + "\"" + " <= 3,0.3,Con(" + "\"" + sRoad1 + "\"" + " <= 5,0.4,0.5)))"; sCalm.expression = sM; Calmpath = Temfile + "\\CalM.tif"; sCalm.output_raster = Calmpath; GP.Execute(sCalm, null); //cal ls sLs = "\"" + Calspath + "\"" + " * Power((" + "\"" + CalKpath + "\"" + " * " + this.txtCellSize.Text + " / 22.1)," + "\"" + Calmpath + "\"" + ")"; sCalLS.expression = sLs; Callspath = Temfile + "\\CalLS.tif"; sCalm.output_raster = Calmpath; sCalLS.output_raster = Callspath; GP.Execute(sCalLS, null); this.rtxtState.AppendText("地形因子LS计算成功...\n"); this.rtxtState.ScrollToCaret(); //4计算参数C if (rbtnVegCover.Checked) { CalCpath = txtC.Text; this.rtxtState.AppendText("地表覆盖因子C读取成功...\n"); this.rtxtState.ScrollToCaret(); } else { this.rtxtState.AppendText("准备计算地表覆盖因子C...\n"); this.rtxtState.ScrollToCaret(); //计算NDVI最小值 //NDVIMin.in_raster = txtC.Text; //CalKpath = txtDem.Text + "/CalK.tif"; //NDVIMin.property_type = "MINIMUM"; //GP.Execute(sCalK, null); double dMin = 0; IGeoProcessor2 gp = new GeoProcessorClass(); gp.OverwriteOutput = true; // Create a variant array to hold the parameter values. IVariantArray parameters2 = new VarArrayClass(); IGeoProcessorResult result = new GeoProcessorResultClass(); // Set parameter values. parameters2.Add(txtC.Text); parameters2.Add("MINIMUM"); result = gp.Execute("GetRasterProperties_management", parameters2, null); dMin = (double)result.ReturnValue; //计算NDVI最大值 double dMax = 0; IGeoProcessor2 gp2 = new GeoProcessorClass(); gp2.OverwriteOutput = true; // Create a variant array to hold the parameter values. IVariantArray parameters3 = new VarArrayClass(); IGeoProcessorResult result3 = new GeoProcessorResultClass(); // Set parameter values. parameters3.Add(txtC.Text); parameters3.Add("MAXIMUM"); result3 = gp2.Execute("GetRasterProperties_management", parameters3, null); dMax = (double)result3.ReturnValue; //最后计算C sC = "(" + "\"" + txtC.Text + "\"" + " - " + dMin + ") / (" + dMax + " - " + dMin + ")"; sCalC.expression = sC; CalCpath = Temfile + "\\CalC.tif"; sCalC.output_raster = CalCpath; GP.Execute(sCalC, null); this.rtxtState.AppendText("地表覆盖因子C计算成功...\n"); this.rtxtState.ScrollToCaret(); } //5计算P sP = txtP.Text; this.rtxtState.AppendText("读取水土保持措施因子P...\n"); this.rtxtState.ScrollToCaret(); //最后开始计算A=R*K*LS*C*P this.rtxtState.AppendText("准备计算水土流失方程...\n"); this.rtxtState.ScrollToCaret(); sA = "\"" + sR + "\"" + " * " + "\"" + CalKpath + "\"" + " * " + "\"" + Callspath + "\"" + " * (1 - " + "\"" + CalCpath + "\"" + ") * " + "\"" + sP + "\""; sCalA.expression = sA; sCalA.output_raster = txtSavePath.Text; GP.Execute(sCalA, null); //删除临时文件夹 string deleteFile = Temfile; DeleteFolder(deleteFile); this.rtxtState.AppendText("计算成功,已将结果成功保存...\n"); this.rtxtState.ScrollToCaret(); }