Example #1
0
 private void btnOK_Click(object sender, EventArgs e)
 {
     if (this.iworkspaceDomains_0 == null)
     {
         base.Close();
     }
     if (this.txtDomainName.Text.Trim().Length == 0)
     {
         MessageBox.Show("请输入域名");
     }
     else if (this.txtTable.Tag == null)
     {
         MessageBox.Show("请选择要创建域值的表");
     }
     else if (this.cboNameField.SelectedIndex == -1)
     {
         MessageBox.Show("请选择要名字字段");
     }
     else if (this.cboNameField.SelectedIndex == -1)
     {
         MessageBox.Show("请选择值字段");
     }
     else if (this.iworkspaceDomains_0.get_DomainByName(this.txtDomainName.Text) != null)
     {
         MessageBox.Show("该域名的域值已存在,请输入其他名称");
     }
     else
     {
         try
         {
             ICodedValueDomain domain2 = new CodedValueDomainClass();
             IDomain           domain  = domain2 as IDomain;
             domain.Description = this.txtDes.Text;
             domain.Name        = this.txtDomainName.Text;
             this.method_0(this.cboMergePolicy.SelectedIndex, domain);
             this.method_1(this.cboSplitPolicy.SelectedIndex, domain);
             ITable tag   = this.txtTable.Tag as ITable;
             int    index = tag.Fields.FindFieldByAliasName(this.cdoCodeField.Text);
             IField field = tag.Fields.get_Field(index);
             domain.FieldType = field.Type;
             int     num2 = tag.Fields.FindField(this.cboNameField.Text);
             ICursor o    = tag.Search(null, false);
             for (IRow row = o.NextRow(); row != null; row = o.NextRow())
             {
                 domain2.AddCode(row.get_Value(index), row.get_Value(num2).ToString());
             }
             this.iworkspaceDomains_0.AddDomain(domain);
             ComReleaser.ReleaseCOMObject(o);
             base.DialogResult = DialogResult.OK;
         }
         catch (Exception exception)
         {
             Logger.Current.Error("", exception, "");
         }
         base.Close();
     }
 }
Example #2
0
 //复制工作空间坐标空间域
 private void CreateWorkspaceDomains(IWorkspace pWs1, IWorkspace pWs2)
 {
     try
     {
         WaitForm.SetCaption("正在复制工作空间域,请稍后...");
         IWorkspaceDomains pWsD1       = pWs1 as IWorkspaceDomains;
         IWorkspaceDomains pWsD2       = pWs2 as IWorkspaceDomains;
         IEnumDomain       pEnumDomain = pWsD1.Domains;
         IDomain           pDomain1    = null;
         IDomain           pDomain2    = null;
         if (pEnumDomain == null)
         {
             return;
         }
         while ((pDomain1 = pEnumDomain.Next()) != null)
         {
             if (pDomain1.Type == esriDomainType.esriDTCodedValue)//编码域
             {
                 ICodedValueDomain tempDomain1 = pDomain1 as ICodedValueDomain;
                 ICodedValueDomain tempDomain2 = new CodedValueDomainClass();
                 for (int i = 0; i < tempDomain1.CodeCount; i++)
                 {
                     tempDomain2.AddCode(tempDomain1.get_Value(i), tempDomain1.get_Name(i));
                 }
                 pDomain2             = tempDomain2 as IDomain;
                 pDomain2.Description = pDomain1.Description;
                 pDomain2.FieldType   = pDomain1.FieldType;
                 pDomain2.DomainID    = pDomain1.DomainID;
                 pDomain2.MergePolicy = pDomain1.MergePolicy;
                 pDomain2.Name        = pDomain1.Name;
                 pDomain2.Owner       = pDomain1.Owner;
                 pDomain2.SplitPolicy = pDomain1.SplitPolicy;
                 pWsD2.AddDomain(pDomain2);
             }
             else//范围域
             {
                 IRangeDomain tempDomain1 = pDomain1 as IRangeDomain;
                 IRangeDomain tempDomain2 = new RangeDomainClass();
                 tempDomain2.MaxValue = tempDomain1.MaxValue;
                 tempDomain2.MinValue = tempDomain1.MinValue;
                 pDomain2             = tempDomain2 as IDomain;
                 pWsD2.AddDomain(pDomain2);
             }
         }
     }
     catch (System.Exception ex)
     {
         return;
     }
 }
Example #3
0
        public static IDomain AddDomain(IWorkspace workspace, IDomain domain)
        {
            if (domain == null)
            {
                return(null);
            }
            IWorkspaceDomains pWorkspaceDomains = workspace as IWorkspaceDomains;

            if (pWorkspaceDomains == null)
            {
                return(null);
            }
            IDomain pDomain = pWorkspaceDomains.DomainByName[domain.Name];

            if (pDomain != null)
            {
                return(pDomain);
            }
            if (domain.Type == esriDomainType.esriDTCodedValue)
            {
                ICodedValueDomain pCodedValueDomain       = new CodedValueDomainClass();
                ICodedValueDomain pOriginCodedValueDomain = domain as ICodedValueDomain;
                for (int i = 0; i < pOriginCodedValueDomain.CodeCount; i++)
                {
                    pCodedValueDomain.AddCode(pOriginCodedValueDomain.Value[i], pOriginCodedValueDomain.Name[i]);
                }
                pDomain = pCodedValueDomain as IDomain;
            }
            else
            {
                IRangeDomain pRangeDomain       = new RangeDomainClass();
                IRangeDomain pOriginRangeDomain = domain as IRangeDomain;
                pRangeDomain.MinValue = pOriginRangeDomain.MinValue;
                pRangeDomain.MaxValue = pOriginRangeDomain.MaxValue;
                pDomain = pRangeDomain as IDomain;
            }
            pDomain.Name        = domain.Name;
            pDomain.FieldType   = domain.FieldType;
            pDomain.Description = domain.Description;
            pDomain.SplitPolicy = esriSplitPolicyType.esriSPTDuplicate;
            pDomain.MergePolicy = esriMergePolicyType.esriMPTDefaultValue;
            pWorkspaceDomains.AddDomain(pDomain);
            return(pDomain);
        }
Example #4
0
        public void TestIsOwnedByConnectedUser()
        {
            IWorkspace workspace = WorkspaceUtils.OpenSDEWorkspace(
                "PROSUITE_DDX", DirectConnectDriver.SqlServer, @".\SQLEXPRESS");

            var domain = new CodedValueDomainClass
            {
                Name      = "Test",
                FieldType = esriFieldType.esriFieldTypeInteger,
                Owner     = "DBO"
            };

            Assert.True(DomainUtils.IsOwnedByConnectedUser(domain, workspace));

            workspace    = WorkspaceUtils.OpenPgdbWorkspace(_simpleGdbPath);
            domain.Owner = string.Empty;             // or null

            Assert.True(DomainUtils.IsOwnedByConnectedUser(domain, workspace));
        }
Example #5
0
        /// <summary>
        /// 创建属性域
        /// </summary>
        /// <param name="workspace">工作空间</param>
        /// <param name="strDomainName">属性域名称</param>
        /// <param name="dicDomainItems">属性域的项</param>
        public static void CreateDomain(this IWorkspace workspace, string strDomainName, Dictionary <string, string> dicDomainItems)
        {
            IWorkspaceDomains wsDomains       = (IWorkspaceDomains)workspace;
            ICodedValueDomain codeValueDomain = new CodedValueDomainClass();

            foreach (KeyValuePair <string, string> domainItem in dicDomainItems)
            {
                codeValueDomain.AddCode(domainItem.Key, domainItem.Value);
            }

            IDomain domain = (IDomain)codeValueDomain;

            domain.Name        = strDomainName;
            domain.FieldType   = esriFieldType.esriFieldTypeString;
            domain.SplitPolicy = esriSplitPolicyType.esriSPTDuplicate;
            domain.MergePolicy = esriMergePolicyType.esriMPTDefaultValue;

            wsDomains.AddDomain(domain);
        }
Example #6
0
        public static ICodedValueDomain CreateCodedValueDomainFromSubtypes(ISubtypes subtypes)
        {
            //  string methodName = MethodInfo.GetCurrentMethod().Name;
            ICodedValueDomain domain = null;
            if (subtypes != null)
            {
                IEnumSubtype subtype = subtypes.Subtypes;
                domain = new CodedValueDomainClass();

                subtype.Reset();
                int subtypeCode;
                string subtypeValue = subtype.Next(out subtypeCode);
                while (subtypeValue != null) //use null subtype.next returns bstr type.
                {
                    domain.AddCode(subtypeCode, subtypeValue);
                    subtypeValue = subtype.Next(out subtypeCode);
                }
            }
            //else
            //    _logger.LogFormat("{0}: Null subtypes parameter.", methodName, LogLevel.enumLogLevelWarn);

            return domain;
        }
Example #7
0
        public static ICodedValueDomain CreateCodedValueDomain(
            [NotNull] string name,
            esriFieldType fieldType,
            [CanBeNull] string description,
            esriSplitPolicyType splitPolicy,
            esriMergePolicyType mergePolicy,
            params CodedValue[] values)
        {
            var result = new CodedValueDomainClass
            {
                Name        = name,
                FieldType   = fieldType,
                Description = description,
                SplitPolicy = splitPolicy,
                MergePolicy = mergePolicy
            };

            foreach (CodedValue codedValue in values)
            {
                result.AddCode(codedValue.Value, codedValue.Name);
            }

            return(result);
        }
Example #8
0
        /// <summary>
        /// Creates vessel type coded domain.
        /// </summary>
        /// <param name="pWorkspace">FileGeodatabase workspace.</param>
        private void CreateTypeDomain(IWorkspace pWorkspace)
        {
            try
            {
                if (!(IsArcInfoLicense()))
                {
                    return;
                }

                IFeatureWorkspace pFWS   = (IFeatureWorkspace)pWorkspace;
                ITable            pTable = pFWS.OpenTable("Vessel");

                IWorkspaceDomains pWSD             = (IWorkspaceDomains)pWorkspace;
                ICodedValueDomain codedValueDomain = new CodedValueDomainClass();
                int i;

                //VESSEL TYPE DOMAIN
                // Value and name pairs.
                for (i = 0; i <= 9; i++)
                {
                    codedValueDomain.AddCode(i, "Not Available");
                }
                for (i = 10; i <= 19; i++)
                {
                    codedValueDomain.AddCode(i, "Reserved for future use");
                }
                for (i = 20; i <= 29; i++)
                {
                    codedValueDomain.AddCode(i, "WIG");
                }
                codedValueDomain.AddCode(30, "Fishing");
                codedValueDomain.AddCode(31, "Towing");
                codedValueDomain.AddCode(32, "Towing and length of the tow exceeds 200 m or breadth exceeds 25 m");
                codedValueDomain.AddCode(33, "Engaged in dredging or underwater operations");
                codedValueDomain.AddCode(34, "Engaged in diving operations");
                codedValueDomain.AddCode(35, "Engaged in military operations");
                codedValueDomain.AddCode(36, "Sailing");
                codedValueDomain.AddCode(37, "Pleasure craft");
                codedValueDomain.AddCode(38, "Reserved for future use");
                codedValueDomain.AddCode(39, "Reserved for future use");
                for (i = 40; i <= 49; i++)
                {
                    codedValueDomain.AddCode(i, "HSC");
                }
                codedValueDomain.AddCode(50, "Pilot vessel");
                codedValueDomain.AddCode(51, "Search and rescue vessels");
                codedValueDomain.AddCode(52, "Tugs");
                codedValueDomain.AddCode(53, "Port tenders");
                codedValueDomain.AddCode(54, "Vessels with anti-pollution facilities or equipment");
                codedValueDomain.AddCode(55, "Law enforcement vessels");
                codedValueDomain.AddCode(56, "Spare - for assignments to local vessels");
                codedValueDomain.AddCode(57, "Spare - for assignments to local vessels");
                codedValueDomain.AddCode(58, "Medical transports (as defined in the 1949 Geneva Conventions and Additional Protocols)");
                codedValueDomain.AddCode(59, "Ships according to RR Resolution No. 18 (Mob-83)");
                for (i = 60; i <= 69; i++)
                {
                    codedValueDomain.AddCode(i, "Passenger ships");
                }
                for (i = 70; i <= 79; i++)
                {
                    codedValueDomain.AddCode(i, "Cargo ships");
                }
                for (i = 80; i <= 89; i++)
                {
                    codedValueDomain.AddCode(i, "Tanker(s)");
                }
                for (i = 90; i <= 99; i++)
                {
                    codedValueDomain.AddCode(i, "Other types of ship");
                }
                for (i = 100; i <= 199; i++)
                {
                    codedValueDomain.AddCode(i, "Reserved, for regional use");
                }
                for (i = 200; i <= 255; i++)
                {
                    codedValueDomain.AddCode(i, "Reserved, for future use");
                }

                // The code to set the common properties for the new coded value domain.
                IDomain domain = (IDomain)codedValueDomain;
                domain.Name        = "VesselType";
                domain.FieldType   = esriFieldType.esriFieldTypeInteger;
                domain.SplitPolicy = esriSplitPolicyType.esriSPTDefaultValue;
                domain.MergePolicy = esriMergePolicyType.esriMPTDefaultValue;

                // Add the new domain to the workspace.
                pWSD.AddDomain(domain);

                //assign the domain to the vessel table VesselType field
                IFields pFields     = pTable.Fields;
                int     iFieldIndex = pTable.FindField("VesselType");
                IField  pField      = pFields.get_Field(iFieldIndex);

                // Check that the field and domain have the same field type.
                if (pField.Type == domain.FieldType)
                {
                    // Cast the feature class to the ISchemaLock and IClassSchemaEdit interfaces.
                    ISchemaLock      schemaLock      = (ISchemaLock)pTable;
                    IClassSchemaEdit classSchemaEdit = (IClassSchemaEdit)pTable;

                    // Attempt to get an exclusive schema lock.
                    try
                    {
                        // Lock the class and alter the domain.
                        schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);
                        classSchemaEdit.AlterDomain("VesselType", domain);
                    }
                    catch (Exception exc)
                    {
                        // Handle the exception in a way appropriate for the application.
                        MessageBox.Show(exc.Message);
                    }
                    finally
                    {
                        // Set the schema lock to be a shared lock.
                        schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "AIS_DataModel:CodedDomain:CreateTypeDomain");
            }
        }
Example #9
0
        /// <summary>
        /// Creates Broadcast feature class Status coded domain.
        /// </summary>
        /// <param name="pWorkspace">FileGeodatabase workspace.</param>
        private void CreateStatusDomain(IWorkspace pWorkspace)
        {
            try
            {
                if (!(IsArcInfoLicense()))
                {
                    return;
                }

                IFeatureWorkspace pFWS = (IFeatureWorkspace)pWorkspace;
                IFeatureClass     pFC  = pFWS.OpenFeatureClass("Broadcast");

                IWorkspaceDomains pWSD             = (IWorkspaceDomains)pWorkspace;
                ICodedValueDomain codedValueDomain = new CodedValueDomainClass();

                //VESSEL STATUS DOMAIN
                // Value and name pairs.
                codedValueDomain.AddCode(0, "Under way using engine");
                codedValueDomain.AddCode(1, "At anchor");
                codedValueDomain.AddCode(2, "Not under command");
                codedValueDomain.AddCode(3, "Restricted maneuverability");
                codedValueDomain.AddCode(4, "Constrained by her draught");
                codedValueDomain.AddCode(5, "Moored");
                codedValueDomain.AddCode(6, "Aground");
                codedValueDomain.AddCode(7, "Fishing");
                codedValueDomain.AddCode(8, "Under way sailing");
                codedValueDomain.AddCode(9, "Reserved for future amendment of navigational status for ships carrying DG, HS, or MP, or IMO hazard or pollutant category C, high speed craft (HSC)");
                codedValueDomain.AddCode(10, "Reserved for future amendment of navigational status for ships carrying dangerous goods (DG), harmful substances (HS) or marine pollutants (MP), or IMO hazard or pollutant category A, wing in grand (WIG)");
                codedValueDomain.AddCode(11, "Reserved for future use");
                codedValueDomain.AddCode(12, "Reserved for future use");
                codedValueDomain.AddCode(13, "Reserved for future use");
                codedValueDomain.AddCode(14, "AIS-START (active)");
                codedValueDomain.AddCode(15, "Not-Defined");


                // The code to set the common properties for the new coded value domain.
                IDomain domain = (IDomain)codedValueDomain;
                domain.Name        = "Status";
                domain.FieldType   = esriFieldType.esriFieldTypeInteger;
                domain.SplitPolicy = esriSplitPolicyType.esriSPTDefaultValue;
                domain.MergePolicy = esriMergePolicyType.esriMPTDefaultValue;

                // Add the new domain to the workspace.
                pWSD.AddDomain(domain);

                //assign the domain to the broadcast feature class status field
                IFields pFields     = pFC.Fields;
                int     iFieldIndex = pFC.FindField("Status");
                IField  pField      = pFields.get_Field(iFieldIndex);

                // Check that the field and domain have the same field type.
                if (pField.Type == domain.FieldType)
                {
                    // Cast the feature class to the ISchemaLock and IClassSchemaEdit interfaces.
                    ISchemaLock      schemaLock      = (ISchemaLock)pFC;
                    IClassSchemaEdit classSchemaEdit = (IClassSchemaEdit)pFC;

                    // Attempt to get an exclusive schema lock.
                    try
                    {
                        // Lock the class and alter the domain.
                        schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);
                        classSchemaEdit.AlterDomain("Status", domain);
                    }
                    catch (Exception exc)
                    {
                        // Handle the exception in a way appropriate for the application.
                        MessageBox.Show(exc.Message);
                    }
                    finally
                    {
                        // Set the schema lock to be a shared lock.
                        schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "AIS_DataModel:CodedDomain:CreateStatusDomain");
            }
        }
Example #10
0
        /// <summary>
        /// Creates Cargo type Voyage workspace.
        /// </summary>
        /// <param name="pWorkspace">FileGeodatabase workspace.</param>
        private void CreateCargoDomain(IWorkspace pWorkspace)
        {
            try
            {
                if (!(IsArcInfoLicense()))
                {
                    return;
                }

                IFeatureWorkspace pFWS   = (IFeatureWorkspace)pWorkspace;
                ITable            pTable = pFWS.OpenTable("Voyage");

                IWorkspaceDomains pWSD             = (IWorkspaceDomains)pWorkspace;
                ICodedValueDomain codedValueDomain = new CodedValueDomainClass();
                int i;

                //VESSEL CARGO DOMAIN
                // Value and name pairs.

                for (i = 0; i <= 9; i++)
                {
                    codedValueDomain.AddCode(i, "Not Available");
                }
                for (i = 10; i <= 19; i++)
                {
                    codedValueDomain.AddCode(i, "Reserved for future use");
                }

                for (i = 20; i <= 90; i += 10)
                {
                    codedValueDomain.AddCode(i, "Not Available");
                }

                for (i = 21; i <= 81; i += 20)
                {
                    codedValueDomain.AddCode(i, "Carrying DG, HS, or MP, IMO hazard or pollutant category A");
                }
                for (i = 22; i <= 82; i += 20)
                {
                    codedValueDomain.AddCode(i, "Carrying DG, HS, or MP, IMO hazard or pollutant category B");
                }
                for (i = 23; i <= 83; i += 20)
                {
                    codedValueDomain.AddCode(i, "Carrying DG, HS, or MP, IMO hazard or pollutant category C");
                }
                for (i = 24; i <= 84; i += 20)
                {
                    codedValueDomain.AddCode(i, "Carrying DG, HS, or MP, IMO hazard or pollutant category D");
                }
                for (i = 29; i <= 89; i += 20)
                {
                    codedValueDomain.AddCode(i, "No additional information");
                }

                for (i = 25; i <= 28; i++)
                {
                    codedValueDomain.AddCode(i, "Reserved for future use");
                }

                for (i = 31; i <= 39; i++)
                {
                    codedValueDomain.AddCode(i, "Not Available");
                }

                for (i = 45; i <= 48; i++)
                {
                    codedValueDomain.AddCode(i, "Reserved for future use");
                }

                for (i = 51; i <= 59; i++)
                {
                    codedValueDomain.AddCode(i, "Not Available");
                }

                for (i = 65; i <= 68; i++)
                {
                    codedValueDomain.AddCode(i, "Reserved for future use");
                }

                for (i = 71; i <= 91; i += 20)
                {
                    codedValueDomain.AddCode(i, "Carrying DG, HS, or MP, IMO hazard or pollutant category A");
                }
                for (i = 72; i <= 92; i += 20)
                {
                    codedValueDomain.AddCode(i, "Carrying DG, HS, or MP, IMO hazard or pollutant category B");
                }
                for (i = 73; i <= 93; i += 20)
                {
                    codedValueDomain.AddCode(i, "Carrying DG, HS, or MP, IMO hazard or pollutant category C");
                }
                for (i = 74; i <= 94; i += 20)
                {
                    codedValueDomain.AddCode(i, "Carrying DG, HS, or MP, IMO hazard or pollutant category D");
                }
                for (i = 79; i <= 99; i += 20)
                {
                    codedValueDomain.AddCode(i, "No additional information");
                }

                for (i = 75; i <= 78; i++)
                {
                    codedValueDomain.AddCode(i, "Reserved for future use");
                }

                for (i = 85; i <= 88; i++)
                {
                    codedValueDomain.AddCode(i, "Reserved for future use");
                }

                for (i = 95; i <= 98; i++)
                {
                    codedValueDomain.AddCode(i, "Reserved for future use");
                }

                for (i = 100; i <= 199; i++)
                {
                    codedValueDomain.AddCode(i, "Reserved, for regional use");
                }
                for (i = 200; i <= 255; i++)
                {
                    codedValueDomain.AddCode(i, "Reserved, for future use");
                }

                // The code to set the common properties for the new coded value domain.
                IDomain domain = (IDomain)codedValueDomain;
                domain.Name        = "Cargo";
                domain.FieldType   = esriFieldType.esriFieldTypeInteger;
                domain.SplitPolicy = esriSplitPolicyType.esriSPTDefaultValue;
                domain.MergePolicy = esriMergePolicyType.esriMPTDefaultValue;

                // Add the new domain to the workspace.
                pWSD.AddDomain(domain);

                //assign the domain to the voyage table cargo field
                IFields pFields     = pTable.Fields;
                int     iFieldIndex = pTable.FindField("Cargo");
                IField  pField      = pFields.get_Field(iFieldIndex);

                // Check that the field and domain have the same field type.
                if (pField.Type == domain.FieldType)
                {
                    // Cast the feature class to the ISchemaLock and IClassSchemaEdit interfaces.
                    ISchemaLock      schemaLock      = (ISchemaLock)pTable;
                    IClassSchemaEdit classSchemaEdit = (IClassSchemaEdit)pTable;

                    // Attempt to get an exclusive schema lock.
                    try
                    {
                        // Lock the class and alter the domain.
                        schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);
                        classSchemaEdit.AlterDomain("Cargo", domain);
                    }
                    catch (Exception exc)
                    {
                        // Handle the exception in a way appropriate for the application.
                        MessageBox.Show(exc.Message);
                    }
                    finally
                    {
                        // Set the schema lock to be a shared lock.
                        schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "AIS_DataModel:CodedDomain:CreateCargoDomain");
            }
        }
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            IFeatureClass osmPointFeatureClass = null;
            IFeatureClass osmLineFeatureClass = null;
            IFeatureClass osmPolygonFeatureClass = null;
            OSMToolHelper osmToolHelper = null;

            try
            {
                DateTime syncTime = DateTime.Now;

                IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();
                osmToolHelper = new OSMToolHelper();

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

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

                // ensure that the specified file does exist
                bool osmFileExists = false;

                try
                {
                    osmFileExists = System.IO.File.Exists(osmFileLocationString.GetAsText());
                }
                catch (Exception ex)
                {
                    message.AddError(120029, String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_problemaccessingfile"), ex.Message));
                    return;
                }

                if (osmFileExists == false)
                {
                    message.AddError(120030, String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_osmfiledoesnotexist"), osmFileLocationString.GetAsText()));
                    return;
                }

                IGPParameter conserveMemoryParameter = paramvalues.get_Element(in_conserveMemoryNumber) as IGPParameter;
                IGPBoolean conserveMemoryGPValue = gpUtilities3.UnpackGPValue(conserveMemoryParameter) as IGPBoolean;

                if (conserveMemoryGPValue == null)
                {
                    message.AddError(120031, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), conserveMemoryParameter.Name));
                    return;
                }

                message.AddMessage(resourceManager.GetString("GPTools_OSMGPFileReader_countingNodes"));
                long nodeCapacity = 0;
                long wayCapacity = 0;
                long relationCapacity = 0;

                Dictionary<esriGeometryType, List<string>> attributeTags = new Dictionary<esriGeometryType, List<string>>();

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

                List<String> tagstoExtract = null;

                if (tagCollectionGPValue.Count > 0)
                {
                    tagstoExtract = new List<string>();

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

                        if (nameOfTag.ToUpper().Equals("ALL"))
                        {
                            tagstoExtract = new List<string>();
                            break;
                        }
                        else
                        {
                            tagstoExtract.Add(nameOfTag);
                        }
                    }
                }

                // if there is an "ALL" keyword then we scan for all tags, otherwise we only add the desired tags to the feature classes and do a 'quick'
                // count scan

                if (tagstoExtract != null)
                {
                    if (tagstoExtract.Count > 0)
                    {
                        // if the number of tags is > 0 then do a simple feature count and take name tags names from the gp value
                        osmToolHelper.countOSMStuff(osmFileLocationString.GetAsText(), ref nodeCapacity, ref wayCapacity, ref relationCapacity, ref TrackCancel);
                        attributeTags.Add(esriGeometryType.esriGeometryPoint, tagstoExtract);
                        attributeTags.Add(esriGeometryType.esriGeometryPolyline, tagstoExtract);
                        attributeTags.Add(esriGeometryType.esriGeometryPolygon, tagstoExtract);
                    }
                    else
                    {
                        // the count should be zero if we encountered the "ALL" keyword 
                        // in this case count the features and create a list of unique tags
                        attributeTags = osmToolHelper.countOSMCapacityAndTags(osmFileLocationString.GetAsText(), ref nodeCapacity, ref wayCapacity, ref relationCapacity, ref TrackCancel);
                    }
                }
                else
                {
                    // no tags we defined, hence we do a simple count and create an empty list indicating that no additional fields
                    // need to be created
                    osmToolHelper.countOSMStuff(osmFileLocationString.GetAsText(), ref nodeCapacity, ref wayCapacity, ref relationCapacity, ref TrackCancel);
                    attributeTags.Add(esriGeometryType.esriGeometryPoint, new List<string>());
                    attributeTags.Add(esriGeometryType.esriGeometryPolyline, new List<string>());
                    attributeTags.Add(esriGeometryType.esriGeometryPolygon, new List<string>());
                }

                if (nodeCapacity == 0 && wayCapacity == 0 && relationCapacity == 0)
                {
                    return;
                }

                if (conserveMemoryGPValue.Value == false)
                {
                    osmNodeDictionary = new Dictionary<string, OSMToolHelper.simplePointRef>(Convert.ToInt32(nodeCapacity));
                }

                message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_countedElements"), nodeCapacity, wayCapacity, relationCapacity));

                // prepare the feature dataset and classes
                IGPParameter targetDatasetParameter = paramvalues.get_Element(out_targetDatasetNumber) as IGPParameter;
                IGPValue targetDatasetGPValue = gpUtilities3.UnpackGPValue(targetDatasetParameter);
                IDEDataset2 targetDEDataset2 = targetDatasetGPValue as IDEDataset2;

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

                string targetDatasetName = ((IGPValue)targetDEDataset2).GetAsText();

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

                IName parentName = null;

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


                // test if the feature classes already exists, 
                // if they do and the environments settings are such that an overwrite is not allowed we need to abort at this point
                IGeoProcessorSettings gpSettings = (IGeoProcessorSettings)envMgr;
                if (gpSettings.OverwriteOutput == true)
                {
                }
                else
                {
                    if (gpUtilities3.Exists((IGPValue)targetDEDataset2) == true)
                    {
                        message.AddError(120032, String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_basenamealreadyexists"), targetDataElement.Name));
                        return;
                    }
                }

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

                // Reading the XML document requires a FileStream.
                System.Xml.XmlTextReader reader = null;
                string xmlDomainFile = "";
                m_editorConfigurationSettings.TryGetValue("osmdomainsfilepath", out xmlDomainFile);

                if (System.IO.File.Exists(xmlDomainFile))
                {
                    reader = new System.Xml.XmlTextReader(xmlDomainFile);
                }

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

                System.Xml.Serialization.XmlSerializer domainSerializer = null;

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

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

                Dictionary<string, IDomain> codedValueDomains = new Dictionary<string, IDomain>();

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

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

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

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

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

                IWorkspaceDomains workspaceDomain = null;
                IFeatureWorkspace featureWorkspace = null;
                // if the target dataset already exists we can go ahead and QI to it directly
                if (targetDataset != null)
                {
                    workspaceDomain = targetDataset.Workspace as IWorkspaceDomains;
                    featureWorkspace = targetDataset.Workspace as IFeatureWorkspace;
                }
                else
                {
                    // in case it doesn't exist yet we will open the parent (the workspace - geodatabase- itself) and 
                    // use it as a reference to create the feature dataset and the feature classes in it.
                    IWorkspace newWorkspace = ((IName)parentName).Open() as IWorkspace;
                    workspaceDomain = newWorkspace as IWorkspaceDomains;
                    featureWorkspace = newWorkspace as IFeatureWorkspace;
                }

                foreach (var domain in codedValueDomains.Values)
                {
                    IDomain testDomain = null;
                    try
                    {
                        testDomain = workspaceDomain.get_DomainByName(domain.Name);
                    }
                    catch { }

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

                // this determines the spatial reference as defined from the gp environment settings and the initial wgs84 SR
                ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass() as ISpatialReferenceFactory;
                ISpatialReference wgs84 = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984) as ISpatialReference;

                ISpatialReference downloadSpatialReference = gpUtilities3.GetGPSpRefEnv(envMgr, wgs84, null, 0, 0, 0, 0, null);

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

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

                string storageKeyword = String.Empty;

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

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


                downloadSpatialReference = ((IGeoDataset)targetFeatureDataset).SpatialReference;

                string metadataAbstract = resourceManager.GetString("GPTools_OSMGPFileReader_metadata_abstract");
                string metadataPurpose = resourceManager.GetString("GPTools_OSMGPFileReader_metadata_purpose");

                // assign the custom class extension for use with the OSM feature inspector
                UID osmClassUID = new UIDClass();
                osmClassUID.Value = "{65CA4847-8661-45eb-8E1E-B2985CA17C78}";

                // points
                try
                {
                    osmPointFeatureClass = osmToolHelper.CreatePointFeatureClass((IWorkspace2)featureWorkspace, targetFeatureDataset, targetDataElement.Name + "_osm_pt", null, null, null, storageKeyword, availableDomains, metadataAbstract, metadataPurpose, attributeTags[esriGeometryType.esriGeometryPoint]);
                }
                catch (Exception ex)
                {
                    message.AddError(120035, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message));
                    return;
                }

                if (osmPointFeatureClass == null)
                {
                    return;
                }

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

                int osmPointIDFieldIndex = osmPointFeatureClass.FindField("OSMID");
                Dictionary<string, int> osmPointDomainAttributeFieldIndices = new Dictionary<string, int>();
                foreach (var domains in availableDomains.domain)
                {
                    int currentFieldIndex = osmPointFeatureClass.FindField(domains.name);

                    if (currentFieldIndex != -1)
                    {
                        osmPointDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex);
                    }
                }
                int tagCollectionPointFieldIndex = osmPointFeatureClass.FindField("osmTags");
                int osmUserPointFieldIndex = osmPointFeatureClass.FindField("osmuser");
                int osmUIDPointFieldIndex = osmPointFeatureClass.FindField("osmuid");
                int osmVisiblePointFieldIndex = osmPointFeatureClass.FindField("osmvisible");
                int osmVersionPointFieldIndex = osmPointFeatureClass.FindField("osmversion");
                int osmChangesetPointFieldIndex = osmPointFeatureClass.FindField("osmchangeset");
                int osmTimeStampPointFieldIndex = osmPointFeatureClass.FindField("osmtimestamp");
                int osmMemberOfPointFieldIndex = osmPointFeatureClass.FindField("osmMemberOf");
                int osmSupportingElementPointFieldIndex = osmPointFeatureClass.FindField("osmSupportingElement");
                int osmWayRefCountFieldIndex = osmPointFeatureClass.FindField("wayRefCount");


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

                if (osmLineFeatureClass == null)
                {
                    return;
                }

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

                int osmLineIDFieldIndex = osmLineFeatureClass.FindField("OSMID");
                Dictionary<string, int> osmLineDomainAttributeFieldIndices = new Dictionary<string, int>();
                foreach (var domains in availableDomains.domain)
                {
                    int currentFieldIndex = osmLineFeatureClass.FindField(domains.name);

                    if (currentFieldIndex != -1)
                    {
                        osmLineDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex);
                    }
                }
                int tagCollectionPolylineFieldIndex = osmLineFeatureClass.FindField("osmTags");
                int osmUserPolylineFieldIndex = osmLineFeatureClass.FindField("osmuser");
                int osmUIDPolylineFieldIndex = osmLineFeatureClass.FindField("osmuid");
                int osmVisiblePolylineFieldIndex = osmLineFeatureClass.FindField("osmvisible");
                int osmVersionPolylineFieldIndex = osmLineFeatureClass.FindField("osmversion");
                int osmChangesetPolylineFieldIndex = osmLineFeatureClass.FindField("osmchangeset");
                int osmTimeStampPolylineFieldIndex = osmLineFeatureClass.FindField("osmtimestamp");
                int osmMemberOfPolylineFieldIndex = osmLineFeatureClass.FindField("osmMemberOf");
                int osmMembersPolylineFieldIndex = osmLineFeatureClass.FindField("osmMembers");
                int osmSupportingElementPolylineFieldIndex = osmLineFeatureClass.FindField("osmSupportingElement");


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

                if (osmPolygonFeatureClass == null)
                {
                    return;
                }

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

                int osmPolygonIDFieldIndex = osmPolygonFeatureClass.FindField("OSMID");
                Dictionary<string, int> osmPolygonDomainAttributeFieldIndices = new Dictionary<string, int>();
                foreach (var domains in availableDomains.domain)
                {
                    int currentFieldIndex = osmPolygonFeatureClass.FindField(domains.name);

                    if (currentFieldIndex != -1)
                    {
                        osmPolygonDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex);
                    }
                }
                int tagCollectionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmTags");
                int osmUserPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuser");
                int osmUIDPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuid");
                int osmVisiblePolygonFieldIndex = osmPolygonFeatureClass.FindField("osmvisible");
                int osmVersionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmversion");
                int osmChangesetPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmchangeset");
                int osmTimeStampPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmtimestamp");
                int osmMemberOfPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMemberOf");
                int osmMembersPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMembers");
                int osmSupportingElementPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmSupportingElement");


                // relation table
                ITable relationTable = null;

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

                if (relationTable == null)
                {
                    return;
                }

                int osmRelationIDFieldIndex = relationTable.FindField("OSMID");
                int tagCollectionRelationFieldIndex = relationTable.FindField("osmTags");
                int osmUserRelationFieldIndex = relationTable.FindField("osmuser");
                int osmUIDRelationFieldIndex = relationTable.FindField("osmuid");
                int osmVisibleRelationFieldIndex = relationTable.FindField("osmvisible");
                int osmVersionRelationFieldIndex = relationTable.FindField("osmversion");
                int osmChangesetRelationFieldIndex = relationTable.FindField("osmchangeset");
                int osmTimeStampRelationFieldIndex = relationTable.FindField("osmtimestamp");
                int osmMemberOfRelationFieldIndex = relationTable.FindField("osmMemberOf");
                int osmMembersRelationFieldIndex = relationTable.FindField("osmMembers");
                int osmSupportingElementRelationFieldIndex = relationTable.FindField("osmSupportingElement");

                // revision table 
                ITable revisionTable = null;

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

                if (revisionTable == null)
                {
                    return;
                }


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

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

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

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

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

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

                bool fastLoad = false;

                //// check for user interruption
                //if (TrackCancel.Continue() == false)
                //{
                //    message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
                //    return;
                //}

                //IFeatureCursor deleteCursor = null;
                //using (ComReleaser comReleaser = new ComReleaser())
                //{
                //    // let's make sure that we clean out any old data that might have existed in the feature classes
                //    deleteCursor = osmPointFeatureClass.Update(null, false);
                //    comReleaser.ManageLifetime(deleteCursor);

                //    for (IFeature feature = deleteCursor.NextFeature(); feature != null; feature = deleteCursor.NextFeature())
                //    {
                //        feature.Delete();

                //        // check for user interruption
                //        if (TrackCancel.Continue() == false)
                //        {
                //            message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
                //            return;
                //        }

                //    }
                //}

                //using (ComReleaser comReleaser = new ComReleaser())
                //{
                //    deleteCursor = osmLineFeatureClass.Update(null, false);
                //    comReleaser.ManageLifetime(deleteCursor);

                //    for (IFeature feature = deleteCursor.NextFeature(); feature != null; feature = deleteCursor.NextFeature())
                //    {
                //        feature.Delete();

                //        // check for user interruption
                //        if (TrackCancel.Continue() == false)
                //        {
                //            message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
                //            return;
                //        }
                //    }
                //}

                //using (ComReleaser comReleaser = new ComReleaser())
                //{
                //    deleteCursor = osmPolygonFeatureClass.Update(null, false);
                //    comReleaser.ManageLifetime(deleteCursor);

                //    for (IFeature feature = deleteCursor.NextFeature(); feature != null; feature = deleteCursor.NextFeature())
                //    {
                //        feature.Delete();

                //        // check for user interruption
                //        if (TrackCancel.Continue() == false)
                //        {
                //            message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
                //            return;
                //        }
                //    }
                //}

                //ICursor tableCursor = null;
                //using (ComReleaser comReleaser = new ComReleaser())
                //{
                //    tableCursor = relationTable.Update(null, false);
                //    comReleaser.ManageLifetime(tableCursor);

                //    for (IRow row = tableCursor.NextRow(); row != null; row = tableCursor.NextRow())
                //    {
                //        row.Delete();

                //        // check for user interruption
                //        if (TrackCancel.Continue() == false)
                //        {
                //            message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
                //            return;
                //        }
                //    }
                //}

                //using (ComReleaser comReleaser = new ComReleaser())
                //{
                //    tableCursor = revisionTable.Update(null, false);
                //    comReleaser.ManageLifetime(tableCursor);

                //    for (IRow row = tableCursor.NextRow(); row != null; row = tableCursor.NextRow())
                //    {
                //        row.Delete();

                //        // check for user interruption
                //        if (TrackCancel.Continue() == false)
                //        {
                //            message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
                //            return;
                //        }
                //    }
                //}

                // define variables helping to invoke core tools for data management
                IGeoProcessorResult2 gpResults2 = null;

                IGeoProcessor2 geoProcessor = new GeoProcessorClass();

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


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

                #region load ways
                List<string> missingWays = osmToolHelper.loadOSMWays(osmFileLocationString.GetAsText(), ref TrackCancel, ref message, targetDatasetGPValue, osmPointFeatureClass, osmLineFeatureClass, osmPolygonFeatureClass, conserveMemoryGPValue.Value, fastLoad, Convert.ToInt32(wayCapacity), ref osmNodeDictionary, featureWorkspace, downloadSpatialReference, availableDomains, false);
                #endregion

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

                #region for local geodatabases enforce spatial integrity

                bool storedOriginalLocal = geoProcessor.AddOutputsToMap;
                geoProcessor.AddOutputsToMap = false;

                if (osmLineFeatureClass != null)
                {
                    if (((IDataset)osmLineFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace)
                    {
                        gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3;

                        IGPParameter outLinesParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter;
                        IGPValue lineFeatureClass = gpUtilities3.UnpackGPValue(outLinesParameter);

                        DataManagementTools.RepairGeometry repairlineGeometry = new DataManagementTools.RepairGeometry(osmLineFeatureClass);

                        IVariantArray repairGeometryParameterArray = new VarArrayClass();
                        repairGeometryParameterArray.Add(lineFeatureClass.GetAsText());
                        repairGeometryParameterArray.Add("DELETE_NULL");

                        gpResults2 = geoProcessor.Execute(repairlineGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2;
                        message.AddMessages(gpResults2.GetResultMessages());

                        ComReleaser.ReleaseCOMObject(gpUtilities3);
                    }
                }

                if (osmPolygonFeatureClass != null)
                {
                    if (((IDataset)osmPolygonFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace)
                    {
                        gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3;

                        IGPParameter outPolygonParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter;
                        IGPValue polygonFeatureClass = gpUtilities3.UnpackGPValue(outPolygonParameter);

                        DataManagementTools.RepairGeometry repairpolygonGeometry = new DataManagementTools.RepairGeometry(osmPolygonFeatureClass);

                        IVariantArray repairGeometryParameterArray = new VarArrayClass();
                        repairGeometryParameterArray.Add(polygonFeatureClass.GetAsText());
                        repairGeometryParameterArray.Add("DELETE_NULL");

                        gpResults2 = geoProcessor.Execute(repairpolygonGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2;
                        message.AddMessages(gpResults2.GetResultMessages());

                        ComReleaser.ReleaseCOMObject(gpUtilities3);
                    }
                }

                geoProcessor.AddOutputsToMap = storedOriginalLocal;

                #endregion


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

                #region load relations
                List<string> missingRelations = osmToolHelper.loadOSMRelations(osmFileLocationString.GetAsText(), ref TrackCancel, ref message, targetDatasetGPValue, osmPointFeatureClass, osmLineFeatureClass, osmPolygonFeatureClass, Convert.ToInt32(relationCapacity), relationTable, availableDomains, fastLoad, false);
                #endregion

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

                //storedOriginalLocal = geoProcessor.AddOutputsToMap;
                //try
                //{
                //    geoProcessor.AddOutputsToMap = false;

                //    // add indexes for revisions
                //    //IGPValue revisionTableGPValue = gpUtilities3.MakeGPValueFromObject(revisionTable);
                //    string revisionTableString = targetDatasetGPValue.GetAsText() + System.IO.Path.DirectorySeparatorChar + ((IDataset)revisionTable).BrowseName;
                //    IVariantArray parameterArrary2 = osmToolHelper.CreateAddIndexParameterArray(revisionTableString, "osmoldid;osmnewid", "osmID_IDX", "", "");
                //    gpResults2 = geoProcessor.Execute("AddIndex_management", parameterArrary2, TrackCancel) as IGeoProcessorResult2;

                //    message.AddMessages(gpResults2.GetResultMessages());
                //}
                //catch (Exception ex)
                //{
                //    message.AddWarning(ex.Message);
                //}
                //finally
                //{
                //    geoProcessor.AddOutputsToMap = storedOriginalLocal;
                //}


                #region update the references counts and member lists for nodes

                message.AddMessage(resourceManager.GetString("GPTools_OSMGPFileReader_updatereferences"));
                IFeatureCursor pointUpdateCursor = null;

                IQueryFilter pointQueryFilter = new QueryFilterClass();

                // adjust of number of all other reference counter from 0 to 1
                if (conserveMemoryGPValue.Value == true)
                {
                    pointQueryFilter.WhereClause = osmPointFeatureClass.SqlIdentifier("wayRefCount") + " = 0";
                    pointQueryFilter.SubFields = osmPointFeatureClass.OIDFieldName + ",wayRefCount";
                }

                using (SchemaLockManager ptLockManager = new SchemaLockManager(osmPointFeatureClass as ITable))
                {
                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        int updateCount = 0;
                        if (conserveMemoryGPValue.Value == true)
                        {
                            pointUpdateCursor = osmPointFeatureClass.Update(pointQueryFilter, false);
                            updateCount = ((ITable)osmPointFeatureClass).RowCount(pointQueryFilter);
                        }
                        else
                        {
                            pointUpdateCursor = osmPointFeatureClass.Update(null, false);
                            updateCount = ((ITable)osmPointFeatureClass).RowCount(null);
                        }

                        IStepProgressor stepProgressor = TrackCancel as IStepProgressor;

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

                        comReleaser.ManageLifetime(pointUpdateCursor);

                        IFeature pointFeature = pointUpdateCursor.NextFeature();

                        int positionCounter = 0;
                        while (pointFeature != null)
                        {
                            positionCounter++;
                            string nodeID = Convert.ToString(pointFeature.get_Value(osmPointIDFieldIndex));

                            if (conserveMemoryGPValue.Value == false)
                            {
                                // let get the reference counter from the internal node dictionary
                                if (osmNodeDictionary[nodeID].RefCounter == 0)
                                {
                                    pointFeature.set_Value(osmWayRefCountFieldIndex, 1);
                                }
                                else
                                {
                                    pointFeature.set_Value(osmWayRefCountFieldIndex, osmNodeDictionary[nodeID].RefCounter);
                                }
                            }
                            else
                            {
                                // in the case of memory conservation let's go change the 0s to 1s
                                pointFeature.set_Value(osmWayRefCountFieldIndex, 1);
                            }

                            pointUpdateCursor.UpdateFeature(pointFeature);

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

                            pointFeature = pointUpdateCursor.NextFeature();

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

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

                        Marshal.ReleaseComObject(pointQueryFilter);
                    }
                }

                #endregion

                if (osmNodeDictionary != null)
                {
                    // clear outstanding resources potentially holding points
                    osmNodeDictionary = null;
                    System.GC.Collect(2, GCCollectionMode.Forced);
                }

                if (missingRelations.Count > 0)
                {
                    missingRelations.Clear();
                    missingRelations = null;
                }

                if (missingWays.Count > 0)
                {
                    missingWays.Clear();
                    missingWays = null;
                }

                SyncState.StoreLastSyncTime(targetDatasetName, syncTime);

                gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3;

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

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

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

                ComReleaser.ReleaseCOMObject(relationTable);
                ComReleaser.ReleaseCOMObject(revisionTable);

                ComReleaser.ReleaseCOMObject(targetFeatureDataset);
                ComReleaser.ReleaseCOMObject(featureWorkspace);

                ComReleaser.ReleaseCOMObject(osmFileLocationString);
                ComReleaser.ReleaseCOMObject(conserveMemoryGPValue);
                ComReleaser.ReleaseCOMObject(targetDataset);

                gpUtilities3.ReleaseInternals();
                ComReleaser.ReleaseCOMObject(gpUtilities3);
            }
            catch (Exception ex)
            {
                message.AddError(120055, ex.Message);
                message.AddError(120055, ex.StackTrace);
            }
            finally
            {
                try
                {
                    // TE -- 1/7/2015
                    // this is a 'breaking' change as the default loader won't no longer enable the edit extension
                    // the reasoning here is that most users would like the OSM in a 'read-only' fashion, and don't need to track 
                    // changes to be properly transmitted back to the OSM server
                    //if (osmPointFeatureClass != null)
                    //{
                    //    osmPointFeatureClass.ApplyOSMClassExtension();
                    //    ComReleaser.ReleaseCOMObject(osmPointFeatureClass);
                    //}

                    //if (osmLineFeatureClass != null)
                    //{
                    //    osmLineFeatureClass.ApplyOSMClassExtension();
                    //    ComReleaser.ReleaseCOMObject(osmLineFeatureClass);
                    //}

                    //if (osmPolygonFeatureClass != null)
                    //{
                    //    osmPolygonFeatureClass.ApplyOSMClassExtension();
                    //    ComReleaser.ReleaseCOMObject(osmPolygonFeatureClass);
                    //}

                    osmToolHelper = null;

                    System.GC.Collect();
                    System.GC.WaitForPendingFinalizers();
                }
                catch (Exception ex)
                {
                    message.AddError(120056, ex.ToString());
                }
            }
        }
Example #12
0
        /// <summary>
        /// Adds coded domain values to the Voyage Tracks feature class.
        /// </summary>
        /// <param name="sWorkspace"></param>
        /// <param name="sLayerName"></param>
        private void AddCodedDomain(string sWorkspace, string sLayerName)
        {
            try
            {
                IWorkspace    pWorkspace = clsStatic.OpenWorkspace(sWorkspace);
                IFeatureLayer pFL        = clsStatic.GetFeatureLayer(pWorkspace, sLayerName); // pFWS.OpenTable("Voyage");
                ITable        pTable     = (ITable)pFL.FeatureClass;

                IWorkspaceDomains pWSD             = (IWorkspaceDomains)pWorkspace;
                ICodedValueDomain codedValueDomain = new CodedValueDomainClass();
                IEnumDomain       pDomains         = pWSD.Domains;
                pDomains.Reset();
                IDomain pDomain = pDomains.Next();
                while (pDomain != null)
                {
                    if (pDomain.Name == "Cargo")
                    {
                        break;
                    }
                }
                if (pDomain == null)
                {
                    if (clsStatic.GetArcLicense())
                    {
                        //VESSEL CARGO DOMAIN
                        // Value and name pairs.
                        for (int i = 0; i <= 9; i++)
                        {
                            codedValueDomain.AddCode(i, "Not Available");
                        }
                        for (int i = 10; i <= 19; i++)
                        {
                            codedValueDomain.AddCode(i, "Reserved for future use");
                        }

                        for (int i = 20; i <= 90; i += 10)
                        {
                            codedValueDomain.AddCode(i, "Not Available");
                        }

                        for (int i = 21; i <= 81; i += 20)
                        {
                            codedValueDomain.AddCode(i, "Carrying DG, HS, or MP, IMO hazard or pollutant category A");
                        }
                        for (int i = 22; i <= 82; i += 20)
                        {
                            codedValueDomain.AddCode(i, "Carrying DG, HS, or MP, IMO hazard or pollutant category B");
                        }
                        for (int i = 23; i <= 83; i += 20)
                        {
                            codedValueDomain.AddCode(i, "Carrying DG, HS, or MP, IMO hazard or pollutant category C");
                        }
                        for (int i = 24; i <= 84; i += 20)
                        {
                            codedValueDomain.AddCode(i, "Carrying DG, HS, or MP, IMO hazard or pollutant category D");
                        }
                        for (int i = 29; i <= 89; i += 20)
                        {
                            codedValueDomain.AddCode(i, "No additional information");
                        }

                        for (int i = 25; i <= 28; i++)
                        {
                            codedValueDomain.AddCode(i, "Reserved for future use");
                        }

                        for (int i = 31; i <= 39; i++)
                        {
                            codedValueDomain.AddCode(i, "Not Available");
                        }

                        for (int i = 45; i <= 48; i++)
                        {
                            codedValueDomain.AddCode(i, "Reserved for future use");
                        }

                        for (int i = 51; i <= 59; i++)
                        {
                            codedValueDomain.AddCode(i, "Not Available");
                        }

                        for (int i = 65; i <= 68; i++)
                        {
                            codedValueDomain.AddCode(i, "Reserved for future use");
                        }

                        for (int i = 71; i <= 91; i += 20)
                        {
                            codedValueDomain.AddCode(i, "Carrying DG, HS, or MP, IMO hazard or pollutant category A");
                        }
                        for (int i = 72; i <= 92; i += 20)
                        {
                            codedValueDomain.AddCode(i, "Carrying DG, HS, or MP, IMO hazard or pollutant category B");
                        }
                        for (int i = 73; i <= 93; i += 20)
                        {
                            codedValueDomain.AddCode(i, "Carrying DG, HS, or MP, IMO hazard or pollutant category C");
                        }
                        for (int i = 74; i <= 94; i += 20)
                        {
                            codedValueDomain.AddCode(i, "Carrying DG, HS, or MP, IMO hazard or pollutant category D");
                        }
                        for (int i = 79; i <= 99; i += 20)
                        {
                            codedValueDomain.AddCode(i, "No additional information");
                        }

                        for (int i = 75; i <= 78; i++)
                        {
                            codedValueDomain.AddCode(i, "Reserved for future use");
                        }

                        for (int i = 85; i <= 88; i++)
                        {
                            codedValueDomain.AddCode(i, "Reserved for future use");
                        }

                        for (int i = 95; i <= 98; i++)
                        {
                            codedValueDomain.AddCode(i, "Reserved for future use");
                        }

                        for (int i = 100; i <= 199; i++)
                        {
                            codedValueDomain.AddCode(i, "Reserved, for regional use");
                        }
                        for (int i = 200; i <= 255; i++)
                        {
                            codedValueDomain.AddCode(i, "Reserved, for future use");
                        }

                        // The code to set the common properties for the new coded value domain.
                        pDomain             = (IDomain)codedValueDomain;
                        pDomain.Name        = "Cargo";
                        pDomain.FieldType   = esriFieldType.esriFieldTypeInteger;
                        pDomain.SplitPolicy = esriSplitPolicyType.esriSPTDefaultValue;
                        pDomain.MergePolicy = esriMergePolicyType.esriMPTDefaultValue;
                        // Add the new domain to the workspace.
                        pWSD.AddDomain(pDomain);
                    }
                }
                //assign the domain to the voyage table cargo field
                IFields pFields     = pTable.Fields;
                int     iFieldIndex = pTable.FindField("Cargo");
                IField  pField      = pFields.get_Field(iFieldIndex);

                // Check that the field and domain have the same field type.
                if (pField.Type == pDomain.FieldType)
                {
                    // Cast the feature class to the ISchemaLock and IClassSchemaEdit interfaces.
                    ISchemaLock      schemaLock      = (ISchemaLock)pTable;
                    IClassSchemaEdit classSchemaEdit = (IClassSchemaEdit)pTable;

                    // Attempt to get an exclusive schema lock.
                    try
                    {
                        // Lock the class and alter the domain.
                        schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);
                        classSchemaEdit.AlterDomain("Cargo", pDomain);
                    }
                    catch (Exception ex)
                    {
                        // Handle the exception in a way appropriate for the application.
                        clsStatic.ShowErrorMessage(ex.ToString());
                    }
                    finally
                    {
                        // Set the schema lock to be a shared lock.
                        schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
                    }
                }
            }
            catch (Exception ex)
            {
                clsStatic.ShowErrorMessage(ex.ToString());
            }
        }
Example #13
0
            public void ChangeDomainType(esriDomainType esriDomainType_0)
            {
                IDomain domain;

                if (!this.bool_0)
                {
                    if (this.idomain_1.Type != esriDomainType_0)
                    {
                        if (this.idomain_0 == null)
                        {
                            this.idomain_0 = this.idomain_1;
                        }
                        domain = null;
                        if (esriDomainType_0 == esriDomainType.esriDTCodedValue)
                        {
                            domain = new CodedValueDomainClass
                            {
                                FieldType = this.idomain_1.FieldType
                            };
                        }
                        else if (esriDomainType_0 == esriDomainType.esriDTRange)
                        {
                            domain = new RangeDomainClass();
                            if (this.idomain_1.FieldType == esriFieldType.esriFieldTypeString)
                            {
                                domain.FieldType = esriFieldType.esriFieldTypeInteger;
                            }
                            else
                            {
                                domain.FieldType = this.idomain_1.FieldType;
                            }
                        }
                        if (domain != null)
                        {
                            domain.Description = this.idomain_1.Description;
                            domain.Name        = this.idomain_1.Name;
                            domain.SplitPolicy = this.idomain_1.SplitPolicy;
                            domain.MergePolicy = this.idomain_1.MergePolicy;
                        }
                        this.idomain_1 = domain;
                        this.bool_2    = true;
                    }
                }
                else if (this.idomain_1.Type != esriDomainType_0)
                {
                    domain = null;
                    if (esriDomainType_0 == esriDomainType.esriDTCodedValue)
                    {
                        domain = new CodedValueDomainClass
                        {
                            FieldType = this.idomain_1.FieldType
                        };
                    }
                    else if (esriDomainType_0 == esriDomainType.esriDTRange)
                    {
                        domain = new RangeDomainClass();
                        if (this.idomain_1.FieldType == esriFieldType.esriFieldTypeString)
                        {
                            domain.FieldType = esriFieldType.esriFieldTypeInteger;
                        }
                        else
                        {
                            domain.FieldType = this.idomain_1.FieldType;
                        }
                    }
                    if (domain != null)
                    {
                        domain.Description = this.idomain_1.Description;
                        domain.Name        = this.idomain_1.Name;
                        domain.SplitPolicy = this.idomain_1.SplitPolicy;
                        domain.MergePolicy = this.idomain_1.MergePolicy;
                    }
                    this.idomain_1 = domain;
                }
            }
Example #14
0
        protected override void OnClick()
        {
            m_pApp = (IApplication)ArcMap.Application;
            if (m_pApp == null)
            {
                //if the app is null then could be running from ArcCatalog
                m_pApp = (IApplication)ArcCatalog.Application;
            }

            if (m_pApp == null)
            {
                MessageBox.Show("Could not access the application.", "No Application found");
                return;
            }
            IGxApplication pGXApp = (IGxApplication)m_pApp;

            stdole.IUnknown pUnk = null;
            try
            {
                pUnk = (stdole.IUnknown)pGXApp.SelectedObject.InternalObjectName.Open();
            }
            catch (COMException ex)
            {
                if (ex.ErrorCode == (int)fdoError.FDO_E_DATASET_TYPE_NOT_SUPPORTED_IN_RELEASE ||
                    ex.ErrorCode == -2147220944)
                {
                    MessageBox.Show("The dataset is not supported in this release.", "Could not open the dataset");
                }
                else
                {
                    MessageBox.Show(ex.ErrorCode.ToString(), "Could not open the dataset");
                }
                return;
            }

            if (pUnk is ICadastralFabric)
            {
                m_pCadaFab = (ICadastralFabric)pUnk;
            }
            else
            {
                MessageBox.Show("Please select a parcel fabric and try again.", "Not a parcel fabric");
                return;
            }


            Utils FabricUTILS = new Utils();

            ITable     pTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTPlans);
            IDataset   pDS    = (IDataset)pTable;
            IWorkspace pWS    = pDS.Workspace;

            //Do a Start and Stop editing to make sure we're not running in an edit session
            if (!FabricUTILS.StartEditing(pWS, true))
            {//if start editing fails then bail
                if (pUnk != null)
                {
                    Marshal.ReleaseComObject(pUnk);
                }
                Cleanup(pTable, pWS);
                FabricUTILS = null;
                return;
            }
            FabricUTILS.StopEditing(pWS);

            bool bAddedField = false;

            if (FabricUTILS.GetFabricVersion((ICadastralFabric2)m_pCadaFab) < 2)
            {
                bAddedField = FabricUTILS.CadastralTableAddFieldV1(m_pCadaFab, esriCadastralFabricTable.esriCFTPlans, esriFieldType.esriFieldTypeInteger,
                                                                   "KeepOnMerge", "KeepOnMerge", 1);
            }
            else
            {
                bAddedField = FabricUTILS.CadastralTableAddField(m_pCadaFab, esriCadastralFabricTable.esriCFTPlans, esriFieldType.esriFieldTypeInteger,
                                                                 "KeepOnMerge", "KeepOnMerge", 1);
            }

            if (bAddedField)
            {
                MessageBox.Show("Plan-merge helper field 'KeepOnMerge' added.", "Add Field");
            }
            else
            {
                MessageBox.Show("Field 'KeepOnMerge' could not be added." + Environment.NewLine + "The field may already exist.",
                                "Add Field");
            }

            if (bAddedField)
            {
                //if the field was added succesfully, add the Yes/No domain
                IDomain pDom = new CodedValueDomainClass();
                try
                {
                    IWorkspaceDomains2 pWSDoms = (IWorkspaceDomains2)pWS;
                    pDom.FieldType   = esriFieldType.esriFieldTypeInteger;
                    pDom.Name        = "Flag for Keep on Plan Merge";
                    pDom.Description = "Flag for Keep on Plan Merge";
                    ICodedValueDomain pCVDom = (ICodedValueDomain)pDom;
                    //pCVDom.AddCode(0, "No");
                    pCVDom.AddCode(1, "Keep On Merge");
                    pWSDoms.AddDomain(pDom);
                }
                catch (COMException ex)
                {
                    MessageBox.Show(ex.ErrorCode.ToString());
                }

                //Get the field
                int iFld = pTable.FindField("KeepOnMerge");
                if (iFld >= 0)
                {
                    IField pFld = pTable.Fields.get_Field(iFld);
                    // Check that the field and domain have the same field type.
                    if (pFld.Type == pDom.FieldType)
                    {
                        // Cast the feature class to the ISchemaLock and IClassSchemaEdit interfaces.
                        ISchemaLock      schemaLock      = (ISchemaLock)pTable;
                        IClassSchemaEdit classSchemaEdit = (IClassSchemaEdit)pTable;

                        // Attempt to get an exclusive schema lock.
                        try
                        {
                            // Lock the class and alter the domain.
                            schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);
                            classSchemaEdit.AlterDomain("KeepOnMerge", pDom);
                            Console.WriteLine("The domain was successfully assigned.");
                        }
                        catch (COMException exc)
                        {
                            // Handle the exception in a way appropriate for the application.
                            Console.WriteLine(exc.Message);
                        }
                        finally
                        {
                            // Set the schema lock to be a shared lock.
                            schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
                        }
                    }
                }

                if (pDom != null)
                {
                    Marshal.ReleaseComObject(pDom);
                }
            }
            Cleanup(pTable, pWS);
            FabricUTILS = null;
        }
Example #15
0
        private void btnTest_Click(object sender, EventArgs e)
        {
            if (txtBoxExcelPath.Text == "")
            {
                MessageBox.Show("请选择导入的外业调查表!");
                return;
            }
            string strExcelPath = this.txtBoxExcelPath.Text;

            ExcelHelper elh = new ExcelHelper(strExcelPath);

            Microsoft.Office.Interop.Excel.Worksheet sheet = elh.excelApp.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
            sheet.Columns.EntireColumn.AutoFit();   //自动调整列宽  added by chulili 2012-11-29


            IFeatureClass pFeatureClass = m_pCurFeaCls;
            IWorkspace    pws           = (pFeatureClass as IDataset).Workspace;

            string strKeyChineseName = cmbKeyField.Text;
            string strKeyFieldName   = "";
            int    indexKeyField     = -1;

            if (_DicFieds.ContainsKey(strKeyChineseName))
            {
                indexKeyField   = _DicFieds[strKeyChineseName];
                strKeyFieldName = m_pCurFeaCls.Fields.get_Field(indexKeyField).Name;
            }

            IField pKeyField = pFeatureClass.Fields.get_Field(indexKeyField);

            IWorkspaceDomains pWorkSpaceDomains = pws as IWorkspaceDomains;
            ICodedValueDomain pCodedDomain      = new CodedValueDomainClass();
            int iNullRowCnt = 0;
            int iNullCnt    = 0;

            for (int i = 2; i <= sheet.UsedRange.Rows.Count; i++)
            {
                Exception er = null;

                string sql = "";
                iNullCnt = 0;

                object objcode  = ((Microsoft.Office.Interop.Excel.Range)sheet.UsedRange.Cells[i, 1]).Text; //对应行的该列的值
                string strcode  = objcode.ToString();
                object objvalue = ((Microsoft.Office.Interop.Excel.Range)sheet.UsedRange.Cells[i, 2]).Text; //对应行的该列的值
                string strvalue = objvalue.ToString();
                if (strcode == "")
                {
                    iNullRowCnt++;
                    if (iNullRowCnt > 10)
                    {
                        break;
                    }
                }
                else
                {
                    iNullRowCnt = 0;
                }
                pCodedDomain.AddCode(strcode, strvalue);
            }
            //pCodedDomain.AddCode("111", "纯林");
            //pCodedDomain.AddCode("112", "混交林");
            IDomain pDomain = pCodedDomain as IDomain;

            pDomain.Name        = pKeyField.Name + "domain2";
            pDomain.FieldType   = pKeyField.Type;
            pDomain.SplitPolicy = esriSplitPolicyType.esriSPTDuplicate;
            pDomain.MergePolicy = esriMergePolicyType.esriMPTDefaultValue;


            pWorkSpaceDomains.AddDomain(pDomain);

            ISchemaLock      schemaLock      = (ISchemaLock)pFeatureClass;
            IClassSchemaEdit classSchemaEdit = (IClassSchemaEdit)pFeatureClass;

            try
            {
                schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);
                classSchemaEdit.AlterDomain(pKeyField.Name, pDomain);
            }
            catch (Exception exc)
            {
            }
            finally
            {
                schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
            }

            sheet = null;
            elh.Close();
        }
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            _message = message;

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

            try
            {
                DateTime syncTime = DateTime.Now;

                IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

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

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

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

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

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

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

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

                IEnvelope newExtent = null;

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

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

                downloadEnvelope.Project(wgs84);

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

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

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

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

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

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

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

                    httpResponse = httpClient.GetResponse() as HttpWebResponse;

                    osm osmCapabilities = null;

                    Stream stream = httpResponse.GetResponseStream();

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

                    apiCapabilities = osmCapabilities.Items[0] as api;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                IName parentName = null;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                string storageKeyword = String.Empty;

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

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


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


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

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

                if (osmPointFeatureClass == null)
                {
                    return;
                }

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

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

                if (osmLineFeatureClass == null)
                {
                    return;
                }

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

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

                if (osmPolygonFeatureClass == null)
                {
                    return;
                }

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

                // relation table
                ITable relationTable = null;

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

                if (relationTable == null)
                {
                    return;
                }

                // revision table 
                ITable revisionTable = null;

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

                if (revisionTable == null)
                {
                    return;
                }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    #endregion

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

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

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

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

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

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



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

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

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

                        IStepProgressor stepProgressor = TrackCancel as IStepProgressor;

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

                        comReleaser.ManageLifetime(pointUpdateCursor);

                        IFeature pointFeature = pointUpdateCursor.NextFeature();

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

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

                            pointUpdateCursor.UpdateFeature(pointFeature);

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

                            pointFeature = pointUpdateCursor.NextFeature();

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

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

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

                SyncState.StoreLastSyncTime(targetDatasetName, syncTime);

                gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3;

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

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

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

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

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

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

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

                    if (osmPolygonFeatureClass != null)
                    {
                        osmPolygonFeatureClass.ApplyOSMClassExtension();
                        Marshal.ReleaseComObject(osmPolygonFeatureClass);
                    }
                }
                catch (Exception ex)
                {
                    message.AddError(120020, ex.ToString());
                }
            }
        }
        void CreateDomain(IWorkspace pWorkspace)
        {
            IWorkspaceDomains pWorkspaceDomains = (IWorkspaceDomains)pWorkspace;

             ICodedValueDomain pCodedValueDomain = new CodedValueDomainClass();

             pCodedValueDomain.AddCode("RES", "Residential");
             pCodedValueDomain.AddCode("COM", "Commercial");
             pCodedValueDomain.AddCode("IND", "Industrial");

             IDomain pDomain = (IDomain)pCodedValueDomain;
             pDomain.Name = "Building Types";
             pDomain.FieldType = esriFieldType.esriFieldTypeString;
             pDomain.SplitPolicy = esriSplitPolicyType.esriSPTDuplicate;
             pDomain.MergePolicy = esriMergePolicyType.esriMPTDefaultValue;

             pWorkspaceDomains.AddDomain(pDomain);
        }