Exemplo n.º 1
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);
            }
        }
        public void SelectDogs()
        {
            // CREATE SELECT QUERY
            RDFSelectQuery selectQuery = new RDFSelectQuery();

            selectQuery.AddPrefix(RDFNamespaceRegister.GetByPrefix("dc"));
            selectQuery.AddPrefix(RDFNamespaceRegister.GetByPrefix("foaf"));

            var x = new RDFVariable("x");
            var y = new RDFVariable("y");

            RDFPatternMember predicate = GraphBuilder2.dogOf;

            var x_dogOf_y = new RDFPattern(x, predicate, y);

            // CREATE PATTERN GROUP FROM A LIST OF PATTERNS
            var patterns = new List <RDFPattern>()
            {
                x_dogOf_y
            };
            var pg1 = new RDFPatternGroup("PG1", patterns);

            // ADD PATTERN GROUPS TO QUERY
            selectQuery.AddPatternGroup(pg1);

            selectQuery.AddProjectionVariable(x);
            selectQuery.AddProjectionVariable(y);

            // APPLY SELECT QUERY TO GRAPH

            var sparqlCommand = selectQuery.ToString();

            /*
             * Generates this sparql command
             *
             * PREFIX dc: <http://purl.org/dc/elements/1.1/>
             * PREFIX foaf: <http://xmlns.com/foaf/0.1/>
             *
             * SELECT ?X ?Y
             * WHERE {
             * {
             * ?X dc:dogOf ?Y .
             * }
             * }
             */

            RDFSelectQueryResult selectQueryResult = selectQuery.ApplyToGraph(graph);

            // EXPORT SELECT QUERY RESULTS TO SPARQL XML FORMAT (FILE)
            selectQueryResult.ToSparqlXmlResult(@"C:\TEMP\select_results.srq");

            Assert.Equal(1, selectQueryResult.SelectResultsCount);

            DataRow row    = selectQueryResult.SelectResults.Rows[0];
            var     dog    = row[0].ToString();
            var     person = row[1].ToString();

            Assert.Equal(pluto.URI.ToString(), dog);
            Assert.Equal(mickeyMouse.URI.ToString(), person);


            /*
             * Generates this file content
             *
             * <?xml version="1.0" encoding="utf-8"?>
             * <sparql xmlns="http://www.w3.org/2005/sparql-results#">
             * <head>
             * <variable name="?X" />
             * <variable name="?Y" />
             * </head>
             * <results>
             * <result>
             * <binding name="?X">
             * <uri>https://en.wikipedia.org/wiki/Pluto_(Disney)</uri>
             * </binding>
             * <binding name="?Y">
             * <uri>https://en.wikipedia.org/wiki/Mickey_Mouse</uri>
             * </binding>
             * </result>
             * </results>
             * </sparql>
             */
        }
        public void SelectDogsOrCats_UnionWithNext_Test()
        {
            // CREATE SELECT QUERY
            RDFSelectQuery selectQuery = new RDFSelectQuery();

            selectQuery.AddPrefix(RDFNamespaceRegister.GetByPrefix("dc"));
            selectQuery.AddPrefix(RDFNamespaceRegister.GetByPrefix("foaf"));

            var x = new RDFVariable("x");
            var y = new RDFVariable("y");

            RDFPatternMember dogOfPredicate = GraphBuilder2.dogOf;
            RDFPatternMember catOfPredicate = GraphBuilder2.catOf;

            var x_dogOf_y = new RDFPattern(x, dogOfPredicate, y);
            var x_catOf_y = new RDFPattern(x, catOfPredicate, y);

            //var orFilter = new RDFBooleanOrFilter(x_dogOf_y, x_catOf_y);

            // CREATE PATTERN GROUP FROM A LIST OF PATTERNS
            var pg1 = new RDFPatternGroup("PG1");

            pg1.AddPattern(x_dogOf_y.UnionWithNext());
            pg1.AddPattern(x_catOf_y);

            selectQuery.AddPatternGroup(pg1);

            selectQuery.AddProjectionVariable(x);
            selectQuery.AddProjectionVariable(y);

            selectQuery.AddModifier(new RDFOrderByModifier(x, RDFQueryEnums.RDFOrderByFlavors.ASC));



            var sparqlCommand = selectQuery.ToString();

            /*
             * Generates this sparql command
             *
             * PREFIX dc: <http://purl.org/dc/elements/1.1/>
             * PREFIX foaf: <http://xmlns.com/foaf/0.1/>
             *
             * SELECT ?X ?Y
             * WHERE {
             * {
             * { ?X dc:dogOf ?Y }
             * UNION
             * { ?X dc:catOf ?Y }
             * }
             * }
             * ORDER BY ASC(?X)
             */

            // APPLY SELECT QUERY TO GRAPH
            RDFSelectQueryResult selectQueryResult = selectQuery.ApplyToGraph(graph);

            // EXPORT SELECT QUERY RESULTS TO SPARQL XML FORMAT (FILE)
            selectQueryResult.ToSparqlXmlResult(@"C:\TEMP\select_results.srq");

            Assert.Equal(2, selectQueryResult.SelectResultsCount);

            //DataRow row = selectQueryResult.SelectResults.Rows[0];
            //var dog = row[0].ToString();
            //var person = row[1].ToString();
            //Assert.Equal(pluto.URI.ToString(), dog);
            //Assert.Equal(mickeyMouse.URI.ToString(), person);


            /*
             * Generates this file content
             *
             * <?xml version="1.0" encoding="utf-8"?>
             * <sparql xmlns="http://www.w3.org/2005/sparql-results#">
             * <head>
             * <variable name="?X" />
             * <variable name="?Y" />
             * </head>
             * <results>
             * <result>
             * <binding name="?X">
             * <uri>https://en.wikipedia.org/wiki/Figaro_(Disney)</uri>
             * </binding>
             * <binding name="?Y">
             * <uri>https://en.wikipedia.org/wiki/Minnie_Mouse</uri>
             * </binding>
             * </result>
             * <result>
             * <binding name="?X">
             * <uri>https://en.wikipedia.org/wiki/Pluto_(Disney)</uri>
             * </binding>
             * <binding name="?Y">
             * <uri>https://en.wikipedia.org/wiki/Mickey_Mouse</uri>
             * </binding>
             * </result>
             * </results>
             * </sparql>
             */
        }
        public void Test1()
        {
            string   filePath = GetPath(@"Files\Test1.ttl");
            RDFGraph graph    = RDFGraph.FromFile(RDFModelEnums.RDFFormats.Turtle, filePath);

            RDFSelectQuery selectQuery = new RDFSelectQuery();

            // PREFIX foaf: <http://xmlns.com/foaf/0.1/>
            selectQuery.AddPrefix(RDFNamespaceRegister.GetByPrefix("foaf"));

            // ?NAME
            var name = new RDFVariable("name");
            // ?FRIEND
            var friend = new RDFVariable("friend");
            // ?PERSON
            var person = new RDFVariable("person");

            // ?PERSON foaf:name ?NAME .
            var person_foaf_name_name = new RDFPattern(person, RDFVocabulary.FOAF.NAME, name);
            // ?PERSON foaf:knows ?FRIEND .
            var person_foaf_knows_friend = new RDFPattern(person, RDFVocabulary.FOAF.KNOWS, friend);

// WHERE {
//  {
//    ?PERSON foaf:name? NAME .
//    ?PERSON foaf:knows? FRIEND .
//  }
// }
            var pg1 = new RDFPatternGroup("PG1");

            pg1.AddPattern(person_foaf_name_name);
            pg1.AddPattern(person_foaf_knows_friend);

            selectQuery.AddPatternGroup(pg1);

            // SELECT ?PERSON ?NAME ?FRIEND
            selectQuery.AddProjectionVariable(person);
            selectQuery.AddProjectionVariable(name);
            selectQuery.AddProjectionVariable(friend);

            var sparqlCommand = selectQuery.ToString();

            #region Generated SPARQL command

            /*
             * Generates this sparql command
             *
             * PREFIX foaf: <http://xmlns.com/foaf/0.1/>
             *
             * SELECT ?PERSON ?NAME ?FRIEND
             * WHERE {
             * {
             * ?PERSON foaf:name ?NAME .
             * ?PERSON foaf:knows ?FRIEND .
             * }
             * }
             *
             */
            #endregion

            // APPLY SELECT QUERY TO GRAPH
            RDFSelectQueryResult selectQueryResult = selectQuery.ApplyToGraph(graph);

            // EXPORT SELECT QUERY RESULTS TO SPARQL XML FORMAT (FILE)
            //selectQueryResult.ToSparqlXmlResult(@"C:\TEMP\Test1.srq");

            #region Generated result file

            /*
             * <?xml version="1.0" encoding="utf-8"?>
             * <sparql xmlns="http://www.w3.org/2005/sparql-results#">
             * <head>
             *  <variable name="?PERSON" />
             *  <variable name="?NAME" />
             *  <variable name="?FRIEND" />
             * </head>
             * <results>
             *  <result>
             *    <binding name="?PERSON">
             *      <uri>http://example.org/alice#me</uri>
             *    </binding>
             *    <binding name="?NAME">
             *      <literal>Alice</literal>
             *    </binding>
             *    <binding name="?FRIEND">
             *      <uri>http://example.org/bob#me</uri>
             *    </binding>
             *  </result>
             *  <result>
             *    <binding name="?PERSON">
             *      <uri>http://example.org/alice#me</uri>
             *    </binding>
             *    <binding name="?NAME">
             *      <literal>Alice</literal>
             *    </binding>
             *    <binding name="?FRIEND">
             *      <uri>http://example.org/charlie#me</uri>
             *    </binding>
             *  </result>
             *  <result>
             *    <binding name="?PERSON">
             *      <uri>http://example.org/alice#me</uri>
             *    </binding>
             *    <binding name="?NAME">
             *      <literal>Alice</literal>
             *    </binding>
             *    <binding name="?FRIEND">
             *      <uri>http://example.org/snoopy</uri>
             *    </binding>
             *  </result>
             *  <result>
             *    <binding name="?PERSON">
             *      <uri>http://example.org/bob#me</uri>
             *    </binding>
             *    <binding name="?NAME">
             *      <literal>Bob</literal>
             *    </binding>
             *    <binding name="?FRIEND">
             *      <uri>http://example.org/alice#me</uri>
             *    </binding>
             *  </result>
             *  <result>
             *    <binding name="?PERSON">
             *      <uri>http://example.org/charlie#me</uri>
             *    </binding>
             *    <binding name="?NAME">
             *      <literal>Charlie</literal>
             *    </binding>
             *    <binding name="?FRIEND">
             *      <uri>http://example.org/alice#me</uri>
             *    </binding>
             *  </result>
             * </results>
             * </sparql>
             */
            #endregion

            Assert.Equal(5, selectQueryResult.SelectResultsCount);
        }
        public void Test2()
        {
            string   filePath = GetPath(@"Files\Test1.ttl");
            RDFGraph graph    = RDFGraph.FromFile(RDFModelEnums.RDFFormats.Turtle, filePath);

            RDFSelectQuery selectQuery = new RDFSelectQuery();

            selectQuery.AddPrefix(RDFNamespaceRegister.GetByPrefix("foaf"));

            var name   = new RDFVariable("name");
            var friend = new RDFVariable("friend");
            var count  = new RDFVariable("count");
            var person = new RDFVariable("person");

            // ?person foaf:name ?name .
            var person_foaf_name_name = new RDFPattern(person, RDFVocabulary.FOAF.NAME, name);
            // ?person foaf:knows ?friend .
            var person_foaf_knows_friend = new RDFPattern(person, RDFVocabulary.FOAF.KNOWS, friend);

            var pg1 = new RDFPatternGroup("PG1");

            pg1.AddPattern(person_foaf_name_name);
            pg1.AddPattern(person_foaf_knows_friend);

            selectQuery.AddPatternGroup(pg1);


            selectQuery.AddProjectionVariable(name);
            //selectQuery.AddProjectionVariable(count);

            // GROUP BY ?PERSON ?NAME
            // var gm = new RDFGroupByModifier(new List<RDFVariable>() { person, name });
            // GROUP BY ?NAME
            var gm = new RDFGroupByModifier(new List <RDFVariable>()
            {
                name
            });

            // (COUNT(?friend) AS ?count)
            gm.AddAggregator(new RDFCountAggregator(friend, count));

            selectQuery.AddModifier(gm);


            var sparqlCommand = selectQuery.ToString();

            #region Target query in the SPARQL 1.1 documentation

            /*
             * Target query in the document
             *
             * PREFIX foaf: <http://xmlns.com/foaf/0.1/>
             * SELECT ?name (COUNT(?friend) AS ?count)
             * WHERE {
             * ?person foaf:name ?name .
             * ?person foaf:knows ?friend .
             * } GROUP BY ?person ?name
             */
            #endregion

            #region Managed to build this command

            /*
             * PREFIX foaf: <http://xmlns.com/foaf/0.1/>
             *
             * SELECT ?NAME (COUNT(?FRIEND) AS ?COUNT)
             * WHERE {
             * {
             * ?PERSON foaf:name ?NAME .
             * ?PERSON foaf:knows ?FRIEND .
             * }
             * }
             * GROUP BY ?NAME
             */
            #endregion

            #region Managed to build this command

            /*
             * Managed to build this command
             *
             * PREFIX foaf: <http://xmlns.com/foaf/0.1/>
             *
             * SELECT ?PERSON ?NAME (COUNT(?FRIEND) AS ?COUNT)
             * WHERE {
             * {
             * ?PERSON foaf:name ?NAME .
             * ?PERSON foaf:knows ?FRIEND .
             * }
             * }
             * GROUP BY ?PERSON ?NAME
             */
            #endregion

            // APPLY SELECT QUERY TO GRAPH
            RDFSelectQueryResult selectQueryResult = selectQuery.ApplyToGraph(graph);

            // EXPORT SELECT QUERY RESULTS TO SPARQL XML FORMAT (FILE)
            //selectQueryResult.ToSparqlXmlResult(@"C:\TEMP\Test2.srq");

            #region Got result

            /*
             * Got result
             *
             * <?xml version="1.0" encoding="utf-8"?>
             * <sparql xmlns="http://www.w3.org/2005/sparql-results#">
             * <head>
             * <variable name="?NAME" />
             * <variable name="?COUNT" />
             * </head>
             * <results>
             * <result>
             * <binding name="?NAME">
             * <literal>Alice</literal>
             * </binding>
             * <binding name="?COUNT">
             * <literal datatype="http://www.w3.org/2001/XMLSchema#decimal">3</literal>
             * </binding>
             * </result>
             * <result>
             * <binding name="?NAME">
             * <literal>Bob</literal>
             * </binding>
             * <binding name="?COUNT">
             * <literal datatype="http://www.w3.org/2001/XMLSchema#decimal">1</literal>
             * </binding>
             * </result>
             * <result>
             * <binding name="?NAME">
             * <literal>Charlie</literal>
             * </binding>
             * <binding name="?COUNT">
             * <literal datatype="http://www.w3.org/2001/XMLSchema#decimal">1</literal>
             * </binding>
             * </result>
             * </results>
             * </sparql>
             *
             */
            #endregion

            #region Got result

            /*
             *
             *
             * <?xml version="1.0" encoding="utf-8"?>
             * <sparql xmlns="http://www.w3.org/2005/sparql-results#">
             * <head>
             * <variable name="?PERSON" />
             * <variable name="?NAME" />
             * <variable name="?COUNT" />
             * </head>
             * <results>
             * <result>
             * <binding name="?PERSON">
             * <uri>http://example.org/alice#me</uri>
             * </binding>
             * <binding name="?NAME">
             * <literal>Alice</literal>
             * </binding>
             * <binding name="?COUNT">
             * <literal datatype="http://www.w3.org/2001/XMLSchema#decimal">3</literal>
             * </binding>
             * </result>
             * <result>
             * <binding name="?PERSON">
             * <uri>http://example.org/bob#me</uri>
             * </binding>
             * <binding name="?NAME">
             * <literal>Bob</literal>
             * </binding>
             * <binding name="?COUNT">
             * <literal datatype="http://www.w3.org/2001/XMLSchema#decimal">1</literal>
             * </binding>
             * </result>
             * <result>
             * <binding name="?PERSON">
             * <uri>http://example.org/charlie#me</uri>
             * </binding>
             * <binding name="?NAME">
             * <literal>Charlie</literal>
             * </binding>
             * <binding name="?COUNT">
             * <literal datatype="http://www.w3.org/2001/XMLSchema#decimal">1</literal>
             * </binding>
             * </result>
             * </results>
             * </sparql>
             *
             */
            #endregion

            #region Target result from SPARQL 1.1 documentation

            /*
             * Target result
             * 3 Different query results formats supported by SPARQL 1.1 (XML, JSON, CSV, TSV)
             *
             * <?xml version="1.0"?>
             * <sparql xmlns="http://www.w3.org/2005/sparql-results#">
             * <head>
             * <variable name="name"/>
             * <variable name="count"/>
             * </head>
             * <results>
             * <result>
             * <binding name="name">
             * <literal>Alice</literal>
             * </binding>
             * <binding name="count">
             * <literal datatype="http://www.w3.org/2001/XMLSchema#integer">3</literal>
             * </binding>
             * </result>
             * <result>
             * <binding name="name">
             * <literal>Bob</literal>
             * </binding>
             * <binding name="count">
             * <literal datatype="http://www.w3.org/2001/XMLSchema#integer">1</literal>
             * </binding>
             * </result>
             * <result>
             * <binding name="name">
             * <literal>Charlie</literal>
             * </binding>
             * <binding name="count">
             * <literal datatype="http://www.w3.org/2001/XMLSchema#integer">1</literal>
             * </binding>
             * </result>
             * </results>
             * </sparql>
             */
            #endregion

            Assert.Equal(3, selectQueryResult.SelectResultsCount);
        }
Exemplo n.º 6
0
        //source: http://dadev.cloudapp.net/Datos%20Abiertos/PDF/ReferenceGuide.pdf
        static void Main(string[] args)
        {
            //create resource from string
            RDFResource donaldduck = new RDFResource("http://www.waltdisney.com/donald_duck");

            //create resource from uri
            RDFResource goofygoof = new RDFResource(new Uri("http://www.waltdisney.com/goofy_goof").ToString());

            //create plain literal
            // "Donald Duck"
            RDFPlainLiteral donaldduck_name = new RDFPlainLiteral("Donald Duck");
            //create typed literal
            // "85"^^xsd:integer
            RDFTypedLiteral 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"),
                                                         mickeymouse_age);

            // "Donald Duck has English-US name "Donald Duck""
            RDFTriple donaldduck_name_enus_triple = new RDFTriple(donaldduck,
                                                                  new RDFResource("http://xmlns.com/foaf/0.1/name"),
                                                                  donaldduck_name);

            // "Goofy Goof is 82 years old"
            RDFTriple goofygoof_is82yr = new RDFTriple(goofygoof,
                                                       RDFVocabulary.FOAF.AGE,
                                                       new RDFPlainLiteral("82"));
            // "Donald Duck knows Goofy Goof"
            RDFTriple donaldduck_knows_goofygoof = new RDFTriple(donaldduck,
                                                                 RDFVocabulary.FOAF.KNOWS,
                                                                 goofygoof);

            //create graph from a list of triples
            List <RDFTriple> triples = new List <RDFTriple>
            {
                mickeymouse_is85yr,
                donaldduck_name_enus_triple,
                goofygoof_is82yr,
                donaldduck_knows_goofygoof
            };
            RDFGraph waltdisney = new RDFGraph(triples);

            //set context of a graph
            waltdisney.SetContext(new Uri("http://waltdisney.com/"));

            //iterate triples of a graph
            foreach (RDFTriple t in waltdisney)
            {
                Console.WriteLine($"Triple: {t}\n");
                Console.WriteLine($"Subject: {t.Subject}");
                Console.WriteLine($"Predicate: {t.Predicate}");
                Console.WriteLine($"Object: {t.Object}");
            }

            //compose multiple selections
            RDFGraph triples_by_subject_and_predicate =
                waltdisney.SelectTriplesBySubject(donaldduck)
                .SelectTriplesByPredicate(new RDFResource("http://xmlns.com/foaf/0.1/name"));

            Console.WriteLine("Number of triples where the subject is Donald Duck and the predicate is foaf:name: " + triples_by_subject_and_predicate.TriplesCount);
            Console.WriteLine();

            //create namespace
            RDFNamespace waltdisney_ns = new RDFNamespace("wd", "http://www.waltdisney.com/");

            //set default namespace
            RDFNamespaceRegister.SetDefaultNamespace(waltdisney_ns); //new graphs will default to this context

            //iterate namespaces
            foreach (RDFNamespace ns in RDFNamespaceRegister.Instance)
            {
                Console.WriteLine($"Prefix: {ns.NamespacePrefix}\n");
                Console.WriteLine($"Namespace: {ns.NamespaceUri}\n");
            }
            Console.ReadKey();
        }