Example #1
0
        public void RunIndexingOn(string uuid)
        {
            try
            {
                SetNorwegianIndexCores();
                RemoveIndexDocument(uuid);

                SetEnglishIndexCores();
                RemoveIndexDocument(uuid);

                MD_Metadata_Type metadata = _geoNorge.GetRecordByUuid(uuid);

                if (metadata != null)
                {
                    SetNorwegianIndexCores();
                    MetadataIndexDoc metadataIndexDoc = _indexDocumentCreator.CreateIndexDoc(new SimpleMetadata(metadata), _geoNorge, Culture.NorwegianCode);
                    RunIndex(metadataIndexDoc, Culture.NorwegianCode);

                    SetEnglishIndexCores();
                    metadataIndexDoc = _indexDocumentCreator.CreateIndexDoc(new SimpleMetadata(metadata), _geoNorge, Culture.EnglishCode);
                    RunIndex(metadataIndexDoc, Culture.EnglishCode);
                }
            }
            catch (Exception exception)
            {
                Log.Error("Error in UUID: " + uuid + "", exception);
                _errorService.AddError(uuid, exception);
            }
        }
Example #2
0
        public void ShouldSearchAndReturnIsoRecords()
        {
            var result = _geonorge.SearchIso("data");

            Assert.Greater(int.Parse(result.numberOfRecordsMatched), 0);

            MD_Metadata_Type md = result.Items[0] as MD_Metadata_Type;

            Assert.NotNull(md);
        }
Example #3
0
 public static SimpleMetadata FetchMetadata(string uuid)
 {
     try
     {
         GeoNorge         g        = new GeoNorge("", "", WebConfigurationManager.AppSettings["GeoNetworkUrl"]);
         MD_Metadata_Type metadata = g.GetRecordByUuid(uuid);
         return(metadata != null ? new SimpleMetadata(metadata) : null);
     }
     catch (Exception e)
     {
         return(null);
     }
 }
        public string GetCoverageLink(string coverageUrl, string uuid)
        {
            MD_Metadata_Type metadata = _geonorge.GetRecordByUuid(uuid);

            if (metadata == null)
            {
                throw new InvalidOperationException("Metadata not found for uuid: " + uuid);
            }

            var simpleMetadata = new SimpleMetadata(metadata);



            string CoverageLink = coverageUrl;
            var    coverageStr  = coverageUrl;

            if (coverageStr.IndexOf("TYPE:") != -1)
            {
                var startPos   = 5;
                var endPosType = coverageStr.IndexOf("@PATH");
                var typeStr    = coverageStr.Substring(startPos, endPosType - startPos);

                var endPath = coverageStr.IndexOf("@LAYER");
                var pathStr = coverageStr.Substring(endPosType + startPos + 1, endPath - (endPosType + startPos + 1));

                var startLayer = endPath + 7;
                var endLayer   = coverageStr.Length - startLayer;
                var layerStr   = coverageStr.Substring(startLayer, endLayer);


                int zoomLevel = simpleMetadata.BoundingBox.WestBoundLongitude != null?ZoomLevel(simpleMetadata.BoundingBox.WestBoundLongitude, simpleMetadata.BoundingBox.SouthBoundLatitude, simpleMetadata.BoundingBox.EastBoundLongitude, simpleMetadata.BoundingBox.NorthBoundLatitude) : 7;

                if (typeStr == "WMS")
                {
                    CoverageLink = "http://norgeskart.no/geoportal/#" + zoomLevel + "/355422/6668909/l/wms/[" + RemoveQueryString(pathStr) + "]/+" + layerStr;
                }

                else if (typeStr == "WFS")
                {
                    CoverageLink = "http://norgeskart.no/geoportal/#" + zoomLevel + "/255216/6653881/l/wfs/[" + RemoveQueryString(pathStr) + "]/+" + layerStr;
                }

                else if (typeStr == "GeoJSON")
                {
                    CoverageLink = "http://norgeskart.no/geoportal/staging/#" + zoomLevel + "/355422/6668909/l/geojson/[" + RemoveQueryString(pathStr) + "]/+" + layerStr;
                }
            }

            return(CoverageLink);
        }
Example #5
0
        public MD_Metadata_Type GetRecordById(GetRecordByIdType request)
        {
            var    requestBody  = SerializeUtil.SerializeToString(request);
            string responseBody = _httpRequestExecutor.PostRequest(GetUrlForCswService(), ContentTypeXml, ContentTypeXml, requestBody);

            responseBody = FixInvalidXml(responseBody);
            GetRecordByIdResponseType response = SerializeUtil.DeserializeFromString <GetRecordByIdResponseType>(responseBody);

            MD_Metadata_Type metadataRecord = null;

            if (response != null && response.Items != null && response.Items.Length > 0)
            {
                metadataRecord = response.Items[0] as MD_Metadata_Type;
            }


            return(metadataRecord);
        }
Example #6
0
        public TransactionType MetadataUpdate(MD_Metadata_Type metadata)
        {
            TransactionType cswTransaction = new TransactionType
            {
                service = "CSW",
                version = "2.0.2",
                Items   = new object[]
                {
                    new UpdateType()
                    {
                        Items = new object[]
                        {
                            metadata
                        }
                    }
                }
            };

            return(cswTransaction);
        }
 private static void CheckDistributionUrl(MD_Metadata_Type metadata, ValidationResult validationResult)
 {
     if (metadata.distributionInfo != null &&
         metadata.distributionInfo.MD_Distribution != null &&
         metadata.distributionInfo.MD_Distribution.transferOptions != null &&
         metadata.distributionInfo.MD_Distribution.transferOptions[0] != null &&
         metadata.distributionInfo.MD_Distribution.transferOptions[0].MD_DigitalTransferOptions != null &&
         metadata.distributionInfo.MD_Distribution.transferOptions[0].MD_DigitalTransferOptions.onLine != null &&
         metadata.distributionInfo.MD_Distribution.transferOptions[0].MD_DigitalTransferOptions.onLine[0] != null
         &&
         metadata.distributionInfo.MD_Distribution.transferOptions[0].MD_DigitalTransferOptions.onLine[0]
         .CI_OnlineResource != null
         &&
         metadata.distributionInfo.MD_Distribution.transferOptions[0].MD_DigitalTransferOptions.onLine[0]
         .CI_OnlineResource.linkage != null
         &&
         metadata.distributionInfo.MD_Distribution.transferOptions[0].MD_DigitalTransferOptions.onLine[0]
         .CI_OnlineResource.linkage.URL != null)
     {
         string url =
             metadata.distributionInfo.MD_Distribution.transferOptions[0].MD_DigitalTransferOptions.onLine[0]
             .CI_OnlineResource.linkage.URL;
         if (url.Trim().Length > 1)
         {
             validationResult.Status = ValidationStatus.Valid;
         }
         else
         {
             validationResult.Status   = ValidationStatus.Invalid;
             validationResult.Messages = "Empty URL in distributionInfo.";
         }
     }
     else
     {
         validationResult.Status   = ValidationStatus.Invalid;
         validationResult.Messages = "Missing URL in distributionInfo.";
     }
     validationResult.Timestamp = DateTime.Now;
 }
        public ValidationResult Validate(MetadataEntry metadataEntry, MD_Metadata_Type metadata, string rawXmlProcessed)
        {
            ValidationResult validationResult = new ValidationResult();

            //if (metadataEntry.HasResourceType(ResourceTypeSoftware))
            //{
            //    CheckDistributionUrl(metadata, validationResult);
            //}
            //else
            //{
            string response = _httpRequestExecutor.GetRequest(EndpointValidatorInMetadataEditor + metadataEntry.Uuid, ContentTypeXml, ContentTypeXml);

            if (!string.IsNullOrWhiteSpace(response))
            {
                External.MetadataEditor.MetadataEntry externalMetadataEntry = SerializeUtil.DeserializeFromString <External.MetadataEditor.MetadataEntry>(response);

                validationResult.Initialize(externalMetadataEntry);
                validationResult.Timestamp = DateTime.Now;
            }
            //}
            return(validationResult);
        }
Example #9
0
        private bool IsInspireResource(MD_Metadata_Type metadata)
        {
            bool isInspireResource = false;

            if (metadata.dataQualityInfo != null && metadata.dataQualityInfo[0] != null && metadata.dataQualityInfo[0].DQ_DataQuality != null &&
                metadata.dataQualityInfo[0].DQ_DataQuality.report != null && metadata.dataQualityInfo[0].DQ_DataQuality.report[0] != null &&
                metadata.dataQualityInfo[0].DQ_DataQuality.report[0].AbstractDQ_Element != null &&
                metadata.dataQualityInfo[0].DQ_DataQuality.report[0].AbstractDQ_Element.result != null &&
                metadata.dataQualityInfo[0].DQ_DataQuality.report[0].AbstractDQ_Element.result[0] != null &&
                metadata.dataQualityInfo[0].DQ_DataQuality.report[0].AbstractDQ_Element.result[0].AbstractDQ_Result != null)
            {
                var result = metadata.dataQualityInfo[0].DQ_DataQuality.report[0].AbstractDQ_Element.result[0].AbstractDQ_Result as DQ_ConformanceResult_Type;

                if (result != null && result.specification != null && result.specification.CI_Citation != null &&
                    result.specification.CI_Citation.title != null &&
                    result.specification.CI_Citation.title.item != null &&
                    result.specification.CI_Citation.title != null)
                {
                    string title       = "";
                    var    anchorTitle = result.specification.CI_Citation.title.item as Anchor_Type;
                    if (anchorTitle != null)
                    {
                        title = anchorTitle.Value;
                    }
                    else
                    {
                        title = GetStringFromObject(result.specification.CI_Citation.title);
                    }

                    if (title.ToUpper().Contains("COMMISSION REGULATION (EU)"))
                    {
                        isInspireResource = true;
                    }
                }
            }
            return(isInspireResource);
        }
Example #10
0
        private void CheckDatasets()
        {
            for (int d = 0; d < metadataSets.Items.Length; d++)
            {
                string           uuid = ((www.opengis.net.DCMIRecordType)(metadataSets.Items[d])).Items[0].Text[0];
                MD_Metadata_Type md   = geoNorge.GetRecordByUuid(uuid);
                var data = new SimpleMetadata(md);

                if (data.DistributionDetails != null && !string.IsNullOrEmpty(data.DistributionDetails.Protocol) &&
                    data.DistributionDetails.Protocol == "GEONORGE:DOWNLOAD")
                {
                    if (string.IsNullOrEmpty(data.DistributionDetails.URL))
                    {
                        downloadProblems.Add(new MetadataEntry {
                            Uuid = uuid, Title = data.Title, Problem = "Distribusjons url er tom"
                        });
                    }
                    else
                    {
                        GetDistribution(uuid, data.Title, data.DistributionDetails.URL);
                    }
                }
            }
        }
        private SimpleMetadata createMetadataForFeature(SimpleMetadata parentMetadata, List <SimpleKeyword> selectedKeywordsFromParent, WfsLayerViewModel layerModel)
        {
            MD_Metadata_Type parent = parentMetadata.GetMetadata();

            MD_Metadata_Type layer = parent.Copy();

            layer.parentIdentifier = new CharacterString_PropertyType {
                CharacterString = parent.fileIdentifier.CharacterString
            };
            layer.fileIdentifier = new CharacterString_PropertyType {
                CharacterString = Guid.NewGuid().ToString()
            };

            SimpleMetadata simpleLayer = new SimpleMetadata(layer);

            string title = layerModel.Title;

            if (string.IsNullOrWhiteSpace(title))
            {
                title = layerModel.Name;
            }

            simpleLayer.Title = title;

            if (!string.IsNullOrWhiteSpace(layerModel.Abstract))
            {
                simpleLayer.Abstract = layerModel.Abstract;
            }

            simpleLayer.Keywords = selectedKeywordsFromParent;

            if (layerModel.Keywords.Count > 0)
            {
                var existingKeywords = simpleLayer.Keywords;
                foreach (var keyword in layerModel.Keywords)
                {
                    existingKeywords.Add(new SimpleKeyword
                    {
                        Keyword = keyword
                    });
                }
                simpleLayer.Keywords = existingKeywords;
            }

            simpleLayer.DistributionDetails = new SimpleDistributionDetails
            {
                Name     = layerModel.Name,
                Protocol = parentMetadata.DistributionDetails.Protocol,
                URL      = parentMetadata.DistributionDetails.URL
            };

            if (!string.IsNullOrWhiteSpace(layerModel.BoundingBoxEast))
            {
                string defaultWestBoundLongitude = "-20";
                string defaultEastBoundLongitude = "38";
                string defaultSouthBoundLatitude = "56";
                string defaultNorthBoundLatitude = "90";

                string parentWestBoundLongitude = defaultWestBoundLongitude;
                string parentEastBoundLongitude = defaultEastBoundLongitude;
                string parentSouthBoundLatitude = defaultSouthBoundLatitude;
                string parentNorthBoundLatitude = defaultNorthBoundLatitude;

                if (parentMetadata.BoundingBox != null)
                {
                    parentWestBoundLongitude = parentMetadata.BoundingBox.WestBoundLongitude;
                    parentEastBoundLongitude = parentMetadata.BoundingBox.EastBoundLongitude;
                    parentSouthBoundLatitude = parentMetadata.BoundingBox.SouthBoundLatitude;
                    parentNorthBoundLatitude = parentMetadata.BoundingBox.NorthBoundLatitude;
                }

                string WestBoundLongitude = layerModel.BoundingBoxWest;
                string EastBoundLongitude = layerModel.BoundingBoxEast;
                string SouthBoundLatitude = layerModel.BoundingBoxSouth;
                string NorthBoundLatitude = layerModel.BoundingBoxNorth;

                decimal number;

                if (!Decimal.TryParse(WestBoundLongitude, out number) ||
                    !Decimal.TryParse(EastBoundLongitude, out number) ||
                    !Decimal.TryParse(SouthBoundLatitude, out number) ||
                    !Decimal.TryParse(NorthBoundLatitude, out number)
                    )
                {
                    WestBoundLongitude = parentWestBoundLongitude;
                    EastBoundLongitude = parentEastBoundLongitude;
                    SouthBoundLatitude = parentSouthBoundLatitude;
                    NorthBoundLatitude = parentNorthBoundLatitude;

                    if (!Decimal.TryParse(WestBoundLongitude, out number) ||
                        !Decimal.TryParse(EastBoundLongitude, out number) ||
                        !Decimal.TryParse(SouthBoundLatitude, out number) ||
                        !Decimal.TryParse(NorthBoundLatitude, out number)
                        )
                    {
                        WestBoundLongitude = defaultWestBoundLongitude;
                        EastBoundLongitude = defaultEastBoundLongitude;
                        SouthBoundLatitude = defaultSouthBoundLatitude;
                        NorthBoundLatitude = defaultNorthBoundLatitude;
                    }
                }


                simpleLayer.BoundingBox = new SimpleBoundingBox
                {
                    EastBoundLongitude = EastBoundLongitude,
                    WestBoundLongitude = WestBoundLongitude,
                    NorthBoundLatitude = NorthBoundLatitude,
                    SouthBoundLatitude = SouthBoundLatitude
                };
            }

            if (!string.IsNullOrWhiteSpace(layerModel.EnglishTitle))
            {
                simpleLayer.EnglishTitle = layerModel.EnglishTitle;
            }

            if (!string.IsNullOrWhiteSpace(layerModel.EnglishAbstract))
            {
                simpleLayer.EnglishAbstract = layerModel.EnglishAbstract;
            }

            return(simpleLayer);
        }
Example #12
0
        /// <summary>
        /// Update metadata record in GeoNorge.
        /// </summary>
        /// <param name="metadata"></param>
        /// <returns></returns>
        public MetadataTransaction MetadataUpdate(MD_Metadata_Type metadata, Dictionary <string, string> additionalRequestHeaders = null)
        {
            TransactionType request = _requestFactory.MetadataUpdate(metadata);

            return(_requestRunner.RunCswTransaction(request, additionalRequestHeaders));
        }
Example #13
0
        public static MD_Metadata_Type CreateMetadataExample()
        {
            MD_Metadata_Type m = new MD_Metadata_Type();

            m.fileIdentifier          = CharString("12345-67890-aabbcc-ddeeff-ggffhhjj");
            m.language                = CharString("nor");
            m.metadataStandardName    = CharString("ISO19139");
            m.metadataStandardVersion = CharString("1.0");
            m.hierarchyLevel          = new[] { new MD_ScopeCode_PropertyType
                                                {
                                                    MD_ScopeCode = new CodeListValue_Type
                                                    {
                                                        codeList      = "http://www.isotc211.org/2005/resources/codeList.xml#MD_ScopeCode",
                                                        codeListValue = "dataset"
                                                    }
                                                } };

            var responsibleParty = new CI_ResponsibleParty_Type()
            {
                individualName = CharString("Hans Hansen"),
                role           = new CI_RoleCode_PropertyType()
                {
                    CI_RoleCode = new CodeListValue_Type
                    {
                        codeList      = "http://www.isotc211.org/2005/resources/codeList.xml#CI_RoleCode",
                        codeListValue = "resourceProvider"
                    }
                },
                organisationName = CharString("Statens Kartverk"),
                contactInfo      = new CI_Contact_PropertyType()
                {
                    CI_Contact = new CI_Contact_Type()
                    {
                        address = new CI_Address_PropertyType()
                        {
                            CI_Address = new CI_Address_Type()
                            {
                                electronicMailAddress = new[] { CharString("*****@*****.**") }
                            }
                        }
                    }
                }
            };

            m.contact = new CI_ResponsibleParty_PropertyType[] { new CI_ResponsibleParty_PropertyType()
                                                                 {
                                                                     CI_ResponsibleParty = responsibleParty
                                                                 } };

            m.dateStamp = new Date_PropertyType()
            {
                Item = DateTime.Now
            };

            var mdDataIdentificationType = new MD_DataIdentification_Type();

            mdDataIdentificationType.pointOfContact = new[] {
                new CI_ResponsibleParty_PropertyType {
                    CI_ResponsibleParty = responsibleParty
                }
            };
            mdDataIdentificationType.citation = new CI_Citation_PropertyType
            {
                CI_Citation = new CI_Citation_Type
                {
                    title = CharString("Eksempeldatasettet sin tittel."),
                    date  = new[] {
                        new CI_Date_PropertyType {
                            CI_Date = new CI_Date_Type {
                                date = new Date_PropertyType {
                                    Item = DateTime.Now.Date.ToString("yyyy-MM-dd")
                                },
                                dateType = new CI_DateTypeCode_PropertyType {
                                    CI_DateTypeCode = new CodeListValue_Type
                                    {
                                        codeList      = "http://www.isotc211.org/2005/resources/codeList.xml#CI_DateTypeCode",
                                        codeListValue = "creation"
                                    }
                                }
                            }
                        }
                    },
                    alternateTitle = new[] { CharString("Dette er en den alternative tittelen til datasettet som tilbys.") },
                    identifier     = new[] { new MD_Identifier_PropertyType
                                             {
                                                 MD_Identifier = new MD_Identifier_Type
                                                 {
                                                     code = CharString("12345-abcdef-67890-ghijkl")
                                                 }
                                             } }
                }
            };
            mdDataIdentificationType.@abstract             = CharString("Dette datasettet inneholder ditt og datt. Kan brukes til dette, men må ikke brukes til andre ting som for eksempel dette.");
            mdDataIdentificationType.purpose               = CharString("Dette er formålet.");
            mdDataIdentificationType.resourceSpecificUsage = new[]
            {
                new MD_Usage_PropertyType()
                {
                    MD_Usage = new MD_Usage_Type()
                    {
                        specificUsage = CharString("Skal bare brukes sånn og sånn"),
                        usageDateTime = new DateTime_PropertyType()
                        {
                            DateTime = DateTime.Now
                        },
                        userContactInfo = new []
                        {
                            new CI_ResponsibleParty_PropertyType
                            {
                                CI_ResponsibleParty = responsibleParty
                            }
                        },
                        userDeterminedLimitations = CharString("Her kommer det begrensninger på bruk av dataene.")
                    }
                }
            };
            mdDataIdentificationType.spatialResolution = new MD_Resolution_PropertyType[] { new MD_Resolution_PropertyType()
                                                                                            {
                                                                                                MD_Resolution = new MD_Resolution_Type()
                                                                                                {
                                                                                                    Item = new MD_RepresentativeFraction_PropertyType()
                                                                                                    {
                                                                                                        MD_RepresentativeFraction = new MD_RepresentativeFraction_Type()
                                                                                                        {
                                                                                                            denominator = new Integer_PropertyType()
                                                                                                            {
                                                                                                                Integer = "1000"
                                                                                                            }
                                                                                                        }
                                                                                                    }
                                                                                                }
                                                                                            } };
            mdDataIdentificationType.language            = new[] { CharString("nor") };
            mdDataIdentificationType.descriptiveKeywords = new[] {
                new MD_Keywords_PropertyType {
                    MD_Keywords = new MD_Keywords_Type {
                        keyword = new CharacterString_PropertyType[]
                        {
                            new PT_FreeText_PropertyType
                            {
                                CharacterString = "Adresser",
                                PT_FreeText     = new PT_FreeText_Type {
                                    id        = "ENG",
                                    textGroup = new LocalisedCharacterString_PropertyType[]
                                    {
                                        new LocalisedCharacterString_PropertyType {
                                            LocalisedCharacterString = new LocalisedCharacterString_Type
                                            {
                                                locale = "#ENG",
                                                Value  = "Addresses"
                                            }
                                        }
                                    }
                                }
                            }
                        },
                        thesaurusName = new CI_Citation_PropertyType
                        {
                            CI_Citation = new CI_Citation_Type
                            {
                                title = CharString("GEMET - INSPIRE themes, version 1.0"),

                                date = new [] { new CI_Date_PropertyType
                                                {
                                                    CI_Date = new CI_Date_Type
                                                    {
                                                        date = new Date_PropertyType {
                                                            Item = DateTime.Now
                                                        },
                                                        dateType = new CI_DateTypeCode_PropertyType
                                                        {
                                                            CI_DateTypeCode = new CodeListValue_Type()
                                                            {
                                                                codeList      = "http://standards.iso.org/ittf/PubliclyAvailableStandards/ISO_19139_Schemas/resources/Codelist/ML_gmxCodelists.xml#CI_DateTypeCode",
                                                                codeListValue = "publication"
                                                            }
                                                        }
                                                    }
                                                } }
                            }
                        }
                    }
                }
            };
            mdDataIdentificationType.resourceConstraints = new[]
            {
                new MD_Constraints_PropertyType
                {
                    MD_Constraints = new MD_Constraints_Type
                    {
                        useLimitation = new [] { CharString("Gratis å benytte til alle formål.") }
                    }
                },
                new MD_Constraints_PropertyType
                {
                    MD_Constraints = new MD_LegalConstraints_Type
                    {
                        accessConstraints = new MD_RestrictionCode_PropertyType[]
                        {
                            new MD_RestrictionCode_PropertyType
                            {
                                MD_RestrictionCode = new CodeListValue_Type {
                                    codeListValue = "none", codeList = "http://standards.iso.org/ittf/PubliclyAvailableStandards/ISO_19139_Schemas/resources/codelist/gmxCodelists.xml#MD_RestrictionCode"
                                }
                            }
                        },
                        useConstraints = new MD_RestrictionCode_PropertyType[]
                        {
                            new MD_RestrictionCode_PropertyType
                            {
                                MD_RestrictionCode = new CodeListValue_Type {
                                    codeListValue = "free", codeList = "http://standards.iso.org/ittf/PubliclyAvailableStandards/ISO_19139_Schemas/resources/codelist/gmxCodelists.xml#MD_RestrictionCode"
                                }
                            }
                        },
                        otherConstraints = new MD_RestrictionOther_PropertyType [] { new MD_RestrictionOther_PropertyType {
                                                                                         MD_RestrictionOther = CharString("Ingen begrensninger på bruk.")
                                                                                     }, new MD_RestrictionOther_PropertyType {
                                                                                         MD_RestrictionOther = new Anchor_Type {
                                                                                             href = "http://test.no", Value = "Link"
                                                                                         }
                                                                                     } }
                    }
                },
                new MD_Constraints_PropertyType
                {
                    MD_Constraints = new MD_SecurityConstraints_Type
                    {
                        userNote = new CharacterString_PropertyType
                        {
                            CharacterString = "Text that describes why it is not freely open"
                        },
                        classification = new MD_ClassificationCode_PropertyType
                        {
                            MD_ClassificationCode = new CodeListValue_Type
                            {
                                codeList      = "http://standards.iso.org/ittf/PubliclyAvailableStandards/ISO_19139_Schemas/resources/codelist/gmxCodelists.xml#MD_ClassificationCode",
                                codeListValue = "unclassified"
                            }
                        }
                    }
                }
            };
            mdDataIdentificationType.topicCategory = new[] { new MD_TopicCategoryCode_PropertyType
                                                             {
                                                                 MD_TopicCategoryCode = MD_TopicCategoryCode_Type.location
                                                             } };
            mdDataIdentificationType.extent = new[]
            {
                new EX_Extent_PropertyType
                {
                    EX_Extent = new EX_Extent_Type
                    {
                        geographicElement = new []
                        {
                            new EX_GeographicExtent_PropertyType
                            {
                                AbstractEX_GeographicExtent = new EX_GeographicBoundingBox_Type
                                {
                                    westBoundLongitude = new Decimal_PropertyType {
                                        Decimal = 2
                                    },
                                    eastBoundLongitude = new Decimal_PropertyType {
                                        Decimal = 33
                                    },
                                    southBoundLatitude = new Decimal_PropertyType {
                                        Decimal = 57
                                    },
                                    northBoundLatitude = new Decimal_PropertyType {
                                        Decimal = 72
                                    }
                                }
                            }
                        },
                        temporalElement = new EX_TemporalExtent_PropertyType[]
                        {
                            new EX_TemporalExtent_PropertyType
                            {
                                EX_TemporalExtent = new EX_TemporalExtent_Type
                                {
                                    extent = new TM_Primitive_PropertyType
                                    {
                                        AbstractTimePrimitive = new TimePeriodType()
                                        {
                                            id = "id_1",

                                            Item = new TimePositionType()
                                            {
                                                Value = "2014-01-01"
                                            },
                                            Item1 = new TimePositionType()
                                            {
                                                Value = "2020-01-01"
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            };

            mdDataIdentificationType.supplementalInformation = CharString("Dette er den utfyllende informasjonen.");

            m.identificationInfo = new[] {
                new MD_Identification_PropertyType
                {
                    AbstractMD_Identification = mdDataIdentificationType
                }
            };


            m.distributionInfo = new MD_Distribution_PropertyType
            {
                MD_Distribution = new MD_Distribution_Type
                {
                    transferOptions = new[]
                    {
                        new MD_DigitalTransferOptions_PropertyType
                        {
                            MD_DigitalTransferOptions = new MD_DigitalTransferOptions_Type
                            {
                                onLine = new[]
                                {
                                    new CI_OnlineResource_PropertyType
                                    {
                                        CI_OnlineResource = new CI_OnlineResource_Type
                                        {
                                            linkage = new URL_PropertyType
                                            {
                                                URL = "http://www.kartverket.no"
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            };

            var dqDataQualityType = new DQ_DataQuality_Type();

            dqDataQualityType.scope = new DQ_Scope_PropertyType
            {
                DQ_Scope = new DQ_Scope_Type
                {
                    level = new MD_ScopeCode_PropertyType
                    {
                        MD_ScopeCode = new CodeListValue_Type
                        {
                            codeList      = "http://www.isotc211.org/2005/resources/codeList.xml#MD_ScopeCode",
                            codeListValue = "dataset"
                        }
                    }
                }
            };
            dqDataQualityType.lineage = new LI_Lineage_PropertyType
            {
                LI_Lineage = new LI_Lineage_Type
                {
                    statement = CharString("Her kommer det en tekst om prosesshistorien.")
                }
            };
            dqDataQualityType.report = new[]
            {
                new DQ_Element_PropertyType
                {
                    AbstractDQ_Element = new DQ_DomainConsistency_Type
                    {
                        result = new [] {
                            new DQ_Result_PropertyType
                            {
                                AbstractDQ_Result = new DQ_ConformanceResult_Type
                                {
                                    specification = new CI_Citation_PropertyType
                                    {
                                        CI_Citation = new CI_Citation_Type
                                        {
                                            title = CharString("COMMISSION REGULATION (EU) No 1089/2010 of 23 November 2010 implementing Directive 2007/2/EC of the European Parliament and of the Council as regards interoperability of spatial data sets and services"),
                                            date  = new CI_Date_PropertyType[]
                                            {
                                                new CI_Date_PropertyType
                                                {
                                                    CI_Date = new CI_Date_Type
                                                    {
                                                        date = new Date_PropertyType
                                                        {
                                                            Item = "2010-12-08"
                                                        },
                                                        dateType = new CI_DateTypeCode_PropertyType
                                                        {
                                                            CI_DateTypeCode = new CodeListValue_Type
                                                            {
                                                                codeList      = "http://standards.iso.org/ittf/PubliclyAvailableStandards/ISO_19139_Schemas/resources/Codelist/ML_gmxCodelists.xml#CI_DateTypeCode",
                                                                codeListValue = "publication"
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    },
                                    explanation = CharString("See the referenced specification"),
                                    pass        = new Boolean_PropertyType {
                                        Boolean = true
                                    }
                                }
                            }
                        }
                    }
                }
            };

            m.dataQualityInfo = new[] { new DQ_DataQuality_PropertyType {
                                            DQ_DataQuality = dqDataQualityType
                                        } };

            m.referenceSystemInfo = new MD_ReferenceSystem_PropertyType[]
            {
                new MD_ReferenceSystem_PropertyType
                {
                    MD_ReferenceSystem = new MD_ReferenceSystem_Type
                    {
                        referenceSystemIdentifier = new RS_Identifier_PropertyType
                        {
                            RS_Identifier = new RS_Identifier_Type
                            {
                                code = new CharacterString_PropertyType
                                {
                                    CharacterString = "http://www.opengis.net/def/crs/EPSG/0/25831"
                                },
                                codeSpace = new CharacterString_PropertyType
                                {
                                    CharacterString = "EPSG"
                                }
                            }
                        }
                    }
                }
            };

            return(m);
        }
Example #14
0
        public MetadataEntry RetrieveAndValidate(string uuid)
        {
            MetadataEntry metadataEntry = null;

            try
            {
                var getCswRecordRequest = CreateGetCswRecordRequest(uuid);
                Log.Info("Henter metadata for uuid=" + uuid + " fra GeoNorge.");
                string cswRecordResponse = _httpRequestExecutor.PostRequest(EndpointUrlGeoNorgeCsw,
                                                                            ContentTypeXml, ContentTypeXml,
                                                                            getCswRecordRequest);

                /* Quick and dirty hacks to fix exceptions in serialization due to invalid xml */

                Regex fixWrongDecimalInRealElements = new Regex("<gco:Real>([0-9]+),([0-9]+)</gco:Real>");

                var fixedResponse = cswRecordResponse.Replace("<gco:Boolean />", "<gco:Boolean>false</gco:Boolean>")
                                    .Replace("<gco:Real />", "<gco:Real>0.0</gco:Real>")
                                    .Replace("<gco:DateTime />", "")
                                    .Replace("<gmd:MD_TopicCategoryCode />", "");

                var rawXmlProcessed = fixWrongDecimalInRealElements.Replace(fixedResponse, "<gco:Real>$1.$2</gco:Real>");

                GetRecordByIdResponseType getRecordResponse = SerializeUtil.DeserializeFromString <GetRecordByIdResponseType>(rawXmlProcessed);
                MD_Metadata_Type          metadata          = getRecordResponse.Items[0] as MD_Metadata_Type;

                metadataEntry = ParseCswRecordResponse(uuid, metadata);
                ValidationResult validationResult;
                if (metadataEntry.ResourceType == "unknown")
                {
                    validationResult = new ValidationResult
                    {
                        Messages  = "Unknown resource type, please check value of hierarchyLevel element.",
                        Status    = ValidationStatus.NotValidated,
                        Timestamp = DateTime.Now
                    };
                    Log.Info("Validation result: " + validationResult.Messages);
                    metadataEntry.ValidationResults.Add(validationResult);
                }
                else
                {
                    if (metadataEntry.InspireResource)
                    {
                        // Check validation state instead of valdating.
                        Log.Info("Check validation state metadata with INSPIRE-validator.");
                        validationResult = new InspireValidator(_httpRequestExecutor).CheckValidationState(uuid);
                        Log.Info("Validation result: " + validationResult.Messages);
                        metadataEntry.ValidationResults.Add(validationResult);
                    }
                    if (metadataEntry.Keywords.Contains("Norge digitalt"))
                    {
                        Log.Info("Validating metadata with Norge Digitalt-validator.");
                        validationResult = new NorgeDigitaltValidator().Validate(metadataEntry, metadata, rawXmlProcessed);
                        Log.Info("Validation result: " + validationResult.Messages);
                        metadataEntry.ValidationResults.Add(validationResult);
                    }
                }
            }
            catch (Exception e)
            {
                metadataEntry = ParseCswRecordResponse(uuid, null);

                string message = e.Message;
                if (e.InnerException != null)
                {
                    message += e.InnerException.Message;
                }

                metadataEntry.ValidationResults.Add(new ValidationResult {
                    Messages = "Exception during validation: " + message, Status = ValidationStatus.NotValidated, Timestamp = DateTime.Now
                });
                Log.Error("Exception occured for uuid=" + uuid + ", not validated. " + message);
            }
            return(metadataEntry);
        }
Example #15
0
        private MetadataEntry ParseCswRecordResponse(string uuid, MD_Metadata_Type metadata)
        {
            var    title           = "unknown";
            var    resourceType    = "unknown";
            var    organization    = "unknown";
            var    inspireResource = false;
            string purpose         = null;
            string abstractText    = null;

            StringBuilder contactInformation = new StringBuilder();

            List <string> keywords = new List <string>();

            if (metadata != null)
            {
                if (metadata.hierarchyLevel != null && metadata.hierarchyLevel[0] != null)
                {
                    resourceType = metadata.hierarchyLevel[0].MD_ScopeCode.codeListValue;
                }

                var dataIdentification = metadata.identificationInfo[0].AbstractMD_Identification;
                if (dataIdentification != null)
                {
                    CharacterString_PropertyType titleString = null;

                    Anchor_Type titleObject = dataIdentification.citation.CI_Citation.title.item as Anchor_Type;
                    if (titleObject != null)
                    {
                        titleString = toCharString(titleObject.Value);
                    }
                    else
                    {
                        titleString = dataIdentification.citation.CI_Citation.title.item as CharacterString_PropertyType;
                    }

                    title = titleString.CharacterString;

                    if (dataIdentification.pointOfContact != null &&
                        dataIdentification.pointOfContact[0] != null &&
                        dataIdentification.pointOfContact[0].CI_ResponsibleParty != null)
                    {
                        CI_ResponsibleParty_Type responsibleParty = dataIdentification.pointOfContact[0].CI_ResponsibleParty;

                        if (responsibleParty.organisationName != null && !string.IsNullOrWhiteSpace(responsibleParty.organisationName.CharacterString))
                        {
                            organization = responsibleParty.organisationName.CharacterString;
                        }

                        if (responsibleParty.individualName != null &&
                            !string.IsNullOrWhiteSpace(responsibleParty.individualName.CharacterString))
                        {
                            contactInformation.Append(responsibleParty.individualName.CharacterString);
                        }

                        if (responsibleParty.contactInfo != null && responsibleParty.contactInfo.CI_Contact != null)
                        {
                            var contact = responsibleParty.contactInfo.CI_Contact;


                            if (contact.address != null && contact.address.CI_Address != null)
                            {
                                var address = contact.address.CI_Address;
                                if (address.electronicMailAddress != null && address.electronicMailAddress[0] != null &&
                                    !string.IsNullOrWhiteSpace(address.electronicMailAddress[0].CharacterString))
                                {
                                    contactInformation.Append(" - ").Append(address.electronicMailAddress[0].CharacterString).Append("\n");
                                }
                                else
                                {
                                    contactInformation.Append("\n");
                                }


                                if (address.deliveryPoint != null && address.deliveryPoint[0] != null &&
                                    !string.IsNullOrWhiteSpace(address.deliveryPoint[0].CharacterString))
                                {
                                    contactInformation.Append(address.deliveryPoint[0].CharacterString).Append(", ");
                                }

                                if (address.postalCode != null && !string.IsNullOrWhiteSpace(address.postalCode.CharacterString))
                                {
                                    contactInformation.Append(address.postalCode.CharacterString).Append(" ");
                                }

                                if (address.city != null && !string.IsNullOrWhiteSpace(address.city.CharacterString))
                                {
                                    contactInformation.Append(address.city.CharacterString);
                                }
                            }



                            if (contact.phone != null && contact.phone.CI_Telephone != null &&
                                contact.phone.CI_Telephone.voice != null && contact.phone.CI_Telephone.voice[0] != null &&
                                !string.IsNullOrWhiteSpace(contact.phone.CI_Telephone.voice[0].CharacterString))
                            {
                                contactInformation.Append("\nTlf: ").Append(contact.phone.CI_Telephone.voice[0].CharacterString);
                            }
                        }
                    }


                    // collect keywords
                    if (dataIdentification.descriptiveKeywords != null)
                    {
                        foreach (var descriptiveKeyword in dataIdentification.descriptiveKeywords)
                        {
                            if (descriptiveKeyword.MD_Keywords != null && descriptiveKeyword.MD_Keywords.keyword != null)
                            {
                                foreach (var singleKeyword in descriptiveKeyword.MD_Keywords.keyword)
                                {
                                    if (singleKeyword.keyword != null)
                                    {
                                        string keywordValue = GetStringOrNull(singleKeyword);

                                        keywords.Add(keywordValue);

                                        /** old way of determine inspire or norge digitalt
                                         * if (singleKeyword.CharacterString.Equals("annet", StringComparison.InvariantCultureIgnoreCase))
                                         * {
                                         *  inspireResource = false;
                                         * }
                                         **/
                                    }
                                }
                            }
                        }
                    }


                    inspireResource = IsInspireResource(metadata);

                    // collect purpose

                    if (dataIdentification.purpose != null && !string.IsNullOrWhiteSpace(dataIdentification.purpose.CharacterString))
                    {
                        purpose = dataIdentification.purpose.CharacterString;
                    }


                    // collect abstract

                    if (dataIdentification.@abstract != null && !string.IsNullOrWhiteSpace([email protected]))
                    {
                        abstractText = [email protected];
                    }
                }
            }

            if (inspireResource)
            {
                inspireResource = IsApplicableForInspireValidation(resourceType);
            }

            return(new MetadataEntry()
            {
                Uuid = uuid,
                Title = title,
                ResourceType = resourceType,
                ResponsibleOrganization = organization,
                InspireResource = inspireResource,
                ValidationResults = new List <ValidationResult>(),
                ContactInformation = contactInformation.ToString(),
                Keywords = string.Join(", ", keywords),
                Purpose = purpose,
                Abstract = abstractText
            });
        }
Example #16
0
        public void ShouldReturnSingleIsoRecord()
        {
            MD_Metadata_Type record = _geonorge.GetRecordByUuid("63c672fa-e180-4601-a176-6bf163e0929d"); // Matrikkelen WMS

            Assert.NotNull(record, "Record does not exist.");
        }
        public ProductSheet UpdateProductSheetFromMetadata(string uuid, ProductSheet productSheet)
        {
            register = new RegisterFetcher();
            MD_Metadata_Type metadata = _geonorge.GetRecordByUuid(uuid);

            if (metadata == null)
            {
                throw new InvalidOperationException("Metadata not found for uuid: " + uuid);
            }

            var simpleMetadata = new SimpleMetadata(metadata);

            dynamic metedataExtended = register.GetMetadataExtended(simpleMetadata.Uuid);


            productSheet.Uuid                          = simpleMetadata.Uuid;
            productSheet.Title                         = simpleMetadata.Title;
            productSheet.Description                   = simpleMetadata.Abstract;
            productSheet.SupplementalDescription       = simpleMetadata.SupplementalDescription;
            productSheet.Purpose                       = simpleMetadata.Purpose;
            productSheet.SpecificUsage                 = simpleMetadata.SpecificUsage;
            productSheet.UseLimitations                = simpleMetadata.Constraints != null ? simpleMetadata.Constraints.UseLimitations : null;
            productSheet.UseConstraintsLicenseLink     = simpleMetadata.Constraints != null ? simpleMetadata.Constraints.UseConstraintsLicenseLink : null;
            productSheet.UseConstraintsLicenseLinkText = simpleMetadata.Constraints != null ? simpleMetadata.Constraints.UseConstraintsLicenseLinkText : null;
            productSheet.ContactMetadata               = simpleMetadata.ContactMetadata != null?CreateContact(simpleMetadata.ContactMetadata) : new Contact();

            productSheet.ContactPublisher = simpleMetadata.ContactPublisher != null?CreateContact(simpleMetadata.ContactPublisher) : new Contact();

            productSheet.ContactOwner = simpleMetadata.ContactOwner != null?CreateContact(simpleMetadata.ContactOwner) : new Contact();

            productSheet.ResolutionScale      = simpleMetadata.ResolutionScale;
            productSheet.KeywordsPlace        = CreateKeywords(SimpleKeyword.Filter(simpleMetadata.Keywords, SimpleKeyword.TYPE_PLACE, null));
            productSheet.ProcessHistory       = simpleMetadata.ProcessHistory;
            productSheet.MaintenanceFrequency = simpleMetadata.MaintenanceFrequency;
            productSheet.Status = simpleMetadata.Status;
            productSheet.DistributionFormatName    = simpleMetadata.DistributionFormat != null ? simpleMetadata.DistributionFormat.Name : null;
            productSheet.DistributionFormatVersion = simpleMetadata.DistributionFormat != null ? simpleMetadata.DistributionFormat.Version : null;
            productSheet.DistributionFormats       = GetDistributionFormats(simpleMetadata.DistributionFormats);
            productSheet.AccessConstraints         = simpleMetadata.Constraints != null?register.GetRestriction(simpleMetadata.Constraints.AccessConstraints, simpleMetadata.Constraints.OtherConstraintsAccess) : null;

            productSheet.LegendDescriptionUrl    = simpleMetadata.LegendDescriptionUrl;
            productSheet.ProductPageUrl          = simpleMetadata.ProductPageUrl;
            productSheet.ProductSpecificationUrl = simpleMetadata.ProductSpecificationUrl;
            foreach (var thumbnail in simpleMetadata.Thumbnails)
            {
                productSheet.Thumbnail = thumbnail.URL;
                if (!thumbnail.URL.StartsWith("http"))
                {
                    productSheet.Thumbnail = "https://www.geonorge.no/geonetwork/srv/nor/resources.get?uuid=" + simpleMetadata.Uuid + "&access=public&fname=" + thumbnail.URL;
                }
                if (thumbnail.Type == "large_thumbnail")
                {
                    break;
                }
            }
            //productSheet.CoverageArea = !string.IsNullOrWhiteSpace(simpleMetadata.CoverageUrl) ? GetCoverageLink(simpleMetadata.CoverageUrl, uuid) : "";
            productSheet.CoverageArea = metedataExtended.CoverageUrl;
            productSheet.Projections  = simpleMetadata.ReferenceSystems != null?getProjections(simpleMetadata.ReferenceSystems) : "";


            return(productSheet);
        }
        private void CreateDatasets(XmlElement root, XmlElement catalog)
        {
            Dictionary <string, XmlNode> foafAgents = new Dictionary <string, XmlNode>();
            Dictionary <string, XmlNode> vcardKinds = new Dictionary <string, XmlNode>();
            Dictionary <string, XmlNode> services   = new Dictionary <string, XmlNode>();

            for (int d = 0; d < metadataSets.Items.Length; d++)
            {
                string           uuid = ((www.opengis.net.DCMIRecordType)(metadataSets.Items[d])).Items[0].Text[0];
                MD_Metadata_Type md   = geoNorge.GetRecordByUuid(uuid);
                var data = new SimpleMetadata(md);

                if (data.DistributionFormats != null && data.DistributionFormats.Count > 0 &&
                    !string.IsNullOrEmpty(data.DistributionFormats[0].Name) &&
                    data.DistributionDetails != null && !string.IsNullOrEmpty(data.DistributionDetails.Protocol))
                {
                    Log.Info($"Processing dataset: [title={data.Title}], [uuid={uuid}]");

                    //Map dataset to catalog
                    XmlElement catalogDataset = doc.CreateElement("dcat", "dataset", xmlnsDcat);
                    catalogDataset.SetAttribute("resource", xmlnsRdf, kartkatalogenUrl + "Metadata/uuid/" + data.Uuid);
                    catalog.AppendChild(catalogDataset);

                    XmlElement dataset = doc.CreateElement("dcat", "Dataset", xmlnsDcat);
                    dataset.SetAttribute("about", xmlnsRdf, kartkatalogenUrl + "Metadata/uuid/" + data.Uuid);
                    root.AppendChild(dataset);

                    XmlElement datasetIdentifier = doc.CreateElement("dct", "identifier", xmlnsDct);
                    datasetIdentifier.InnerText = data.Uuid.ToString();
                    dataset.AppendChild(datasetIdentifier);

                    XmlElement datasetTitle = doc.CreateElement("dct", "title", xmlnsDct);
                    datasetTitle.SetAttribute("xml:lang", "no");
                    datasetTitle.InnerText = data.Title;
                    dataset.AppendChild(datasetTitle);


                    XmlElement datasetDescription = doc.CreateElement("dct", "description", xmlnsDct);
                    datasetDescription.SetAttribute("xml:lang", "no");
                    if (!string.IsNullOrEmpty(data.Abstract))
                    {
                        datasetDescription.InnerText = data.Abstract;
                    }
                    dataset.AppendChild(datasetDescription);

                    foreach (var keyword in data.Keywords)
                    {
                        XmlElement datasetKeyword = doc.CreateElement("dcat", "keyword", xmlnsDcat);
                        datasetKeyword.SetAttribute("xml:lang", "no");
                        datasetKeyword.InnerText = keyword.Keyword;
                        dataset.AppendChild(datasetKeyword);
                    }

                    //Place
                    // URI for the geographic identifier
                    var places = SimpleKeyword.Filter(data.Keywords, null, SimpleKeyword.THESAURUS_ADMIN_UNITS);

                    foreach (var place in places)
                    {
                        var aboutPlace = place.KeywordLink;

                        if (!string.IsNullOrEmpty(aboutPlace))
                        {
                            XmlElement datasetLocation = doc.CreateElement("dct", "spatial", xmlnsDct);
                            datasetLocation.InnerText = aboutPlace;
                            dataset.AppendChild(datasetLocation);
                        }
                    }

                    //Resource metadata in GeoDCAT - AP using a geographic bounding box
                    if (data.BoundingBox != null)
                    {
                        XmlElement datasetSpatial = doc.CreateElement("dct", "spatial", xmlnsDct);
                        datasetSpatial.SetAttribute("rdf:parseType", "Resource");

                        XmlElement spatialLocn = doc.CreateElement("locn", "geometry", xmlnsLocn);
                        spatialLocn.SetAttribute("rdf:datatype", "http://www.opengis.net/ont/geosparql#gmlLiteral");

                        var cdata = doc.CreateCDataSection("<gml:Envelope srsName=\"http://www.opengis.net/def/crs/OGC/1.3/CRS84\"><gml:lowerCorner>" + data.BoundingBox.WestBoundLongitude + " " + data.BoundingBox.SouthBoundLatitude + "</gml:lowerCorner><gml:upperCorner>" + data.BoundingBox.EastBoundLongitude + " " + data.BoundingBox.NorthBoundLatitude + "</gml:upperCorner></gml:Envelope>");
                        spatialLocn.AppendChild(cdata);

                        datasetSpatial.AppendChild(spatialLocn);

                        dataset.AppendChild(datasetSpatial);
                    }

                    List <string> themes = new List <string>();

                    string euLink = "http://publications.europa.eu/resource/authority/data-theme/";

                    //National theme
                    var nationalThemes = SimpleKeyword.Filter(data.Keywords, null, SimpleKeyword.THESAURUS_NATIONAL_THEME);

                    foreach (var theme in nationalThemes)
                    {
                        var aboutConcept = GetConcept(theme.Keyword);

                        if (!string.IsNullOrEmpty(aboutConcept))
                        {
                            themes.Add(aboutConcept);
                        }

                        if (Mappings.ThemeNationalToEU.ContainsKey(theme.Keyword))
                        {
                            themes.Add(euLink + Mappings.ThemeNationalToEU[theme.Keyword]);
                        }
                    }

                    //Inspire thene
                    var themeInspires = SimpleKeyword.Filter(data.Keywords, null, SimpleKeyword.THESAURUS_GEMET_INSPIRE_V1);

                    foreach (var themeInspire in themeInspires)
                    {
                        if (Mappings.ThemeInspireToEU.ContainsKey(themeInspire.Keyword))
                        {
                            if (!themes.Contains(euLink + Mappings.ThemeInspireToEU[themeInspire.Keyword]))
                            {
                                themes.Add(euLink + Mappings.ThemeInspireToEU[themeInspire.Keyword]);
                            }
                        }
                    }

                    //Concepts
                    var conceptThemes = SimpleKeyword.Filter(data.Keywords, null, SimpleKeyword.THESAURUS_CONCEPT);

                    foreach (var theme in conceptThemes)
                    {
                        var aboutConcept = theme.KeywordLink;

                        if (!string.IsNullOrEmpty(aboutConcept))
                        {
                            if (!ConceptObjects.ContainsKey(aboutConcept))
                            {
                                ConceptObjects.Add(aboutConcept, aboutConcept);
                                themes.Add(aboutConcept);
                            }
                        }
                    }

                    foreach (var theme in themes)
                    {
                        XmlElement datasetTheme;
                        if (theme.Contains("objektkatalog.geonorge.no"))
                        {
                            datasetTheme = doc.CreateElement("dct", "subject", xmlnsDct);
                        }
                        else
                        {
                            datasetTheme = doc.CreateElement("dcat", "theme", xmlnsDcat);
                        }
                        datasetTheme.SetAttribute("resource", xmlnsRdf, theme);
                        dataset.AppendChild(datasetTheme);
                    }


                    if (data.Thumbnails != null && data.Thumbnails.Count > 0)
                    {
                        XmlElement datasetThumbnail = doc.CreateElement("foaf", "thumbnail", xmlnsFoaf);
                        datasetThumbnail.SetAttribute("resource", xmlnsRdf, EncodeUrl(data.Thumbnails[0].URL));
                        dataset.AppendChild(datasetThumbnail);
                    }


                    XmlElement datasetUpdated = doc.CreateElement("dct", "updated", xmlnsDct);
                    datasetUpdated.SetAttribute("datatype", xmlnsRdf, "http://www.w3.org/2001/XMLSchema#date");
                    if (data.DateUpdated.HasValue)
                    {
                        datasetUpdated.InnerText = data.DateUpdated.Value.ToString("yyyy-MM-dd");
                        if (!catalogLastModified.HasValue || data.DateUpdated > catalogLastModified)
                        {
                            catalogLastModified = data.DateUpdated;
                        }
                    }
                    dataset.AppendChild(datasetUpdated);


                    XmlElement datasetPublisher = doc.CreateElement("dct", "publisher", xmlnsDct);
                    if (data.ContactOwner != null && !string.IsNullOrEmpty(data.ContactOwner.Organization) && OrganizationsLink.ContainsKey(data.ContactOwner.Organization) && OrganizationsLink[data.ContactOwner.Organization] != null)
                    {
                        datasetPublisher.SetAttribute("resource", xmlnsRdf, OrganizationsLink[data.ContactOwner.Organization]);
                    }

                    dataset.AppendChild(datasetPublisher);

                    Organization organization = null;

                    if (data.ContactOwner != null)
                    {
                        Log.Info("Looking up organization: " + data.ContactOwner.Organization);
                        Task <Organization> getOrganizationTask = _organizationService.GetOrganizationByName(data.ContactOwner.Organization);
                        organization = getOrganizationTask.Result;
                    }

                    XmlElement datasetContactPoint = doc.CreateElement("dcat", "contactPoint", xmlnsDcat);
                    if (data.ContactOwner != null && !string.IsNullOrEmpty(data.ContactOwner.Organization) && OrganizationsLink.ContainsKey(data.ContactOwner.Organization) && OrganizationsLink[data.ContactOwner.Organization] != null)
                    {
                        datasetContactPoint.SetAttribute("resource", xmlnsRdf, OrganizationsLink[data.ContactOwner.Organization].Replace("organisasjoner/kartverket/", "organisasjoner/"));
                    }
                    dataset.AppendChild(datasetContactPoint);

                    XmlElement datasetKind = doc.CreateElement("vcard", "Organization", xmlnsVcard);
                    if (data.ContactOwner != null && !string.IsNullOrEmpty(data.ContactOwner.Organization) && OrganizationsLink.ContainsKey(data.ContactOwner.Organization) && OrganizationsLink[data.ContactOwner.Organization] != null)
                    {
                        datasetKind.SetAttribute("about", xmlnsRdf, OrganizationsLink[data.ContactOwner.Organization].Replace("organisasjoner/kartverket/", "organisasjoner/"));
                    }

                    XmlElement datasetOrganizationName = doc.CreateElement("vcard", "organization-unit", xmlnsVcard);
                    datasetOrganizationName.SetAttribute("xml:lang", "");
                    if (organization != null)
                    {
                        datasetOrganizationName.InnerText = organization.Name;
                    }
                    datasetKind.AppendChild(datasetOrganizationName);

                    if (data.ContactOwner != null && !string.IsNullOrEmpty(data.ContactOwner.Email))
                    {
                        XmlElement datasetHasEmail = doc.CreateElement("vcard", "hasEmail", xmlnsVcard);
                        datasetHasEmail.SetAttribute("resource", xmlnsRdf, "mailto:" + data.ContactOwner.Email);
                        datasetKind.AppendChild(datasetHasEmail);
                    }
                    if (data.ContactOwner != null && !string.IsNullOrEmpty(data.ContactOwner.Organization) && OrganizationsLink.ContainsKey(data.ContactOwner.Organization) && OrganizationsLink[data.ContactOwner.Organization] != null)
                    {
                        if (!vcardKinds.ContainsKey(OrganizationsLink[data.ContactOwner.Organization].Replace("organisasjoner/kartverket/", "organisasjoner/")))
                        {
                            vcardKinds.Add(OrganizationsLink[data.ContactOwner.Organization].Replace("organisasjoner/kartverket/", "organisasjoner/"), datasetKind);
                        }
                    }


                    XmlElement datasetAccrualPeriodicity = doc.CreateElement("dct", "accrualPeriodicity", xmlnsDct);
                    if (!string.IsNullOrEmpty(data.MaintenanceFrequency))
                    {
                        datasetAccrualPeriodicity.InnerText = data.MaintenanceFrequency;
                    }
                    dataset.AppendChild(datasetAccrualPeriodicity);

                    XmlElement datasetGranularity = doc.CreateElement("dcat", "granularity", xmlnsDcat);
                    if (!string.IsNullOrEmpty(data.ResolutionScale))
                    {
                        datasetGranularity.InnerText = data.ResolutionScale;
                    }
                    dataset.AppendChild(datasetGranularity);

                    XmlElement datasetLicense = doc.CreateElement("dct", "license", xmlnsDct);
                    if (data.Constraints != null && !string.IsNullOrEmpty(data.Constraints.OtherConstraintsLink))
                    {
                        datasetLicense.SetAttribute("resource", xmlnsRdf, data.Constraints.OtherConstraintsLink);
                    }
                    dataset.AppendChild(datasetLicense);

                    var        accessConstraint = "PUBLIC";
                    XmlElement datasetAccess    = doc.CreateElement("dct", "accessRights", xmlnsDct);
                    if (data.Constraints != null &&
                        !string.IsNullOrEmpty(data.Constraints.AccessConstraints))
                    {
                        if (data.Constraints.AccessConstraints.ToLower() == "restricted")
                        {
                            accessConstraint = "NON-PUBLIC";
                        }
                        else if (data.Constraints.AccessConstraints == "norway digital restricted" || (data.Constraints.AccessConstraints == "otherRestrictions" && !string.IsNullOrEmpty(data.Constraints.OtherConstraintsAccess) &&
                                                                                                       data.Constraints.OtherConstraintsAccess.ToLower() == "norway digital restricted"))
                        {
                            accessConstraint = "RESTRICTED";
                        }
                    }
                    datasetAccess.SetAttribute("resource", xmlnsRdf, "http://publications.europa.eu/resource/authority/access-right/" + accessConstraint);
                    dataset.AppendChild(datasetAccess);


                    XmlElement datasetDataQuality = doc.CreateElement("dcat", "dataQuality", xmlnsDcat);
                    if (!string.IsNullOrEmpty(data.ProcessHistory))
                    {
                        datasetDataQuality.InnerText = data.ProcessHistory;
                    }
                    dataset.AppendChild(datasetDataQuality);

                    //Distribution
                    if (data.DistributionFormats != null)
                    {
                        foreach (var distro in data.DistributionFormats)
                        {
                            if (!string.IsNullOrEmpty(distro.Name))
                            {
                                //Map distribution to dataset
                                XmlElement distributionDataset = doc.CreateElement("dcat", "distribution", xmlnsDcat);
                                distributionDataset.SetAttribute("resource", xmlnsRdf, kartkatalogenUrl + "Metadata/uuid/" + data.Uuid + "/" + HttpUtility.UrlEncode(distro.Name));
                                dataset.AppendChild(distributionDataset);

                                XmlElement distribution = doc.CreateElement("dcat", "Distribution", xmlnsDcat);
                                distribution.SetAttribute("about", xmlnsRdf, kartkatalogenUrl + "Metadata/uuid/" + data.Uuid + "/" + HttpUtility.UrlEncode(distro.Name));
                                root.AppendChild(distribution);

                                XmlElement distributionTitle = doc.CreateElement("dct", "title", xmlnsDct);
                                distributionTitle.SetAttribute("xml:lang", "no");
                                if (data.DistributionDetails != null && !string.IsNullOrEmpty(data.DistributionDetails.Protocol))
                                {
                                    distributionTitle.InnerText = GetDistributionTitle(data.DistributionDetails.Protocol);
                                }
                                distribution.AppendChild(distributionTitle);

                                XmlElement distributionDescription = doc.CreateElement("dct", "description", xmlnsDct);
                                if (data.DistributionDetails != null && !string.IsNullOrEmpty(data.DistributionDetails.Protocol))
                                {
                                    distributionDescription.InnerText = GetDistributionDescription(data.DistributionDetails.Protocol);
                                }
                                distribution.AppendChild(distributionDescription);

                                XmlElement distributionFormat = doc.CreateElement("dct", "format", xmlnsDct);
                                if (MediaTypes.ContainsKey(distro.Name))
                                {
                                    distributionFormat.SetAttribute("resource", xmlnsRdf, MediaTypes[distro.Name]);
                                }
                                else
                                {
                                    distributionFormat.InnerText = distro.Name;
                                }
                                distribution.AppendChild(distributionFormat);

                                XmlElement distributionAccessURL = doc.CreateElement("dcat", "accessURL", xmlnsDcat);
                                distributionAccessURL.SetAttribute("resource", xmlnsRdf, kartkatalogenUrl + "metadata/uuid/" + uuid);
                                distribution.AppendChild(distributionAccessURL);

                                XmlElement distributionLicense = doc.CreateElement("dct", "license", xmlnsDct);
                                if (data.Constraints != null && !string.IsNullOrEmpty(data.Constraints.OtherConstraintsLink))
                                {
                                    distributionLicense.SetAttribute("resource", xmlnsRdf, data.Constraints.OtherConstraintsLink);
                                }
                                distribution.AppendChild(distributionLicense);

                                XmlElement distributionStatus = doc.CreateElement("adms", "status", xmlnsAdms);
                                if (!string.IsNullOrEmpty(data.Status))
                                {
                                    distributionStatus.SetAttribute("resource", xmlnsRdf, "http://purl.org/adms/status/" + data.Status);
                                }
                                distribution.AppendChild(distributionStatus);
                            }
                        }
                    }

                    // Dataset distributions
                    AddDistributions(uuid, dataset, data, services);


                    //Agent/publisher

                    XmlElement agent = doc.CreateElement("foaf", "Agent", xmlnsFoaf);
                    if (data.ContactOwner != null && !string.IsNullOrEmpty(data.ContactOwner.Organization) && OrganizationsLink.ContainsKey(data.ContactOwner.Organization) && OrganizationsLink[data.ContactOwner.Organization] != null)
                    {
                        agent.SetAttribute("about", xmlnsRdf, OrganizationsLink[data.ContactOwner.Organization]);
                    }

                    XmlElement agentType = doc.CreateElement("dct", "type", xmlnsDct);
                    agentType.SetAttribute("resource", xmlnsRdf, "http://purl.org/adms/publishertype/NationalAuthority");
                    agent.AppendChild(agentType);


                    if (organization != null && !string.IsNullOrEmpty(organization.Number))
                    {
                        XmlElement agentIdentifier = doc.CreateElement("dct", "identifier", xmlnsDct);
                        agentIdentifier.InnerText = organization.Number;
                        agent.AppendChild(agentIdentifier);
                    }

                    XmlElement agentName = doc.CreateElement("foaf", "name", xmlnsFoaf);
                    if (organization != null)
                    {
                        agentName.InnerText = organization.Name;
                    }
                    agent.AppendChild(agentName);

                    if (data.ContactOwner != null && !string.IsNullOrEmpty(data.ContactOwner.Email))
                    {
                        XmlElement agentMbox = doc.CreateElement("foaf", "mbox", xmlnsFoaf);
                        agentMbox.InnerText = data.ContactOwner.Email;
                        agent.AppendChild(agentMbox);
                    }

                    if (organization != null && !string.IsNullOrEmpty(organization.Number))
                    {
                        XmlElement agentSameAs = doc.CreateElement("owl", "sameAs", xmlnsOwl);
                        agentSameAs.InnerText = "http://data.brreg.no/enhetsregisteret/enhet/" + organization.Number;
                        agent.AppendChild(agentSameAs);
                    }

                    if (data.ContactOwner != null && !string.IsNullOrEmpty(data.ContactOwner.Organization) && OrganizationsLink.ContainsKey(data.ContactOwner.Organization) && OrganizationsLink[data.ContactOwner.Organization] != null)
                    {
                        if (!foafAgents.ContainsKey(OrganizationsLink[data.ContactOwner.Organization]))
                        {
                            foafAgents.Add(OrganizationsLink[data.ContactOwner.Organization], agent);
                        }
                    }
                }
            }

            foreach (var foafAgent in foafAgents)
            {
                root.AppendChild(foafAgent.Value);
            }

            foreach (var vcardKind in vcardKinds)
            {
                root.AppendChild(vcardKind.Value);
            }

            foreach (var service in services)
            {
                root.AppendChild(service.Value);
            }

            AppendConcepts(root);
        }