Beispiel #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="vt"></param>
        /// <returns></returns>
        private IJTXAttributeConditionSet ExtractAttributeConditionsFromWhereClause(IGPValueTable vt)
        {
            IJTXAttributeConditionSet attributeConditions = new JTXAttributeConditionSetClass();

            // Preliminary error-checking
            for (int i = 0; i < vt.RecordCount; i++)
            {
                IArray   tempRecord = vt.GetRecord(i);
                IGPValue tempVal    = tempRecord.get_Element(m_whereClauseIndices[C_ID_VT_OPERATOR]) as IGPValue;
                if (!m_optWhereClauseOps.ContainsKey(tempVal.GetAsText()))
                {
                    throw new WmauException(WmauErrorCodes.C_OPERATOR_NOT_FOUND_ERROR);
                }
            }

            // Build out the attribute conditions
            for (int i = 0; i < vt.RecordCount; i++)
            {
                IArray   tempRecord   = vt.GetRecord(i);
                IGPValue attribute    = tempRecord.get_Element(m_whereClauseIndices[C_ID_VT_ATTRIBUTE]) as IGPValue;
                IGPValue compOperator = tempRecord.get_Element(m_whereClauseIndices[C_ID_VT_OPERATOR]) as IGPValue;
                IGPValue value        = tempRecord.get_Element(m_whereClauseIndices[C_ID_VT_VALUE]) as IGPValue;

                IJTXAttributeCondition attributeCondition = new JTXAttributeConditionClass();
                attributeCondition.FieldName    = attribute.GetAsText();
                attributeCondition.Operator     = m_optWhereClauseOps[compOperator.GetAsText()];
                attributeCondition.CompareValue = value.GetAsText();

                attributeConditions.Add(attributeCondition);
            }

            return(attributeConditions);
        }
Beispiel #2
0
        /// <summary>
        ///     Executes the geoprocessing function using the given array of parameter values.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="trackCancel">The track cancel.</param>
        /// <param name="environmentManager">Provides access to all the current environments and settings of the current client.</param>
        /// <param name="messages">The messages that are reported to the user.</param>
        /// <param name="utilities">
        ///     The utilities object that provides access to the properties and methods of a geoprocessing
        ///     objects.
        /// </param>
        protected override void Execute(Dictionary <string, IGPValue> parameters, ITrackCancel trackCancel, IGPEnvironmentManager environmentManager, IGPMessages messages, IGPUtilities2 utilities)
        {
            IGPValue      field      = parameters["in_field"];
            IObjectClass  table      = utilities.OpenTable(parameters["in_table"]);
            IGPMultiValue modelNames = (IGPMultiValue)parameters["in_field_model_names"];

            if (!field.IsEmpty() && modelNames.Count > 0)
            {
                var fieldName = field.GetAsText();
                int index     = table.FindField(fieldName);

                foreach (var modelName in modelNames.AsEnumerable().Select(o => o.GetAsText()))
                {
                    messages.Add(esriGPMessageType.esriGPMessageTypeInformative, "Removing the {0} field model name from the {1} field.", modelName, fieldName);

                    ModelNameManager.Instance.RemoveFieldModelName(table, table.Fields.Field[index], modelName);
                }

                // Success.
                parameters["out_results"].SetAsText("true");
            }
            else
            {
                // Failure.
                parameters["out_results"].SetAsText("false");
            }
        }
Beispiel #3
0
        /// <summary>
        ///     Executes the geoprocessing function using the given array of parameter values.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="trackCancel">The track cancel.</param>
        /// <param name="environmentManager">Provides access to all the current environments and settings of the current client.</param>
        /// <param name="messages">The messages that are reported to the user.</param>
        /// <param name="utilities">
        ///     The utilities object that provides access to the properties and methods of a geoprocessing
        ///     objects.
        /// </param>
        protected override void Execute(Dictionary <string, IGPValue> parameters, ITrackCancel trackCancel, IGPEnvironmentManager environmentManager, IGPMessages messages, IGPUtilities2 utilities)
        {
            IGPValue     value = parameters["in_table"];
            IObjectClass table = utilities.OpenTable(value);

            if (table != null)
            {
                IMMConfigTopLevel configTopLevel = ConfigTopLevel.Instance;
                configTopLevel.Workspace = utilities.GetWorkspace(value);

                // Load all of the subtypes when the user specified "All" or "-1".
                int subtype      = parameters["in_subtype"].Cast(-1);
                var subtypeCodes = new List <int>(new[] { subtype });
                if (subtype == -1)
                {
                    ISubtypes subtypes = (ISubtypes)table;
                    subtypeCodes.AddRange(subtypes.Subtypes.AsEnumerable().Select(o => o.Key));
                }

                IGPMultiValue onCreate = (IGPMultiValue)parameters["in_create"];
                IGPMultiValue onUpdate = (IGPMultiValue)parameters["in_update"];
                IGPMultiValue onDelete = (IGPMultiValue)parameters["in_delete"];

                // Load the "Attribute" AUs.
                var uids = new Dictionary <mmEditEvent, IEnumerable <IUID> >();
                uids.Add(mmEditEvent.mmEventFeatureCreate, onCreate.AsEnumerable().Cast <IGPAutoValue>().Select(o => o.UID));
                uids.Add(mmEditEvent.mmEventFeatureUpdate, onUpdate.AsEnumerable().Cast <IGPAutoValue>().Select(o => o.UID));
                uids.Add(mmEditEvent.mmEventFeatureDelete, onDelete.AsEnumerable().Cast <IGPAutoValue>().Select(o => o.UID));

                IGPValue field = parameters["in_field"];
                int      index = table.FindField(field.GetAsText());

                // Enumerate through all of the subtypes making changes.
                foreach (var subtypeCode in subtypeCodes)
                {
                    // Load the configurations for the table and subtype.
                    IMMSubtype mmsubtype = configTopLevel.GetSubtypeByID(table, subtypeCode, false);

                    // Load the field configurations.
                    IMMField mmfield = null;
                    mmsubtype.GetField(index, ref mmfield);

                    // Update the list to have these UIDs removed.
                    ID8List list = (ID8List)mmfield;
                    base.Remove(uids, list, messages);
                }

                // Commit the changes to the database.
                configTopLevel.SaveFeatureClassToDB(table);

                // Success.
                parameters["out_results"].SetAsText("true");
            }
            else
            {
                // Failure.
                parameters["out_results"].SetAsText("false");
            }
        }
        /// <summary>
        /// Updates the internal values used by this tool based on the parameters from an input array
        /// </summary>
        /// <param name="paramValues"></param>
        protected override void ExtractParameters(IArray paramValues)
        {
            // Get the values for any parameters common to all GP tools
            ExtractParametersCommon(paramValues);

            WmauParameterMap paramMap = new WmauParameterMap(paramValues);
            IGPParameter3    param    = null;

            // Ensure that the various parameter values are all restored to their
            // defaults because of how this function works
            ResetVariables();

            // Update the internal values of whatever parameters we're maintaining
            param            = paramMap.GetParam(C_PARAM_PREVIEW_CHANGES);
            m_previewChanges = (param.Value as IGPBoolean).Value;

            param = paramMap.GetParam(C_PARAM_CHECKLIST);
            IGPValue      paramValue      = m_gpUtilities.UnpackGPValue(param);
            IGPMultiValue paramMultiValue = paramValue as IGPMultiValue;

            for (int i = 0; i < paramMultiValue.Count; i++)
            {
                IGPValue check  = paramMultiValue.get_Value(i);
                string   strVal = check.GetAsText();
                if (strVal.Equals(C_OPT_CLEAN_WORKFLOWS))
                {
                    m_cleanWorkflows = true;
                }
                else if (strVal.Equals(C_OPT_CLEAN_STEP_TYPES))
                {
                    m_cleanStepTypes = true;
                }
                else if (strVal.Equals(C_OPT_CLEAN_STATUS_TYPES))
                {
                    m_cleanStatusTypes = true;
                }
                else if (strVal.Equals(C_OPT_CLEAN_PRIORITIES))
                {
                    m_cleanPriorities = true;
                }
                else if (strVal.Equals(C_OPT_CLEAN_TA_WORKBOOKS))
                {
                    m_cleanTaWorkbooks = true;
                }
                else if (strVal.Equals(C_OPT_CLEAN_USERS))
                {
                    m_cleanUsers = true;
                }
                else if (strVal.Equals(C_OPT_CLEAN_MAP_DOCS))
                {
                    m_cleanMapDocs = true;
                }
            }
        }
        public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
        {
            IGPUtilities3 execute_Utilities = new GPUtilitiesClass();
            IGPValue inputFeatureDatasetGPValue = execute_Utilities.UnpackGPValue(paramvalues.get_Element(in_featureDatasetParameterNumber));

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

            if (fdDemlimiterPosition == -1)
            {
                Messages.ReplaceError(in_featureDatasetParameterNumber, -33, resourceManager.GetString("GPTools_OSMGPExport2OSM_invalid_featuredataset"));
            }
        }
Beispiel #6
0
        public void UpdateParameters(IArray paramvalues, IGPEnvironmentManager pEnvMgr)
        {
            IGPUtilities2 gpUtil = null;

            try
            {
                gpUtil = new GPUtilitiesClass();

                IGPParameter targetDatasetParameter = paramvalues.get_Element(in_osmFeatureDataset) as IGPParameter;
                IDataElement dataElement            = gpUtil.UnpackGPValue(targetDatasetParameter) as IDataElement;
                string       osmDatasetPath         = dataElement.CatalogPath;

                IGPParameter gppNetworkDataset = paramvalues.get_Element(out_NetworkDataset) as IGPParameter;
                IGPValue     gpvNetworkDataset = gpUtil.UnpackGPValue(gppNetworkDataset);
                string       ndsPath           = gpvNetworkDataset.GetAsText();

                string ndsDir = string.Empty;
                if (!string.IsNullOrEmpty(ndsPath))
                {
                    ndsDir = System.IO.Path.GetDirectoryName(ndsPath);
                }

                if (!ndsDir.Equals(osmDatasetPath))
                {
                    string ndsName = System.IO.Path.GetFileName(ndsPath);
                    if (string.IsNullOrEmpty(ndsName))
                    {
                        ndsName = _defaultNetworkDatasetName;
                    }

                    ndsName = System.IO.Path.GetFileName(osmDatasetPath) + "_" + ndsName;
                    gpvNetworkDataset.SetAsText(System.IO.Path.Combine(osmDatasetPath, ndsName));
                    gpUtil.PackGPValue(gpvNetworkDataset, gppNetworkDataset);
                }
            }
            finally
            {
                if (gpUtil != null)
                {
                    ComReleaser.ReleaseCOMObject(gpUtil);
                }
            }
        }
Beispiel #7
0
        /// <summary>
        ///     Pre validates the given set of values.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="environmentManager">Provides access to all the current environments and settings of the current client.</param>
        /// <param name="utilities">
        ///     The utilities object that provides access to the properties and methods of a geoprocessing
        ///     objects.
        /// </param>
        protected override void UpdateParameters(Dictionary <string, IGPParameter> parameters, IGPEnvironmentManager environmentManager, IGPUtilities2 utilities)
        {
            // Retrieve the input parameter value.
            IGPValue table = utilities.UnpackGPValue(parameters["in_table"]);

            if (!table.IsEmpty())
            {
                // Create the domain based on the fields on the table.
                IObjectClass oclass = utilities.OpenTable(table);
                if (oclass != null)
                {
                    IFields fields = oclass.Fields;
                    if (fields != null)
                    {
                        IGPCodedValueDomain codedValueDomain = new GPCodedValueDomainClass();
                        foreach (var o in fields.AsEnumerable())
                        {
                            codedValueDomain.AddStringCode(o.Name, o.Name);
                        }

                        IGPParameterEdit3 derivedFields = (IGPParameterEdit3)parameters["in_field"];
                        derivedFields.Domain = (IGPDomain)codedValueDomain;
                    }

                    IGPValue field = utilities.UnpackGPValue(parameters["in_field"]);
                    if (!field.IsEmpty())
                    {
                        int index = oclass.FindField(field.GetAsText());

                        IGPCodedValueDomain codedValueDomain = new GPCodedValueDomainClass();
                        foreach (var o in oclass.GetFieldModelNames(oclass.Fields.Field[index]))
                        {
                            codedValueDomain.AddStringCode(o, o);
                        }

                        IGPParameterEdit3 derivedParameter = (IGPParameterEdit3)parameters["in_field_model_names"];
                        derivedParameter.Domain = (IGPDomain)codedValueDomain;
                    }
                }
            }
        }
        private string GetLocationString(IGPValue gpValue, IFeatureClass featureClass)
        {
            string locationString = String.Empty;

            if (featureClass.FeatureDataset != null)
            {
                if (featureClass.FeatureDataset.Workspace.PathName.ToUpper().Contains(".GDS\\"))
                {
                    locationString = gpValue.GetAsText() + System.IO.Path.DirectorySeparatorChar + ((IDataset)featureClass).BrowseName;
                }
                else
                    locationString = featureClass.FeatureDataset.Workspace.PathName + System.IO.Path.DirectorySeparatorChar + featureClass.FeatureDataset.BrowseName + System.IO.Path.DirectorySeparatorChar + ((IDataset)featureClass).BrowseName;
            }
            else
            {
                locationString = ((IDataset)featureClass).Workspace.PathName + System.IO.Path.DirectorySeparatorChar + ((IDataset)featureClass).BrowseName;
            }

            return locationString;
        }
Beispiel #9
0
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            try
            {
                IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

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

                IGPParameter inputSourceLayerParameter = paramvalues.get_Element(in_sourcelayerNumber) as IGPParameter;
                IGPValue     inputSourceLayerGPValue   = gpUtilities3.UnpackGPValue(inputSourceLayerParameter) as IGPValue;

                IGPParameter inputTargetLayerParameter = paramvalues.get_Element(in_targetlayerNumber) as IGPParameter;
                IGPValue     inputTargetLayerGPValue   = gpUtilities3.UnpackGPValue(inputTargetLayerParameter) as IGPValue;

                ILayer sourceLayer = gpUtilities3.DecodeLayer(inputSourceLayerGPValue);
                ILayer targetLayer = gpUtilities3.DecodeLayer(inputTargetLayerGPValue);

                ILayerExtensions sourceLayerExtensions = sourceLayer as ILayerExtensions;

                if (sourceLayerExtensions == null)
                {
                    message.AddWarning(resourceManager.GetString("GPTools_GPCopyLayerExtension_source_noext_support"));
                    return;
                }

                ILayerExtensions targetLayerExtensions = targetLayer as ILayerExtensions;

                if (targetLayerExtensions == null)
                {
                    message.AddWarning(resourceManager.GetString("GPTools_GPCopyLayerExtension_target_noext_support"));
                    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(inputTargetLayerGPValue) == true)
                    {
                        message.AddError(120003, String.Format(resourceManager.GetString("GPTools_GPCopyLayerExtension_targetlayeralreadyexists"), inputTargetLayerGPValue.GetAsText()));
                        return;
                    }
                }

                for (int targetExtensionIndex = 0; targetExtensionIndex < targetLayerExtensions.ExtensionCount; targetExtensionIndex++)
                {
                    targetLayerExtensions.RemoveExtension(targetExtensionIndex);
                }


                for (int sourceExtensionIndex = 0; sourceExtensionIndex < sourceLayerExtensions.ExtensionCount; sourceExtensionIndex++)
                {
                    targetLayerExtensions.AddExtension(sourceLayerExtensions.get_Extension(sourceExtensionIndex));
                }
            }
            catch (Exception ex)
            {
                message.AddError(120004, ex.Message);
            }
        }
        public static IFeatureClass CreateFeatureClass(IGPValue gpFeatureClass, IGPEnvironmentManager environment, IFields fields = null)
        {
            if (gpFeatureClass == null)
                throw new ArgumentException("Argument can not be null", "gpFeatureClass");
            if (environment == null)
                throw new ArgumentException("Argument can not be null", "environment");

            IGeoProcessorSettings gpSettings = (IGeoProcessorSettings)environment;
            if (gpUtilities.Exists(gpFeatureClass))
            {
                if (gpSettings.OverwriteOutput == true)
                    gpUtilities.Delete(gpFeatureClass);
                else
                    throw new Exception("Output feature class already exists: " + gpFeatureClass.GetAsText());
            }

            IDEFeatureClass deFeatureClass = (IDEFeatureClass)gpUtilities.DecodeDETable(gpFeatureClass);
            if (deFeatureClass == null)
                throw new Exception("Data Element decode return null");

            IObjectClassDescription objectClassDescription = (IObjectClassDescription)new FeatureClassDescriptionClass();
            UID clsid = objectClassDescription.InstanceCLSID;
            UID extclsid = objectClassDescription.ClassExtensionCLSID;

            IDataElement dataElement = (IDataElement)deFeatureClass;
            if (dataElement.CatalogPath == null)
                throw new ArgumentException("Catalog path is null", "CatalogPath");
            IFeatureClassName featureClassName = (IFeatureClassName)gpUtilities.CreateFeatureClassName(dataElement.CatalogPath);

            string path = dataElement.GetPath();
            string name = dataElement.Name;

            IDEGeoDataset geoDataElement = (IDEGeoDataset)deFeatureClass;
            ISpatialReference spatialReference = geoDataElement.SpatialReference;

            IDETable deTable = (IDETable)deFeatureClass;
            string shapeFieldName = deFeatureClass.ShapeFieldName;

            Dictionary<string,IField> fieldBuilder = new Dictionary<string,IField>();
            foreach(var input_fields in new IFields[] { deTable.Fields, fields })
            {
                if (input_fields == null) continue;
                for (int i = 0; i < input_fields.FieldCount; i++)
                {
                    IField field = deTable.Fields.get_Field(i);

                    if (fieldBuilder.ContainsKey(field.Name.ToLower()))
                        fieldBuilder[field.Name.ToLower()] = (IField)((IClone)field).Clone();
                    else
                        fieldBuilder.Add(field.Name.ToLower(), (IField)((IClone)field).Clone());

                    if (field.Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        shapeFieldName = field.Name;
                        break;
                    }
                }
            }

            IFields output_fields = new FieldsClass();
            IFieldsEdit fields_edit = (IFieldsEdit)output_fields;
            foreach(IField field in fieldBuilder.Values)
            {
                fields_edit.AddField(field);
                if(field.Type == esriFieldType.esriFieldTypeGeometry)
                {
                    IGeometryDefEdit defEdit = (IGeometryDefEdit)field.GeometryDef;
                    defEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
                }
            }

            string configKeyword = ((IGPString)environment.FindEnvironment(CONFIG_KEYWORD_PROP_NAME).Value).Value;
            //if (String.IsNullOrWhiteSpace(configKeyword)) configKeyword = "DEFAULTS";

            IFeatureClass ret = null;
            if(featureClassName.FeatureDatasetName != null)
            {
                IFeatureDataset featureDataset = (IFeatureDataset)((IName)featureClassName.FeatureDatasetName).Open();
                try
                {
                    ret = featureDataset.CreateFeatureClass(name, output_fields, clsid, extclsid, esriFeatureType.esriFTSimple, shapeFieldName, configKeyword);
                }
                finally
                {
                    Marshal.ReleaseComObject(featureDataset);
                }
            }
            else
            {
                IWorkspace workspace = (IWorkspace)((IName)((IDatasetName)featureClassName).WorkspaceName).Open();
                try
                {
                    IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;
                    ret = featureWorkspace.CreateFeatureClass(name, output_fields, clsid, extclsid, esriFeatureType.esriFTSimple, shapeFieldName, configKeyword);
                }
                finally
                {
                    Marshal.ReleaseComObject(workspace);
                }
            }
            return ret;
        }
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            try
            {
                IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

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

                IGPValue      inputLayersGPValue    = gpUtilities3.UnpackGPValue(paramvalues.get_Element(in_LayersNumber));
                IGPMultiValue inputLayersMultiValue = gpUtilities3.UnpackGPValue(inputLayersGPValue) as IGPMultiValue;

                IGPParameter      outputGroupLayerParameter = paramvalues.get_Element(out_groupLayerNumber) as IGPParameter;
                IGPValue          outputGPGroupLayer        = gpUtilities3.UnpackGPValue(outputGroupLayerParameter);
                IGPCompositeLayer outputCompositeLayer      = outputGPGroupLayer as IGPCompositeLayer;

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


                IGroupLayer groupLayer = null;

                // find the last position of the "\" string
                // in case we find such a thing, i.e. position is >= -1 then let's assume that we are dealing with a layer file on disk
                // otherwise let's create a new group layer instance
                string outputGPLayerNameAsString = outputGPGroupLayer.GetAsText();
                int    separatorPosition         = outputGPLayerNameAsString.LastIndexOf(System.IO.Path.DirectorySeparatorChar);
                string layerName = String.Empty;

                if (separatorPosition > -1)
                {
                    layerName = outputGPGroupLayer.GetAsText().Substring(separatorPosition + 1);
                }
                else
                {
                    layerName = outputGPGroupLayer.GetAsText();
                }

                ILayer   foundLayer      = null;
                IGPLayer existingGPLayer = gpUtilities3.FindMapLayer2(layerName, out foundLayer);

                if (foundLayer != null)
                {
                    gpUtilities3.RemoveFromMapEx((IGPValue)existingGPLayer);
                    gpUtilities3.RemoveInternalLayerEx(foundLayer);
                }

                groupLayer = new GroupLayer();
                ((ILayer)groupLayer).Name = layerName;

                for (int layerIndex = 0; layerIndex < inputLayersMultiValue.Count; layerIndex++)
                {
                    IGPValue gpLayerToAdd = inputLayersMultiValue.get_Value(layerIndex) as IGPValue;

                    ILayer sourceLayer = gpUtilities3.DecodeLayer(gpLayerToAdd);

                    groupLayer.Add(sourceLayer);
                }

                outputGPGroupLayer = gpUtilities3.MakeGPValueFromObject(groupLayer);

                if (separatorPosition > -1)
                {
                    try
                    {
                        // in the case that we are dealing with a layer file on disk
                        // let's persist the group layer information into the file
                        ILayerFile pointLayerFile = new LayerFileClass();

                        if (System.IO.Path.GetExtension(outputGPLayerNameAsString).ToUpper().Equals(".LYR"))
                        {
                            if (pointLayerFile.get_IsPresent(outputGPLayerNameAsString))
                            {
                                try
                                {
                                    gpUtilities3.Delete(outputGPGroupLayer);
                                }
                                catch (Exception ex)
                                {
                                    message.AddError(120001, ex.Message);
                                    return;
                                }
                            }

                            pointLayerFile.New(outputGPLayerNameAsString);

                            pointLayerFile.ReplaceContents(groupLayer);

                            pointLayerFile.Save();
                        }

                        outputGPGroupLayer = gpUtilities3.MakeGPValueFromObject(pointLayerFile.Layer);
                    }
                    catch (Exception ex)
                    {
                        message.AddError(120002, ex.Message);
                        return;
                    }
                }

                gpUtilities3.PackGPValue(outputGPGroupLayer, outputGroupLayerParameter);
            }
            catch (Exception ex)
            {
                message.AddError(120049, ex.Message);
            }
        }
Beispiel #12
0
        public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr)
        {
            IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

            #region update the output point parameter based on the input of template point layer
            IGPParameter inputPointLayerParameter = paramvalues.get_Element(in_osmPointLayerNumber) as IGPParameter;
            IGPValue     inputPointLayer          = gpUtilities3.UnpackGPValue(inputPointLayerParameter);

            IGPParameter3 outputPointLayerParameter = paramvalues.get_Element(out_osmPointLayerNumber) as IGPParameter3;
            if (((inputPointLayer).IsEmpty() == false) && (outputPointLayerParameter.Altered == false))
            {
                IGPValue outputPointGPValue = gpUtilities3.UnpackGPValue(outputPointLayerParameter);
                if (outputPointGPValue.IsEmpty())
                {
                    IClone   clonedObject  = inputPointLayer as IClone;
                    IGPValue clonedGPValue = clonedObject.Clone() as IGPValue;

                    // if it is an internal group layer
                    IGPGroupLayer inputPointGroupLayer = clonedObject as IGPGroupLayer;

                    if (inputPointGroupLayer != null)
                    {
                        string proposedLayerName = "Points";
                        string tempLayerName     = proposedLayerName;
                        int    index             = 1;
                        ILayer currentMapLayer   = gpUtilities3.FindMapLayer(proposedLayerName);

                        while (currentMapLayer != null)
                        {
                            tempLayerName = proposedLayerName + "_" + index.ToString();

                            currentMapLayer = gpUtilities3.FindMapLayer(tempLayerName);
                            index           = index + 1;
                        }

                        clonedGPValue.SetAsText(tempLayerName);
                        gpUtilities3.PackGPValue(clonedGPValue, outputPointLayerParameter);
                    }
                    else
                    {
                        IDELayer deLayer = clonedGPValue as IDELayer;

                        if (deLayer != null)
                        {
                            FileInfo sourceLyrFileInfo = new FileInfo(clonedGPValue.GetAsText());

                            // check the output location of the file with respect to the gp environment settings
                            sourceLyrFileInfo = new FileInfo(DetermineLyrLocation(pEnvMgr.GetEnvironments(), sourceLyrFileInfo));

                            if (sourceLyrFileInfo.Exists)
                            {
                                int    layerFileIndex  = 1;
                                string tempFileLyrName = sourceLyrFileInfo.DirectoryName + System.IO.Path.DirectorySeparatorChar + sourceLyrFileInfo.Name.Substring(0, sourceLyrFileInfo.Name.Length - sourceLyrFileInfo.Extension.Length) + "_" + layerFileIndex.ToString() + sourceLyrFileInfo.Extension;

                                while (File.Exists(tempFileLyrName))
                                {
                                    tempFileLyrName = sourceLyrFileInfo.DirectoryName + System.IO.Path.DirectorySeparatorChar + sourceLyrFileInfo.Name.Substring(0, sourceLyrFileInfo.Name.Length - sourceLyrFileInfo.Extension.Length) + "_" + layerFileIndex.ToString() + sourceLyrFileInfo.Extension;
                                    layerFileIndex  = layerFileIndex + 1;
                                }

                                clonedGPValue.SetAsText(tempFileLyrName);
                                gpUtilities3.PackGPValue(clonedGPValue, outputPointLayerParameter);
                            }
                            else
                            {
                                clonedGPValue.SetAsText(sourceLyrFileInfo.FullName);
                                gpUtilities3.PackGPValue(clonedGPValue, outputPointLayerParameter);
                            }
                        }
                    }
                }
            }
            #endregion

            #region update the output line parameter based on the input of template line layer
            IGPParameter inputLineLayerParameter = paramvalues.get_Element(in_osmLineLayerNumber) as IGPParameter;
            IGPValue     inputLineLayer          = gpUtilities3.UnpackGPValue(inputLineLayerParameter);

            IGPParameter3 outputLineLayerParameter = paramvalues.get_Element(out_osmLineLayerNumber) as IGPParameter3;
            if (((inputLineLayer).IsEmpty() == false) && (outputLineLayerParameter.Altered == false))
            {
                IGPValue outputLineGPValue = gpUtilities3.UnpackGPValue(outputLineLayerParameter);
                if (outputLineGPValue.IsEmpty())
                {
                    IClone   clonedObject  = inputLineLayer as IClone;
                    IGPValue clonedGPValue = clonedObject.Clone() as IGPValue;

                    // if it is an internal group layer
                    IGPGroupLayer inputLineGroupLayer = clonedObject as IGPGroupLayer;

                    if (inputLineGroupLayer != null)
                    {
                        string proposedLayerName = "Lines";
                        string tempLayerName     = proposedLayerName;
                        int    index             = 1;
                        ILayer currentMapLayer   = gpUtilities3.FindMapLayer(proposedLayerName);

                        while (currentMapLayer != null)
                        {
                            tempLayerName = proposedLayerName + "_" + index.ToString();

                            currentMapLayer = gpUtilities3.FindMapLayer(tempLayerName);
                            index           = index + 1;
                        }

                        clonedGPValue.SetAsText(tempLayerName);
                        gpUtilities3.PackGPValue(clonedGPValue, outputLineLayerParameter);
                    }
                    else
                    {
                        IDELayer deLayer = clonedGPValue as IDELayer;

                        if (deLayer != null)
                        {
                            FileInfo sourceLyrFileInfo = new FileInfo(clonedGPValue.GetAsText());

                            // check the output location of the file with respect to the gp environment settings
                            sourceLyrFileInfo = new FileInfo(DetermineLyrLocation(pEnvMgr.GetEnvironments(), sourceLyrFileInfo));

                            if (sourceLyrFileInfo.Exists)
                            {
                                int    layerFileIndex  = 1;
                                string tempFileLyrName = sourceLyrFileInfo.DirectoryName + System.IO.Path.DirectorySeparatorChar + sourceLyrFileInfo.Name.Substring(0, sourceLyrFileInfo.Name.Length - sourceLyrFileInfo.Extension.Length) + "_" + layerFileIndex.ToString() + sourceLyrFileInfo.Extension;

                                while (File.Exists(tempFileLyrName))
                                {
                                    tempFileLyrName = sourceLyrFileInfo.DirectoryName + System.IO.Path.DirectorySeparatorChar + sourceLyrFileInfo.Name.Substring(0, sourceLyrFileInfo.Name.Length - sourceLyrFileInfo.Extension.Length) + "_" + layerFileIndex.ToString() + sourceLyrFileInfo.Extension;
                                    layerFileIndex  = layerFileIndex + 1;
                                }

                                clonedGPValue.SetAsText(tempFileLyrName);
                                gpUtilities3.PackGPValue(clonedGPValue, outputLineLayerParameter);
                            }
                            else
                            {
                                clonedGPValue.SetAsText(sourceLyrFileInfo.FullName);
                                gpUtilities3.PackGPValue(clonedGPValue, outputLineLayerParameter);
                            }
                        }
                    }
                }
            }
            #endregion

            #region update the output polygon parameter based on the input of template polygon layer
            IGPParameter inputPolygonLayerParameter = paramvalues.get_Element(in_osmPolygonLayerNumber) as IGPParameter;
            IGPValue     inputPolygonLayer          = gpUtilities3.UnpackGPValue(inputPolygonLayerParameter);

            IGPParameter3 outputPolygonLayerParameter = paramvalues.get_Element(out_osmPolygonLayerNumber) as IGPParameter3;
            if (((inputPolygonLayer).IsEmpty() == false) && (outputPolygonLayerParameter.Altered == false))
            {
                IGPValue outputPolygonGPValue = gpUtilities3.UnpackGPValue(outputPolygonLayerParameter);
                if (outputPolygonGPValue.IsEmpty())
                {
                    IClone   clonedObject  = inputPolygonLayer as IClone;
                    IGPValue clonedGPValue = clonedObject.Clone() as IGPValue;

                    // if it is an internal group layer
                    IGPGroupLayer inputPolygonGroupLayer = clonedObject as IGPGroupLayer;

                    if (inputPolygonGroupLayer != null)
                    {
                        string proposedLayerName = "Polygons";
                        string tempLayerName     = proposedLayerName;
                        int    index             = 1;
                        ILayer currentMapLayer   = gpUtilities3.FindMapLayer(proposedLayerName);

                        while (currentMapLayer != null)
                        {
                            tempLayerName = proposedLayerName + "_" + index.ToString();

                            currentMapLayer = gpUtilities3.FindMapLayer(tempLayerName);
                            index           = index + 1;
                        }

                        clonedGPValue.SetAsText(tempLayerName);
                        gpUtilities3.PackGPValue(clonedGPValue, outputPolygonLayerParameter);
                    }
                    else
                    {
                        IDELayer deLayer = clonedGPValue as IDELayer;

                        if (deLayer != null)
                        {
                            FileInfo sourceLyrFileInfo = new FileInfo(clonedGPValue.GetAsText());

                            // check the output location of the file with respect to the gp environment settings
                            sourceLyrFileInfo = new FileInfo(DetermineLyrLocation(pEnvMgr.GetEnvironments(), sourceLyrFileInfo));

                            if (sourceLyrFileInfo.Exists)
                            {
                                int    layerFileIndex  = 1;
                                string tempFileLyrName = sourceLyrFileInfo.DirectoryName + System.IO.Path.DirectorySeparatorChar + sourceLyrFileInfo.Name.Substring(0, sourceLyrFileInfo.Name.Length - sourceLyrFileInfo.Extension.Length) + "_" + layerFileIndex.ToString() + sourceLyrFileInfo.Extension;

                                while (File.Exists(tempFileLyrName))
                                {
                                    tempFileLyrName = sourceLyrFileInfo.DirectoryName + System.IO.Path.DirectorySeparatorChar + sourceLyrFileInfo.Name.Substring(0, sourceLyrFileInfo.Name.Length - sourceLyrFileInfo.Extension.Length) + "_" + layerFileIndex.ToString() + sourceLyrFileInfo.Extension;
                                    layerFileIndex  = layerFileIndex + 1;
                                }

                                clonedGPValue.SetAsText(tempFileLyrName);
                                gpUtilities3.PackGPValue(clonedGPValue, outputPolygonLayerParameter);
                            }
                            else
                            {
                                clonedGPValue.SetAsText(sourceLyrFileInfo.FullName);
                                gpUtilities3.PackGPValue(clonedGPValue, outputPolygonLayerParameter);
                            }
                        }
                    }
                }
            }
            #endregion
        }
Beispiel #13
0
        /// <summary>
        ///     Casts an object to the type of the given default value. If the object is null
        ///     or DBNull, the default value specified will be returned. If the object is
        ///     convertible to the type of the default value, the explicit conversion will
        ///     be performed.
        /// </summary>
        /// <typeparam name="TValue">The type of the value.</typeparam>
        /// <param name="source">The source.</param>
        /// <param name="fallbackValue">The fallback value.</param>
        /// <returns>
        ///     The value of the object cast to the type of the default value.
        /// </returns>
        /// <exception cref="System.InvalidCastException">
        ///     Thrown if the type of the object
        ///     cannot be cast to the type of the default value.
        /// </exception>
        public static TValue Cast <TValue>(this IGPValue source, TValue fallbackValue)
        {
            string value = source.GetAsText();

            return(TypeCast.Cast(value, fallbackValue));
        }
Beispiel #14
0
        public void Execute(IArray paramvalues,
                            ITrackCancel trackcancel,
                            IGPEnvironmentManager envMgr,
                            IGPMessages messages)
        {
            // Re-validate.
            IGPMessages ms = m_util.InternalValidate(ParameterInfo,
                                                     paramvalues,
                                                     false, false,
                                                     envMgr);


            messages.AddMessage("MWSW Boundary Generator, v. 0.0");

            if (((IGPMessage)(ms)).IsError())
            {
                messages.AddMessages(ms);
                return;
            }
            if (!AoGPParameter.ValidateAll(m_parms, paramvalues, messages))
            {
                return;
            }

            try {
                IGPValue  inlyr    = m_util.UnpackGPValue((paramvalues.get_Element(0) as IGPParameter).Value);
                IGPDouble ang_tol  = m_util.UnpackGPValue((paramvalues.get_Element(1) as IGPParameter).Value) as IGPDouble;
                IGPDouble dist_tol = m_util.UnpackGPValue((paramvalues.get_Element(2) as IGPParameter).Value) as IGPDouble;
                IGPValue  outlyr   = m_util.UnpackGPValue((paramvalues.get_Element(3) as IGPParameter).Value);

                //		DumpIt("In layer",inlyr,messages);
                //		DumpIt("Out layer",outlyr,typeof(IGPValue),messages);

                IFeatureClass inputfc;
                IQueryFilter  inputqf;
                m_util.DecodeFeatureLayer(inlyr, out inputfc, out inputqf);

                //			DumpIt("In Featureclass",inputfc,typeof(IFeatureClass),messages);
                //			DumpIt("In QF",inputqf,typeof(IQueryFilter),messages);

                messages.AddMessage("In angle tolerance: " + ang_tol.Value);
                messages.AddMessage("In distance tolerance: " + dist_tol.Value);
                messages.AddMessage("Input featureclass: " + inputfc.AliasName);
                messages.AddMessage("Output path: " + outlyr.GetAsText());

                trackcancel.Progressor.Show();
                trackcancel.Progressor.Message = "Processing...";

                string             outp_txt = outlyr.GetAsText();
                AoFeatureClassName fcname   = new AoFeatureClassName(outp_txt);
                ISpatialReference  spref    = AoTable.From(inputfc)[inputfc.ShapeFieldName].Field.GeometryDef.SpatialReference;

                string shapename = fcname.ShapeFieldName != "" ? fcname.ShapeFieldName : "Shape";
                m_outp_schema[shapename] = AoField.Shape(shapename,
                                                         esriGeometryType.esriGeometryPolyline,
                                                         spref);


                // TODO: shapefiles seem to get an FID automatically,
                //   while geodb needs an 'OBJECTID',
                //   who knows about other workspace types?
                // Is there a way to figure this out w/o looking at the type?

                IFeatureClass outputfc =
                    fcname.Workspace.CreateFeatureClass(fcname.Basename,
                                                        m_outp_schema.Fields,
                                                        null,
                                                        null,
                                                        esriFeatureType.esriFTSimple,
                                                        shapename,
                                                        "");

                IStepProgressor progressor = trackcancel.Progressor as IStepProgressor;
                progressor.MaxRange = 200;

                BGenImp implementation = new BGenImp(spref, ang_tol.Value, dist_tol.Value);
                implementation.Run(inputfc, outputfc, delegate(double howfar) {
                    progressor.Position = (int)(200.0 * howfar);
                });

                messages.AddMessage("Finished, worked through " + implementation.TotalSegments + " line segments total.");
                return;
            } catch (Exception e) {
                while (e != null)
                {
                    messages.AddError(1, "Exception: " + e.Message);
                    e = e.InnerException;
                }
            }
        }
Beispiel #15
0
        public void Execute(IArray paramvalues, ITrackCancel TrackCancel, IGPEnvironmentManager envMgr, IGPMessages message)
        {
            IAoInitialize     aoInitialize = new AoInitializeClass();
            esriLicenseStatus naStatus     = esriLicenseStatus.esriLicenseUnavailable;

            IGPUtilities2 gpUtil     = null;
            IDataset      osmDataset = null;

            try
            {
                if (!aoInitialize.IsExtensionCheckedOut(esriLicenseExtensionCode.esriLicenseExtensionCodeNetwork))
                {
                    naStatus = aoInitialize.CheckOutExtension(esriLicenseExtensionCode.esriLicenseExtensionCodeNetwork);
                }

                gpUtil = new GPUtilitiesClass();

                // OSM Dataset Param
                IGPParameter osmDatasetParam = paramvalues.get_Element(in_osmFeatureDataset) as IGPParameter;
                IDEDataset2  osmDEDataset    = gpUtil.UnpackGPValue(osmDatasetParam) as IDEDataset2;
                if (osmDEDataset == null)
                {
                    message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), osmDatasetParam.Name));
                    return;
                }

                osmDataset = gpUtil.OpenDatasetFromLocation(((IDataElement)osmDEDataset).CatalogPath) as IDataset;

                // Network Config File Param
                IGPParameter osmNetConfigParam = paramvalues.get_Element(in_NetworkConfigurationFile) as IGPParameter;
                IGPValue     osmNetConfigFile  = gpUtil.UnpackGPValue(osmNetConfigParam) as IGPValue;
                if ((osmNetConfigFile == null) || (string.IsNullOrEmpty(osmNetConfigFile.GetAsText())))
                {
                    message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), osmNetConfigParam.Name));
                    return;
                }

                // Target Network Dataset Param
                IGPParameter ndsParam = paramvalues.get_Element(out_NetworkDataset) as IGPParameter;
                IDataElement deNDS    = gpUtil.UnpackGPValue(ndsParam) as IDataElement;
                if (deNDS == null)
                {
                    message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), ndsParam.Name));
                    return;
                }

                // Create Network Dataset
                using (NetworkDataset nd = new NetworkDataset(osmNetConfigFile.GetAsText(), osmDataset, deNDS.Name, message, TrackCancel))
                {
                    if (nd.CanCreateNetworkDataset())
                    {
                        nd.CreateNetworkDataset();
                    }
                }
            }
            catch (UserCancelException ex)
            {
                message.AddWarning(ex.Message);
            }
            catch (Exception ex)
            {
                message.AddError(120008, ex.Message);
#if DEBUG
                message.AddError(120008, ex.StackTrace);
#endif
            }
            finally
            {
                if (osmDataset != null)
                {
                    ComReleaser.ReleaseCOMObject(osmDataset);
                }

                if (naStatus == esriLicenseStatus.esriLicenseCheckedOut)
                {
                    aoInitialize.CheckInExtension(esriLicenseExtensionCode.esriLicenseExtensionCodeNetwork);
                }

                if (gpUtil != null)
                {
                    ComReleaser.ReleaseCOMObject(gpUtil);
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }
        }
        private string GetLocationString(IGPValue gpValue, ITable table)
        {
            string locationString = String.Empty;

            {
                if (((IDataset)table).Workspace.PathName.ToUpper().Contains(".GDS\\"))
                {
                    string partialString = gpValue.GetAsText().Substring(0, gpValue.GetAsText().ToUpper().IndexOf(".GDS\\") + 4);

                    string secondString = gpValue.GetAsText().Substring(0, gpValue.GetAsText().LastIndexOf("\\"));

                    locationString = secondString + System.IO.Path.DirectorySeparatorChar + ((IDataset)table).BrowseName;
                }
                else
                {
                    locationString = ((IDataset)table).Workspace.PathName + System.IO.Path.DirectorySeparatorChar + ((IDataset)table).BrowseName;
                }
            }

            return locationString;
        }
        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;
        }
        public static IFeatureClass CreateFeatureClass(IGPValue gpFeatureClass, IGPEnvironmentManager environment, IFields fields = null)
        {
            if (gpFeatureClass == null)
            {
                throw new ArgumentException("Argument can not be null", "gpFeatureClass");
            }
            if (environment == null)
            {
                throw new ArgumentException("Argument can not be null", "environment");
            }


            IGeoProcessorSettings gpSettings = (IGeoProcessorSettings)environment;

            if (gpUtilities.Exists(gpFeatureClass))
            {
                if (gpSettings.OverwriteOutput == true)
                {
                    gpUtilities.Delete(gpFeatureClass);
                }
                else
                {
                    throw new Exception("Output feature class already exists: " + gpFeatureClass.GetAsText());
                }
            }


            IDEFeatureClass deFeatureClass = (IDEFeatureClass)gpUtilities.DecodeDETable(gpFeatureClass);

            if (deFeatureClass == null)
            {
                throw new Exception("Data Element decode return null");
            }

            IObjectClassDescription objectClassDescription = (IObjectClassDescription) new FeatureClassDescriptionClass();
            UID clsid    = objectClassDescription.InstanceCLSID;
            UID extclsid = objectClassDescription.ClassExtensionCLSID;

            IDataElement dataElement = (IDataElement)deFeatureClass;

            if (dataElement.CatalogPath == null)
            {
                throw new ArgumentException("Catalog path is null", "CatalogPath");
            }
            IFeatureClassName featureClassName = (IFeatureClassName)gpUtilities.CreateFeatureClassName(dataElement.CatalogPath);

            string path = dataElement.GetPath();
            string name = dataElement.Name;

            IDEGeoDataset     geoDataElement   = (IDEGeoDataset)deFeatureClass;
            ISpatialReference spatialReference = geoDataElement.SpatialReference;

            IDETable deTable        = (IDETable)deFeatureClass;
            string   shapeFieldName = deFeatureClass.ShapeFieldName;

            Dictionary <string, IField> fieldBuilder = new Dictionary <string, IField>();

            foreach (var input_fields in new IFields[] { deTable.Fields, fields })
            {
                if (input_fields == null)
                {
                    continue;
                }
                for (int i = 0; i < input_fields.FieldCount; i++)
                {
                    IField field = deTable.Fields.get_Field(i);

                    if (fieldBuilder.ContainsKey(field.Name.ToLower()))
                    {
                        fieldBuilder[field.Name.ToLower()] = (IField)((IClone)field).Clone();
                    }
                    else
                    {
                        fieldBuilder.Add(field.Name.ToLower(), (IField)((IClone)field).Clone());
                    }

                    if (field.Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        shapeFieldName = field.Name;
                        break;
                    }
                }
            }

            IFields     output_fields = new FieldsClass();
            IFieldsEdit fields_edit   = (IFieldsEdit)output_fields;

            foreach (IField field in fieldBuilder.Values)
            {
                fields_edit.AddField(field);
                if (field.Type == esriFieldType.esriFieldTypeGeometry)
                {
                    IGeometryDefEdit defEdit = (IGeometryDefEdit)field.GeometryDef;
                    defEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
                }
            }

            string configKeyword = ((IGPString)environment.FindEnvironment(CONFIG_KEYWORD_PROP_NAME).Value).Value;
            //if (String.IsNullOrWhiteSpace(configKeyword)) configKeyword = "DEFAULTS";

            IFeatureClass ret = null;

            if (featureClassName.FeatureDatasetName != null)
            {
                IFeatureDataset featureDataset = (IFeatureDataset)((IName)featureClassName.FeatureDatasetName).Open();
                try
                {
                    ret = featureDataset.CreateFeatureClass(name, output_fields, clsid, extclsid, esriFeatureType.esriFTSimple, shapeFieldName, configKeyword);
                }
                finally
                {
                    Marshal.ReleaseComObject(featureDataset);
                }
            }
            else
            {
                IWorkspace workspace = (IWorkspace)((IName)((IDatasetName)featureClassName).WorkspaceName).Open();
                try
                {
                    IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;
                    ret = featureWorkspace.CreateFeatureClass(name, output_fields, clsid, extclsid, esriFeatureType.esriFTSimple, shapeFieldName, configKeyword);
                }
                finally
                {
                    Marshal.ReleaseComObject(workspace);
                }
            }
            return(ret);
        }
Beispiel #19
0
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            IGPUtilities3 gpUtilities3  = new GPUtilitiesClass();
            OSMToolHelper osmToolHelper = new OSMToolHelper();

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

            IGPEnvironment configKeyword = OSMToolHelper.getEnvironment(envMgr, "configKeyword");
            IGPString      gpString      = configKeyword.Value as IGPString;

            string storageKeyword = String.Empty;

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

            IGPParameter osmFileParameter      = paramvalues.get_Element(0) as IGPParameter;
            IGPValue     osmFileLocationString = gpUtilities3.UnpackGPValue(osmFileParameter) as IGPValue;

            IGPParameter loadSuperRelationParameter = paramvalues.get_Element(1) as IGPParameter;
            IGPBoolean   loadSuperRelationGPValue   = gpUtilities3.UnpackGPValue(loadSuperRelationParameter) as IGPBoolean;

            IGPParameter osmSourceLineFeatureClassParameter = paramvalues.get_Element(2) as IGPParameter;
            IGPValue     osmSourceLineFeatureClassGPValue   = gpUtilities3.UnpackGPValue(osmSourceLineFeatureClassParameter) as IGPValue;

            IGPParameter osmSourcePolygonFeatureClassParameter = paramvalues.get_Element(3) as IGPParameter;
            IGPValue     osmSourcePolygonFeatureClassGPValue   = gpUtilities3.UnpackGPValue(osmSourcePolygonFeatureClassParameter) as IGPValue;


            IGPParameter osmTargetLineFeatureClassParameter = paramvalues.get_Element(6) as IGPParameter;
            IGPValue     osmTargetLineFeatureClassGPValue   = gpUtilities3.UnpackGPValue(osmTargetLineFeatureClassParameter) as IGPValue;

            IName       workspaceName        = gpUtilities3.CreateParentFromCatalogPath(osmTargetLineFeatureClassGPValue.GetAsText());
            IWorkspace2 lineFeatureWorkspace = workspaceName.Open() as IWorkspace2;

            string[] lineFCNameElements = osmTargetLineFeatureClassGPValue.GetAsText().Split(System.IO.Path.DirectorySeparatorChar);

            IFeatureClass osmLineFeatureClass = null;

            IGPParameter  tagLineCollectionParameter = paramvalues.get_Element(4) 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, "", "", lineTagstoExtract);
            }
            catch (Exception ex)
            {
                message.AddError(120035, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message));
                return;
            }

            if (osmLineFeatureClass == null)
            {
                return;
            }


            IGPParameter osmTargetPolygonFeatureClassParameter = paramvalues.get_Element(7) as IGPParameter;
            IGPValue     osmTargetPolygonFeatureClassGPValue   = gpUtilities3.UnpackGPValue(osmTargetPolygonFeatureClassParameter) as IGPValue;

            workspaceName = gpUtilities3.CreateParentFromCatalogPath(osmTargetPolygonFeatureClassGPValue.GetAsText());
            IWorkspace2 polygonFeatureWorkspace = workspaceName.Open() as IWorkspace2;

            string[] polygonFCNameElements = osmTargetPolygonFeatureClassGPValue.GetAsText().Split(System.IO.Path.DirectorySeparatorChar);

            IFeatureClass osmPolygonFeatureClass = null;

            IGPParameter  tagPolygonCollectionParameter = paramvalues.get_Element(5) 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, "", "", polygonTagstoExtract);
            }
            catch (Exception ex)
            {
                message.AddError(120035, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message));
                return;
            }

            if (osmPolygonFeatureClass == null)
            {
                return;
            }

            ComReleaser.ReleaseCOMObject(osmPolygonFeatureClass);
            ComReleaser.ReleaseCOMObject(osmLineFeatureClass);


            string[] gdbComponents = new string[polygonFCNameElements.Length - 1];
            System.Array.Copy(lineFCNameElements, gdbComponents, lineFCNameElements.Length - 1);
            string fileGDBLocation = String.Join(System.IO.Path.DirectorySeparatorChar.ToString(), gdbComponents);

            osmToolHelper.smallLoadOSMRelations(osmFileLocationString.GetAsText(),
                                                osmSourceLineFeatureClassGPValue.GetAsText(),
                                                osmSourcePolygonFeatureClassGPValue.GetAsText(),
                                                osmTargetLineFeatureClassGPValue.GetAsText(),
                                                osmTargetPolygonFeatureClassGPValue.GetAsText(),
                                                lineTagstoExtract, polygonTagstoExtract, loadSuperRelationGPValue.Value);
        }
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            try
            {
                IGPUtilities3 gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3;

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

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

                IFeatureClass sourceFeatureClass = null;
                IQueryFilter  queryFilter        = null;

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

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

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

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

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

                IFeatureClass matchFeatureClass = null;
                IQueryFilter  matchQueryFilter  = null;

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


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

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


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

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

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

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

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

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

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

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

                    IFeature sourceFeature = null;

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

                        IPolyline sourceLine = sourceFeature.Shape as IPolyline;

                        matchFCSpatialFilter.Geometry = sourceLine;

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

                            IFeature matchFeature = null;

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

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

                                    IPolyline matchPolyline = matchFeature.Shape as IPolyline;

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

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

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

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

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

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

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

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

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

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

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

                if (stepProgressor != null)
                {
                    stepProgressor.Hide();
                }
            }
            catch (Exception ex)
            {
                message.AddAbort(ex.Message);
            }
        }
Beispiel #21
0
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            try
            {
                IGPUtilities3 execute_Utilities = new GPUtilitiesClass();

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

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

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

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

                bool useUpdateCursor = false;

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

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

                    osmInputTable = osmFeatureClass as ITable;
                }
                catch { }

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

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

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


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

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

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

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

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

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

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

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

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

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

                String illegalCharacters = String.Empty;

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

                IFieldsEdit fieldsEdit = osmInputTable.Fields as IFieldsEdit;


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

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

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

                                    int fieldIndex = osmInputTable.FindField(tagKey);

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

                                        osmInputTable.AddField(fieldEdit);

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

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

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

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

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

                                    int fieldIndex = osmInputTable.FindField(tagKey);

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

                                        osmInputTable.AddField(fieldEdit);

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

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

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

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

                    osmInputTable = osmFeatureClass as ITable;
                }
                catch { }

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

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

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

                        comReleaser.ManageLifetime(rowCursor);

                        IRow osmRow = null;


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

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

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

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

                                        int fieldLength = attributeFieldLength[fieldIndex];

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

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

                            storedTags = null;

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

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

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

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

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

                execute_Utilities.ReleaseInternals();
                Marshal.ReleaseComObject(execute_Utilities);
            }
            catch (Exception ex)
            {
                message.AddError(120054, ex.Message);
            }
        }
Beispiel #22
0
        public void Execute(IArray paramvalues, ITrackCancel trackcancel, IGPEnvironmentManager envMgr, IGPMessages message)
        {
            // Get Parameters
            IGPParameter3 inputParameter   = (IGPParameter3)paramvalues.get_Element(0);
            IGPParameter3 polygonParameter = (IGPParameter3)paramvalues.get_Element(1);
            IGPParameter3 outputParameter  = (IGPParameter3)paramvalues.get_Element(2);
            IGPParameter3 fieldParameter   = (IGPParameter3)paramvalues.get_Element(3);

            // UnPackGPValue. This ensures you get the value from either the dataelement or GpVariable (ModelBuilder)
            IGPValue inputParameterValue   = m_GPUtilities.UnpackGPValue(inputParameter);
            IGPValue polygonParameterValue = m_GPUtilities.UnpackGPValue(polygonParameter);
            IGPValue outputParameterValue  = m_GPUtilities.UnpackGPValue(outputParameter);
            IGPValue fieldParameterValue   = m_GPUtilities.UnpackGPValue(fieldParameter);

            // Decode Input Feature Layers
            IFeatureClass inputFeatureClass;
            IFeatureClass polygonFeatureClass;

            IQueryFilter inputFeatureClassQF;
            IQueryFilter polygonFeatureClassQF;

            m_GPUtilities.DecodeFeatureLayer(inputParameterValue, out inputFeatureClass, out inputFeatureClassQF);
            m_GPUtilities.DecodeFeatureLayer(polygonParameterValue, out polygonFeatureClass, out polygonFeatureClassQF);

            if (inputFeatureClass == null)
            {
                message.AddError(2, "Could not open input dataset.");
                return;
            }

            if (polygonFeatureClass == null)
            {
                message.AddError(2, "Could not open clipping polygon dataset.");
                return;
            }

            if (polygonFeatureClass.FeatureCount(null) > 1)
            {
                message.AddWarning("Clipping polygon feature class contains more than one feature.");
            }

            // Create the Geoprocessor
            Geoprocessor gp = new Geoprocessor();

            // Create Output Polygon Feature Class
            CreateFeatureclass cfc      = new CreateFeatureclass();
            IName               name    = m_GPUtilities.CreateFeatureClassName(outputParameterValue.GetAsText());
            IDatasetName        dsName  = name as IDatasetName;
            IFeatureClassName   fcName  = dsName as IFeatureClassName;
            IFeatureDatasetName fdsName = fcName.FeatureDatasetName as IFeatureDatasetName;

            // Check if output is in a FeatureDataset or not. Set the output path parameter for CreateFeatureClass tool.
            if (fdsName != null)
            {
                cfc.out_path = fdsName;
            }
            else
            {
                cfc.out_path = dsName.WorkspaceName.PathName;
            }

            // Set the output Coordinate System for CreateFeatureClass tool.
            // ISpatialReference3 sr = null;
            IGPEnvironment env = envMgr.FindEnvironment("outputCoordinateSystem");

            // Same as Input
            if (env.Value.IsEmpty())
            {
                IGeoDataset ds = inputFeatureClass as IGeoDataset;
                cfc.spatial_reference = ds.SpatialReference as ISpatialReference3;
            }
            // Use the environment setting
            else
            {
                IGPCoordinateSystem cs = env.Value as IGPCoordinateSystem;
                cfc.spatial_reference = cs.SpatialReference as ISpatialReference3;
            }

            // Remaining properties for Create Feature Class Tool
            cfc.out_name      = dsName.Name;
            cfc.geometry_type = "POLYGON";

            // Execute Geoprocessor
            gp.Execute(cfc, null);

            // Get Unique Field
            int    iField      = inputFeatureClass.FindField(fieldParameterValue.GetAsText());
            IField uniqueField = inputFeatureClass.Fields.get_Field(iField);

            // Extract Clipping Polygon Geometry
            IFeature polygonFeature  = polygonFeatureClass.GetFeature(0);
            IPolygon clippingPolygon = (IPolygon)polygonFeature.Shape;

            // Spatial Filter
            ISpatialFilter spatialFilter = new SpatialFilterClass();

            spatialFilter.Geometry   = polygonFeature.ShapeCopy;
            spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains;

            // Debug Message
            message.AddMessage("Generating TIN...");

            // Create TIN
            ITinEdit tinEdit = new TinClass();

            // Advanced TIN Functions
            ITinAdvanced2 tinAdv = (ITinAdvanced2)tinEdit;

            try
            {
                // Initialize New TIN
                IGeoDataset gds = inputFeatureClass as IGeoDataset;
                tinEdit.InitNew(gds.Extent);

                // Add Mass Points to TIN
                tinEdit.StartEditing();
                tinEdit.AddFromFeatureClass(inputFeatureClass, spatialFilter, uniqueField, uniqueField, esriTinSurfaceType.esriTinMassPoint);
                tinEdit.Refresh();

                // Get TIN Nodes
                ITinNodeCollection tinNodeCollection = (ITinNodeCollection)tinEdit;

                // Report Node Count
                message.AddMessage("Input Node Count: " + inputFeatureClass.FeatureCount(null).ToString());
                message.AddMessage("TIN Node Count: " + tinNodeCollection.NodeCount.ToString());

                // Open Output Feature Class
                IFeatureClass outputFeatureClass = m_GPUtilities.OpenFeatureClassFromString(outputParameterValue.GetAsText());

                // Debug Message
                message.AddMessage("Generating Polygons...");

                // Create Voronoi Polygons
                tinNodeCollection.ConvertToVoronoiRegions(outputFeatureClass, null, clippingPolygon, "", "");

                // Release COM Objects
                tinEdit.StopEditing(false);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(tinNodeCollection);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(tinEdit);
            }
            catch (Exception ex)
            {
                message.AddError(2, ex.Message);
            }
        }
Beispiel #23
0
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            try
            {
                IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

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

                // find feature class inside the given feature dataset
                IGPParameter      osmFeatureDatasetParameter = paramvalues.get_Element(in_osmFeatureDatasetNumber) as IGPParameter;
                IDEFeatureDataset osmFeatureDataset          = gpUtilities3.UnpackGPValue(osmFeatureDatasetParameter) as IDEFeatureDataset;

                string osmPointFeatureClassString   = ((IDataElement)osmFeatureDataset).Name + "_osm_pt";
                string osmLineFeatureClassString    = ((IDataElement)osmFeatureDataset).Name + "_osm_ln";
                string osmPolygonFeatureClassString = ((IDataElement)osmFeatureDataset).Name + "_osm_ply";

                IFeatureClass osmPointFeatureClass   = gpUtilities3.OpenFeatureClassFromString(((IDataElement)osmFeatureDataset).CatalogPath + "/" + osmPointFeatureClassString);
                IFeatureClass osmLineFeatureClass    = gpUtilities3.OpenFeatureClassFromString(((IDataElement)osmFeatureDataset).CatalogPath + "/" + osmLineFeatureClassString);
                IFeatureClass osmPoylgonFeatureClass = gpUtilities3.OpenFeatureClassFromString(((IDataElement)osmFeatureDataset).CatalogPath + "/" + osmPolygonFeatureClassString);

                // open the specified layers holding the symbology and editing templates
                IGPParameter osmPointSymbolTemplateParameter = paramvalues.get_Element(in_osmPointLayerNumber) as IGPParameter;
                IGPValue     osmGPPointLayerValue            = gpUtilities3.UnpackGPValue(osmPointSymbolTemplateParameter);

                IGPParameter outputPointGPParameter  = paramvalues.get_Element(out_osmPointLayerNumber) as IGPParameter;
                IGPValue     outputPointLayerGPValue = gpUtilities3.UnpackGPValue(outputPointGPParameter);

                bool isLayerOnDisk = false;

                // create a clone of the source layer
                // we will then go ahead and adjust the data source (dataset) of the cloned layer
                IObjectCopy     objectCopy = new ObjectCopyClass();
                ICompositeLayer adjustedPointTemplateLayer = objectCopy.Copy(osmGPPointLayerValue) as ICompositeLayer;

                IGPGroupLayer osmPointGroupTemplateLayer = adjustedPointTemplateLayer as IGPGroupLayer;

                ICompositeLayer compositeLayer = gpUtilities3.Open((IGPValue)osmPointGroupTemplateLayer) as ICompositeLayer;
                //ICompositeLayer adjustedPointTemplateLayer = osmGPPointLayerValue as ICompositeLayer;
                //IGPGroupLayer osmPointGroupTemplateLayer = osmGPPointLayerValue as IGPGroupLayer;
                //IClone cloneSource = osmPointGroupTemplateLayer as IClone;
                //ICompositeLayer compositeLayer = m_gpUtilities3.Open((IGPValue)cloneSource.Clone()) as ICompositeLayer;

                if (compositeLayer == null)
                {
                    ILayerFactoryHelper layerFactoryHelper = new LayerFactoryHelperClass();
                    IFileName           layerFileName      = new FileNameClass();

                    layerFileName.Path = osmGPPointLayerValue.GetAsText();
                    IEnumLayer enumLayer = layerFactoryHelper.CreateLayersFromName((IName)layerFileName);
                    enumLayer.Reset();

                    compositeLayer = enumLayer.Next() as ICompositeLayer;

                    isLayerOnDisk = true;
                }

                IFeatureLayerDefinition2 featureLayerDefinition2 = null;
                ISQLSyntax sqlSyntax = null;

                IGPLayer adjustedPointGPLayer = null;

                if (compositeLayer != null)
                {
                    for (int layerIndex = 0; layerIndex < compositeLayer.Count; layerIndex++)
                    {
                        IFeatureLayer2 geoFeatureLayer = compositeLayer.get_Layer(layerIndex) as IFeatureLayer2;

                        if (geoFeatureLayer != null)
                        {
                            if (geoFeatureLayer.ShapeType == osmPointFeatureClass.ShapeType)
                            {
                                try
                                {
                                    ((IDataLayer2)geoFeatureLayer).Disconnect();
                                }
                                catch { }

                                ((IDataLayer2)geoFeatureLayer).DataSourceName = ((IDataset)osmPointFeatureClass).FullName;

                                ((IDataLayer2)geoFeatureLayer).Connect(((IDataset)osmPointFeatureClass).FullName);

                                featureLayerDefinition2 = geoFeatureLayer as IFeatureLayerDefinition2;
                                if (featureLayerDefinition2 != null)
                                {
                                    string queryDefinition = featureLayerDefinition2.DefinitionExpression;

                                    sqlSyntax = ((IDataset)osmPointFeatureClass).Workspace as ISQLSyntax;
                                    string delimiterIdentifier = sqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix);

                                    if (String.IsNullOrEmpty(queryDefinition) == false)
                                    {
                                        string stringToReplace = queryDefinition.Substring(0, 1);
                                        queryDefinition = queryDefinition.Replace(stringToReplace, delimiterIdentifier);
                                    }

                                    featureLayerDefinition2.DefinitionExpression = queryDefinition;
                                }
                            }
                        }
                    }

                    adjustedPointGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)compositeLayer);

                    // save the newly adjusted layer information to disk
                    if (isLayerOnDisk == true)
                    {
                        ILayerFile pointLayerFile = new LayerFileClass();
                        if (pointLayerFile.get_IsPresent(outputPointLayerGPValue.GetAsText()))
                        {
                            try
                            {
                                File.Delete(outputPointLayerGPValue.GetAsText());
                            }
                            catch (Exception ex)
                            {
                                message.AddError(120041, ex.Message);
                                return;
                            }
                        }

                        pointLayerFile.New(outputPointLayerGPValue.GetAsText());

                        pointLayerFile.ReplaceContents((ILayer)compositeLayer);

                        pointLayerFile.Save();

                        adjustedPointGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)pointLayerFile.Layer);
                    }

                    //   IGPLayer adjustedPointGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)compositeLayer);
                    gpUtilities3.AddInternalLayer2((ILayer)compositeLayer, adjustedPointGPLayer);
                    gpUtilities3.PackGPValue((IGPValue)adjustedPointGPLayer, outputPointGPParameter);
                }


                isLayerOnDisk = false;

                IGPParameter osmLineSymbolTemplateParameter = paramvalues.get_Element(in_osmLineLayerNumber) as IGPParameter;
                IGPValue     osmGPLineLayerValue            = gpUtilities3.UnpackGPValue(osmLineSymbolTemplateParameter) as IGPValue;

                IGPParameter outputLineGPParameter  = paramvalues.get_Element(out_osmLineLayerNumber) as IGPParameter;
                IGPValue     outputLineLayerGPValue = gpUtilities3.UnpackGPValue(outputLineGPParameter);

                IGPValue adjustedLineTemplateLayer = objectCopy.Copy(osmGPLineLayerValue) as IGPValue;

                IGPGroupLayer osmLineGroupTemplateLayer = adjustedLineTemplateLayer as IGPGroupLayer;

                compositeLayer = gpUtilities3.Open((IGPValue)osmLineGroupTemplateLayer) as ICompositeLayer;

                if (compositeLayer == null)
                {
                    ILayerFactoryHelper layerFactoryHelper = new LayerFactoryHelperClass();
                    IFileName           layerFileName      = new FileNameClass();

                    layerFileName.Path = osmGPLineLayerValue.GetAsText();
                    IEnumLayer enumLayer = layerFactoryHelper.CreateLayersFromName((IName)layerFileName);
                    enumLayer.Reset();

                    compositeLayer = enumLayer.Next() as ICompositeLayer;

                    isLayerOnDisk = true;
                }


                if (compositeLayer != null)
                {
                    for (int layerIndex = 0; layerIndex < compositeLayer.Count; layerIndex++)
                    {
                        IFeatureLayer2 geoFeatureLayer = compositeLayer.get_Layer(layerIndex) as IFeatureLayer2;
                        if (geoFeatureLayer.ShapeType == osmLineFeatureClass.ShapeType)
                        {
                            try
                            {
                                ((IDataLayer2)geoFeatureLayer).Disconnect();
                            }
                            catch { }
                            ((IDataLayer2)geoFeatureLayer).DataSourceName = ((IDataset)osmLineFeatureClass).FullName;
                            ((IDataLayer2)geoFeatureLayer).Connect(((IDataset)osmLineFeatureClass).FullName);

                            featureLayerDefinition2 = geoFeatureLayer as IFeatureLayerDefinition2;
                            if (featureLayerDefinition2 != null)
                            {
                                string queryDefinition = featureLayerDefinition2.DefinitionExpression;

                                sqlSyntax = ((IDataset)osmLineFeatureClass).Workspace as ISQLSyntax;
                                string delimiterIdentifier = sqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix);

                                if (string.IsNullOrEmpty(queryDefinition) == false)
                                {
                                    string stringToReplace = queryDefinition.Substring(0, 1);
                                    queryDefinition = queryDefinition.Replace(stringToReplace, delimiterIdentifier);
                                }

                                featureLayerDefinition2.DefinitionExpression = queryDefinition;
                            }
                        }
                    }

                    // save the newly adjusted layer information to disk
                    if (isLayerOnDisk == true)
                    {
                        ILayerFile lineLayerFile = new LayerFileClass();
                        if (lineLayerFile.get_IsPresent(outputLineLayerGPValue.GetAsText()))
                        {
                            try
                            {
                                File.Delete(outputLineLayerGPValue.GetAsText());
                            }
                            catch (Exception ex)
                            {
                                message.AddError(120042, ex.Message);
                                return;
                            }
                        }

                        lineLayerFile.New(outputLineLayerGPValue.GetAsText());

                        lineLayerFile.ReplaceContents((ILayer)compositeLayer);

                        lineLayerFile.Save();
                    }

                    IGPLayer adjustLineGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)compositeLayer);

                    gpUtilities3.AddInternalLayer2((ILayer)compositeLayer, adjustLineGPLayer);
                    gpUtilities3.PackGPValue((IGPValue)adjustLineGPLayer, outputLineGPParameter);
                }


                isLayerOnDisk = false;
                IGPParameter osmPolygonSymbolTemplateParameter = paramvalues.get_Element(in_osmPolygonLayerNumber) as IGPParameter;
                IGPValue     osmGPPolygonLayerValue            = gpUtilities3.UnpackGPValue(osmPolygonSymbolTemplateParameter);

                IGPParameter outputPolygonGPParameter  = paramvalues.get_Element(out_osmPolygonLayerNumber) as IGPParameter;
                IGPValue     outputPolygonLayerGPValue = gpUtilities3.UnpackGPValue(outputPolygonGPParameter);

                IGPValue adjustedPolygonTemplateLayer = objectCopy.Copy(osmGPPolygonLayerValue) as IGPValue;

                IGPGroupLayer osmPolygonGroupTemplateLayer = adjustedPolygonTemplateLayer as IGPGroupLayer;
                compositeLayer = gpUtilities3.Open((IGPValue)osmPolygonGroupTemplateLayer) as ICompositeLayer;

                if (compositeLayer == null)
                {
                    ILayerFactoryHelper layerFactoryHelper = new LayerFactoryHelperClass();
                    IFileName           layerFileName      = new FileNameClass();

                    layerFileName.Path = osmGPPolygonLayerValue.GetAsText();
                    IEnumLayer enumLayer = layerFactoryHelper.CreateLayersFromName((IName)layerFileName);
                    enumLayer.Reset();

                    compositeLayer = enumLayer.Next() as ICompositeLayer;

                    isLayerOnDisk = true;
                }

                if (compositeLayer != null)
                {
                    for (int layerIndex = 0; layerIndex < compositeLayer.Count; layerIndex++)
                    {
                        IFeatureLayer2 geoFeatureLayer = compositeLayer.get_Layer(layerIndex) as IFeatureLayer2;

                        if (geoFeatureLayer.ShapeType == osmPoylgonFeatureClass.ShapeType)
                        {
                            try
                            {
                                ((IDataLayer2)geoFeatureLayer).Disconnect();
                            }
                            catch { }
                            ((IDataLayer2)geoFeatureLayer).DataSourceName = ((IDataset)osmPoylgonFeatureClass).FullName;
                            ((IDataLayer2)geoFeatureLayer).Connect(((IDataset)osmPoylgonFeatureClass).FullName);

                            featureLayerDefinition2 = geoFeatureLayer as IFeatureLayerDefinition2;
                            if (featureLayerDefinition2 != null)
                            {
                                string queryDefinition = featureLayerDefinition2.DefinitionExpression;

                                sqlSyntax = ((IDataset)osmPoylgonFeatureClass).Workspace as ISQLSyntax;
                                string delimiterIdentifier = sqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix);

                                if (String.IsNullOrEmpty(queryDefinition) == false)
                                {
                                    string stringToReplace = queryDefinition.Substring(0, 1);
                                    queryDefinition = queryDefinition.Replace(stringToReplace, delimiterIdentifier);
                                }

                                featureLayerDefinition2.DefinitionExpression = queryDefinition;
                            }
                        }
                    }

                    // save the newly adjusted layer information to disk
                    if (isLayerOnDisk == true)
                    {
                        ILayerFile polygonLayerFile = new LayerFileClass();
                        if (polygonLayerFile.get_IsPresent(outputPolygonLayerGPValue.GetAsText()))
                        {
                            try
                            {
                                File.Delete(outputPolygonLayerGPValue.GetAsText());
                            }
                            catch (Exception ex)
                            {
                                message.AddError(120043, ex.Message);
                                return;
                            }
                        }

                        polygonLayerFile.New(outputPolygonLayerGPValue.GetAsText());

                        polygonLayerFile.ReplaceContents((ILayer)compositeLayer);

                        polygonLayerFile.Save();
                    }

                    IGPLayer adjustedPolygonGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)compositeLayer);
                    gpUtilities3.AddInternalLayer2((ILayer)compositeLayer, adjustedPolygonGPLayer);

                    gpUtilities3.PackGPValue((IGPValue)adjustedPolygonGPLayer, outputPolygonGPParameter);
                }
            }
            catch (Exception ex)
            {
                message.AddError(-10, ex.Message);
            }
        }
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            try
            {
                IGPUtilities3 execute_Utilities = new GPUtilitiesClass();

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

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

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

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


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

                System.Xml.XmlWriter xmlWriter = null;

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

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

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

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

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

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

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

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

                IFeatureCursor searchCursor = null;

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

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

                string nodesExportedMessage = String.Empty;

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

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

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

                    IFeature currentFeature = searchCursor.NextFeature();

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

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

                            pointSerializer.Serialize(xmlWriter, osmNode, xmlnsEmpty);

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

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

                            xmlWriter.Close(); // closing the document

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

                            return;
                        }
                    }
                }

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

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

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

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

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

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

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

                    IFeature currentFeature = searchCursor.NextFeature();

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

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

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

                            xmlWriter.Close(); // closing the document

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

                            return;
                        }

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

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

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

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

                        currentFeature = searchCursor.NextFeature();
                    }
                }


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

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

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

                    IFeature currentFeature = searchCursor.NextFeature();

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

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

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

                            xmlWriter.Close(); // closing the document

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

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

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

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

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

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

                        currentFeature = searchCursor.NextFeature();
                    }
                }

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


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

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


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

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

                    IRow currentRow = rowCursor.NextRow();

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

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


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

                            xmlWriter.Close(); // closing the document

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

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

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

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

                        currentRow = rowCursor.NextRow();
                    }
                }

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

                        xmlWriter.Close(); // closing the document

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

                        return;
                    }

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

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


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

                xmlWriter.Close(); // closing the document
            }
            catch (Exception ex)
            {
                message.AddError(11111, ex.StackTrace);
                message.AddError(120026, ex.Message);
            }
        }
        private void BuildSpatialIndex(IGPValue gpFeatureClass, Geoprocessor.Geoprocessor geoProcessor, IGPUtilities gpUtil,
            ITrackCancel trackCancel, IGPMessages message)
        {
            if ((gpFeatureClass == null) || (geoProcessor == null) || (gpUtil == null))
                return;

            // Check if the feature class supports spatial index grids
            IFeatureClass fc = gpUtil.OpenDataset(gpFeatureClass) as IFeatureClass;
            if (fc == null)
                return;

            int idxShapeField = fc.FindField(fc.ShapeFieldName);
            if (idxShapeField >= 0)
            {
                IField shapeField = fc.Fields.get_Field(idxShapeField);
                if (shapeField.GeometryDef.GridCount > 0)
                {
                    if (shapeField.GeometryDef.get_GridSize(0) == -2.0)
                        return;
                }
            }

            // Create the new spatial index grid
            bool storedOriginal = geoProcessor.AddOutputsToMap;

            try
            {
                geoProcessor.AddOutputsToMap = false;

                DataManagementTools.CalculateDefaultGridIndex calculateDefaultGridIndex =
                    new DataManagementTools.CalculateDefaultGridIndex(gpFeatureClass);
                IGeoProcessorResult2 gpResults2 =
                    geoProcessor.Execute(calculateDefaultGridIndex, trackCancel) as IGeoProcessorResult2;
                message.AddMessages(gpResults2.GetResultMessages());

                if (gpResults2 != null)
                {
                    DataManagementTools.RemoveSpatialIndex removeSpatialIndex =
                        new DataManagementTools.RemoveSpatialIndex(gpFeatureClass.GetAsText());
                    removeSpatialIndex.out_feature_class = gpFeatureClass.GetAsText();
                    gpResults2 = geoProcessor.Execute(removeSpatialIndex, trackCancel) as IGeoProcessorResult2;
                    message.AddMessages(gpResults2.GetResultMessages());

                    DataManagementTools.AddSpatialIndex addSpatialIndex =
                        new DataManagementTools.AddSpatialIndex(gpFeatureClass.GetAsText());
                    addSpatialIndex.out_feature_class = gpFeatureClass.GetAsText();

                    addSpatialIndex.spatial_grid_1 = calculateDefaultGridIndex.grid_index1;
                    addSpatialIndex.spatial_grid_2 = calculateDefaultGridIndex.grid_index2;
                    addSpatialIndex.spatial_grid_3 = calculateDefaultGridIndex.grid_index3;

                    gpResults2 = geoProcessor.Execute(addSpatialIndex, trackCancel) as IGeoProcessorResult2;
                    message.AddMessages(gpResults2.GetResultMessages());
                }
            }
            catch (Exception ex)
            {
                message.AddWarning(ex.Message);
            }
            finally
            {
                geoProcessor.AddOutputsToMap = storedOriginal;
            }
        }
        /// <summary>
        /// Updates the internal values used by this tool based on the parameters from an input array
        /// </summary>
        /// <param name="paramValues"></param>
        protected override void ExtractParameters(IArray paramValues)
        {
            // Get the values for any parameters common to all GP tools
            ExtractParametersCommon(paramValues);

            WmauParameterMap paramMap = new WmauParameterMap(paramValues);
            IGPParameter3    param    = null;

            // Ensure that the various parameter values are all restored to their
            // defaults because of how this function works
            ResetVariables();

            // Update the internal values of whatever parameters we're maintaining
            param = paramMap.GetParam(C_PARAM_CHECKLIST);
            IGPValue      paramValue      = m_gpUtilities.UnpackGPValue(param);
            IGPMultiValue paramMultiValue = paramValue as IGPMultiValue;

            for (int i = 0; i < paramMultiValue.Count; i++)
            {
                IGPValue check  = paramMultiValue.get_Value(i);
                string   strVal = check.GetAsText();
                if (strVal.Equals(C_OPT_DIFF_STEP_NAMES))
                {
                    m_flagDifferingStepNames = true;
                }
                else if (strVal.Equals(C_OPT_GROUPS_WITHOUT_EMAILS))
                {
                    m_flagGroupsWithoutEmails = true;
                }
                else if (strVal.Equals(C_OPT_GROUPS_WITHOUT_PRIVILEGES))
                {
                    m_flagGroupsWithoutPrivileges = true;
                }
                else if (strVal.Equals(C_OPT_GROUPS_WITHOUT_USERS))
                {
                    m_flagGroupsWithoutUsers = true;
                }
                else if (strVal.Equals(C_OPT_INVALID_JOB_ASSIGN))
                {
                    m_flagInvalidJobAssign = true;
                }
                else if (strVal.Equals(C_OPT_INVALID_JOB_TYPE_ASSIGN))
                {
                    m_flagInvalidJobTypeAssign = true;
                }
                else if (strVal.Equals(C_OPT_INVALID_STEP_ASSIGN))
                {
                    m_flagInvalidStepAssign = true;
                }
                else if (strVal.Equals(C_OPT_IS_SELF_PARENT))
                {
                    m_flagIsSelfParent = true;
                }
                else if (strVal.Equals(C_OPT_JOBS_WITHOUT_TYPES))
                {
                    m_flagJobsWithoutTypes = true;
                }
                else if (strVal.Equals(C_OPT_JOB_TYPES_WITHOUT_WORKFLOWS))
                {
                    m_flagJobTypesWithoutWorkflows = true;
                }
                else if (strVal.Equals(C_OPT_MISSING_AOI_MXDS))
                {
                    m_flagMissingAoiMxds = true;
                }
                else if (strVal.Equals(C_OPT_MISSING_BASE_MXDS))
                {
                    m_flagMissingBaseMxds = true;
                }
                else if (strVal.Equals(C_OPT_NON_ACTIVE_JOB_TYPES))
                {
                    m_flagNonActiveJobTypes = true;
                }
                else if (strVal.Equals(C_OPT_UNASSIGNED_STEPS))
                {
                    m_flagUnassignedSteps = true;
                }
                else if (strVal.Equals(C_OPT_USERS_WITHOUT_EMAILS))
                {
                    m_flagUsersWithoutEmails = true;
                }
                else if (strVal.Equals(C_OPT_USERS_WITHOUT_GROUPS))
                {
                    m_flagUsersWithoutGroups = true;
                }
                else if (strVal.Equals(C_OPT_ZERO_PCT_STEPS))
                {
                    m_flagZeroPctSteps = true;
                }
            }

            param         = paramMap.GetParam(C_PARAM_OUT_LOG_FILE_PATH);
            m_logFilePath = param.Value.GetAsText();
        }