/// <summary>
        /// Gets a graph corresponding to the query result
        /// </summary>
        public RDFGraph ToRDFGraph()
        {
            RDFGraph         result = new RDFGraph();
            RDFPatternMember subj   = null;
            RDFPatternMember pred   = null;
            RDFPatternMember obj    = null;

            //Iterate the datatable rows and generate the corresponding triples to be added to the result graph
            IEnumerator resultRows = this.ConstructResults.Rows.GetEnumerator();

            while (resultRows.MoveNext())
            {
                subj = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["?SUBJECT"].ToString());
                pred = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["?PREDICATE"].ToString());
                obj  = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["?OBJECT"].ToString());
                if (obj is RDFResource)
                {
                    result.AddTriple(new RDFTriple((RDFResource)subj, (RDFResource)pred, (RDFResource)obj));
                }
                else
                {
                    result.AddTriple(new RDFTriple((RDFResource)subj, (RDFResource)pred, (RDFLiteral)obj));
                }
            }

            return(result);
        }
 /// <summary>
 /// Rebuild the metadata of the given graph
 /// </summary>
 internal static void RebuildGraph(RDFGraph graph) {
     var triples = new Dictionary<Int64, RDFTriple>(graph.Triples);
     graph.ClearTriples();
     foreach (var t in triples) {
         graph.AddTriple(t.Value);
     }
 }
        /// <summary>
        /// Gets a graph representation of this reasoner report
        /// </summary>
        public RDFGraph ToRDFGraph()
        {
            RDFGraph result = new RDFGraph();

            foreach (RDFOntologyReasonerEvidence evidence in this)
            {
                result.AddTriple(evidence.ToRDFTriple());
            }
            return(result);
        }
Exemple #4
0
        private void BuildGraphWithValues(RDFGraph grap)
        {
            const int SUBJ_COUNT = 5;
            const int VAL_COUNT  = 5;

            RDFResource obj = new RDFResource(string.Concat(RDF.BASE_URI, "example_object"));

            for (int j = 0; j < SUBJ_COUNT; j++)
            {
                RDFResource tempSubject = new RDFResource(string.Concat(RDF.BASE_URI, "example_subject" + j));
                graph.AddTriple(new RDFTriple(tempSubject, RDF.TYPE, obj));
                for (int k = 0; k < VAL_COUNT; k++)
                {
                    int tempValue = (j + 1) * 10;
                    graph.AddTriple(new RDFTriple(
                                        tempSubject,
                                        RDF.VALUE,
                                        new RDFTypedLiteral(tempValue.ToString(), RDFModelEnums.RDFDatatypes.XSD_INTEGER)));
                }
            }
        }
        private void BuildGraph(RDFGraph graph, int count)
        {
            RDFResource tempObject1 = new RDFResource(string.Concat(RDF.BASE_URI, "example_object_1"));
            RDFResource tempObject2 = new RDFResource(string.Concat(RDF.BASE_URI, "example_object_2"));

            for (int i = 0; i < count; i++)
            {
                RDFResource newSubject = new RDFResource(string.Concat(RDF.BASE_URI, "example_subject_" + i));
                RDFResource newObject  = (count < 30) ? tempObject1 : tempObject2;
                graph.AddTriple(new RDFTriple(newSubject, RDF.TYPE, newObject));
            }
        }
Exemple #6
0
        /// <summary>
        /// Gets a graph representation of this target
        /// </summary>
        internal override RDFGraph ToRDFGraph(RDFShape shape)
        {
            var result = new RDFGraph();

            //sh:targetClass
            if (shape != null)
            {
                result.AddTriple(new RDFTriple(shape, RDFVocabulary.SHACL.TARGET_CLASS, this.TargetValue));
            }

            return(result);
        }
        /// <summary>
        /// Gets a graph representation of this target
        /// </summary>
        internal override RDFGraph ToRDFGraph(RDFShape shape)
        {
            var result = new RDFGraph();

            //sh:targetSubjectsOf
            if (shape != null)
            {
                result.AddTriple(new RDFTriple(shape, RDFVocabulary.SHACL.TARGET_SUBJECTS_OF, this.TargetValue));
            }

            return(result);
        }
        /// <summary>
        /// Builds a graph corresponding to the query result
        /// </summary>
        public RDFGraph ToRDFGraph() {
            RDFGraph result        = new RDFGraph();
            RDFPatternMember subj  = null;
            RDFPatternMember pred  = null;
            RDFPatternMember obj   = null;

            //Iterate the datatable rows and generate the corresponding triples to be added to the result graph
            IEnumerator resultRows = this.DescribeResults.Rows.GetEnumerator();
            while (resultRows.MoveNext()) {
                subj               = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["SUBJECT"].ToString());
                pred               = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["PREDICATE"].ToString());
                obj                = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["OBJECT"].ToString());
                if (obj is RDFResource) {
                    result.AddTriple(new RDFTriple((RDFResource)subj, (RDFResource)pred, (RDFResource)obj));
                }
                else {
                    result.AddTriple(new RDFTriple((RDFResource)subj, (RDFResource)pred, (RDFLiteral)obj));
                }
            }

            return result;
        }
        /// <summary>
        /// Gets a graph representation of this taxonomy, exporting inferences according to the selected behavior
        /// </summary>
        internal RDFGraph ToRDFGraph(RDFSemanticsEnums.RDFOntologyInferenceExportBehavior infexpBehavior)
        {
            var result = new RDFGraph();

            //Taxonomy entries
            foreach (var te in this)
            {
                //Do not export semantic inferences
                if (infexpBehavior == RDFSemanticsEnums.RDFOntologyInferenceExportBehavior.None)
                {
                    if (te.InferenceType == RDFSemanticsEnums.RDFOntologyInferenceType.None)
                    {
                        result.AddTriple(te.ToRDFTriple());
                    }
                }

                //Export semantic inferences related only to ontology model
                else if (infexpBehavior == RDFSemanticsEnums.RDFOntologyInferenceExportBehavior.OnlyModel)
                {
                    if (this.Category == RDFSemanticsEnums.RDFOntologyTaxonomyCategory.Model ||
                        this.Category == RDFSemanticsEnums.RDFOntologyTaxonomyCategory.Annotation)
                    {
                        result.AddTriple(te.ToRDFTriple());
                    }
                    else
                    {
                        if (te.InferenceType == RDFSemanticsEnums.RDFOntologyInferenceType.None)
                        {
                            result.AddTriple(te.ToRDFTriple());
                        }
                    }
                }

                //Export semantic inferences related only to ontology data
                else if (infexpBehavior == RDFSemanticsEnums.RDFOntologyInferenceExportBehavior.OnlyData)
                {
                    if (this.Category == RDFSemanticsEnums.RDFOntologyTaxonomyCategory.Data ||
                        this.Category == RDFSemanticsEnums.RDFOntologyTaxonomyCategory.Annotation)
                    {
                        result.AddTriple(te.ToRDFTriple());
                    }
                    else
                    {
                        if (te.InferenceType == RDFSemanticsEnums.RDFOntologyInferenceType.None)
                        {
                            result.AddTriple(te.ToRDFTriple());
                        }
                    }
                }

                //Export semantic inferences related both to ontology model and data
                else
                {
                    result.AddTriple(te.ToRDFTriple());
                }
            }
            return(result);
        }
Exemple #10
0
        private void BuildGraph(RDFGraph graph)
        {
            const int OBJ_COUNT  = 3;
            const int SUBJ_COUNT = 10;

            for (int i = 0; i < OBJ_COUNT; i++)
            {
                RDFResource obj = new RDFResource(string.Concat(RDF.BASE_URI, "example_object" + i));
                for (int j = 0; j < SUBJ_COUNT; j++)
                {
                    RDFResource tempSubject = new RDFResource(string.Concat(RDF.BASE_URI, "example_subject" + j));
                    graph.AddTriple(new RDFTriple(tempSubject, RDF.TYPE, obj));
                }
            }
        }
        public void AddTripleTest()
        {
            var testGraph = new RDFGraph(defaultTriples);
            var old       = new List <RDFTriple>(defaultTriples);
            var newTriple = TestModelObject.triples[2];

            old.Add(newTriple);
            testGraph.AddTriple(newTriple);
            var newList = new List <RDFTriple>();

            foreach (var triple in testGraph)
            {
                newList.Add(triple);
            }

            Assert.Equal(old, newList);
        }
Exemple #12
0
        public void TestSelectDistinctModifier()
        {
            // Arrange
            graph = new RDFGraph();
            RDFSelectQuery query;

            BuildGraph(graph);
            graph.AddTriple(        // add duplicate triple
                new RDFTriple(
                    new RDFResource(string.Concat(RDF.BASE_URI, "example_subject" + 0)),
                    RDF.TYPE,
                    new RDFResource(string.Concat(RDF.BASE_URI, "example_object" + 0))
                    )
                );

            // Act
            query = BuildSelectAllQuery();
            query.AddModifier(new RDFDistinctModifier());
            var result = query.ApplyToGraph(graph);

            // Assert
            Assert.AreEqual(30, result.SelectResultsCount);
        }
Exemple #13
0
        private void WorkingWithRdfModels()
        {
            // CREATE RESOURCE
            var donaldduck = new RDFResource("http://www.waltdisney.com/donald_duck");

            // CREATE BLANK RESOURCE
            var disney_group = new RDFResource();

            // CREATE PLAIN LITERAL
            // "Donald Duck"
            var donaldduck_name = new RDFPlainLiteral("Donald Duck");
            // CREATE PLAIN LITERAL WITH LANGUAGE TAG
            // "Donald Duck"@en-US
            var donaldduck_name_enusLiteral = new RDFPlainLiteral("Donald Duck", "en-US");
            // CREATE TYPED LITERAL
            // "85"^^xsd:integer
            var mickeymouse_age = new RDFTypedLiteral("85", RDFModelEnums.RDFDatatypes.XSD_INTEGER);


            // CREATE TRIPLES
            // "Mickey Mouse is 85 years old"
            RDFTriple mickeymouse_is85yr
                = new RDFTriple(
                      new RDFResource("http://www.waltdisney.com/mickey_mouse"),
                      new RDFResource("http://xmlns.com/foaf/0.1/age"),
                      new RDFTypedLiteral("85", RDFModelEnums.RDFDatatypes.XSD_INTEGER));

            // "Donald Duck has english (US) name "Donald Duck""
            RDFTriple donaldduck_name_enus = new RDFTriple(
                new RDFResource("http://www.waltdisney.com/donald_duck"),
                new RDFResource("http://xmlns.com/foaf/0.1/name"),
                new RDFPlainLiteral("Donald Duck", "en-US"));


            // CREATE EMPTY GRAPH
            var another_graph     = new RDFGraph();
            var waltdisney_filled = new RDFGraph();

            // CREATE GRAPH FROM A LIST OF TRIPLES
            var triples = new List <RDFTriple> {
                mickeymouse_is85yr, donaldduck_name_enus
            };
            var waltdisney = new RDFGraph(triples);

            // SET CONTEXT OF A GRAPH
            waltdisney.SetContext(new Uri("http://waltdisney.com/"));

            // GET A DATATABLE FROM A GRAPH
            var waltdisney_table = waltdisney.ToDataTable();
            // GET A GRAPH FROM A DATATABLE
            var waltdisney_newgraph = RDFGraph.FromDataTable(waltdisney_table);

            // ITERATE TRIPLES OF A GRAPH WITH FOREACH
            foreach (var t in waltdisney)
            {
                Console.WriteLine("Triple: " + t);
                Console.WriteLine(" Subject: " + t.Subject);
                Console.WriteLine(" Predicate: " + t.Predicate);
                Console.WriteLine(" Object: " + t.Object);
            }

            // ITERATE TRIPLES OF A GRAPH WITH ENUMERATOR
            var triplesEnum = waltdisney.TriplesEnumerator;

            while (triplesEnum.MoveNext())
            {
                Console.WriteLine("Triple: " + triplesEnum.Current);
                Console.WriteLine(" Subject: " + triplesEnum.Current.Subject);
                Console.WriteLine(" Predicate: " + triplesEnum.Current.Predicate);
                Console.WriteLine(" Object: " + triplesEnum.Current.Object);
            }

            // GET COUNT OF TRIPLES CONTAINED IN A GRAPH
            var triplesCount = waltdisney.TriplesCount;

            // MULTIPLE SELECTIONS
            var multiple_selections_graph =
                waltdisney.SelectTriplesBySubject(new RDFResource("http://www.waltdisney.com/donald_duck"))
                .SelectTriplesByPredicate(new RDFResource("http://xmlns.com/foaf/0.1/name"));

            // SET OPERATIONS
            var set_operations_graph = waltdisney.IntersectWith(waltdisney_filled).UnionWith(another_graph);



            /*
             * var ntriplesFormat = RDFModelEnums.RDFFormats.NTriples;
             * // READ N-TRIPLES FILE
             * var graph = RDFGraph.FromFile(ntriplesFormat, "C:\\file.nt");
             * // READ N-TRIPLES STREAM
             * var graph = RDFGraph.FromStream(ntriplesFormat, inStream);
             * // WRITE N-TRIPLES FILE
             * graph.ToFile(ntriplesFormat, "C:\\newfile.nt");
             * // WRITE N-TRIPLES STREAM
             * graph.ToStream(ntriplesFormat, outStream);
             */

            /*
             * var turtleFormat = RDFModelEnums.RDFFormats.Turtle;
             * // READ TURTLE FILE
             * var graph = RDFGraph.FromFile(turtleFormat, "C:\\file.ttl");
             * // READ TURTLE STREAM
             * var graph = RDFGraph.FromStream(turtleFormat, inStream);
             * // WRITE TURTLE FILE
             * graph.ToFile(turtleFormat, "C:\\newfile.ttl");
             * // WRITE TURTLE STREAM
             * graph.ToStream(turtleFormat, outStream);
             */

            /*
             * var xmlFormat = RDFModelEnums.RDFFormats.RdfXml;
             * // READ RDF/XML FILE
             * var graph = RDFGraph.FromFile(xmlFormat, "C:\\file.rdf");
             * // READ RDF/XML STREAM
             * var graph = RDFGraph.FromStream(xmlFormat, inStream);
             * // WRITE RDF/XML FILE
             * graph.ToFile(xmlFormat, "C:\\newfile.rdf");
             * // WRITE RDF/XML STREAM
             * graph.ToStream(xmlFormat, outStream);
             */

            // CREATE NAMESPACE
            var waltdisney_ns = new RDFNamespace("wd", "http://www.waltdisney.com/");

            // USE NAMESPACE IN RESOURCE CREATION
            var duckburg = new RDFResource(waltdisney_ns + "duckburg");
            var mouseton = new RDFResource(waltdisney_ns + "mouseton");


            RDFNamespaceRegister.AddNamespace(waltdisney_ns);

            // Retrieves a namespace by seeking presence of its prefix (null if not found). Supports prefix.cc
            var ns1 = RDFNamespaceRegister.GetByPrefix("dbpedia", false); //local search
            var ns2 = RDFNamespaceRegister.GetByPrefix("dbpedia", true);  //search prefix.cc service if no result

            // GET DEFAULT NAMESPACE
            var nSpace = RDFNamespaceRegister.DefaultNamespace;

            // SET DEFAULT NAMESPACE
            RDFNamespaceRegister.SetDefaultNamespace(waltdisney_ns); //new graphs will default to this context

            // ITERATE NAMESPACES OF REGISTER WITH FOREACH
            foreach (var ns in RDFNamespaceRegister.Instance)
            {
                Console.WriteLine("Prefix: " + ns.NamespacePrefix);
                Console.WriteLine("Namespace: " + ns.NamespaceUri);
            }

            // ITERATE NAMESPACES OF REGISTER WITH ENUMERATOR
            var nspacesEnum = RDFNamespaceRegister.NamespacesEnumerator;

            while (nspacesEnum.MoveNext())
            {
                Console.WriteLine("Prefix: " + nspacesEnum.Current.NamespacePrefix);
                Console.WriteLine("Namespace: " + nspacesEnum.Current.NamespaceUri);
            }


            // CREATE TRIPLES WITH VOCABULARY FACILITIES
            // "Goofy Goof is 82 years old"
            RDFTriple goofygoof_is82yr = new RDFTriple(
                new RDFResource(new Uri("http://www.waltdisney.com/goofy_goof").ToString()),
                RDFVocabulary.FOAF.AGE,
                new RDFPlainLiteral("82")
                );

            // "Donald Duck knows Goofy Goof"
            RDFTriple donaldduck_knows_goofygoof = new RDFTriple(
                new RDFResource(new Uri("http://www.waltdisney.com/donald_duck").ToString()),
                RDFVocabulary.FOAF.KNOWS,
                new RDFResource(new Uri("http://www.waltdisney.com/goofy_goof").ToString())
                );

            // CREATE TYPED LITERALS
            var myAge      = new RDFTypedLiteral("34", RDFModelEnums.RDFDatatypes.XSD_INT);
            var myDate     = new RDFTypedLiteral("2017-01-07", RDFModelEnums.RDFDatatypes.XSD_DATE);
            var myDateTime = new RDFTypedLiteral("2017-01-07T23:11:05", RDFModelEnums.RDFDatatypes.XSD_DATETIME);
            var myXml      = new RDFTypedLiteral("<book>title</book>", RDFModelEnums.RDFDatatypes.RDF_XMLLITERAL);
            var myLiteral  = new RDFTypedLiteral("generic literal", RDFModelEnums.RDFDatatypes.RDFS_LITERAL);

            /*
             * The given list of items may be incomplete.
             * A container is semantically opened to the possibility of having further elements
             *
             * Alt: unordered semantic, duplicates not allowed;
             * Bag: unordered semantic, duplicates allowed;
             * Seq: ordered semantic, duplicates allowed;
             */

            // CREATE CONTAINER AND ADD ITEMS
            RDFContainer beatles_cont = new RDFContainer(RDFModelEnums.RDFContainerTypes.Bag, RDFModelEnums.RDFItemTypes.Resource);

            beatles_cont.AddItem(new RDFResource("http://beatles.com/ringo_starr"));
            beatles_cont.AddItem(new RDFResource("http://beatles.com/john_lennon"));
            beatles_cont.AddItem(new RDFResource("http://beatles.com/paul_mc_cartney"));
            beatles_cont.AddItem(new RDFResource("http://beatles.com/george_harrison"));

            /*
             * The given list of items may not be incomplete.
             * A collection is semantically closed to the possibility of having further elements
             */

            // CREATE COLLECTION AND ADD ITEMS
            RDFCollection beatles_coll = new RDFCollection(RDFModelEnums.RDFItemTypes.Resource);

            beatles_coll.AddItem(new RDFResource("http://beatles.com/ringo_starr"));
            beatles_coll.AddItem(new RDFResource("http://beatles.com/john_lennon"));
            beatles_coll.AddItem(new RDFResource("http://beatles.com/paul_mc_cartney"));
            beatles_coll.AddItem(new RDFResource("http://beatles.com/george_harrison"));


            // ADD CONTAINER/COLLECTION TO GRAPH
            waltdisney.AddContainer(beatles_cont);
            waltdisney.AddCollection(beatles_coll);



            // REIFY TRIPLE AND MERGE IT INTO A GRAPH
            RDFGraph reifGraph = goofygoof_is82yr.ReifyTriple();

            waltdisney = waltdisney.UnionWith(reifGraph);

            // ASSERT SOMETHING ABOUT REIFIED TRIPLE
            waltdisney.AddTriple(new RDFTriple(
                                     new RDFResource("http://www.wikipedia.com/"),
                                     new RDFResource("http://example.org/verb_state"),
                                     goofygoof_is82yr.ReificationSubject
                                     ));


            var existingGraph = new RDFGraph();


            // REIFY CONTAINER
            existingGraph.AddContainer(beatles_cont);

            existingGraph.AddTriple(new RDFTriple(
                                        new RDFResource("http://www.thebeatles.com/"),
                                        RDFVocabulary.FOAF.GROUP,
                                        beatles_cont.ReificationSubject
                                        ));

            // REIFY COLLECTION
            existingGraph.AddCollection(beatles_coll);

            existingGraph.AddTriple(new RDFTriple(
                                        new RDFResource("http://www.thebeatles.com/"),
                                        RDFVocabulary.FOAF.GROUP,
                                        beatles_coll.ReificationSubject
                                        ));

            // WORKING WITH RDF STORES

            // CREATE CONTEXT FROM STRING
            var wdisney_ctx = new RDFContext("http://www.waltdisney.com/");
            // CREATE CONTEXT FROM URI
            var wdisney_ctx_uri = new RDFContext(new Uri("http://www.waltdisney.com/"));
            // CREATE DEFAULT CONTEXT (DEFAULT NAMESPACE)
            var wdisney_ctx_default = new RDFContext();

            // CREATE QUADRUPLES
            // "From Wikipedia.com: Mickey Mouse is 85 years old"
            RDFQuadruple wk_mickeymouse_is85yr = new RDFQuadruple(
                new RDFContext("http://www.wikipedia.com/"),
                new RDFResource("http://www.waltdisney.com/mickey_mouse"),
                RDFVocabulary.FOAF.AGE,
                new RDFTypedLiteral("85", RDFModelEnums.RDFDatatypes.XSD_INTEGER)
                );

            // "From WaltDisney.com: Mickey Mouse is 85 years old"
            RDFQuadruple wd_mickeymouse_is85yr = new RDFQuadruple(
                new RDFContext("http://www.waltdisney.com/"),
                new RDFResource("http://www.waltdisney.com/mickey_mouse"),
                RDFVocabulary.FOAF.AGE,
                new RDFTypedLiteral("85", RDFModelEnums.RDFDatatypes.XSD_INTEGER)
                );

            // "From Wikipedia.com: Donald Duck has english name "Donald Duck""
            RDFQuadruple wk_donald_duck_name_enus = new RDFQuadruple(
                new RDFContext("http://www.wikipedia.com/"),
                new RDFResource("http://www.waltdisney.com/donald_duck"),
                RDFVocabulary.FOAF.NAME,
                new RDFPlainLiteral("Donald Duck", "en")
                );

            // CREATE EMPTY MEMORY STORE
            var wdStore = new RDFMemoryStore();

            // CREATE MEMORY STORE FROM A LIST OF QUADRUPLES
            var quadruples = new List <RDFQuadruple> {
                wk_mickeymouse_is85yr, wk_mickeymouse_is85yr
            };
            var wdStoreFilled = new RDFMemoryStore();

            foreach (var q in quadruples)
            {
                wdStoreFilled.AddQuadruple(q);
            }

            // GET A DATATABLE FROM A MEMORY STORE (any kind of store can be exported to datatable)
            var wdStore_table = wdStoreFilled.ToDataTable();
            // GET A MEMORY STORE FROM A DATATABLE
            var wdStore_new = RDFMemoryStore.FromDataTable(wdStore_table);


            // ITERATE QUADRUPLES OF A MEMORY STORE WITH FOREACH
            foreach (var q in wdStore)
            {
                Console.WriteLine("Quadruple: " + q);
                Console.WriteLine(" Context: " + q.Context);
                Console.WriteLine(" Subject: " + q.Subject);
                Console.WriteLine(" Predicate: " + q.Predicate);
                Console.WriteLine(" Object: " + q.Object);
            }

            // ITERATE QUADRUPLES OF A MEMORY STORE WITH ENUMERATOR
            var quadruplesEnum = wdStore.QuadruplesEnumerator;

            while (quadruplesEnum.MoveNext())
            {
                Console.WriteLine("Quadruple: " + quadruplesEnum.Current);
                Console.WriteLine(" Context: " + quadruplesEnum.Current.Context);
                Console.WriteLine(" Subject: " + quadruplesEnum.Current.Subject);
                Console.WriteLine(" Predicate: " + quadruplesEnum.Current.Predicate);
                Console.WriteLine(" Object: " + quadruplesEnum.Current.Object);
            }

            var nquadsFormat = RDFStoreEnums.RDFFormats.NQuads;

            // READ N-QUADS FILE
            //var myStore = RDFMemoryStore.FromFile(nquadsFormat, "C:\\file.nq");
            // READ N-QUADS STREAM
            //var myStore = RDFMemoryStore.FromStream(nquadsFormat, inStream);
            // WRITE N-QUADS FILE
            wdStoreFilled.ToFile(nquadsFormat, @"C:\TEMP\newfile.nq");
            // WRITE N-QUADS STREAM
            //myStore.ToStream(nquadsFormat, outStream);


            var trixFormat = RDFStoreEnums.RDFFormats.TriX;

            // READ TRIX FILE
            //var memStore = RDFMemoryStore.FromFile(trixFormat, "C:\\file.trix");
            // READ TRIX STREAM
            //var memStore = RDFMemoryStore.FromStream(trixFormat, inStream);
            // WRITE TRIX FILE
            wdStoreFilled.ToFile(trixFormat, @"C:\TEMP\newfile.trix");
            // WRITE TRIX STREAM
            //myStore.ToStream(trixFormat, outStream);


            // CONNECT TO SQLSERVER STORE WITH CONNECTION STRING
            //var sqlServer = new RDFSQLServerStore(sqlServerConnectionString);


            // CREATE EMPTY FEDERATION
            var fed = new RDFFederation();

            /*
             * // CREATE FEDERATION FROM A LIST OF STORES
             * var stores = new List<RDFStore>{ waltDisneyStore, waltDisneyStoreFilled };
             * var fedFilled = new RDFFederation();
             * foreach(var store in stores)
             * {
             *  fedFilled.AddStore(store);
             * }
             */

            // ITERATE STORES OF A FEDERATION
            foreach (var s in fed)
            {
                Console.WriteLine("Store: " + s);
                Console.WriteLine(" Type: " + s.StoreType);
            }
        }
        /// <summary>
        /// Gets a graph representation of the given ontology, eventually including inferences
        /// </summary>
        internal static RDFGraph ToRDFGraph(RDFOntology ontology, Boolean includeInferences) {
            var result    = new RDFGraph();
            if (ontology != null) {

                //Ontology
                result.AddTriple(new RDFTriple((RDFResource)ontology.Value, RDFVocabulary.RDF.TYPE, RDFVocabulary.OWL.ONTOLOGY));
                result    = result.UnionWith(ontology.Annotations.VersionInfo.ToRDFGraph(includeInferences))
                                  .UnionWith(ontology.Annotations.Comment.ToRDFGraph(includeInferences))
                                  .UnionWith(ontology.Annotations.Label.ToRDFGraph(includeInferences))
                                  .UnionWith(ontology.Annotations.SeeAlso.ToRDFGraph(includeInferences))
                                  .UnionWith(ontology.Annotations.IsDefinedBy.ToRDFGraph(includeInferences))
                                  .UnionWith(ontology.Annotations.BackwardCompatibleWith.ToRDFGraph(includeInferences))
                                  .UnionWith(ontology.Annotations.IncompatibleWith.ToRDFGraph(includeInferences))
                                  .UnionWith(ontology.Annotations.PriorVersion.ToRDFGraph(includeInferences))
                                  .UnionWith(ontology.Annotations.Imports.ToRDFGraph(includeInferences))
                                  .UnionWith(ontology.Annotations.CustomAnnotations.ToRDFGraph(includeInferences));

                //Model
                result    = result.UnionWith(ontology.Model.ToRDFGraph(includeInferences));

                //Data
                result    = result.UnionWith(ontology.Data.ToRDFGraph(includeInferences));

                //Ontology Name
                result.SetContext(((RDFResource)ontology.Value).URI);
            }

            return result;
        }
Exemple #15
0
        /// <summary>
        /// Deserializes the given TriX stream to a graph. 
        /// </summary>
        internal static RDFGraph Deserialize(Stream inputStream)
        {
            try {

                #region deserialize
                RDFGraph result = new RDFGraph();
                using(StreamReader streamReader      = new StreamReader(inputStream, Encoding.UTF8)) {
                    using(XmlTextReader trixReader   = new XmlTextReader(streamReader)) {
                        trixReader.DtdProcessing     = DtdProcessing.Ignore;
                        trixReader.Normalization     = false;

                        #region document
                        XmlDocument trixDoc          = new XmlDocument();
                        trixDoc.Load(trixReader);
                        #endregion

                        #region graph
                        if (trixDoc.DocumentElement != null) {
                            if (trixDoc.DocumentElement.ChildNodes.Count > 1) {
                                throw new Exception(" given TriX file seems to encode more than one graph.");
                            }

                            var graphEnum            = trixDoc.DocumentElement.ChildNodes.GetEnumerator();
                            while(graphEnum         != null && graphEnum.MoveNext()) {
                                XmlNode  graph       = (XmlNode)graphEnum.Current;
                                if (!graph.Name.Equals("graph", StringComparison.Ordinal)) {
                                     throw new Exception(" a \"<graph>\" element was expected, instead of unrecognized \"<" + graph.Name + ">\".");
                                }

                                #region triple
                                var encodedUris      = 0;
                                var tripleEnum       = graph.ChildNodes.GetEnumerator();
                                while (tripleEnum   != null && tripleEnum.MoveNext()) {
                                    XmlNode triple   = (XmlNode)tripleEnum.Current;

                                    #region uri
                                    if (triple.Name.Equals("uri", StringComparison.Ordinal)) {
                                        encodedUris++;
                                        if (encodedUris > 1) {
                                            throw new Exception(" given file encodes a graph with more than one \"<uri>\" element.");
                                        }
                                        result.SetContext(RDFModelUtilities.GetUriFromString(triple.ChildNodes[0].InnerText));
                                    }
                                    #endregion

                                    #region triple
                                    else if(triple.Name.Equals("triple", StringComparison.Ordinal) && triple.ChildNodes.Count == 3) {

                                        #region subj
                                        //Subject is a resource ("<uri>") or a blank node ("<id>")
                                        if (triple.ChildNodes[0].Name.Equals("uri", StringComparison.Ordinal) ||
                                            triple.ChildNodes[0].Name.Equals("id", StringComparison.Ordinal))  {
                                            //Sanitize eventual blank node value
                                            if (triple.ChildNodes[0].Name.Equals("id", StringComparison.Ordinal)) {
                                                if (!triple.ChildNodes[0].InnerText.StartsWith("bnode:")) {
                                                     triple.ChildNodes[0].InnerText = "bnode:" + triple.ChildNodes[0].InnerText.Replace("_:", String.Empty);
                                                }
                                            }
                                        }
                                        //Subject is not valid: exception must be raised
                                        else {
                                            throw new RDFModelException("subject (" + triple.ChildNodes[0].Name + ") of \"<triple>\" element is neither \"<uri>\" or \"<id>\".");
                                        }
                                        #endregion

                                        #region pred
                                        //Predicate is not valid: exception must be raised
                                        if (!triple.ChildNodes[1].Name.Equals("uri", StringComparison.Ordinal)) {
                                             throw new RDFModelException("predicate (" + triple.ChildNodes[1].Name + ") of \"<triple>\" element must be \"<uri>\".");
                                        }
                                        #endregion

                                        #region object
                                        //Object is a resource ("<uri>") or a blank node ("<id>")
                                        if (triple.ChildNodes[2].Name.Equals("uri", StringComparison.Ordinal) ||
                                            triple.ChildNodes[2].Name.Equals("id", StringComparison.Ordinal))  {
                                            //Sanitize eventual blank node value
                                            if (triple.ChildNodes[2].Name.Equals("id", StringComparison.Ordinal)) {
                                                if (!triple.ChildNodes[2].InnerText.StartsWith("bnode:")) {
                                                     triple.ChildNodes[2].InnerText = "bnode:" + triple.ChildNodes[2].InnerText.Replace("_:", String.Empty);
                                                }
                                            }
                                            result.AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                           new RDFResource(triple.ChildNodes[1].InnerText),
                                                                           new RDFResource(triple.ChildNodes[2].InnerText)));
                                        }
                                        #endregion

                                        #region literal

                                        #region plain literal
                                        else if(triple.ChildNodes[2].Name.Equals("plainLiteral")) {
                                            if (triple.ChildNodes[2].Attributes != null && triple.ChildNodes[2].Attributes.Count > 0) {
                                                XmlAttribute xmlLang = triple.ChildNodes[2].Attributes[RDFVocabulary.XML.PREFIX + ":lang"];
                                                if (xmlLang         != null) {

                                                    //Plain literal with language
                                                    result.AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                                   new RDFResource(triple.ChildNodes[1].InnerText),
                                                                                   new RDFPlainLiteral(RDFModelUtilities.ASCII_To_Unicode(HttpUtility.HtmlDecode(triple.ChildNodes[2].InnerText)), xmlLang.Value)));

                                                }
                                                else {

                                                    //Plain literal without language
                                                    result.AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                                   new RDFResource(triple.ChildNodes[1].InnerText),
                                                                                   new RDFPlainLiteral(RDFModelUtilities.ASCII_To_Unicode(HttpUtility.HtmlDecode(triple.ChildNodes[2].InnerText)))));

                                                }
                                            }
                                            else {

                                                //Plain literal without language
                                                result.AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                               new RDFResource(triple.ChildNodes[1].InnerText),
                                                                               new RDFPlainLiteral(RDFModelUtilities.ASCII_To_Unicode(HttpUtility.HtmlDecode(triple.ChildNodes[2].InnerText)))));

                                            }
                                        }
                                        #endregion

                                        #region typed literal
                                        else if(triple.ChildNodes[2].Name.Equals("typedLiteral", StringComparison.Ordinal)) {
                                            if (triple.ChildNodes[2].Attributes != null && triple.ChildNodes[2].Attributes.Count > 0) {
                                                XmlAttribute rdfDtype = triple.ChildNodes[2].Attributes["datatype"];
                                                if (rdfDtype         != null) {
                                                    result.AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                                   new RDFResource(triple.ChildNodes[1].InnerText),
                                                                                   new RDFTypedLiteral(RDFModelUtilities.ASCII_To_Unicode(HttpUtility.HtmlDecode(triple.ChildNodes[2].InnerText)), RDFModelUtilities.GetDatatypeFromString(rdfDtype.Value))));
                                                }
                                                else {
                                                    throw new Exception(" found typed literal without required \"datatype\" attribute.");
                                                }
                                            }
                                            else {
                                                throw new Exception(" found typed literal without required \"datatype\" attribute.");
                                            }
                                        }
                                        #endregion

                                        #endregion

                                        #region exception
                                        //Object is not valid: exception must be raised
                                        else {
                                            throw new RDFModelException("object (" + triple.ChildNodes[2].Name + ") of \"<triple>\" element is neither \"<uri>\" or \"<id>\" or \"<plainLiteral>\" or \"<typedLiteral>\".");
                                        }
                                        #endregion

                                    }
                                    #endregion

                                    #region exception
                                    else {
                                        throw new RDFModelException("found a TriX element (" + triple.Name + ") which is neither \"<uri>\" or \"<triple>\", or is a \"<triple>\" without the required 3 childs.");
                                    }
                                    #endregion

                                }
                                #endregion

                            }
                        }
                        #endregion

                    }
                }
                return result;
                #endregion

            }
            catch(Exception ex) {
                throw new RDFModelException("Cannot deserialize TriX because: " + ex.Message, ex);
            }
        }
Exemple #16
0
        /// <summary>
        /// Builds the reification graph of the container:
        /// Subject -> rdf:type -> [rdf:Bag|rdf:Seq|rdf:Alt] 
        /// Subject -> rdf:_N   -> RDFContainer.ITEM(N)
        /// </summary>
        public RDFGraph ReifyContainer() {
		    RDFGraph reifCont = new RDFGraph();

            //  Subject -> rdf:type -> [rdf:Bag|rdf:Seq|rdf:Alt] 
            switch (this.ContainerType) {
                case RDFModelEnums.RDFContainerTypes.Bag:
                    reifCont.AddTriple(new RDFTriple(this.ReificationSubject, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.BAG));
                    break;
                case RDFModelEnums.RDFContainerTypes.Seq:
                    reifCont.AddTriple(new RDFTriple(this.ReificationSubject, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.SEQ));
                    break;
                default:
                    reifCont.AddTriple(new RDFTriple(this.ReificationSubject, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.ALT));
                    break;
            }

            //  Subject -> rdf:_N -> RDFContainer.ITEM(N)
            Int32 index = 0;
            foreach (Object item in this) {
                RDFResource ordPred = new RDFResource(RDFVocabulary.RDF.BASE_URI + "_" + (++index));
                if (this.ItemType  == RDFModelEnums.RDFItemTypes.Resource) {
                    reifCont.AddTriple(new RDFTriple(this.ReificationSubject, ordPred, (RDFResource)item));
                }
                else {
                    reifCont.AddTriple(new RDFTriple(this.ReificationSubject, ordPred, (RDFLiteral)item));
                }
            }

            return reifCont;
        }
        /// <summary>
        /// Emits a graph containing the ontology triples describing this ontology resource
        /// </summary>
        public virtual RDFGraph ToRDFGraph() {
            var result   = new RDFGraph();

            //THIS -> owl:versionInfo  -> THIS.VERSIONINFO[i]
            var verInfos = this.VersionInfoEnumerator();
            while (verInfos.MoveNext()) {
                result.AddTriple(new RDFTriple((RDFResource)this.Value, RDFVocabulary.OWL.VERSION_INFO, (RDFLiteral)verInfos.Current.Value));
            }

            //THIS -> rdfs:comment     -> THIS.COMMENT[i]
            var comments = this.CommentEnumerator();
            while (comments.MoveNext()) {
                result.AddTriple(new RDFTriple((RDFResource)this.Value, RDFVocabulary.RDFS.COMMENT, (RDFLiteral)comments.Current.Value));
            }

            //THIS -> rdfs:label       -> THIS.LABEL[i]
            var labels   = this.LabelEnumerator();
            while (labels.MoveNext()) {
                result.AddTriple(new RDFTriple((RDFResource)this.Value, RDFVocabulary.RDFS.LABEL, (RDFLiteral)labels.Current.Value));
            }

            //THIS -> rdfs:seeAlso     -> THIS.SEEALSO[i]
            var seeAlso  = this.SeeAlsoEnumerator();
            while (seeAlso.MoveNext()) {
                result.AddTriple(new RDFTriple((RDFResource)this.Value, RDFVocabulary.RDFS.SEE_ALSO, (RDFResource)seeAlso.Current.Value));
            }

            //THIS -> rdfs:isDefinedBy -> THIS.ISDEFINEDBY[i]
            var isDefBy  = this.IsDefinedByEnumerator();
            while (isDefBy.MoveNext()) {
                result.AddTriple(new RDFTriple((RDFResource)this.Value, RDFVocabulary.RDFS.IS_DEFINED_BY, (RDFResource)isDefBy.Current.Value));
            }

            //THIS -> THIS.CUSTOMANNOTATION[i].PROPERTY -> THIS.CUSTOMANNOTATION[i].FACT
            var custAnn  = this.CustomAnnotationsEnumerator();
            while (custAnn.MoveNext()) {
                if (custAnn.Current.AttributeValue.IsObjectFact()) {
                    result.AddTriple(new RDFTriple((RDFResource)this.Value, (RDFResource)custAnn.Current.AttributeProperty.Value, (RDFResource)custAnn.Current.AttributeValue.Value));
                }
                else {
                    result.AddTriple(new RDFTriple((RDFResource)this.Value, (RDFResource)custAnn.Current.AttributeProperty.Value, (RDFLiteral)custAnn.Current.AttributeValue.Value));
                }
            }

            return result;
        }
Exemple #18
0
        /// <summary>
        /// Deserializes the given N-Triples stream to a graph. 
        /// </summary>
        internal static RDFGraph Deserialize(Stream inputStream)
        {
            Int64 ntripleIndex = 0;
            try {

                #region deserialize
                using (StreamReader sr = new StreamReader(inputStream, Encoding.ASCII)) {
                    RDFGraph result    = new RDFGraph();
                    String  ntriple    = String.Empty;
                    String[] tokens    = new String[3];
                    RDFResource S      = null;
                    RDFResource P      = null;
                    RDFResource O      = null;
                    RDFLiteral  L      = null;
                    while((ntriple     = sr.ReadLine()) != null) {
                        ntripleIndex++;

                        #region sanitize  & tokenize
                        //Cleanup previous data
                        S              = null;
                        tokens[0]      = String.Empty;
                        P              = null;
                        tokens[1]      = String.Empty;
                        O              = null;
                        L              = null;
                        tokens[2]      = String.Empty;

                        //Preliminary sanitizations: clean trailing space-like chars
                        ntriple        = ntriple.Trim(new Char[] { ' ', '\t', '\r', '\n' });

                        //Skip empty or comment lines
                        if (ntriple   == String.Empty || ntriple.StartsWith("#")) {
                            continue;
                        }

                        //Tokenizes the sanitized triple
                        tokens         = TokenizeNTriple(ntriple);
                        #endregion

                        #region subj
                        String subj    = tokens[0].TrimStart(new Char[] { '<' })
                                                  .TrimEnd(new   Char[] { '>' })
                                                  .Replace("_:", "bnode:");
                        S              = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(subj));
                        #endregion

                        #region pred
                        String pred    = tokens[1].TrimStart(new Char[] { '<' })
                                                  .TrimEnd(new   Char[] { '>' });
                        P              = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(pred));
                        #endregion

                        #region object
                        if (tokens[2].StartsWith("<")      ||
                            tokens[2].StartsWith("bnode:") ||
                            tokens[2].StartsWith("_:")) {
                            String obj = tokens[2].TrimStart(new Char[] { '<' })
                                                  .TrimEnd(new Char[] { '>' })
                                                  .Replace("_:", "bnode:")
                                                  .Trim(new Char[] { ' ', '\n', '\t', '\r' });
                            O          = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(obj));
                        }
                        #endregion

                        #region literal
                        else {

                            #region sanitize
                            tokens[2]  = regexSqt.Replace(tokens[2], String.Empty);
                            tokens[2]  = regexEqt.Replace(tokens[2], String.Empty);
                            tokens[2]  = tokens[2].Replace("\\\\", "\\")
                                                  .Replace("\\\"", "\"")
                                                  .Replace("\\n", "\n")
                                                  .Replace("\\t", "\t")
                                                  .Replace("\\r", "\r");
                            tokens[2]  = RDFModelUtilities.ASCII_To_Unicode(tokens[2]);
                            #endregion

                            #region plain literal
                            if (!tokens[2].Contains("^^") ||
                                 tokens[2].EndsWith("^^") ||
                                 tokens[2].Substring(tokens[2].LastIndexOf("^^", StringComparison.Ordinal) + 2, 1) != "<") {
                                 if (regexLPL.Match(tokens[2]).Success) {
                                     tokens[2]        = tokens[2].Replace("\"@", "@");
                                     String pLitValue = tokens[2].Substring(0, tokens[2].LastIndexOf("@", StringComparison.Ordinal));
                                     String pLitLang  = tokens[2].Substring(tokens[2].LastIndexOf("@", StringComparison.Ordinal) + 1);
                                     L                = new RDFPlainLiteral(HttpUtility.HtmlDecode(pLitValue), pLitLang);
                                 }
                                 else {
                                     L                = new RDFPlainLiteral(HttpUtility.HtmlDecode(tokens[2]));
                                 }
                            }
                            #endregion

                            #region typed literal
                            else {
                                tokens[2]                    = tokens[2].Replace("\"^^", "^^");
                                String tLitValue             = tokens[2].Substring(0, tokens[2].LastIndexOf("^^", StringComparison.Ordinal));
                                String tLitDatatype          = tokens[2].Substring(tokens[2].LastIndexOf("^^", StringComparison.Ordinal) + 2)
                                                                        .TrimStart(new Char[] { '<' })
                                                                        .TrimEnd(new   Char[] { '>' });
                                RDFModelEnums.RDFDatatypes dt = RDFModelUtilities.GetDatatypeFromString(tLitDatatype);
                                L                            = new RDFTypedLiteral(HttpUtility.HtmlDecode(tLitValue), dt);
                            }
                            #endregion

                        }
                        #endregion

                        #region addtriple
                        if (O != null) {
                            result.AddTriple(new RDFTriple(S, P, O));
                        }
                        else {
                            result.AddTriple(new RDFTriple(S, P, L));
                        }
                        #endregion

                    }
                    return result;
                }
                #endregion

            }
            catch(Exception ex) {
                throw new RDFModelException("Cannot deserialize N-Triples (line " + ntripleIndex + ") because: " + ex.Message, ex);
            }
        }
Exemple #19
0
        /// <summary>
        /// Deserializes the given Xml filepath to a graph. 
        /// </summary>
        internal static RDFGraph Deserialize(String filepath) {
            try {

                #region deserialize
                XmlReaderSettings xrs    = new XmlReaderSettings(); 
                xrs.IgnoreComments       = true;
                xrs.DtdProcessing        = DtdProcessing.Ignore;

                RDFGraph result          = new RDFGraph();
                using(XmlReader xr       = XmlReader.Create(new StreamReader(filepath, Encoding.UTF8), xrs)) {

                    #region load
                    XmlDocument xmlDoc   = new XmlDocument();
                    xmlDoc.Load(xr);
                    #endregion

                    #region root
                    //Prepare the namespace table for the Xml selections
                    var nsMgr            = new XmlNamespaceManager(new NameTable());
                    nsMgr.AddNamespace(RDFVocabulary.RDF.PREFIX, RDFVocabulary.RDF.BASE_URI);

                    //Select "rdf:RDF" root node
                    XmlNode rdfRDF       = RDFModelUtilities.GetRdfRootNode(xmlDoc, nsMgr);
                    #endregion

                    #region prefixes
                    //Select "xmlns" attributes and try to add them to the namespace register
                    var xmlnsAttrs       = RDFModelUtilities.GetXmlnsNamespaces(rdfRDF, nsMgr);
                        
                    //Try to get the "xml:base" attribute, which is needed to resolve eventual relative #IDs in "rdf:about" nodes
                    //If it is not found, set it to the graph Uri
                    Uri xmlBase          = null;
                    if (xmlnsAttrs      != null && xmlnsAttrs.Count > 0) {
                        var xmlBaseAttr  = (rdfRDF.Attributes["xml:base"] ?? rdfRDF.Attributes["xmlns"]);
                        if (xmlBaseAttr != null) {
                            xmlBase      = RDFModelUtilities.GetUriFromString(xmlBaseAttr.Value);
                        }                        
                    }
                    //Always keep in synch the Context and the xmlBase
                    if (xmlBase         != null) {
                        result.SetContext(xmlBase);
                    }
                    else {
                        xmlBase          = result.Context;
                    }
                    #endregion

                    #region elements
                    //Parse resource elements, which are the childs of root node and represent the subjects
                    if (rdfRDF.HasChildNodes) {
                        var subjNodesEnum     = rdfRDF.ChildNodes.GetEnumerator();
                        while (subjNodesEnum != null && subjNodesEnum.MoveNext()) {
                                
                            #region subj
                            //Get the current resource node
                            XmlNode subjNode  = (XmlNode)subjNodesEnum.Current;
                            RDFResource subj  = RDFModelUtilities.GetSubjectNode(subjNode, xmlBase, result);
                            if (subj         == null) {
                                continue;
                            }
                            #endregion

                            #region predObjList
                            //Parse pred elements, which are the childs of subj element
                            if (subjNode.HasChildNodes) {
                                IEnumerator predNodesEnum     = subjNode.ChildNodes.GetEnumerator();
                                while (predNodesEnum != null && predNodesEnum.MoveNext()) {
                                        
                                    //Get the current pred node
                                    RDFResource pred          = null;
                                    XmlNode predNode          = (XmlNode)predNodesEnum.Current;
                                    if (predNode.NamespaceURI == String.Empty) {
                                        pred                  = new RDFResource(xmlBase + predNode.LocalName);
                                    }
                                    else { 
                                        pred                  = (predNode.LocalName.StartsWith("autoNS")   ? 
                                                                    new RDFResource(predNode.NamespaceURI) : 
                                                                    new RDFResource(predNode.NamespaceURI + predNode.LocalName));
                                    }

                                    #region object
                                    //Check if there is a "rdf:about" or a "rdf:resource" attribute
                                    XmlAttribute rdfObject    = 
                                        (RDFModelUtilities.GetRdfAboutAttribute(predNode) ?? 
                                            RDFModelUtilities.GetRdfResourceAttribute(predNode));
                                    if (rdfObject != null) {
                                        //Attribute found, but we must check if it is "rdf:ID", "rdf:nodeID" or a relative Uri
                                        String rdfObjectValue = RDFModelUtilities.ResolveRelativeNode(rdfObject, xmlBase);
                                        RDFResource  obj      = new RDFResource(rdfObjectValue);
                                        result.AddTriple(new RDFTriple(subj, pred, obj));
                                        continue;
                                    }
                                    #endregion

                                    #region typed literal
                                    //Check if there is a "rdf:datatype" attribute
                                    XmlAttribute rdfDatatype  = RDFModelUtilities.GetRdfDatatypeAttribute(predNode);
                                    if (rdfDatatype != null) {
                                        RDFDatatype dt        = RDFModelUtilities.GetDatatypeFromString(rdfDatatype.Value);
                                        RDFTypedLiteral tLit  = new RDFTypedLiteral(HttpUtility.HtmlDecode(predNode.InnerText), dt);
                                        result.AddTriple(new RDFTriple(subj, pred, tLit));
                                        continue;
                                    }
									//Check if there is a "rdf:parseType=Literal" attribute
                                    XmlAttribute parseLiteral = RDFModelUtilities.GetParseTypeLiteralAttribute(predNode);
                                    if (parseLiteral != null) {
                                        RDFTypedLiteral tLit  = new RDFTypedLiteral(HttpUtility.HtmlDecode(predNode.InnerXml), RDFDatatypeRegister.GetByPrefixAndDatatype(RDFVocabulary.RDFS.PREFIX, "Literal"));
                                        result.AddTriple(new RDFTriple(subj, pred, tLit));
                                        continue;
                                    }
                                    #endregion

                                    #region plain literal
                                    //Check if there is a "xml:lang" attribute, or if a unique textual child
                                    XmlAttribute xmlLang      = RDFModelUtilities.GetXmlLangAttribute(predNode);
                                    if (xmlLang != null ||  (predNode.HasChildNodes && predNode.ChildNodes.Count == 1 && predNode.ChildNodes[0].NodeType == XmlNodeType.Text)) {
                                        RDFPlainLiteral pLit  = new RDFPlainLiteral(HttpUtility.HtmlDecode(predNode.InnerText), (xmlLang != null ? xmlLang.Value : String.Empty));
                                        result.AddTriple(new RDFTriple(subj, pred, pLit));
                                        continue;
                                    }
                                    #endregion

                                    #region collection
                                    //Check if there is a "rdf:parseType=Collection" attribute
                                    XmlAttribute rdfCollect   = RDFModelUtilities.GetParseTypeCollectionAttribute(predNode);
                                    if (rdfCollect           != null) {
                                        RDFModelUtilities.ParseCollectionElements(xmlBase, predNode, subj, pred, result);
                                        continue;
                                    }
                                    #endregion

                                    #region container
                                    //Check if there is a "rdf:[Bag|Seq|Alt]" child node
                                    XmlNode container        = RDFModelUtilities.GetContainerNode(predNode);
                                    if (container != null) {
                                        //Distinguish the right type of RDF container to build
                                        if (container.LocalName.Equals(RDFVocabulary.RDF.PREFIX + ":Bag", StringComparison.Ordinal)      || container.LocalName.Equals("Bag", StringComparison.Ordinal)) {
                                                RDFModelUtilities.ParseContainerElements(RDFModelEnums.RDFContainerTypes.Bag, container, subj, pred, result);
                                        }
                                        else if (container.LocalName.Equals(RDFVocabulary.RDF.PREFIX + ":Seq", StringComparison.Ordinal) || container.LocalName.Equals("Seq", StringComparison.Ordinal)) {
                                            RDFModelUtilities.ParseContainerElements(RDFModelEnums.RDFContainerTypes.Seq, container, subj, pred, result);
                                        }
                                        else if (container.LocalName.Equals(RDFVocabulary.RDF.PREFIX + ":Alt", StringComparison.Ordinal) || container.LocalName.Equals("Alt", StringComparison.Ordinal)) {
                                            RDFModelUtilities.ParseContainerElements(RDFModelEnums.RDFContainerTypes.Alt, container, subj, pred, result);
                                        }                                        
                                    }
                                    #endregion

                                }
                            }
                            #endregion

                        }
                    }
                    #endregion

                }
                return result;
                #endregion

            }
            catch (Exception ex) {
                throw new RDFModelException("Cannot deserialize Xml because: " + ex.Message, ex);
            }
        }
        /// <summary>
        /// Gives the subj node extracted from the attribute list of the current element 
        /// </summary>
        internal static RDFResource GetSubjectNode(XmlNode subjNode, Uri xmlBase, RDFGraph result) {
            RDFResource subj             = null;

            //If there are attributes, search them for the one representing the subj
            if (subjNode.Attributes     != null && subjNode.Attributes.Count > 0) {

                //We are interested in finding the "rdf:about" node for the subj
                XmlAttribute rdfAbout    = GetRdfAboutAttribute(subjNode);
                if (rdfAbout != null) {
                    //Attribute found, but we must check if it is "rdf:ID", "rdf:nodeID" or a relative Uri: 
                    //in this case it must be resolved against the xmlBase namespace, or else it remains the same
                    String rdfAboutValue = RDFModelUtilities.ResolveRelativeNode(rdfAbout, xmlBase);
                    subj      = new RDFResource(rdfAboutValue);
                }

                //If "rdf:about" attribute has been found for the subj, we must
                //check if the node is not a standard "rdf:Description": this is
                //the case we can directly build a triple with "rdf:type" pred
                if (subj     != null && !CheckIfRdfDescriptionNode(subjNode)) {
                    RDFResource obj      = null;
                    if (subjNode.NamespaceURI == String.Empty) {
                        obj   = new RDFResource(xmlBase + subjNode.LocalName);
                    }
                    else {
                        obj   = new RDFResource(subjNode.NamespaceURI + subjNode.LocalName);
                    }
                    result.AddTriple(new RDFTriple(subj, RDFVocabulary.RDF.TYPE, obj));
                }

            }

            //There are no attributes, so there's only one way we can handle this element:
            //if it is a standard rdf:Description, it is a blank Subject
            else {
                if (CheckIfRdfDescriptionNode(subjNode)) {
                    subj      = new RDFResource();
                }
            }

            return subj;
        }
        /// <summary>
        /// Given an element representing a RDF container, iterates on its constituent elements
        /// to build its standard reification triples. 
        /// </summary>
        internal static void ParseContainerElements(RDFModelEnums.RDFContainerTypes contType, XmlNode container,
                                                    RDFResource subj, RDFResource pred, RDFGraph result) {

            //Attach the container as the blank object of the current pred
            RDFResource  obj                 = new RDFResource();
            result.AddTriple(new RDFTriple(subj, pred, obj));

            //obj -> rdf:type -> rdf:[Bag|Seq|Alt]
            switch (contType) {
                case RDFModelEnums.RDFContainerTypes.Bag:
                    result.AddTriple(new RDFTriple(obj, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.BAG));
                    break;
                case RDFModelEnums.RDFContainerTypes.Seq:
                    result.AddTriple(new RDFTriple(obj, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.SEQ));
                    break;
                default:
                    result.AddTriple(new RDFTriple(obj, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.ALT));
                    break;
            }

            //Iterate on the container items
            if (container.HasChildNodes) {
                IEnumerator elems              = container.ChildNodes.GetEnumerator();
                List<String> elemVals          = new List<String>();
                while (elems != null && elems.MoveNext()) {
                    XmlNode elem               = (XmlNode)elems.Current;
                    XmlAttribute elemUri       = GetRdfResourceAttribute(elem);

                    #region Container Resource Item
                    //This is a container of resources
                    if (elemUri               != null) {

                        //Sanitize eventual blank node value detected by presence of "nodeID" attribute
                        if (elemUri.LocalName.Equals("nodeID", StringComparison.Ordinal)) {
                            if (!elemUri.Value.StartsWith("bnode:")) {
                                 elemUri.Value = "bnode:" + elemUri.Value;
                            }
                        }

                        //obj -> rdf:_N -> VALUE 
                        if (contType          == RDFModelEnums.RDFContainerTypes.Alt) {
                            if (!elemVals.Contains(elemUri.Value)) {
                                elemVals.Add(elemUri.Value);
                                result.AddTriple(new RDFTriple(obj, new RDFResource(RDFVocabulary.RDF.BASE_URI + elem.LocalName), new RDFResource(elemUri.Value)));
                            }
                        }
                        else {
                            result.AddTriple(new RDFTriple(obj, new RDFResource(RDFVocabulary.RDF.BASE_URI + elem.LocalName), new RDFResource(elemUri.Value)));
                        }

                    }
                    #endregion

                    #region Container Literal Item
                    //This is a container of literals
                    else {

                        //Parse the literal contained in the item
                        RDFLiteral literal     = null;
                        XmlAttribute attr      = GetRdfDatatypeAttribute(elem);
                        if (attr              != null) {
                            literal            = new RDFTypedLiteral(elem.InnerText, RDFModelUtilities.GetDatatypeFromString(attr.InnerText));
                        }
                        else {
                            attr               = GetXmlLangAttribute(elem);
                            literal            = new RDFPlainLiteral(elem.InnerText, (attr != null ? attr.InnerText : String.Empty));
                        }

                        //obj -> rdf:_N -> VALUE 
                        if (contType          == RDFModelEnums.RDFContainerTypes.Alt) {
                            if (!elemVals.Contains(literal.ToString())) {
                                 elemVals.Add(literal.ToString());
                                 result.AddTriple(new RDFTriple(obj, new RDFResource(RDFVocabulary.RDF.BASE_URI + elem.LocalName), literal));
                            }
                        }
                        else {
                            result.AddTriple(new RDFTriple(obj, new RDFResource(RDFVocabulary.RDF.BASE_URI + elem.LocalName), literal));
                        }

                    }
                    #endregion

                }
            }

        }
        /// <summary>
        /// Given an attribute representing a RDF collection, iterates on its constituent elements
        /// to build its standard reification triples. 
        /// </summary>
        internal static void ParseCollectionElements(Uri xmlBase, XmlNode predNode, RDFResource subj,
                                                     RDFResource pred, RDFGraph result) {

            //Attach the collection as the blank object of the current pred
            RDFResource  obj              = new RDFResource();
            result.AddTriple(new RDFTriple(subj, pred, obj));

            //Iterate on the collection items to reify it
            if (predNode.HasChildNodes) {
                IEnumerator elems         = predNode.ChildNodes.GetEnumerator();
                while (elems != null && elems.MoveNext()) {
                    XmlNode elem          = (XmlNode)elems.Current;

                    //Try to get items as "rdf:about" attributes, or as "rdf:resource"
                    XmlAttribute elemUri  = 
					    (GetRdfAboutAttribute(elem) ??
                             GetRdfResourceAttribute(elem));
                    if (elemUri          != null) {

                        //Sanitize eventual blank node or relative value, depending on attribute found
                        elemUri.Value     = RDFModelUtilities.ResolveRelativeNode(elemUri, xmlBase);

                        // obj -> rdf:type -> rdf:list
                        result.AddTriple(new RDFTriple(obj, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.LIST));

                        // obj -> rdf:first -> res
                        result.AddTriple(new RDFTriple(obj, RDFVocabulary.RDF.FIRST, new RDFResource(elemUri.Value)));

                        //Last element of a collection must give a triple to a "rdf:nil" object
                        RDFResource newObj;
                        if (elem         != predNode.ChildNodes.Item(predNode.ChildNodes.Count - 1)) {
                            // obj -> rdf:rest -> newObj
                            newObj        = new RDFResource();
                        }
                        else {
                            // obj -> rdf:rest -> rdf:nil
                            newObj        = RDFVocabulary.RDF.NIL;
                        }
                        result.AddTriple(new RDFTriple(obj, RDFVocabulary.RDF.REST, newObj));
                        obj               = newObj;

                    }
                }
            }
        }
        public static RDFGraph WaltDisneyGraphBuild()
        {
            RDFGraph waltdisney = new RDFGraph();

            waltdisney.SetContext(new Uri("http://waltdisney.com/"));

            // https://en.wikipedia.org/wiki/Mickey_Mouse_universe#Minnie_Mouse_family

            // Create triples

            // "Mickey Mouse is 85 years old"
            RDFTriple mickeyMouse_is85yr                  = new RDFTriple(mickeyMouse, RDFVocabulary.FOAF.AGE, new RDFTypedLiteral("85", RDFModelEnums.RDFDatatypes.XSD_INTEGER));
            RDFTriple mickeyMouse_isMale                  = new RDFTriple(mickeyMouse, RDFVocabulary.FOAF.GENDER, new RDFPlainLiteral("Male", "en"));
            RDFTriple mickeyMouseNameEn                   = new RDFTriple(mickeyMouse, RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Mickey Mouse", "en"));
            RDFTriple mickeyMouseFamilyNameEn             = new RDFTriple(mickeyMouse, RDFVocabulary.FOAF.FAMILY_NAME, new RDFPlainLiteral("Mouse", "en"));
            RDFTriple mickeyMouse_boyFriendOf_MinnieMouse = new RDFTriple(mickeyMouse, boyFriendOf, minnieMouse);

            List <RDFTriple> mickeyMouseTriples = new List <RDFTriple> {
                mickeyMouse_is85yr, mickeyMouse_isMale, mickeyMouseNameEn, mickeyMouseFamilyNameEn, mickeyMouse_boyFriendOf_MinnieMouse
            };

            RDFGraph mickeyMouseGraph = new RDFGraph(mickeyMouseTriples);

            foreach (var triple in mickeyMouseGraph)
            {
                waltdisney.AddTriple(triple);
            }

            RDFTriple minnieMouse_is82yr                 = new RDFTriple(minnieMouse, RDFVocabulary.FOAF.AGE, new RDFTypedLiteral("82", RDFModelEnums.RDFDatatypes.XSD_INTEGER));
            RDFTriple minnieMouse_isFemale               = new RDFTriple(minnieMouse, RDFVocabulary.FOAF.GENDER, new RDFPlainLiteral("Female", "en"));
            RDFTriple minnieMouseNameEn                  = new RDFTriple(minnieMouse, RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Minnie Mouse", "en"));
            RDFTriple minnieMouseFamilyNameEn            = new RDFTriple(minnieMouse, RDFVocabulary.FOAF.FAMILY_NAME, new RDFPlainLiteral("Mouse", "en"));
            RDFTriple minnieMouseGirlFriendOfMickeyMouse = new RDFTriple(minnieMouse, girlFriendOf, mickeyMouse);

            List <RDFTriple> minnieMouseTriples = new List <RDFTriple> {
                minnieMouse_is82yr, minnieMouse_isFemale, minnieMouseNameEn, minnieMouseFamilyNameEn, minnieMouseGirlFriendOfMickeyMouse
            };

            foreach (var triple in minnieMouseTriples)
            {
                waltdisney.AddTriple(triple);
            }

            // Figaro is based on and acts like an immature and spoiled little boy.
            RDFTriple figaro_isMale = new RDFTriple(figaro, RDFVocabulary.FOAF.GENDER, new RDFPlainLiteral("Male", "en"));
            RDFTriple figaroNameEn  = new RDFTriple(figaro, RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Figaro", "en"));
            // Figaro is now Minnie's pet.
            RDFTriple figaroCatOfMinnieMouse   = new RDFTriple(figaro, catOf, minnieMouse);
            RDFTriple figaroIsPetOfMinnieMouse = new RDFTriple(figaro, isPetOf, minnieMouse);

            List <RDFTriple> figaroTriples = new List <RDFTriple> {
                figaro_isMale, figaroNameEn, figaroCatOfMinnieMouse, figaroIsPetOfMinnieMouse
            };

            foreach (var triple in figaroTriples)
            {
                waltdisney.AddTriple(triple);
            }

            RDFTriple pluto_isMale = new RDFTriple(pluto, RDFVocabulary.FOAF.GENDER, new RDFPlainLiteral("Male", "en"));
            RDFTriple plutoNameEn  = new RDFTriple(pluto, RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Pluto", "en"));
            // Pluto is Mickey Mouse's pet
            RDFTriple plutoDogOfMickeyMouse   = new RDFTriple(pluto, dogOf, mickeyMouse);
            RDFTriple plutoIsPetOfMickeyMouse = new RDFTriple(pluto, isPetOf, mickeyMouse);

            List <RDFTriple> plutoTriples = new List <RDFTriple> {
                pluto_isMale, plutoNameEn, plutoDogOfMickeyMouse, plutoIsPetOfMickeyMouse
            };

            foreach (var triple in plutoTriples)
            {
                waltdisney.AddTriple(triple);
            }

            RDFTriple goofy_isMale      = new RDFTriple(goofy, RDFVocabulary.FOAF.GENDER, new RDFPlainLiteral("Male", "en"));
            RDFTriple goofyNameEn       = new RDFTriple(goofy, RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Goofy Goof", "en"));
            RDFTriple goofyFamilyNameEn = new RDFTriple(goofy, RDFVocabulary.FOAF.FAMILY_NAME, new RDFPlainLiteral("Goof", "en"));
            // Goofy is a close friend of Mickey Mouse and Donald Duck
            RDFTriple goofyFriendOfMickeyMouse = new RDFTriple(goofy, RDFVocabulary.FOAF.KNOWS, mickeyMouse);
            RDFTriple goofyFriendOfDonaldDuck  = new RDFTriple(goofy, RDFVocabulary.FOAF.KNOWS, donaldDuck);

            List <RDFTriple> goofyTriples = new List <RDFTriple> {
                goofy_isMale, goofyNameEn, goofyFamilyNameEn, goofyFriendOfMickeyMouse, goofyFriendOfDonaldDuck
            };

            foreach (var triple in goofyTriples)
            {
                waltdisney.AddTriple(triple);
            }

            RDFTriple donaldDuckNameEn = new RDFTriple(donaldDuck, RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Donald Duck", "en"));
            // "Donald Duck is 85 years old"
            RDFTriple donaldDuck_is85yr                = new RDFTriple(donaldDuck, RDFVocabulary.FOAF.AGE, new RDFTypedLiteral("85", RDFModelEnums.RDFDatatypes.XSD_INTEGER));
            RDFTriple donaldDuck_isMale                = new RDFTriple(donaldDuck, RDFVocabulary.FOAF.GENDER, new RDFPlainLiteral("Male", "en"));
            RDFTriple donaldDuckFamilyNameEn           = new RDFTriple(donaldDuck, RDFVocabulary.FOAF.FAMILY_NAME, new RDFPlainLiteral("Duck", "en"));
            RDFTriple donaldDuck_boyFriendOf_daisyDuck = new RDFTriple(donaldDuck, boyFriendOf, daisyDuck);

            List <RDFTriple> donaldDuckTriples = new List <RDFTriple> {
                donaldDuckNameEn, donaldDuck_is85yr, donaldDuck_isMale, donaldDuckFamilyNameEn, donaldDuck_boyFriendOf_daisyDuck
            };

            foreach (var triple in donaldDuckTriples)
            {
                waltdisney.AddTriple(triple);
            }

            RDFTriple daisyDuckNameEn                 = new RDFTriple(daisyDuck, RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Daisy Duck", "en"));
            RDFTriple daisyDuck_isFemale              = new RDFTriple(daisyDuck, RDFVocabulary.FOAF.GENDER, new RDFPlainLiteral("Female", "en"));
            RDFTriple daisyDuckFamilyNameEn           = new RDFTriple(daisyDuck, RDFVocabulary.FOAF.FAMILY_NAME, new RDFPlainLiteral("Duck", "en"));
            RDFTriple daisyDuckGirlFriendOfDonaldDuck = new RDFTriple(daisyDuck, girlFriendOf, donaldDuck);

            List <RDFTriple> daisyDuckTriples = new List <RDFTriple> {
                daisyDuckNameEn, daisyDuck_isFemale, daisyDuckFamilyNameEn, daisyDuckGirlFriendOfDonaldDuck
            };

            foreach (var triple in daisyDuckTriples)
            {
                waltdisney.AddTriple(triple);
            }

            RDFTriple dellaDuckNameEn             = new RDFTriple(dellaDuck, RDFVocabulary.FOAF.NAME, new RDFPlainLiteral("Della Duck", "en"));
            RDFTriple dellaDuck_isFemale          = new RDFTriple(dellaDuck, RDFVocabulary.FOAF.GENDER, new RDFPlainLiteral("Female", "en"));
            RDFTriple dellaDuckFamilyNameEn       = new RDFTriple(dellaDuck, RDFVocabulary.FOAF.FAMILY_NAME, new RDFPlainLiteral("Duck", "en"));
            RDFTriple dellaDuckSisterOfDonaldDuck = new RDFTriple(dellaDuck, sisterOf, donaldDuck);

            List <RDFTriple> dellaDuckTriples = new List <RDFTriple> {
                dellaDuckNameEn, dellaDuck_isFemale, dellaDuckFamilyNameEn, dellaDuckSisterOfDonaldDuck
            };

            foreach (var triple in dellaDuckTriples)
            {
                waltdisney.AddTriple(triple);
            }

            return(waltdisney);
        }
        /// <summary>
        /// Deserializes the given TriX filepath to a graph. 
        /// </summary>
        internal static RDFGraph Deserialize(String filepath) {
            try {

                #region deserialize
                XmlReaderSettings xrs       = new XmlReaderSettings();
                xrs.IgnoreComments          = true;
                xrs.DtdProcessing           = DtdProcessing.Ignore;

                RDFGraph result             = new RDFGraph();
                using(XmlReader xr          = XmlReader.Create(new StreamReader(filepath, Encoding.UTF8), xrs)) {                    

                    #region load
                    XmlDocument trixDoc     = new XmlDocument();
                    trixDoc.Load(xr);
                    #endregion

                    #region graph
                    if (trixDoc.DocumentElement != null) {
                        var graphEnum                   = trixDoc.DocumentElement.ChildNodes.GetEnumerator();
                        while (graphEnum != null       && graphEnum.MoveNext()) {
                            XmlNode  graph              = (XmlNode)graphEnum.Current;
                            RDFGraph g                  = new RDFGraph();

                            #region triple
                            var tripleEnum              = graph.ChildNodes.GetEnumerator();
                            while (tripleEnum != null  && tripleEnum.MoveNext()) {
                                XmlNode triple          = (XmlNode)tripleEnum.Current;

                                #region uri
                                if (triple.Name.Equals("uri", StringComparison.Ordinal)) {
                                    g.Context           = RDFModelUtilities.GetUriFromString(triple.ChildNodes[0].InnerText);
                                }
                                #endregion

                                #region triple
                                else if (triple.Name.Equals("triple", StringComparison.Ordinal) && triple.ChildNodes.Count == 3) {

                                    #region subj
                                    //Subject is a resource ("<uri>") or a blank node ("<id>")
                                    if (triple.ChildNodes[0].Name.Equals("uri", StringComparison.Ordinal) ||
                                        triple.ChildNodes[0].Name.Equals("id", StringComparison.Ordinal)) {
                                        //Sanitize eventual blank node value
                                        if (triple.ChildNodes[0].Name.Equals("id", StringComparison.Ordinal)) {
                                            if (!triple.ChildNodes[0].InnerText.StartsWith("bnode:")) {
                                                triple.ChildNodes[0].InnerText = "bnode:" + triple.ChildNodes[0].InnerText.Replace("_:", String.Empty);
                                            }
                                        }
                                    }
                                    //Subject is not valid: exception must be raised
                                    else  {
                                        throw new RDFModelException("subject of \"<triple>\" element is neither \"<uri>\" or \"<id>\".");
                                    }
                                    #endregion

                                    #region pred
                                    //Predicate is not valid: exception must be raised
                                    if (!triple.ChildNodes[1].Name.Equals("uri", StringComparison.Ordinal)) {
                                        throw new RDFModelException("predicate of \"<triple>\" element must be \"<uri>\".");
                                    }
                                    #endregion

                                    #region object
                                    //Object is a resource ("<uri>") or a blank node ("<id>")
                                    if (triple.ChildNodes[2].Name.Equals("uri", StringComparison.Ordinal) ||
                                        triple.ChildNodes[2].Name.Equals("id", StringComparison.Ordinal)) {
                                        //Sanitize eventual blank node value
                                        if (triple.ChildNodes[2].Name.Equals("id", StringComparison.Ordinal)) {
                                            if (!triple.ChildNodes[2].InnerText.StartsWith("bnode:")) {
                                                triple.ChildNodes[2].InnerText = "bnode:" + triple.ChildNodes[2].InnerText.Replace("_:", String.Empty);
                                            }
                                        }
                                        g.AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText), 
                                                                    new RDFResource(triple.ChildNodes[1].InnerText), 
                                                                    new RDFResource(triple.ChildNodes[2].InnerText)));
                                    }
                                    #endregion

                                    #region literal

                                    #region plain literal
                                    else if (triple.ChildNodes[2].Name.Equals("plainLiteral")) {
                                        if (triple.ChildNodes[2].Attributes != null && triple.ChildNodes[2].Attributes.Count > 0) {
                                            XmlAttribute xmlLang = triple.ChildNodes[2].Attributes[RDFVocabulary.XML.PREFIX + ":lang"];
                                            if (xmlLang != null) {

                                                //Plain literal with language
                                                g.AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                            new RDFResource(triple.ChildNodes[1].InnerText),
                                                                            new RDFPlainLiteral(HttpUtility.HtmlDecode(triple.ChildNodes[2].InnerText), xmlLang.Value)));

                                            }
                                            else {

                                                //Plain literal without language
                                                g.AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                        new RDFResource(triple.ChildNodes[1].InnerText),
                                                                        new RDFPlainLiteral(HttpUtility.HtmlDecode(triple.ChildNodes[2].InnerText))));

                                            }
                                        }
                                        else {

                                            //Plain literal without language
                                            g.AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                        new RDFResource(triple.ChildNodes[1].InnerText),
                                                                        new RDFPlainLiteral(HttpUtility.HtmlDecode(triple.ChildNodes[2].InnerText))));

                                        }
                                    }
                                    #endregion

                                    #region typed literal
                                    else if (triple.ChildNodes[2].Name.Equals("typedLiteral", StringComparison.Ordinal)) {
                                        if (triple.ChildNodes[2].Attributes != null && triple.ChildNodes[2].Attributes.Count > 0) {
                                            XmlAttribute rdfDtype = triple.ChildNodes[2].Attributes["datatype"];
                                            if (rdfDtype != null) {
                                                g.AddTriple(new RDFTriple(new RDFResource(triple.ChildNodes[0].InnerText),
                                                                            new RDFResource(triple.ChildNodes[1].InnerText),
                                                                            new RDFTypedLiteral(HttpUtility.HtmlDecode(triple.ChildNodes[2].InnerText), RDFModelUtilities.GetDatatypeFromString(rdfDtype.Value))));
                                            }
                                            else {
                                                throw new Exception(" found typed literal without required \"datatype\" attribute.");
                                            }
                                        }
                                        else {
                                            throw new Exception(" found typed literal without required \"datatype\" attribute.");
                                        }
                                    }
                                    #endregion

                                    #endregion

                                    #region exception
                                    //Object is not valid: exception must be raised
                                    else {
                                        throw new RDFModelException("object of \"<triple>\" element is neither \"<uri>\" or \"<id>\" or \"<plainLiteral>\" or \"<typedLiteral>\".");
                                    }
                                    #endregion

                                }
                                #endregion

                                #region exception
                                else {
                                    throw new RDFModelException("found a TriX element which is neither \"<uri>\" or \"<triple>\", or is a \"<triple>\" without required 3 childs.");
                                }
                                #endregion

                            }
                            #endregion

                            result                      = result.UnionWith(g);
                            result.Context              = g.Context;
                        }
                    }
                    #endregion

                }
                return result;
                #endregion

            }
            catch (Exception ex) {
                throw new RDFModelException("Cannot deserialize TriX because: " + ex.Message);
            }
        }
Exemple #25
0
        /// <summary>
        /// Builds the reification graph of the collection
        /// </summary>
        public RDFGraph ReifyCollection()
        {
            RDFGraph reifColl          = new RDFGraph();
            RDFResource reifSubj       = this.ReificationSubject;
            Int32 itemCount            = 0;

            //Manage the empty collection
            if (this.ItemsCount       == 0) {

                //  Subject -> rdf:type  -> rdf:List
                reifColl.AddTriple(new RDFTriple(reifSubj, RDFVocabulary.RDF.TYPE,  RDFVocabulary.RDF.LIST));

                // Subject  -> rdf:first -> rdf:nil
                reifColl.AddTriple(new RDFTriple(reifSubj, RDFVocabulary.RDF.FIRST, RDFVocabulary.RDF.NIL));

                // Subject  -> rdf:rest  -> rdf:nil
                reifColl.AddTriple(new RDFTriple(reifSubj, RDFVocabulary.RDF.REST,  RDFVocabulary.RDF.NIL));

            }

            //Manage the non-empty collection
            else {

                foreach (Object listEnum in this) {

                    //Count the items to keep track of the last one, which will be connected to rdf:nil
                    itemCount++;

                    //  Subject -> rdf:type  -> rdf:List
                    reifColl.AddTriple(new RDFTriple(reifSubj, RDFVocabulary.RDF.TYPE, RDFVocabulary.RDF.LIST));

                    //  Subject -> rdf:first -> RDFCollection.ITEM[i]
                    if (this.ItemType     == RDFModelEnums.RDFItemTypes.Resource) {
                        reifColl.AddTriple(new RDFTriple(reifSubj, RDFVocabulary.RDF.FIRST, (RDFResource)listEnum));
                    }
                    else {
                        reifColl.AddTriple(new RDFTriple(reifSubj, RDFVocabulary.RDF.FIRST, (RDFLiteral)listEnum));
                    }

                    //Not the last one: Subject -> rdf:rest  -> NEWBLANK
                    if (itemCount          < this.ItemsCount) {
                        RDFResource newSub = new RDFResource();
                        reifColl.AddTriple(new RDFTriple(reifSubj, RDFVocabulary.RDF.REST, newSub));
                        reifSubj           = newSub;
                    }
                    //The last one:     Subject -> rdf:rest  -> rdf:nil
                    else {
                        reifColl.AddTriple(new RDFTriple(reifSubj, RDFVocabulary.RDF.REST, RDFVocabulary.RDF.NIL));
                    }

                }

            }

            return reifColl;
        }
Exemple #26
0
        protected void LoadRDF()
        {
            // First we set some core RDF resources
            // agent refers to artist(s)
            RDFResource type = RDFVocabulary.RDF.TYPE;
            RDFResource name = RDFVocabulary.FOAF.NAME;
            RDFResource agent = RDFVocabulary.FOAF.AGENT;

            // TGN is a Getty vocabulary for locations
            // TGN added to RDFSharp vocabularies manually.  TGN ID is stored in TMSThes (or equivalent in TMS 2014+)
            RDFResource tgn = new RDFResource(RDFVocabulary.TGN.BASE_URI);

            // The predicates below are often part of ULAN (which we don't have)
            // unsure if using bio events this way is acceptable...

            RDFResource livedIn = new RDFResource("http://purl.org/vocab/bio/0.1/event/livedIn");
            RDFResource activeIn = new RDFResource("http://purl.org/vocab/bio/0.1/event/activeIn");
            RDFResource educatedIn = new RDFResource("http://purl.org/vocab/bio/0.1/event/educatedIn");
            RDFResource bornIn = new RDFResource("http://purl.org/vocab/bio/0.1/event/bornIn");
            RDFResource diedIn = new RDFResource("http://purl.org/vocab/bio/0.1/event/diedIn");

            RDFResource anUri = new RDFResource("http://example.org/uris#anUri");

            // The following entries are all generated from SQL queries which you can find in the file SQL.txt  Technically we could load them into the database directly,
            // but this allows us to see how a resource is "built" and it creates the correct RDF format files (NTriples, RdfXml, TriX), as well as inserts into the db.
            // Once in the db, we do not need to run LoadRDF() except to refresh data.

            #region Artists (agents)
            // Ideally this would reference the Getty vocabulary for ULAN but we don't have the ULAN ID stored in the db
            RDFResource raimundabraham = new RDFResource("http://example.org/artists/47");
            RDFResource emilioambasz = new RDFResource("http://example.org/artists/141");
            RDFResource mariobotta = new RDFResource("http://example.org/artists/696");
            RDFResource louisikahn = new RDFResource("http://example.org/artists/2964");
            RDFResource frederickkiesler = new RDFResource("http://example.org/artists/3091");
            RDFResource leonkrier = new RDFResource("http://example.org/artists/3250");
            RDFResource masayukikurokawa = new RDFResource("http://example.org/artists/3308");
            RDFResource ernestobrunolapadula = new RDFResource("http://example.org/artists/3381");
            RDFResource richardmeier = new RDFResource("http://example.org/artists/3910");
            RDFResource eerosaarinen = new RDFResource("http://example.org/artists/5103");
            RDFResource franklloydwright = new RDFResource("http://example.org/artists/6459");
            RDFResource evazeisel = new RDFResource("http://example.org/artists/6556");
            RDFResource zahahadid = new RDFResource("http://example.org/artists/6953");
            RDFResource santiagocalatrava = new RDFResource("http://example.org/artists/6968");
            RDFResource tadaoando = new RDFResource("http://example.org/artists/7055");
            RDFResource ludwigmiesvanderrohe = new RDFResource("http://example.org/artists/7166");
            RDFResource rafaelviñoly = new RDFResource("http://example.org/artists/7229");
            RDFResource aldorossi = new RDFResource("http://example.org/artists/7661");
            RDFResource simonungers = new RDFResource("http://example.org/artists/7992");
            RDFResource giovanniguerrini = new RDFResource("http://example.org/artists/8157");
            RDFResource marioromano = new RDFResource("http://example.org/artists/8158");
            RDFResource thommayne = new RDFResource("http://example.org/artists/8218");
            RDFResource thomaskinslow = new RDFResource("http://example.org/artists/8248");
            RDFResource fusogomuindcoltdtokyo = new RDFResource("http://example.org/artists/9029");
            RDFResource hallchinacoeastliverpooloh = new RDFResource("http://example.org/artists/10013");
            RDFResource andrewzago = new RDFResource("http://example.org/artists/22884");
            RDFResource morphosissantamonicaca = new RDFResource("http://example.org/artists/29711");

            // Artists(agents): plain literal name

            RDFPlainLiteral aldorossiName = new RDFPlainLiteral("Aldo Rossi");
            RDFPlainLiteral andrewzagoName = new RDFPlainLiteral("Andrew Zago");
            RDFPlainLiteral eerosaarinenName = new RDFPlainLiteral("Eero Saarinen");
            RDFPlainLiteral emilioambaszName = new RDFPlainLiteral("Emilio Ambasz");
            RDFPlainLiteral ernestobrunolapadulaName = new RDFPlainLiteral("Ernesto Bruno La Padula");
            RDFPlainLiteral evazeiselName = new RDFPlainLiteral("Eva Zeisel");
            RDFPlainLiteral franklloydwrightName = new RDFPlainLiteral("Frank Lloyd Wright");
            RDFPlainLiteral frederickkieslerName = new RDFPlainLiteral("Frederick Kiesler");
            RDFPlainLiteral fusogomuindcoltdtokyoName = new RDFPlainLiteral("Fuso Gomu Ind. Co., Ltd., Tokyo");
            RDFPlainLiteral giovanniguerriniName = new RDFPlainLiteral("Giovanni Guerrini");
            RDFPlainLiteral hallchinacoeastliverpoolohName = new RDFPlainLiteral("Hall China Co., East Liverpool, OH");
            RDFPlainLiteral leonkrierName = new RDFPlainLiteral("Leon Krier");
            RDFPlainLiteral louisikahnName = new RDFPlainLiteral("Louis I. Kahn");
            RDFPlainLiteral ludwigmiesvanderroheName = new RDFPlainLiteral("Ludwig Mies van der Rohe");
            RDFPlainLiteral mariobottaName = new RDFPlainLiteral("Mario Botta");
            RDFPlainLiteral marioromanoName = new RDFPlainLiteral("Mario Romano");
            RDFPlainLiteral masayukikurokawaName = new RDFPlainLiteral("Masayuki Kurokawa");
            RDFPlainLiteral morphosissantamonicacaName = new RDFPlainLiteral("Morphosis, Santa Monica, CA");
            RDFPlainLiteral rafaelviñolyName = new RDFPlainLiteral("Rafael Viñoly");
            RDFPlainLiteral raimundabrahamName = new RDFPlainLiteral("Raimund Abraham");
            RDFPlainLiteral richardmeierName = new RDFPlainLiteral("Richard Meier");
            RDFPlainLiteral santiagocalatravaName = new RDFPlainLiteral("Santiago Calatrava");
            RDFPlainLiteral simonungersName = new RDFPlainLiteral("Simon Ungers");
            RDFPlainLiteral tadaoandoName = new RDFPlainLiteral("Tadao Ando");
            RDFPlainLiteral thommayneName = new RDFPlainLiteral("Thom Mayne");
            RDFPlainLiteral thomaskinslowName = new RDFPlainLiteral("Thomas Kinslow");
            RDFPlainLiteral zahahadidName = new RDFPlainLiteral("Zaha Hadid");

            #endregion

            #region Locations (tgn)

            RDFResource northwales = new RDFResource("http://vocab.getty.edu/tgn/2091433-place");
            RDFResource wales = new RDFResource("http://vocab.getty.edu/tgn/7002443-place");
            RDFResource berlin = new RDFResource("http://vocab.getty.edu/tgn/7003712-place");
            RDFResource newyork = new RDFResource("http://vocab.getty.edu/tgn/7007567-place");
            RDFResource edinburgh = new RDFResource("http://vocab.getty.edu/tgn/7009546-place");
            RDFResource kiyev = new RDFResource("http://vocab.getty.edu/tgn/7010171-place");
            RDFResource london = new RDFResource("http://vocab.getty.edu/tgn/7011781-place");
            RDFResource moskva = new RDFResource("http://vocab.getty.edu/tgn/7012974-place");
            RDFResource boston = new RDFResource("http://vocab.getty.edu/tgn/7013445-place");
            RDFResource detroit = new RDFResource("http://vocab.getty.edu/tgn/7013547-place");
            RDFResource longbeach = new RDFResource("http://vocab.getty.edu/tgn/7013905-place");
            RDFResource sanfrancisco = new RDFResource("http://vocab.getty.edu/tgn/7014456-place");

            // Locations (tgn): plain literal name

            RDFPlainLiteral berlinName = new RDFPlainLiteral("Berlin");
            RDFPlainLiteral bostonName = new RDFPlainLiteral("Boston");
            RDFPlainLiteral detroitName = new RDFPlainLiteral("Detroit");
            RDFPlainLiteral edinburghName = new RDFPlainLiteral("Edinburgh");
            RDFPlainLiteral kiyevName = new RDFPlainLiteral("Kiyev");
            RDFPlainLiteral londonName = new RDFPlainLiteral("London");
            RDFPlainLiteral longbeachName = new RDFPlainLiteral("Long Beach");
            RDFPlainLiteral moskvaName = new RDFPlainLiteral("Moskva");
            RDFPlainLiteral newyorkName = new RDFPlainLiteral("New York");
            RDFPlainLiteral northwalesName = new RDFPlainLiteral("North Wales");
            RDFPlainLiteral sanfranciscoName = new RDFPlainLiteral("San Francisco");
            RDFPlainLiteral walesName = new RDFPlainLiteral("Wales");

            #endregion

            #region Triples

            // Create triple resources

            RDFTriple aldorossi_type_agent = new RDFTriple(aldorossi, type, agent);
            RDFTriple andrewzago_type_agent = new RDFTriple(andrewzago, type, agent);
            RDFTriple eerosaarinen_type_agent = new RDFTriple(eerosaarinen, type, agent);
            RDFTriple emilioambasz_type_agent = new RDFTriple(emilioambasz, type, agent);
            RDFTriple ernestobrunolapadula_type_agent = new RDFTriple(ernestobrunolapadula, type, agent);
            RDFTriple evazeisel_type_agent = new RDFTriple(evazeisel, type, agent);
            RDFTriple franklloydwright_type_agent = new RDFTriple(franklloydwright, type, agent);
            RDFTriple frederickkiesler_type_agent = new RDFTriple(frederickkiesler, type, agent);
            RDFTriple fusogomuindcoltdtokyo_type_agent = new RDFTriple(fusogomuindcoltdtokyo, type, agent);
            RDFTriple giovanniguerrini_type_agent = new RDFTriple(giovanniguerrini, type, agent);
            RDFTriple hallchinacoeastliverpooloh_type_agent = new RDFTriple(hallchinacoeastliverpooloh, type, agent);
            RDFTriple leonkrier_type_agent = new RDFTriple(leonkrier, type, agent);
            RDFTriple louisikahn_type_agent = new RDFTriple(louisikahn, type, agent);
            RDFTriple ludwigmiesvanderrohe_type_agent = new RDFTriple(ludwigmiesvanderrohe, type, agent);
            RDFTriple mariobotta_type_agent = new RDFTriple(mariobotta, type, agent);
            RDFTriple marioromano_type_agent = new RDFTriple(marioromano, type, agent);
            RDFTriple masayukikurokawa_type_agent = new RDFTriple(masayukikurokawa, type, agent);
            RDFTriple morphosissantamonicaca_type_agent = new RDFTriple(morphosissantamonicaca, type, agent);
            RDFTriple rafaelviñoly_type_agent = new RDFTriple(rafaelviñoly, type, agent);
            RDFTriple raimundabraham_type_agent = new RDFTriple(raimundabraham, type, agent);
            RDFTriple richardmeier_type_agent = new RDFTriple(richardmeier, type, agent);
            RDFTriple santiagocalatrava_type_agent = new RDFTriple(santiagocalatrava, type, agent);
            RDFTriple simonungers_type_agent = new RDFTriple(simonungers, type, agent);
            RDFTriple tadaoando_type_agent = new RDFTriple(tadaoando, type, agent);
            RDFTriple thommayne_type_agent = new RDFTriple(thommayne, type, agent);
            RDFTriple thomaskinslow_type_agent = new RDFTriple(thomaskinslow, type, agent);
            RDFTriple zahahadid_type_agent = new RDFTriple(zahahadid, type, agent);

            RDFTriple berlin_type_tgn = new RDFTriple(berlin, type, tgn);
            RDFTriple boston_type_tgn = new RDFTriple(boston, type, tgn);
            RDFTriple detroit_type_tgn = new RDFTriple(detroit, type, tgn);
            RDFTriple edinburgh_type_tgn = new RDFTriple(edinburgh, type, tgn);
            RDFTriple kiyev_type_tgn = new RDFTriple(kiyev, type, tgn);
            RDFTriple london_type_tgn = new RDFTriple(london, type, tgn);
            RDFTriple longbeach_type_tgn = new RDFTriple(longbeach, type, tgn);
            RDFTriple moskva_type_tgn = new RDFTriple(moskva, type, tgn);
            RDFTriple newyork_type_tgn = new RDFTriple(newyork, type, tgn);
            RDFTriple northwales_type_tgn = new RDFTriple(northwales, type, tgn);
            RDFTriple sanfrancisco_type_tgn = new RDFTriple(sanfrancisco, type, tgn);
            RDFTriple wales_type_tgn = new RDFTriple(wales, type, tgn);

            RDFTriple aldorossi_name_aldorossiName = new RDFTriple(aldorossi, name, aldorossiName);
            RDFTriple andrewzago_name_andrewzagoName = new RDFTriple(andrewzago, name, andrewzagoName);
            RDFTriple eerosaarinen_name_eerosaarinenName = new RDFTriple(eerosaarinen, name, eerosaarinenName);
            RDFTriple emilioambasz_name_emilioambaszName = new RDFTriple(emilioambasz, name, emilioambaszName);
            RDFTriple ernestobrunolapadula_name_ernestobrunolapadulaName = new RDFTriple(ernestobrunolapadula, name, ernestobrunolapadulaName);
            RDFTriple evazeisel_name_evazeiselName = new RDFTriple(evazeisel, name, evazeiselName);
            RDFTriple franklloydwright_name_franklloydwrightName = new RDFTriple(franklloydwright, name, franklloydwrightName);
            RDFTriple frederickkiesler_name_frederickkieslerName = new RDFTriple(frederickkiesler, name, frederickkieslerName);
            RDFTriple fusogomuindcoltdtokyo_name_fusogomuindcoltdtokyoName = new RDFTriple(fusogomuindcoltdtokyo, name, fusogomuindcoltdtokyoName);
            RDFTriple giovanniguerrini_name_giovanniguerriniName = new RDFTriple(giovanniguerrini, name, giovanniguerriniName);
            RDFTriple hallchinacoeastliverpooloh_name_hallchinacoeastliverpoolohName = new RDFTriple(hallchinacoeastliverpooloh, name, hallchinacoeastliverpoolohName);
            RDFTriple leonkrier_name_leonkrierName = new RDFTriple(leonkrier, name, leonkrierName);
            RDFTriple louisikahn_name_louisikahnName = new RDFTriple(louisikahn, name, louisikahnName);
            RDFTriple ludwigmiesvanderrohe_name_ludwigmiesvanderroheName = new RDFTriple(ludwigmiesvanderrohe, name, ludwigmiesvanderroheName);
            RDFTriple mariobotta_name_mariobottaName = new RDFTriple(mariobotta, name, mariobottaName);
            RDFTriple marioromano_name_marioromanoName = new RDFTriple(marioromano, name, marioromanoName);
            RDFTriple masayukikurokawa_name_masayukikurokawaName = new RDFTriple(masayukikurokawa, name, masayukikurokawaName);
            RDFTriple morphosissantamonicaca_name_morphosissantamonicacaName = new RDFTriple(morphosissantamonicaca, name, morphosissantamonicacaName);
            RDFTriple rafaelviñoly_name_rafaelviñolyName = new RDFTriple(rafaelviñoly, name, rafaelviñolyName);
            RDFTriple raimundabraham_name_raimundabrahamName = new RDFTriple(raimundabraham, name, raimundabrahamName);
            RDFTriple richardmeier_name_richardmeierName = new RDFTriple(richardmeier, name, richardmeierName);
            RDFTriple santiagocalatrava_name_santiagocalatravaName = new RDFTriple(santiagocalatrava, name, santiagocalatravaName);
            RDFTriple simonungers_name_simonungersName = new RDFTriple(simonungers, name, simonungersName);
            RDFTriple tadaoando_name_tadaoandoName = new RDFTriple(tadaoando, name, tadaoandoName);
            RDFTriple thommayne_name_thommayneName = new RDFTriple(thommayne, name, thommayneName);
            RDFTriple thomaskinslow_name_thomaskinslowName = new RDFTriple(thomaskinslow, name, thomaskinslowName);
            RDFTriple zahahadid_name_zahahadidName = new RDFTriple(zahahadid, name, zahahadidName);

            RDFTriple berlin_name_berlinName = new RDFTriple(berlin, name, berlinName);
            RDFTriple boston_name_bostonName = new RDFTriple(boston, name, bostonName);
            RDFTriple detroit_name_detroitName = new RDFTriple(detroit, name, detroitName);
            RDFTriple edinburgh_name_edinburghName = new RDFTriple(edinburgh, name, edinburghName);
            RDFTriple kiyev_name_kiyevName = new RDFTriple(kiyev, name, kiyevName);
            RDFTriple london_name_londonName = new RDFTriple(london, name, londonName);
            RDFTriple longbeach_name_longbeachName = new RDFTriple(longbeach, name, longbeachName);
            RDFTriple moskva_name_moskvaName = new RDFTriple(moskva, name, moskvaName);
            RDFTriple newyork_name_newyorkName = new RDFTriple(newyork, name, newyorkName);
            RDFTriple northwales_name_northwalesName = new RDFTriple(northwales, name, northwalesName);
            RDFTriple sanfrancisco_name_sanfranciscoName = new RDFTriple(sanfrancisco, name, sanfranciscoName);
            RDFTriple wales_name_walesName = new RDFTriple(wales, name, walesName);

            RDFTriple aldorossi_activeIn_moskva = new RDFTriple(aldorossi, activeIn, moskva);
            RDFTriple andrewzago_activeIn_moskva = new RDFTriple(andrewzago, activeIn, moskva);
            RDFTriple eerosaarinen_activeIn_newyork = new RDFTriple(eerosaarinen, activeIn, newyork);
            RDFTriple emilioambasz_activeIn_newyork = new RDFTriple(emilioambasz, activeIn, newyork);
            RDFTriple ernestobrunolapadula_activeIn_newyork = new RDFTriple(ernestobrunolapadula, activeIn, newyork);
            RDFTriple evazeisel_educatedIn_berlin = new RDFTriple(evazeisel, educatedIn, berlin);
            RDFTriple franklloydwright_activeIn_detroit = new RDFTriple(franklloydwright, activeIn, detroit);
            RDFTriple franklloydwright_livedIn_moskva = new RDFTriple(franklloydwright, livedIn, moskva);
            RDFTriple frederickkiesler_livedIn_longbeach = new RDFTriple(frederickkiesler, livedIn, longbeach);
            RDFTriple fusogomuindcoltdtokyo_livedIn_london = new RDFTriple(fusogomuindcoltdtokyo, livedIn, london);
            RDFTriple giovanniguerrini_activeIn_newyork = new RDFTriple(giovanniguerrini, activeIn, newyork);
            RDFTriple hallchinacoeastliverpooloh_educatedIn_berlin = new RDFTriple(hallchinacoeastliverpooloh, educatedIn, berlin);
            RDFTriple leonkrier_activeIn_newyork = new RDFTriple(leonkrier, activeIn, newyork);
            RDFTriple leonkrier_educatedIn_london = new RDFTriple(leonkrier, educatedIn, london);
            RDFTriple louisikahn_livedIn_longbeach = new RDFTriple(louisikahn, livedIn, longbeach);
            RDFTriple louisikahn_livedIn_newyork = new RDFTriple(louisikahn, livedIn, newyork);
            RDFTriple ludwigmiesvanderrohe_activeIn_moskva = new RDFTriple(ludwigmiesvanderrohe, activeIn, moskva);
            RDFTriple ludwigmiesvanderrohe_livedIn_moskva = new RDFTriple(ludwigmiesvanderrohe, livedIn, moskva);
            RDFTriple mariobotta_activeIn_kiyev = new RDFTriple(mariobotta, activeIn, kiyev);
            RDFTriple mariobotta_activeIn_moskva = new RDFTriple(mariobotta, activeIn, moskva);
            RDFTriple mariobotta_livedIn_moskva = new RDFTriple(mariobotta, livedIn, moskva);
            RDFTriple marioromano_activeIn_newyork = new RDFTriple(marioromano, activeIn, newyork);
            RDFTriple masayukikurokawa_livedIn_london = new RDFTriple(masayukikurokawa, livedIn, london);
            RDFTriple morphosissantamonicaca_activeIn_moskva = new RDFTriple(morphosissantamonicaca, activeIn, moskva);
            RDFTriple rafaelviñoly_activeIn_newyork = new RDFTriple(rafaelviñoly, activeIn, newyork);
            RDFTriple raimundabraham_livedIn_moskva = new RDFTriple(raimundabraham, livedIn, moskva);
            RDFTriple richardmeier_activeIn_edinburgh = new RDFTriple(richardmeier, activeIn, edinburgh);
            RDFTriple richardmeier_activeIn_london = new RDFTriple(richardmeier, activeIn, london);
            RDFTriple richardmeier_educatedIn_london = new RDFTriple(richardmeier, educatedIn, london);
            RDFTriple santiagocalatrava_livedIn_newyork = new RDFTriple(santiagocalatrava, livedIn, newyork);
            RDFTriple simonungers_livedIn_boston = new RDFTriple(simonungers, livedIn, boston);
            RDFTriple simonungers_livedIn_newyork = new RDFTriple(simonungers, livedIn, newyork);
            RDFTriple tadaoando_activeIn_newyork = new RDFTriple(tadaoando, activeIn, newyork);
            RDFTriple tadaoando_livedIn_northwales = new RDFTriple(tadaoando, livedIn, northwales);
            RDFTriple tadaoando_livedIn_wales = new RDFTriple(tadaoando, livedIn, wales);
            RDFTriple thommayne_activeIn_moskva = new RDFTriple(thommayne, activeIn, moskva);
            RDFTriple thomaskinslow_livedIn_boston = new RDFTriple(thomaskinslow, livedIn, boston);
            RDFTriple thomaskinslow_livedIn_newyork = new RDFTriple(thomaskinslow, livedIn, newyork);
            RDFTriple zahahadid_activeIn_sanfrancisco = new RDFTriple(zahahadid, activeIn, sanfrancisco);

            #endregion

            #region Add triples to graph

            RDFGraph m_graph = new RDFGraph();

            m_graph.AddTriple(aldorossi_activeIn_moskva);
            m_graph.AddTriple(aldorossi_name_aldorossiName);
            m_graph.AddTriple(aldorossi_type_agent);
            m_graph.AddTriple(andrewzago_activeIn_moskva);
            m_graph.AddTriple(andrewzago_name_andrewzagoName);
            m_graph.AddTriple(andrewzago_type_agent);
            m_graph.AddTriple(berlin_name_berlinName);
            m_graph.AddTriple(berlin_type_tgn);
            m_graph.AddTriple(boston_name_bostonName);
            m_graph.AddTriple(boston_type_tgn);
            m_graph.AddTriple(detroit_name_detroitName);
            m_graph.AddTriple(detroit_type_tgn);
            m_graph.AddTriple(edinburgh_name_edinburghName);
            m_graph.AddTriple(edinburgh_type_tgn);
            m_graph.AddTriple(eerosaarinen_activeIn_newyork);
            m_graph.AddTriple(eerosaarinen_name_eerosaarinenName);
            m_graph.AddTriple(eerosaarinen_type_agent);
            m_graph.AddTriple(emilioambasz_activeIn_newyork);
            m_graph.AddTriple(emilioambasz_name_emilioambaszName);
            m_graph.AddTriple(emilioambasz_type_agent);
            m_graph.AddTriple(ernestobrunolapadula_activeIn_newyork);
            m_graph.AddTriple(ernestobrunolapadula_name_ernestobrunolapadulaName);
            m_graph.AddTriple(ernestobrunolapadula_type_agent);
            m_graph.AddTriple(evazeisel_educatedIn_berlin);
            m_graph.AddTriple(evazeisel_name_evazeiselName);
            m_graph.AddTriple(evazeisel_type_agent);
            m_graph.AddTriple(franklloydwright_activeIn_detroit);
            m_graph.AddTriple(franklloydwright_livedIn_moskva);
            m_graph.AddTriple(franklloydwright_name_franklloydwrightName);
            m_graph.AddTriple(franklloydwright_type_agent);
            m_graph.AddTriple(frederickkiesler_livedIn_longbeach);
            m_graph.AddTriple(frederickkiesler_name_frederickkieslerName);
            m_graph.AddTriple(frederickkiesler_type_agent);
            m_graph.AddTriple(fusogomuindcoltdtokyo_livedIn_london);
            m_graph.AddTriple(fusogomuindcoltdtokyo_name_fusogomuindcoltdtokyoName);
            m_graph.AddTriple(fusogomuindcoltdtokyo_type_agent);
            m_graph.AddTriple(giovanniguerrini_activeIn_newyork);
            m_graph.AddTriple(giovanniguerrini_name_giovanniguerriniName);
            m_graph.AddTriple(giovanniguerrini_type_agent);
            m_graph.AddTriple(hallchinacoeastliverpooloh_educatedIn_berlin);
            m_graph.AddTriple(hallchinacoeastliverpooloh_name_hallchinacoeastliverpoolohName);
            m_graph.AddTriple(hallchinacoeastliverpooloh_type_agent);
            m_graph.AddTriple(kiyev_name_kiyevName);
            m_graph.AddTriple(kiyev_type_tgn);
            m_graph.AddTriple(leonkrier_activeIn_newyork);
            m_graph.AddTriple(leonkrier_educatedIn_london);
            m_graph.AddTriple(leonkrier_name_leonkrierName);
            m_graph.AddTriple(leonkrier_type_agent);
            m_graph.AddTriple(london_name_londonName);
            m_graph.AddTriple(london_type_tgn);
            m_graph.AddTriple(longbeach_name_longbeachName);
            m_graph.AddTriple(longbeach_type_tgn);
            m_graph.AddTriple(louisikahn_livedIn_longbeach);
            m_graph.AddTriple(louisikahn_livedIn_newyork);
            m_graph.AddTriple(louisikahn_name_louisikahnName);
            m_graph.AddTriple(louisikahn_type_agent);
            m_graph.AddTriple(ludwigmiesvanderrohe_activeIn_moskva);
            m_graph.AddTriple(ludwigmiesvanderrohe_livedIn_moskva);
            m_graph.AddTriple(ludwigmiesvanderrohe_name_ludwigmiesvanderroheName);
            m_graph.AddTriple(ludwigmiesvanderrohe_type_agent);
            m_graph.AddTriple(mariobotta_activeIn_kiyev);
            m_graph.AddTriple(mariobotta_activeIn_moskva);
            m_graph.AddTriple(mariobotta_livedIn_moskva);
            m_graph.AddTriple(mariobotta_name_mariobottaName);
            m_graph.AddTriple(mariobotta_type_agent);
            m_graph.AddTriple(marioromano_activeIn_newyork);
            m_graph.AddTriple(marioromano_name_marioromanoName);
            m_graph.AddTriple(marioromano_type_agent);
            m_graph.AddTriple(masayukikurokawa_livedIn_london);
            m_graph.AddTriple(masayukikurokawa_name_masayukikurokawaName);
            m_graph.AddTriple(masayukikurokawa_type_agent);
            m_graph.AddTriple(morphosissantamonicaca_activeIn_moskva);
            m_graph.AddTriple(morphosissantamonicaca_name_morphosissantamonicacaName);
            m_graph.AddTriple(morphosissantamonicaca_type_agent);
            m_graph.AddTriple(moskva_name_moskvaName);
            m_graph.AddTriple(moskva_type_tgn);
            m_graph.AddTriple(newyork_name_newyorkName);
            m_graph.AddTriple(newyork_type_tgn);
            m_graph.AddTriple(northwales_name_northwalesName);
            m_graph.AddTriple(northwales_type_tgn);
            m_graph.AddTriple(rafaelviñoly_activeIn_newyork);
            m_graph.AddTriple(rafaelviñoly_name_rafaelviñolyName);
            m_graph.AddTriple(rafaelviñoly_type_agent);
            m_graph.AddTriple(raimundabraham_livedIn_moskva);
            m_graph.AddTriple(raimundabraham_name_raimundabrahamName);
            m_graph.AddTriple(raimundabraham_type_agent);
            m_graph.AddTriple(richardmeier_activeIn_edinburgh);
            m_graph.AddTriple(richardmeier_activeIn_london);
            m_graph.AddTriple(richardmeier_educatedIn_london);
            m_graph.AddTriple(richardmeier_name_richardmeierName);
            m_graph.AddTriple(richardmeier_type_agent);
            m_graph.AddTriple(sanfrancisco_name_sanfranciscoName);
            m_graph.AddTriple(sanfrancisco_type_tgn);
            m_graph.AddTriple(santiagocalatrava_livedIn_newyork);
            m_graph.AddTriple(santiagocalatrava_name_santiagocalatravaName);
            m_graph.AddTriple(santiagocalatrava_type_agent);
            m_graph.AddTriple(simonungers_livedIn_boston);
            m_graph.AddTriple(simonungers_livedIn_newyork);
            m_graph.AddTriple(simonungers_name_simonungersName);
            m_graph.AddTriple(simonungers_type_agent);
            m_graph.AddTriple(tadaoando_activeIn_newyork);
            m_graph.AddTriple(tadaoando_livedIn_northwales);
            m_graph.AddTriple(tadaoando_livedIn_wales);
            m_graph.AddTriple(tadaoando_name_tadaoandoName);
            m_graph.AddTriple(tadaoando_type_agent);
            m_graph.AddTriple(thomaskinslow_livedIn_boston);
            m_graph.AddTriple(thomaskinslow_livedIn_newyork);
            m_graph.AddTriple(thomaskinslow_name_thomaskinslowName);
            m_graph.AddTriple(thomaskinslow_type_agent);
            m_graph.AddTriple(thommayne_activeIn_moskva);
            m_graph.AddTriple(thommayne_name_thommayneName);
            m_graph.AddTriple(thommayne_type_agent);
            m_graph.AddTriple(wales_name_walesName);
            m_graph.AddTriple(wales_type_tgn);
            m_graph.AddTriple(zahahadid_activeIn_sanfrancisco);
            m_graph.AddTriple(zahahadid_name_zahahadidName);
            m_graph.AddTriple(zahahadid_type_agent);

            #endregion

            // Only using RdfXml for this example so no need to write/read all files
            // Write RDF
            RDFSerializer.WriteRDF(RDFModelEnums.RDFFormats.RdfXml, m_graph, Server.MapPath("~/").ToString() + "\\" + "tms.rdf");
            //RDFSerializer.WriteRDF(RDFModelEnums.RDFFormats.Turtle, m_graph, Server.MapPath("~/").ToString() + "\\" + "\\tms.ttl");
            //RDFSerializer.WriteRDF(RDFModelEnums.RDFFormats.TriX, m_graph, Server.MapPath("~/").ToString() + "\\" + "\\tms.trix");
            //RDFSerializer.WriteRDF(RDFModelEnums.RDFFormats.NTriples, m_graph, Server.MapPath("~/").ToString() + "\\" + "\\tms.nt");

            // Read RDF
            RDFGraph tmsRDF = RDFSerializer.ReadRDF(RDFModelEnums.RDFFormats.RdfXml, Server.MapPath("~/").ToString() + "\\tms.rdf");
            //RDFGraph tmsTURTLE = RDFSerializer.ReadRDF(RDFModelEnums.RDFFormats.Turtle, Environment.CurrentDirectory + "\\tms.ttl");
            //RDFGraph tmsTRIX = RDFSerializer.ReadRDF(RDFModelEnums.RDFFormats.TriX, Environment.CurrentDirectory + "\\tms.trix");
            //RDFGraph tmsNT = RDFSerializer.ReadRDF(RDFModelEnums.RDFFormats.NTriples, Environment.CurrentDirectory + "\\tms.nt");

            // Write the RDF into SQL Server.  You have other choices with RDFSharp including RDFMemoryStore

            string m_conn = ConfigurationManager.ConnectionStrings["RDFConnectionString"].ConnectionString;

            RDFSQLServerStore rdf_mssql = new RDFSQLServerStore(m_conn);

            rdf_mssql.MergeGraph(tmsRDF);

            // At this point you can open SQL Server and see a new table called Quadruples with all of the data in the correct format.
            // The first time you run this (successfully), the RdfViewer.aspx page will be empty.
            // Uncomment GetRDF() above and comment LoadRDF() and you should see a datagrid with RDF data.
        }