public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
        {
            IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

            IGPParameter inputFCParameter = paramvalues.get_Element(in_osmFeaturesNumber) as IGPParameter;
            IGPValue     osmFCGPValue     = gpUtilities3.UnpackGPValue(inputFCParameter);

            if (osmFCGPValue.IsEmpty())
            {
                return;
            }

            IFeatureClass osmFeatureClass = null;
            IQueryFilter  queryFilter     = null;

            if (osmFCGPValue is IGPFeatureLayer)
            {
                gpUtilities3.DecodeFeatureLayer(osmFCGPValue, out osmFeatureClass, out queryFilter);

                int osmTagFieldIndex = osmFeatureClass.Fields.FindField("osmTags");

                if (osmTagFieldIndex == -1)
                {
                    Messages.ReplaceError(in_osmFeaturesNumber, -1, resourceManager.GetString("GPTools_OSMGPAddExtension_noosmtagfield"));
                }
            }
        }
        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 inputFeatureClassParameter = paramvalues.get_Element(in_osmFeaturesNumber) as IGPParameter;
                IGPValue     inputFeatureGPValue        = gpUtilities3.UnpackGPValue(inputFeatureClassParameter) as IGPValue;

                IFeatureClass osmFeatureClass = null;
                IQueryFilter  queryFilter     = null;

                gpUtilities3.DecodeFeatureLayer(inputFeatureGPValue, out osmFeatureClass, out queryFilter);

                ((ITable)osmFeatureClass).RemoveOSMClassExtension();
            }
            catch (Exception ex)
            {
                message.AddError(120057, ex.Message);
            }
        }
        public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
        {
            IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

            IGPParameter inputFCParameter = paramvalues.get_Element(in_osmFeaturesNumber) as IGPParameter;
            IGPValue     osmFCGPValue     = gpUtilities3.UnpackGPValue(inputFCParameter);

            if (osmFCGPValue.IsEmpty())
            {
                return;
            }

            IFeatureClass osmFeatureClass = null;
            IQueryFilter  queryFilter     = null;

            if (osmFCGPValue is IGPFeatureLayer)
            {
                gpUtilities3.DecodeFeatureLayer(osmFCGPValue, out osmFeatureClass, out queryFilter);

                if (osmFeatureClass.EXTCLSID != null)
                {
                    UID osmEditorExtensionCLSID = osmFeatureClass.EXTCLSID;

                    if (osmEditorExtensionCLSID.Value.ToString().Equals("{65CA4847-8661-45eb-8E1E-B2985CA17C78}", StringComparison.InvariantCultureIgnoreCase) == false)
                    {
                        Messages.ReplaceError(in_osmFeaturesNumber, -1, resourceManager.GetString("GPTools_OSMGPRemoveExtension_noEXTCLSID"));
                    }
                }
                else
                {
                    Messages.ReplaceError(in_osmFeaturesNumber, -1, resourceManager.GetString("GPTools_OSMGPRemoveExtension_noEXTCLSID"));
                }
            }
        }
        public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
        {
            IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

            for (int i = 0; i < Messages.Count; i++)
            {
                IGPMessage blah = Messages.GetMessage(i);
                if (blah.IsError())
                {
                    IGPMessage something = new GPMessageClass();
                    something.Description = String.Empty;
                    something.Type        = esriGPMessageType.esriGPMessageTypeInformative;
                    something.ErrorCode   = 0;
                    Messages.Replace(i, something);
                }
            }

            IGPParameter inputOSMParameter = paramvalues.get_Element(in_osmFeatureClassNumber) as IGPParameter;
            IGPValue     inputOSMGPValue   = gpUtilities3.UnpackGPValue(inputOSMParameter);

            if (inputOSMGPValue.IsEmpty() == false)
            {
                IFeatureClass osmFeatureClass = null;
                ITable        osmInputTable   = null;
                IQueryFilter  osmQueryFilter  = null;

                try
                {
                    gpUtilities3.DecodeFeatureLayer(inputOSMGPValue, out osmFeatureClass, out osmQueryFilter);
                    osmInputTable = osmFeatureClass as ITable;
                }
                catch { }

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

                if (osmInputTable == null)
                {
                    return;
                }

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

                if (osmTagCollectionFieldIndex == -1)
                {
                    Messages.ReplaceAbort(in_osmFeatureClassNumber, resourceManager.GetString("GPTools_OSMGPCombineAttributes_inputlayer_missingtagfield"));
                    return;
                }
            }
        }
        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"));
            }
        }
        public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr)
        {
            IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

            IGPParameter3 inputLayersParameter = paramvalues.get_Element(in_LayersNumber) as IGPParameter3;
            IGPMultiValue inputLayersGPValue   = gpUtilities3.UnpackGPValue(inputLayersParameter) as IGPMultiValue;

            if (inputLayersGPValue == null)
            {
                return;
            }

            // check if there are input layer provided
            if (inputLayersGPValue.Count == 0)
            {
                return;
            }

            IGPParameter3 outputLayerParameter = paramvalues.get_Element(out_groupLayerNumber) as IGPParameter3;
            IGPValue      outputLayerGPValue   = gpUtilities3.UnpackGPValue(outputLayerParameter);

            // if the output layer value is still empty and build a proposal for a name
            if (outputLayerGPValue.IsEmpty())
            {
                // read the proposed name from the resources
                string proposedOutputLayerName = resourceManager.GetString("GPTools_GPCombineLayers_outputgrouplayer_proposedname");

                string proposedOutputLayerNameTest = proposedOutputLayerName;
                int    layerIndex = 2;

                // check if a layer with the same name already exists
                // if it does then attempt to append some index numbers to build a unique, new name
                ILayer foundLayer = gpUtilities3.FindMapLayer(proposedOutputLayerNameTest);

                while (foundLayer != null)
                {
                    proposedOutputLayerNameTest = proposedOutputLayerName + " (" + layerIndex + ")";

                    foundLayer = gpUtilities3.FindMapLayer(proposedOutputLayerNameTest);
                    layerIndex = layerIndex + 1;

                    if (layerIndex > 10000)
                    {
                        break;
                    }
                }

                outputLayerGPValue.SetAsText(proposedOutputLayerNameTest);
                gpUtilities3.PackGPValue(outputLayerGPValue, outputLayerParameter);
            }
        }
        //listen to MapReplaced event in order to update the status bar and the Save menu
        private void axMapControl1_OnMapReplaced(object sender, IMapControlEvents2_OnMapReplacedEvent e)
        {
            //get the current document name from the MapControl
            m_mapDocumentName = m_mapControl.DocumentFilename;

            if (m_blnToolbarItemClick == true)
            {
                m_blnToolbarItemClick = false;
                m_blnExistingMap      = true;
                //need to add the new diagram to the combobox
                IMap p = (IMap)e.newMap;
                if (!cboFrame.Items.Contains(p.Name))
                {
                    cboFrame.Items.Add(p.Name.ToString());
                }
                m_arrMaps.Add(p);
            }

            if (m_blnExistingMap == false)
            {
                IMap m;
                m_arrMaps = axMapControl1.ReadMxMaps(m_mapDocumentName);
                Int16 i;
                for (i = 0; i < m_arrMaps.Count; i++)
                {
                    m = (IMap)m_arrMaps.Element[i];

                    if (!cboFrame.Items.Contains(m.Name.ToString()))
                    {
                        cboFrame.Items.Add(m.Name.ToString());
                    }
                }
                cboFrame.Text = this.axMapControl1.ActiveView.FocusMap.Name;
            }
            //if there is no MapDocument, disable the Save menu and clear the status bar
            if (m_mapDocumentName == string.Empty)
            {
                menuSaveDoc.Enabled = false;
                statusBarXY.Text    = string.Empty;
            }
            else
            {
                //enable the Save menu and write the doc name to the status bar
                menuSaveDoc.Enabled = true;
                statusBarXY.Text    = Path.GetFileName(m_mapDocumentName);
            }

            m_blnExistingMap = true;

            cboFrame.Text = axMapControl1.Map.Name.ToString();
        }
Esempio n. 8
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);
            }
        }
Esempio n. 9
0
        public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr)
        {
            try
            {
                IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

                IGPValue inputOSMGPValue = gpUtilities3.UnpackGPValue(paramvalues.get_Element(in_osmFeatureClass));

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


                try
                {
                    gpUtilities3.DecodeFeatureLayer(inputOSMGPValue, out osmFeatureClass, out osmQueryFilter);
                    osmInputTable = osmFeatureClass as ITable;
                }
                catch { }

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

                if (osmInputTable == null)
                {
                    return;
                }

                String illegalCharacters = String.Empty;

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

                // 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)
                {
                    return;
                }

                if (((IGPParameter)paramvalues.get_Element(in_attributeSelector)).Altered)
                {
                    IGPParameter  tagCollectionParameter = paramvalues.get_Element(in_attributeSelector) as IGPParameter;
                    IGPMultiValue tagCollectionGPValue   = gpUtilities3.UnpackGPValue(tagCollectionParameter) as IGPMultiValue;

                    IGPCodedValueDomain codedTagDomain = tagCollectionParameter.Domain as IGPCodedValueDomain;

                    for (int attributeValueIndex = 0; attributeValueIndex < tagCollectionGPValue.Count; attributeValueIndex++)
                    {
                        string   valueString    = tagCollectionGPValue.get_Value(attributeValueIndex).GetAsText();
                        IGPValue testFieldValue = codedTagDomain.FindValue(valueString);

                        if (testFieldValue == null)
                        {
                            codedTagDomain.AddStringCode(valueString, valueString);
                        }
                    }

                    // Get the derived output feature class schema and empty the additional fields. This ensures
                    // that you don't get dublicate entries.
                    // Derived output is the third parameter, so use index 2 for get_Element.
                    IGPParameter3    derivedFeatures = (IGPParameter3)paramvalues.get_Element(out_osmFeatureClass);
                    IGPFeatureSchema schema          = (IGPFeatureSchema)derivedFeatures.Schema;
                    schema.AdditionalFields = null;

                    IFieldsEdit fieldsEdit = new FieldsClass();

                    for (int valueIndex = 0; valueIndex < tagCollectionGPValue.Count; valueIndex++)
                    {
                        string tagString = tagCollectionGPValue.get_Value(valueIndex).GetAsText();

                        if (tagString != "ALL")
                        {
                            // Check if the input field already exists.
                            string cleanedTagKey = convert2AttributeFieldName(tagString, illegalCharacters);
                            IField tagField      = gpUtilities3.FindField(inputOSMGPValue, cleanedTagKey);
                            if (tagField == null)
                            {
                                IFieldEdit fieldEdit = new FieldClass();
                                fieldEdit.Name_2      = cleanedTagKey;
                                fieldEdit.AliasName_2 = tagCollectionGPValue.get_Value(valueIndex).GetAsText();
                                fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                                fieldEdit.Length_2    = 100;
                                fieldsEdit.AddField(fieldEdit);
                            }
                        }
                    }

                    // Add the additional field to the derived output.
                    IFields fields = fieldsEdit as IFields;
                    schema.AdditionalFields = fields;
                }

                //if (inputOSMGPValue.IsEmpty() == false)
                //{
                //    if (((IGPParameter)paramvalues.get_Element(in_osmFeatureClass)).HasBeenValidated == false)
                //    {
                //        IGPParameter tagCollectionGPParameter = paramvalues.get_Element(in_attributeSelector) as IGPParameter;
                //        IGPValue tagCollectionGPValue = gpUtilities3.UnpackGPValue(tagCollectionGPParameter);

                //        IGPCodedValueDomain osmTagKeyCodedValues = new GPCodedValueDomainClass();
                //        if (((IGPMultiValue)tagCollectionGPValue).Count == 0)
                //        {
                //            if (osmTagKeyCodedValues == null)
                //                extractAllTags(ref osmTagKeyCodedValues, osmInputTable, osmQueryFilter, osmTagCollectionFieldIndex, true);

                //            if (osmTagKeyCodedValues != null)
                //            {
                //                tagsParameter = tagCollectionGPParameter as IGPParameterEdit;
                //                tagsParameter.Domain = (IGPDomain)osmTagKeyCodedValues;
                //            }
                //        }
                //        else
                //        {
                //            // let's take the given values and make then part of the domain -- if they are not already
                //            // if we don't do this step then we won't pass the internal validation
                //            IGPCodedValueDomain gpTagDomain = tagCollectionGPParameter.Domain as IGPCodedValueDomain;

                //            if (gpTagDomain != null)
                //            {
                //                if (gpTagDomain.CodeCount == 0)
                //                {
                //                    // let's add the value existing in the mentioned multi value to the domain
                //                    for (int i = 0; i < ((IGPMultiValue)tagCollectionGPValue).Count; i++)
                //                    {
                //                        string tagStringValue = ((IGPMultiValue)tagCollectionGPValue).get_Value(i).GetAsText();
                //                        gpTagDomain.AddStringCode(tagStringValue, tagStringValue);
                //                    }

                //                    ((IGPParameterEdit)tagCollectionGPParameter).Domain = gpTagDomain as IGPDomain;
                //                }
                //            }
                //        }

                //        // Get the derived output feature class schema and empty the additional fields. This ensures
                //        // that you don't get dublicate entries.
                //        // Derived output is the third parameter, so use index 2 for get_Element.
                //        IGPParameter3 derivedFeatures = (IGPParameter3)paramvalues.get_Element(out_osmFeatureClass);
                //        IGPFeatureSchema schema = (IGPFeatureSchema)derivedFeatures.Schema;
                //        schema.AdditionalFields = null;

                //        // Area field name is the second parameter, so use index 1 for get_Element.
                //        IGPMultiValue tagsGPMultiValue = gpUtilities3.UnpackGPValue(paramvalues.get_Element(in_attributeSelector)) as IGPMultiValue;

                //        IFieldsEdit fieldsEdit = new FieldsClass();
                //        bool extractALLTags = false;

                //        // check if the list contains the "ALL" keyword
                //        for (int valueIndex = 0; valueIndex < tagsGPMultiValue.Count; valueIndex++)
                //        {
                //            if (tagsGPMultiValue.get_Value(valueIndex).GetAsText().Equals("ALL"))
                //            {
                //                extractALLTags = true;
                //            }
                //        }

                //        if (extractALLTags)
                //        {
                //            if (osmTagKeyCodedValues == null)
                //            {
                //                extractAllTags(ref osmTagKeyCodedValues, osmInputTable, osmQueryFilter, osmTagCollectionFieldIndex, false);
                //            }

                //            if (osmTagKeyCodedValues != null)
                //            {
                //                for (int valueIndex = 0; valueIndex < osmTagKeyCodedValues.CodeCount; valueIndex++)
                //                {
                //                    // Check if the input field already exists.
                //                    string cleanedTagKey = convert2AttributeFieldName(osmTagKeyCodedValues.get_Value(valueIndex).GetAsText(), illegalCharacters);
                //                    IField tagField = gpUtilities3.FindField(inputOSMGPValue, cleanedTagKey);
                //                    if (tagField == null)
                //                    {
                //                        IFieldEdit fieldEdit = new FieldClass();
                //                        fieldEdit.Name_2 = cleanedTagKey;
                //                        fieldEdit.AliasName_2 = osmTagKeyCodedValues.get_Value(valueIndex).GetAsText();
                //                        fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                //                        fieldEdit.Length_2 = 100;
                //                        fieldsEdit.AddField(fieldEdit);
                //                    }
                //                }
                //            }
                //        }
                //        else
                //        {
                //            for (int valueIndex = 0; valueIndex < tagsGPMultiValue.Count; valueIndex++)
                //            {
                //                // Check if the input field already exists.
                //                string cleanedTagKey = convert2AttributeFieldName(tagsGPMultiValue.get_Value(valueIndex).GetAsText(), illegalCharacters);
                //                IField tagField = gpUtilities3.FindField(inputOSMGPValue, cleanedTagKey);
                //                if (tagField == null)
                //                {
                //                    IFieldEdit fieldEdit = new FieldClass();
                //                    fieldEdit.Name_2 = cleanedTagKey;
                //                    fieldEdit.AliasName_2 = tagsGPMultiValue.get_Value(valueIndex).GetAsText();
                //                    fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                //                    fieldEdit.Length_2 = 100;
                //                    fieldsEdit.AddField(fieldEdit);
                //                }
                //            }
                //        }

                //        // Add the additional field to the derived output.
                //        IFields fields = fieldsEdit as IFields;
                //        schema.AdditionalFields = fields;

                //    }
                //}
            }
            catch { }
        }
Esempio n. 10
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);
        }
Esempio n. 11
0
 public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr)
 {
 }
Esempio n. 12
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 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();
                OSMUtility    osmUtility        = new OSMUtility();

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

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

                IGPParameter  tagFieldsParameter   = paramvalues.get_Element(in_attributeSelectorNumber) as IGPParameter;
                IGPMultiValue tagCollectionGPValue = execute_Utilities.UnpackGPValue(tagFieldsParameter) as IGPMultiValue;

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


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

                try
                {
                    execute_Utilities.DecodeFeatureLayer(inputOSMGPValue, out osmFeatureClass, out osmQueryFilter);
                    osmInputTable = osmFeatureClass as ITable;
                }
                catch { }

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

                if (osmInputTable == null)
                {
                    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;
                }

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

                if (stepProgressor != null)
                {
                    int featureCount = osmInputTable.RowCount(osmQueryFilter);

                    stepProgressor.MinRange  = 0;
                    stepProgressor.MaxRange  = featureCount;
                    stepProgressor.Position  = 0;
                    stepProgressor.Message   = resourceManager.GetString("GPTools_OSMGPCombineAttributes_progressMessage");
                    stepProgressor.StepValue = 1;
                    stepProgressor.Show();
                }

                String illegalCharacters = String.Empty;

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

                // establish the list of field indexes only once
                Dictionary <string, int> fieldIndexes = new Dictionary <string, int>();
                for (int selectedGPValueIndex = 0; selectedGPValueIndex < tagCollectionGPValue.Count; selectedGPValueIndex++)
                {
                    // find the field index
                    int fieldIndex = osmInputTable.FindField(tagCollectionGPValue.get_Value(selectedGPValueIndex).GetAsText());

                    if (fieldIndex != -1)
                    {
                        string tagKeyName = osmInputTable.Fields.get_Field(fieldIndex).Name;

                        tagKeyName = OSMToolHelper.convert2OSMKey(tagKeyName, illegalCharacters);

                        fieldIndexes.Add(tagKeyName, fieldIndex);
                    }
                }

                ICursor updateCursor = null;
                IRow    osmRow       = null;

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    updateCursor = osmInputTable.Update(osmQueryFilter, false);
                    comReleaser.ManageLifetime(updateCursor);

                    osmRow = updateCursor.NextRow();
                    int progressIndex = 0;

                    while (osmRow != null)
                    {
                        // get the current tag collection from the row
                        ESRI.ArcGIS.OSM.OSMClassExtension.tag[] osmTags = osmUtility.retrieveOSMTags(osmRow, osmTagCollectionFieldIndex, ((IDataset)osmInputTable).Workspace);

                        Dictionary <string, string> tagsDictionary = new Dictionary <string, string>();
                        for (int tagIndex = 0; tagIndex < osmTags.Length; tagIndex++)
                        {
                            tagsDictionary.Add(osmTags[tagIndex].k, osmTags[tagIndex].v);
                        }

                        // look if the tag needs to be updated or added
                        bool tagsUpdated = false;
                        foreach (var fieldItem in fieldIndexes)
                        {
                            object fldValue = osmRow.get_Value(fieldItem.Value);
                            if (fldValue != System.DBNull.Value)
                            {
                                if (tagsDictionary.ContainsKey(fieldItem.Key))
                                {
                                    if (!tagsDictionary[fieldItem.Key].Equals(fldValue))
                                    {
                                        tagsDictionary[fieldItem.Key] = Convert.ToString(fldValue);
                                        tagsUpdated = true;
                                    }
                                }
                                else
                                {
                                    tagsDictionary.Add(fieldItem.Key, Convert.ToString(fldValue));
                                    tagsUpdated = true;
                                }
                            }
                            else
                            {
                                if (tagsDictionary.ContainsKey(fieldItem.Key))
                                {
                                    tagsDictionary.Remove(fieldItem.Key);
                                    tagsUpdated = true;
                                }
                            }
                        }

                        if (tagsUpdated)
                        {
                            List <ESRI.ArcGIS.OSM.OSMClassExtension.tag> updatedTags = new List <ESRI.ArcGIS.OSM.OSMClassExtension.tag>();

                            foreach (var tagItem in tagsDictionary)
                            {
                                ESRI.ArcGIS.OSM.OSMClassExtension.tag newTag = new ESRI.ArcGIS.OSM.OSMClassExtension.tag();
                                newTag.k = tagItem.Key;
                                newTag.v = tagItem.Value;
                                updatedTags.Add(newTag);
                            }

                            // insert the tags back into the collection field
                            if (updatedTags.Count != 0)
                            {
                                osmUtility.insertOSMTags(osmTagCollectionFieldIndex, osmRow, updatedTags.ToArray(), ((IDataset)osmInputTable).Workspace);

                                updateCursor.UpdateRow(osmRow);
                            }
                        }

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

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

                        osmRow = updateCursor.NextRow();
                    }

                    if (stepProgressor != null)
                    {
                        stepProgressor.Hide();
                    }
                }
            }
            catch (Exception ex)
            {
                message.AddError(120007, ex.Message);
            }
        }
        public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr)
        {
            try
            {
                IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

                IGPParameter inputOSMParameter = paramvalues.get_Element(in_osmFeatureClassNumber) as IGPParameter;
                IGPValue     inputOSMGPValue   = gpUtilities3.UnpackGPValue(inputOSMParameter);

                if (inputOSMGPValue.IsEmpty() == false)
                {
                    if (inputOSMParameter.Altered == true)
                    {
                        IGPParameter attributeCollectionParameter = paramvalues.get_Element(in_attributeSelectorNumber) as IGPParameter;
                        IGPValue     attributeCollectionGPValue   = gpUtilities3.UnpackGPValue(attributeCollectionParameter);

                        if (inputOSMParameter.HasBeenValidated == false && ((IGPMultiValue)attributeCollectionGPValue).Count == 0)
                        {
                            IFeatureClass osmFeatureClass = null;
                            ITable        osmInputTable   = null;
                            IQueryFilter  osmQueryFilter  = null;

                            try
                            {
                                gpUtilities3.DecodeFeatureLayer(inputOSMGPValue, out osmFeatureClass, out osmQueryFilter);
                                osmInputTable = osmFeatureClass as ITable;
                            }
                            catch { }

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

                            if (osmInputTable == null)
                            {
                                return;
                            }

                            using (ComReleaser comReleaser = new ComReleaser())
                            {
                                ICursor osmCursor = osmInputTable.Search(osmQueryFilter, true);
                                comReleaser.ManageLifetime(osmCursor);

                                IRow          osmRow             = osmCursor.NextRow();
                                List <string> potentialOSMFields = new List <string>();

                                if (osmRow != null)
                                {
                                    IFields osmFields = osmRow.Fields;

                                    for (int fieldIndex = 0; fieldIndex < osmFields.FieldCount; fieldIndex++)
                                    {
                                        if (osmFields.get_Field(fieldIndex).Name.Substring(0, 4).Equals("osm_"))
                                        {
                                            potentialOSMFields.Add(osmFields.get_Field(fieldIndex).Name);
                                        }
                                    }
                                }

                                if (potentialOSMFields.Count == 0)
                                {
                                    return;
                                }

                                IGPCodedValueDomain osmTagKeyCodedValues = new GPCodedValueDomainClass();
                                foreach (string tagOSMField in potentialOSMFields)
                                {
                                    osmTagKeyCodedValues.AddStringCode(tagOSMField, tagOSMField);
                                }

                                ((IGPParameterEdit)attributeCollectionParameter).Domain = (IGPDomain)osmTagKeyCodedValues;
                            }
                        }
                    }
                }
            }
            catch { }
        }
        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);
            }
        }
Esempio n. 16
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);
            }
        }
Esempio n. 17
0
 public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
 {
 }
Esempio n. 18
0
 public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
 {
     // no special code required - let the framework handle it
 }
        public ESRI.ArcGIS.Carto.IRasterRenderer Pick(ESRI.ArcGIS.esriSystem.IArray pRenderers, ESRI.ArcGIS.Geodatabase.IRasterDataset pRasterDataset)
        {
            IRasterRenderer    rasterRenderer    = null;
            IRasterRGBRenderer rasterRGBRenderer = null;
            IRasterStretchColorRampRenderer rasterStretchColorRampRenderer = null;

            // Get the renderers
            int Count = pRenderers.Count;
            int i     = 0;

            for (i = 0; i < Count; i++)
            {
                rasterRenderer = (IRasterRenderer)(pRenderers.get_Element(i));

                if (rasterRenderer is IRasterStretchColorRampRenderer)
                {
                    rasterStretchColorRampRenderer = (IRasterStretchColorRampRenderer)rasterRenderer;
                }
                else if (rasterRenderer is IRasterRGBRenderer)
                {
                    rasterRGBRenderer = (IRasterRGBRenderer)rasterRenderer;
                }
            }

            IRasterDataset2       rasterDataset2       = (IRasterDataset2)pRasterDataset;
            IRasterBandCollection rasterBandCollection = (IRasterBandCollection)rasterDataset2;

            if (rasterBandCollection.Count > 5)
            {
                // Use band 4,5 and 3 as red, green and blue
                rasterRenderer = (IRasterRenderer)rasterRGBRenderer;
                rasterRGBRenderer.SetBandIndices(3, 4, 2);
                return((IRasterRenderer)rasterRGBRenderer);
            }
            else // Special stretch
            {
                IRasterBand rasterBand = rasterBandCollection.Item(0);

                bool hasTable = false;
                rasterBand.HasTable(out hasTable);

                if (hasTable == false)
                {
                    // Simply change the color ramp for the stretch renderer
                    //IColor fromColor = new RgbColorClass();
                    //fromColor.RGB = Microsoft.VisualBasic.Information.RGB(255, 200, 50);
                    IColor fromColor = CreateRGBColor(255, 200, 50) as IColor;

                    //IColor toColor = new RgbColorClass();
                    //toColor.RGB = Microsoft.VisualBasic.Information.RGB(180, 125, 0);
                    IColor toColor = CreateRGBColor(180, 125, 0) as IColor;

                    // Create color ramp
                    IAlgorithmicColorRamp algorithmicColorRamp = new AlgorithmicColorRampClass();
                    algorithmicColorRamp.Size      = 255;
                    algorithmicColorRamp.FromColor = fromColor;
                    algorithmicColorRamp.ToColor   = toColor;
                    bool createRamp = false;
                    algorithmicColorRamp.CreateRamp(out createRamp);

                    if (createRamp == true)
                    {
                        rasterRenderer = (IRasterRenderer)rasterStretchColorRampRenderer;
                        rasterStretchColorRampRenderer.BandIndex = 0;
                        rasterStretchColorRampRenderer.ColorRamp = algorithmicColorRamp;
                        return((IRasterRenderer)rasterStretchColorRampRenderer);
                    }
                }
            }

            return(rasterRenderer);
        }
Esempio n. 20
0
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            try
            {
                IGPUtilities3 execute_Utilities = new GPUtilitiesClass();

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

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

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

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


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

                System.Xml.XmlWriter xmlWriter = null;

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

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

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

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

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

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

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

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

                IFeatureCursor searchCursor = null;

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

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

                string nodesExportedMessage = String.Empty;

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

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

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

                    IFeature currentFeature = searchCursor.NextFeature();

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

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

                            pointSerializer.Serialize(xmlWriter, osmNode, xmlnsEmpty);

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

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

                            xmlWriter.Close(); // closing the document

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

                            return;
                        }
                    }
                }

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

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

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

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

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

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

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

                    IFeature currentFeature = searchCursor.NextFeature();

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

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

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

                            xmlWriter.Close(); // closing the document

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

                            return;
                        }

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

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

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

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

                        currentFeature = searchCursor.NextFeature();
                    }
                }


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

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

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

                    IFeature currentFeature = searchCursor.NextFeature();

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

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

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

                            xmlWriter.Close(); // closing the document

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

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

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

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

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

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

                        currentFeature = searchCursor.NextFeature();
                    }
                }

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


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

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


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

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

                    IRow currentRow = rowCursor.NextRow();

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

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


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

                            xmlWriter.Close(); // closing the document

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

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

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

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

                        currentRow = rowCursor.NextRow();
                    }
                }

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

                        xmlWriter.Close(); // closing the document

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

                        return;
                    }

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

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


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

                xmlWriter.Close(); // closing the document
            }
            catch (Exception ex)
            {
                message.AddError(11111, ex.StackTrace);
                message.AddError(120026, ex.Message);
            }
        }
Esempio n. 21
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
        }
Esempio n. 22
0
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            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);
            }
        }
Esempio n. 23
0
 public ESRI.ArcGIS.Geodatabase.IGPMessages Validate(ESRI.ArcGIS.esriSystem.IArray paramvalues, bool updateValues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr)
 {
     return(default(ESRI.ArcGIS.Geodatabase.IGPMessages));
 }
		//listen to MapReplaced event in order to update the status bar and the Save menu
		private void axMapControl1_OnMapReplaced(object sender, IMapControlEvents2_OnMapReplacedEvent e)
		{
			//get the current document name from the MapControl
			m_mapDocumentName = m_mapControl.DocumentFilename;

			if (m_blnToolbarItemClick == true)
			{
				m_blnToolbarItemClick = false;
				m_blnExistingMap = true;
				//need to add the new diagram to the combobox
				IMap p = (IMap)e.newMap;
				if (!cboFrame.Items.Contains(p.Name))
					cboFrame.Items.Add(p.Name.ToString());
				m_arrMaps.Add(p);
			}

			if (m_blnExistingMap == false)
			{
				IMap m;
				m_arrMaps = axMapControl1.ReadMxMaps(m_mapDocumentName);
				Int16 i;
				for (i = 0; i < m_arrMaps.Count; i++)
				{
					m = (IMap)m_arrMaps.Element[i];

					if (!cboFrame.Items.Contains(m.Name.ToString()))
						cboFrame.Items.Add(m.Name.ToString());
				}
				cboFrame.Text = this.axMapControl1.ActiveView.FocusMap.Name;
			}
			//if there is no MapDocument, disable the Save menu and clear the status bar
			if (m_mapDocumentName == string.Empty)
			{
				menuSaveDoc.Enabled = false;
				statusBarXY.Text = string.Empty;
			}
			else
			{
				//enable the Save menu and write the doc name to the status bar
				menuSaveDoc.Enabled = true;
				statusBarXY.Text = Path.GetFileName(m_mapDocumentName);
			}

			m_blnExistingMap = true;

			cboFrame.Text = axMapControl1.Map.Name.ToString();
		}