protected override async Task ProcessBatch(CollectorHttpClient client, IList<JObject> items, JObject context)
        {
            List<Task<IGraph>> tasks = new List<Task<IGraph>>();

            foreach (JObject item in items)
            {
                if (Utils.IsType(context, item, Constants.Package))
                {
                    Uri itemUri = item["url"].ToObject<Uri>();
                    tasks.Add(client.GetGraphAsync(itemUri));
                }
            }

            if (tasks.Count > 0)
            {
                await Task.WhenAll(tasks.ToArray());

                TripleStore store = new TripleStore();

                foreach (Task<IGraph> task in tasks)
                {
                    store.Add(task.Result, true);
                }

                await ProcessStore(store);
            }
        }
        protected override async Task<bool> OnProcessBatch(CollectorHttpClient client, IEnumerable<JToken> items, JToken context, DateTime commitTimeStamp, bool isLastBatch, CancellationToken cancellationToken)
        {
            List<Task<IGraph>> tasks = new List<Task<IGraph>>();

            foreach (JObject item in items)
            {
                if (Utils.IsType((JObject)context, item, _types))
                {
                    Uri itemUri = item["@id"].ToObject<Uri>();
                    tasks.Add(client.GetGraphAsync(itemUri));
                }
            }

            if (tasks.Count > 0)
            {
                await Task.WhenAll(tasks.ToArray());

                TripleStore store = new TripleStore();

                foreach (Task<IGraph> task in tasks)
                {
                    store.Add(task.Result, true);
                }

                await ProcessStore(store, cancellationToken);
            }

            return true;
        }
        public void SparqlBind()
        {
            String query = "PREFIX fn: <" + XPathFunctionFactory.XPathFunctionsNamespace + "> SELECT ?triple WHERE { ?s ?p ?o . BIND(fn:concat(STR(?s), ' ', STR(?p), ' ', STR(?o)) AS ?triple) }";

            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);

            Object results = q.Evaluate(store);
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count > 0, "Expected 1 or more results");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
        }
        public void SparqlBindLazy()
        {
            String query = "PREFIX fn: <" + XPathFunctionFactory.XPathFunctionsNamespace + "> SELECT ?triple WHERE { ?s ?p ?o . BIND(fn:concat(STR(?s), ' ', STR(?p), ' ', STR(?o)) AS ?triple) } LIMIT 1";

            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);

            Console.WriteLine(q.ToAlgebra().ToString());
            Assert.IsTrue(q.ToAlgebra().ToString().Contains("LazyBgp"), "Should have been optimised to use a Lazy BGP");
            Console.WriteLine();

            Object results = q.Evaluate(store);
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count == 1, "Expected exactly 1 results");
                Assert.IsTrue(rset.All(r => r.HasValue("triple")), "All Results should have had a value for ?triple");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
        }
Exemple #5
0
 public MetadataSource(Options opts)
 {
     if (!String.IsNullOrEmpty(opts.EndpointUri))
     {
         if (String.IsNullOrEmpty(opts.DefaultGraphUri))
         {
             this._processor = new RemoteQueryProcessor(new SparqlRemoteEndpoint(new Uri(opts.EndpointUri)));
         }
         else
         {
             this._processor = new RemoteQueryProcessor(new SparqlRemoteEndpoint(new Uri(opts.EndpointUri), opts.DefaultGraphUri));
         }
     }
     else if (!String.IsNullOrEmpty(opts.SourceFile))
     {
         TripleStore store = new TripleStore();
         Graph g = new Graph();
         FileLoader.Load(g, opts.SourceFile);
         store.Add(g);
         this._processor = new LeviathanQueryProcessor(store);
     }
     else
     {
         throw new Exception("Must specify an endpoint or a file to query");
     }
 }
 /// <summary>
 /// Construictir for MyLoFacebookContextReader
 /// </summary>
 /// <param name="gpsl">A GPSLookup instance implementing IGPSlookup</param>
 public MyLoFacebookContextReader(IGPSlookup gpsl)
 {
     _store = new TripleStore();
     _g = new Graph();
     _g.BaseUri = new Uri("http://facebook.MyLo.com");
     _store.Add(_g);
     gpsLookup = gpsl;
 }
Exemple #7
0
 /// <summary>
 /// Gets a Graph Reference for the given Graph URI.
 /// </summary>
 /// <param name="graphUri">Graph URI.</param>
 /// <returns></returns>
 public IGraph this[Uri graphUri]
 {
     get
     {
         if (_store.HasGraph(graphUri))
         {
             return(_store[graphUri]);
         }
         else
         {
             Graph g = new Graph();
             g.BaseUri = graphUri;
             _store.Add(g);
             return(g);
         }
     }
 }
        protected static IInMemoryQueryableStore CreateMemoryStore()
		{
            string musicOntology = Settings.Default.testStoreLocation;
            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, musicOntology);
			store.Add(g);
            return store;
		}
		private static IInMemoryQueryableStore CreateMemoryStore()
		{
			TripleStore result = new TripleStore();
			string serialisedLocation = Settings.Default.testStoreLocation;
            Graph g = new Graph();
            FileLoader.Load(g, serialisedLocation);
            result.Add(g);
			return result;
		}
Exemple #10
0
        public void GraphCollectionBasic1()
        {
            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            store.Add(g);

            Assert.True(store.HasGraph(g.BaseUri), "Graph Collection should contain the Graph");
            Assert.Equal(g, store[g.BaseUri]);
        }
        public void SparqlLazyWithAndWithoutOffset()
        {
            String query  = "SELECT * WHERE { ?s a ?vehicle . FILTER (SAMETERM(?vehicle, <http://example.org/vehicles/Car>)) } LIMIT 3";
            String query2 = "SELECT * WHERE { ?s a ?vehicle . FILTER (SAMETERM(?vehicle, <http://example.org/vehicles/Car>)) } LIMIT 3 OFFSET 3";

            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery       q      = parser.ParseFromString(query);
            SparqlQuery       q2     = parser.ParseFromString(query2);

            Console.WriteLine(q.ToAlgebra().ToString());
            Assert.IsTrue(q.ToAlgebra().ToString().Contains("LazyBgp"), "Should have been optimised to use a Lazy BGP");
            Console.WriteLine();

            Console.WriteLine(q2.ToAlgebra().ToString());
            Assert.IsTrue(q2.ToAlgebra().ToString().Contains("LazyBgp"), "Should have been optimised to use a Lazy BGP");
            Console.WriteLine();

            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(AsDataset(store));
            Object results = processor.ProcessQuery(q);

            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count == 3, "Expected exactly 3 results");

                Object results2 = processor.ProcessQuery(q2);
                if (results2 is SparqlResultSet)
                {
                    SparqlResultSet rset2 = (SparqlResultSet)results2;
                    foreach (SparqlResult r in rset2)
                    {
                        Console.WriteLine(r.ToString());
                    }
                    Assert.IsTrue(rset2.Count == 1, "Expected exactly 1 results");
                }
                else
                {
                    Assert.Fail("Expected a SPARQL Result Set");
                }
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
        }
 public void InitialiseStore(string storeLocation)
 {
     TripleStore store = new TripleStore();
     //store.AddReasoner(new Euler(new N3Reader(MusicConstants.OntologyURL)));
     if (File.Exists(storeLocation))
     {
         Graph g = new Graph();
         FileLoader.Load(g, storeLocation);
         store.Add(g);
     }
 }
Exemple #13
0
        public void GraphCollectionBasic2()
        {
            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");
            store.Add(g);

            Assert.True(store.HasGraph(g.BaseUri), "Graph Collection should contain the Graph");
            Assert.Equal(g, store[g.BaseUri]);
        }
        public static void ApplyInference(IGraph graph, IGraph schema)
        {
            string inverseOf = @"
                PREFIX owl: <http://www.w3.org/2002/07/owl#>
                CONSTRUCT { ?y ?q ?x }
                WHERE { ?p owl:inverseOf ?q .
                        ?x ?p ?y . }
            ";

            var parser = new SparqlQueryParser();

            var rules = new List<SparqlQuery>();
            rules.Add(parser.ParseFromString(inverseOf));

            var store = new TripleStore();
            store.Add(graph, true);
            store.Add(schema, true);

            var queryProcessor = new LeviathanQueryProcessor(store);

            while (true)
            {
                int before = store.Triples.Count();

                foreach (var rule in rules)
                {
                    IGraph inferred = (IGraph)queryProcessor.ProcessQuery(rule);
                    //store.Add(inferred);
                    graph.Merge(inferred);
                }

                int after = store.Triples.Count();

                if (after == before)
                {
                    break;
                }
            }
        }
        static IDictionary<RegistrationEntryKey, RegistrationCatalogEntry> GetResources(IGraph graph)
        {
            IDictionary<RegistrationEntryKey, RegistrationCatalogEntry> resources = new Dictionary<RegistrationEntryKey, RegistrationCatalogEntry>();

            TripleStore store = new TripleStore();
            store.Add(graph);

            IList<Uri> existingItems = ListExistingItems(store);

            foreach (Uri existingItem in existingItems)
            {
                AddExistingItem(resources, store, existingItem);
            }

            return resources;
        }
Exemple #16
0
        public void GraphCollectionDiskDemand2()
        {
            //Test that on-demand loading does not kick in for pre-existing graphs
            TripleStore store = new TripleStore(new DiskDemandGraphCollection());

            Graph g = new Graph();

            g.LoadFromFile("resources\\InferenceTest.ttl");
            g.BaseUri = new Uri("file:///" + Path.GetFullPath("resources\\InferenceTest.ttl"));

            Graph empty = new Graph();

            empty.BaseUri = g.BaseUri;
            store.Add(empty);

            Assert.True(store.HasGraph(g.BaseUri), "Graph Collection should contain the Graph");
            Assert.NotEqual(g, store[g.BaseUri]);
        }
        public void SparqlFilterLazy3()
        {
            long currTimeout = Options.QueryExecutionTimeout;

            try
            {
                Options.QueryExecutionTimeout = 0;

                String query = "SELECT * WHERE { ?s a ?vehicle . FILTER (SAMETERM(?vehicle, <http://example.org/vehicles/Car>)) . ?s <http://example.org/vehicles/Speed> ?speed } LIMIT 3";

                TripleStore store = new TripleStore();
                Graph       g     = new Graph();
                FileLoader.Load(g, "InferenceTest.ttl");
                store.Add(g);

                SparqlQueryParser parser = new SparqlQueryParser();
                SparqlQuery       q      = parser.ParseFromString(query);
                q.Timeout = 0;

                Console.WriteLine(q.ToAlgebra().ToString());
                Assert.IsTrue(q.ToAlgebra().ToString().Contains("LazyBgp"), "Should have been optimised to use a Lazy BGP");
                Console.WriteLine();

                LeviathanQueryProcessor processor = new LeviathanQueryProcessor(AsDataset(store));
                Object results = processor.ProcessQuery(q);
                if (results is SparqlResultSet)
                {
                    SparqlResultSet rset = (SparqlResultSet)results;
                    foreach (SparqlResult r in rset)
                    {
                        Console.WriteLine(r.ToString());
                    }
                    Assert.IsTrue(rset.Count == 3, "Expected exactly 3 results");
                }
                else
                {
                    Assert.Fail("Expected a SPARQL Result Set");
                }
            }
            finally
            {
                Options.QueryExecutionTimeout = currTimeout;
            }
        }
        private VDS.RDF.TripleStore CreateNewTripleStore(IDictionary <string, string> graphs)
        {
            var store = new VDS.RDF.TripleStore();

            foreach (var graph in graphs)
            {
                var g = new VDS.RDF.Graph();

                g.BaseUri = new Uri(graph.Value);

                var ttlparser = new TurtleParser();
                ttlparser.Load(g, AppDomain.CurrentDomain.BaseDirectory + $"Setup/Graphs/{graph.Key}");
                store.Add(g);
            }
            ;

            // TODO: Check if usesGraph is in graphGraph
            return(store);
        }
Exemple #19
0
        public void GraphCollectionWebDemand2()
        {
            //Test that on-demand loading does not kick in for pre-existing graphs
            TripleStore store = new TripleStore(new WebDemandGraphCollection());

            Graph g = new Graph();
            Uri   u = new Uri("http://www.dotnetrdf.org/configuration#");

            g.LoadFromUri(u);
            g.BaseUri = u;

            Graph empty = new Graph();

            empty.BaseUri = g.BaseUri;
            store.Add(empty);

            Assert.True(store.HasGraph(g.BaseUri), "Graph Collection should contain the Graph");
            Assert.NotEqual(g, store[g.BaseUri]);
        }
        private IGraph ExecuteDiff(IGraph older, IGraph newer, Uri graphUri = null)
        {
            var diff   = new GraphDiff().Difference(older, newer);
            var update = diff.AsUpdate(graphUri);
            var sparql = update.ToString();

            output.WriteLine(sparql);

            older = older ?? new Graph();

            var ts = new TripleStore();

            ts.Add(older);

            var store = new InMemoryManager(ts) as IUpdateableStorage;

            store.Update(sparql);

            return(older);
        }
Exemple #21
0
        public void GraphEventBubbling()
        {
            try
            {
                this._graphAdded   = false;
                this._graphRemoved = false;
                this._graphChanged = false;

                //Create Store and Graph add attach handlers to Store
                TripleStore store = new TripleStore();
                Graph       g     = new Graph();
                store.GraphAdded   += this.HandleGraphAdded;
                store.GraphRemoved += this.HandleGraphRemoved;
                store.GraphChanged += this.HandleGraphChanged;

                //Add the Graph to the Store which should fire the GraphAdded event
                store.Add(g);
                Assert.IsTrue(this._graphAdded, "GraphAdded event of the Triple Store should have fired");

                //Assert a Triple
                INode  s = g.CreateBlankNode();
                INode  p = g.CreateUriNode("rdf:type");
                INode  o = g.CreateUriNode("rdfs:Class");
                Triple t = new Triple(s, p, o);
                g.Assert(t);
                Assert.IsTrue(this._graphChanged, "GraphChanged event of the Triple Store should have fired");

                //Retract the Triple
                this._graphChanged = false;
                g.Retract(t);
                Assert.IsTrue(this._graphChanged, "GraphChanged event of the Triple Store should have fired");

                //Remove the Graph from the Store which should fire the GraphRemoved event
                store.Remove(g.BaseUri);
                Assert.IsTrue(this._graphRemoved, "GraphRemoved event of the Triple Store should have fired");
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public void SparqlBindToExistingVariableLazy()
        {
            String query = "PREFIX fn: <" + XPathFunctionFactory.XPathFunctionsNamespace + "> SELECT * WHERE { ?s ?p ?o . BIND(?s AS ?p) } LIMIT 1";

            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();

            try
            {
                SparqlQuery q = parser.ParseFromString(query);

                Console.WriteLine(q.ToAlgebra().ToString());
                Assert.IsTrue(q.ToAlgebra().ToString().Contains("LazyBgp"), "Should have been optimised to use a Lazy BGP");
                Console.WriteLine();

                store.ExecuteQuery(q);
                Assert.Fail("Expected a RdfParseException/RdfQueryException to be thrown");
            }
            catch (RdfParseException parseEx)
            {
                Console.WriteLine("Parsing Error thrown as expected");
                TestTools.ReportError("Parser Error", parseEx);
            }
            catch (RdfQueryException queryEx)
            {
                Console.WriteLine("Query Error thrown as expected");
                TestTools.ReportError("Query Error", queryEx);
            }
            catch (Exception ex)
            {
                TestTools.ReportError("Unexpected Error", ex);
                Assert.Fail("Did not get a RdfParseException/RdfQueryException as expected");
            }
        }
        public void SparqlFilterLazyDBPedia()
        {
            SparqlParameterizedString query = new SparqlParameterizedString();

            query.Namespaces.AddNamespace("rdfs", new Uri(NamespaceMapper.RDFS));
            query.CommandText = "SELECT * WHERE {?s ?p ?label . FILTER(ISLITERAL(?label) && LANGMATCHES(LANG(?label), \"en\")) } LIMIT 5";

            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            UriLoader.Load(g, new Uri("http://dbpedia.org/resource/Southampton"));
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery       q      = parser.ParseFromString(query);

            Console.WriteLine(q.ToAlgebra().ToString());
            Assert.IsTrue(q.ToAlgebra().ToString().Contains("LazyBgp"), "Should have been optimised to use a Lazy BGP");
            Console.WriteLine();

            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(AsDataset(store));
            Object results = processor.ProcessQuery(q);

            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count == 5, "Expected exactly 5 results");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
        }
        public void SparqlFilterLazy4()
        {
            String query = "SELECT * WHERE { ?s a <http://example.org/vehicles/Car> ; <http://example.org/vehicles/Speed> ?speed } LIMIT 3";

            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);

            Console.WriteLine(q.ToAlgebra().ToString());
            Assert.IsTrue(q.ToAlgebra().ToString().Contains("LazyBgp"), "Should have been optimised to use a Lazy BGP");
            Console.WriteLine();

            Object results = q.Evaluate(store);
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count == 3, "Expected exactly 3 results");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
        }
        public void SparqlFilterLazy2()
        {
            String query = "SELECT * WHERE { ?s a ?vehicle . FILTER (SAMETERM(?vehicle, <http://example.org/Vehicles/Car>)) } LIMIT 3";

            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);

            Console.WriteLine("NOTE: The URI for Car is purposefully wrong in this case so no results should be returned");
            Console.WriteLine(q.ToAlgebra().ToString());
            Assert.IsTrue(q.ToAlgebra().ToString().Contains("LazyBgp"), "Should have been optimised to use a Lazy BGP");
            Console.WriteLine();

            Object results = q.Evaluate(store);
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count == 0, "Expected no results");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
        }
        async Task DeletePackage(Uri resourceUri, string version)
        {
            string existingJson = await _storage.Load(resourceUri);
            if (existingJson != null)
            {
                IGraph currentPackageRegistration = Utils.CreateGraph(existingJson);

                using (TripleStore store = new TripleStore())
                {
                    store.Add(currentPackageRegistration, true);

                    SparqlParameterizedString sparql = new SparqlParameterizedString();
                    sparql.CommandText = Utils.GetResource("sparql.DeletePackage.rq");

                    sparql.SetLiteral("version", version);

                    IGraph modifiedPackageRegistration = SparqlHelpers.Construct(store, sparql.ToString());

                    if (CountPackage(modifiedPackageRegistration) == 0)
                    {
                        await _storage.Delete(resourceUri);
                    }
                    else
                    {
                        string content = Utils.CreateJson(modifiedPackageRegistration, _resolverFrame);
                        await _storage.Save("application/json", resourceUri, content);
                    }
                }
            }
        }
        public void SparqlJsonResultSet()
        {
            Console.WriteLine("Tests that JSON Parser parses language specifiers correctly");

            String query = "PREFIX rdfs: <" + NamespaceMapper.RDFS + ">\nSELECT DISTINCT ?comment WHERE {?s rdfs:comment ?comment}";

            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "json.owl");
            store.Add(g);

            Object results = store.ExecuteQuery(query);
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;

                //Serialize to both XML and JSON Results format
                SparqlXmlWriter xmlwriter = new SparqlXmlWriter();
                xmlwriter.Save(rset, "results.xml");
                SparqlJsonWriter jsonwriter = new SparqlJsonWriter();
                jsonwriter.Save(rset, "results.json");

                //Read both back in
                SparqlXmlParser xmlparser = new SparqlXmlParser();
                SparqlResultSet r1 = new SparqlResultSet();
                xmlparser.Load(r1, "results.xml");
                Console.WriteLine("Result Set after XML serialization and reparsing contains:");
                foreach (SparqlResult r in r1)
                {
                    Console.WriteLine(r.ToString());
                }
                Console.WriteLine();

                SparqlJsonParser jsonparser = new SparqlJsonParser();
                SparqlResultSet r2 = new SparqlResultSet();
                jsonparser.Load(r2, "results.json");
                Console.WriteLine("Result Set after JSON serialization and reparsing contains:");
                foreach (SparqlResult r in r2)
                {
                    Console.WriteLine(r.ToString());
                }
                Console.WriteLine();

                Assert.AreEqual(r1, r2, "Results Sets should be equal");

                Console.WriteLine("Result Sets were equal as expected");
            }
            else
            {
                Assert.Fail("Query did not return a Result Set");
            }
        }
        int CountPackage(IGraph packageRegistration)
        {
            using (TripleStore store = new TripleStore())
            {
                store.Add(packageRegistration, true);

                SparqlResultSet countResultSet = SparqlHelpers.Select(store, Utils.GetResource("sparql.SelectPackageCount.rq"));

                foreach (SparqlResult row in countResultSet)
                {
                    string s = ((ILiteralNode)row["count"]).Value;
                    return int.Parse(s);
                }
            }
            return 0;
        }
        public void SparqlLazyWithAndWithoutOffset()
        {
            String query = "SELECT * WHERE { ?s a ?vehicle . FILTER (SAMETERM(?vehicle, <http://example.org/vehicles/Car>)) } LIMIT 3";
            String query2 = "SELECT * WHERE { ?s a ?vehicle . FILTER (SAMETERM(?vehicle, <http://example.org/vehicles/Car>)) } LIMIT 3 OFFSET 3";

            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);
            SparqlQuery q2 = parser.ParseFromString(query2);

            Console.WriteLine(q.ToAlgebra().ToString());
            Assert.IsTrue(q.ToAlgebra().ToString().Contains("LazyBgp"), "Should have been optimised to use a Lazy BGP");
            Console.WriteLine();

            Console.WriteLine(q2.ToAlgebra().ToString());
            Assert.IsTrue(q2.ToAlgebra().ToString().Contains("LazyBgp"), "Should have been optimised to use a Lazy BGP");
            Console.WriteLine();

            Object results = q.Evaluate(store);
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count == 3, "Expected exactly 3 results");

                Object results2 = q2.Evaluate(store);
                if (results2 is SparqlResultSet)
                {
                    SparqlResultSet rset2 = (SparqlResultSet)results2;
                    foreach (SparqlResult r in rset2)
                    {
                        Console.WriteLine(r.ToString());
                    }
                    Assert.IsTrue(rset2.Count == 1, "Expected exactly 1 results");
                }
                else
                {
                    Assert.Fail("Expected a SPARQL Result Set");
                }
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
        }
        //

        internal LinqTripleStore CreateSparqlTripleStore()
        {
            string tasksOntology = Path.Combine(Settings.Default.taskStorePath, Settings.Default.tasksOntologyName);
            string tasks = Path.Combine(Settings.Default.taskStorePath, Settings.Default.tasksDataName);
            TripleStore store = new TripleStore();
            //store.AddReasoner(new Euler(new N3Reader(tasksOntology)));
            //store.Import(new N3Reader(tasksOntology));
            Graph g = new Graph();
            FileLoader.Load(g, tasks);
            store.Add(g);
            g = new Graph();
            FileLoader.Load(g, tasksOntology);
            store.Add(g);
            return new LinqTripleStore(store);
        }
 private void chkWebDemand_CheckedChanged(object sender, EventArgs e)
 {
     if (this.chkWebDemand.Checked)
     {
         if (this._store is WebDemandTripleStore)
         {
             //Nothing to do
         }
         else
         {
             WebDemandTripleStore store = new WebDemandTripleStore();
             foreach (IGraph g in this._store.Graphs)
             {
                 store.Add(g);
             }
             this._store = store;
         }
     }
     else
     {
         if (this._store is TripleStore)
         {
             //Nothing to do
         }
         else
         {
             TripleStore store = new TripleStore();
             foreach (IGraph g in this._store.Graphs)
             {
                 store.Add(g);
             }
             this._store = store;
         }
     }
 }
        public override IGraph CreatePageContent(CatalogContext context)
        {
            try
            {
                IGraph content;

                using (TripleStore store = new TripleStore())
                {
                    store.Add(_catalogItem, true);

                    SparqlParameterizedString sparql = new SparqlParameterizedString();
                    sparql.CommandText = Utils.GetResource("sparql.ConstructPackagePageContentGraph.rq");

                    sparql.SetUri("package", GetItemAddress());
                    sparql.SetUri("catalogPackage", _catalogUri);
                    sparql.SetUri("baseAddress", BaseAddress);
                    sparql.SetUri("packageContent", GetPackageContentAddress());
                    sparql.SetUri("registrationBaseAddress", _registrationBaseAddress);

                    content = SparqlHelpers.Construct(store, sparql.ToString());
                }

                return content;
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("Exception processing catalog item {0}", _catalogUri), e);
            }
        }
        public void SparqlFilterLazyDBPedia()
        {
            SparqlParameterizedString query = new SparqlParameterizedString();
            query.Namespaces.AddNamespace("rdfs", new Uri(NamespaceMapper.RDFS));
            query.QueryText = "SELECT * WHERE {?s ?p ?label . FILTER(ISLITERAL(?label) && LANGMATCHES(LANG(?label), \"en\")) } LIMIT 5";

            TripleStore store = new TripleStore();
            Graph g = new Graph();
            UriLoader.Load(g, new Uri("http://dbpedia.org/resource/Southampton"));
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);

            Console.WriteLine(q.ToAlgebra().ToString());
            Assert.IsTrue(q.ToAlgebra().ToString().Contains("LazyBgp"), "Should have been optimised to use a Lazy BGP");
            Console.WriteLine();

            Object results = q.Evaluate(store);
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count == 5, "Expected exactly 5 results");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
        }
        public static void Main(string[] args)
        {
            StreamWriter output = new StreamWriter("InferenceTest.txt");
            try
            {
                //Set Output
                Console.SetOut(output);

                Console.WriteLine("## Inference Test Suite");

                //Load the Test RDF
                TurtleParser ttlparser = new TurtleParser();
                Graph g = new Graph();
                //ttlparser.TraceParsing = true;
                ttlparser.Load(g, "InferenceTest.ttl");

                Console.WriteLine("Inference Test Data Loaded OK");
                Console.WriteLine();

                Console.WriteLine("Graph contains the following Triples:");
                foreach (Triple t in g.Triples)
                {
                    Console.WriteLine(t.ToString());
                }
                Console.WriteLine();

                //Select everything that is exactly a Car
                Console.WriteLine("# Selecting things whose class is exactly Car");
                ExactClassSelector carsel = new ExactClassSelector(g, g.CreateUriNode("eg:Car"));
                Test(g, carsel);
                Console.WriteLine();

                //Select everything that is any sort of Car
                Console.WriteLine("# Selecting things whose class is Car or a subclass thereof");
                ClassSelector allcarsel = new ClassSelector(g, g.CreateUriNode("eg:Car"));
                Test(g, allcarsel);
                Console.WriteLine();

                //Select everything that is a SportsCar or superclass thereof
                Console.WriteLine("# Selecting things whose class is SportsCar or superclass thereof");
                Console.WriteLine("# Thus things which are Cars are selected but not PeopleCarriers since they are a sibling class and not a superclass");
                WideningClassSelector wcarsel = new WideningClassSelector(g, g.CreateUriNode("eg:SportsCar"));
                Test(g, wcarsel);
                Console.WriteLine();

                //Select everything that is exactly a Jumbo Jet
                Console.WriteLine("# Selecting things whose class is exactly JumboJet");
                ExactClassSelector jjsel = new ExactClassSelector(g, g.CreateUriNode("eg:JumboJet"));
                Test(g, jjsel);
                Console.WriteLine();

                //Select everything that is an Air Vehicle
                Console.WriteLine("# Selecting things which are Air Vehicles");
                ClassSelector avsel = new ClassSelector(g, g.CreateUriNode("eg:AirVehicle"));
                Test(g, avsel);
                Console.WriteLine();

                //Select everything that has a defined Speed
                Console.WriteLine("# Selecting things which have exactly Speed defined");
                HasExactPropertySelector spsel = new HasExactPropertySelector(g.CreateUriNode("eg:Speed"));
                Test(g, spsel);
                Console.WriteLine();

                //Select things with a limited Speed
                Console.WriteLine("# Selecting things which have a Limited Speed defined");
                HasExactPropertySelector lspsel = new HasExactPropertySelector(g.CreateUriNode("eg:LimitedSpeed"));
                Test(g, lspsel);
                Console.WriteLine();

                //Select things with any kinds of Speed
                Console.WriteLine("# Selecting things which have any kinds of Speed defined");
                HasPropertySelector allspsel = new HasPropertySelector(g, g.CreateUriNode("eg:Speed"));
                Test(g, allspsel);
                Console.WriteLine();

                //Now stick the Graph in a Triple Store with a Reasoner attached
                Console.WriteLine("# Using a Triple Store with an RDFS Reasoner attached");
                TripleStore store = new TripleStore();
                store.AddInferenceEngine(new RdfsReasoner());
                g.BaseUri = new Uri("http://example.org/Inference");
                //Add a couple of additional Triples, their types must be inferred
                g.Assert(new Triple(g.CreateUriNode("eg:AudiA8"), g.CreateUriNode("eg:Speed"), (180).ToLiteral(g)));
                g.Assert(new Triple(g.CreateUriNode("eg:SpaceShuttle"), g.CreateUriNode("eg:AirSpeed"), (17500).ToLiteral(g)));
                //Add the Graph to the store, this is when inference occurs
                store.Add(g);
                Console.WriteLine("Triple Store contains the following Triples");
                foreach (Triple t in store.Triples)
                {
                    Console.WriteLine(t.ToString());
                }
                Console.WriteLine();

                //Select things which are a Car
                Console.WriteLine("# Selecting things which are a Car (or subclass thereof)");
                HasPropertyValueSelector carsel2 = new HasPropertyValueSelector(g.CreateUriNode("rdf:type"), g.CreateUriNode("eg:Car"));
                Test(store, carsel2);
                Console.WriteLine();

                //Select things which are Air Vehicles
                Console.WriteLine("# Selecting things which are Air Vehicles");
                HasPropertyValueSelector avsel2 = new HasPropertyValueSelector(g.CreateUriNode("rdf:type"), g.CreateUriNode("eg:AirVehicle"));
                Test(store, avsel2);
                Console.WriteLine();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            output.Close();
        }
        public void SparqlBindToExistingVariableNested()
        {
            String query = "PREFIX fn: <" + XPathFunctionFactory.XPathFunctionsNamespace + "> SELECT * WHERE { ?s ?p ?o .{ BIND(?s AS ?p)} }";

            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();
            try
            {
                SparqlQuery q = parser.ParseFromString(query);
                store.ExecuteQuery(q);
                Assert.Fail("Expected a RdfQueryException to be thrown");
            }
            catch (RdfQueryException)
            {
                Console.WriteLine("Error thrown as expected");
            }
            catch
            {
                Assert.Fail("Expected a RdfQueryException");
            }
        }
        public void SparqlOrderByComplexLazyPerformance()
        {
            String query = "SELECT * WHERE { ?s ?p ?o . } ORDER BY ?s DESC(?p) LIMIT 5";

            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            FileLoader.Load(g, "dataset_50.ttl.gz");
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();

            //First do with Optimisation
            Stopwatch   timer = new Stopwatch();
            SparqlQuery q     = parser.ParseFromString(query);

            Console.WriteLine(q.ToAlgebra().ToString());
            Assert.IsTrue(q.ToAlgebra().ToString().Contains("LazyBgp"), "Should have been optimised to use a Lazy BGP");
            Console.WriteLine();

            timer.Start();
            LeviathanQueryProcessor processor = new LeviathanQueryProcessor(AsDataset(store));
            Object results = processor.ProcessQuery(q);

            timer.Stop();
            Console.WriteLine("Took " + timer.Elapsed + " to execute when Optimised");
            timer.Reset();
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count == 5, "Expected exactly 5 results");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }

            //Then do without optimisation
            Options.AlgebraOptimisation = false;
            timer.Start();
            results = processor.ProcessQuery(q);
            timer.Stop();
            Console.WriteLine("Took " + timer.Elapsed + " to execute when Unoptimised");
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count == 5, "Expected exactly 5 results");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
            Options.AlgebraOptimisation = true;
        }
        public void SparqlLetIn11Standard()
        {
            String query = "PREFIX fn: <" + XPathFunctionFactory.XPathFunctionsNamespace + "> SELECT ?triple WHERE { ?s ?p ?o . LET (?triple := fn:concat(STR(?s), ' ', STR(?p), ' ', STR(?o))) }";

            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser(SparqlQuerySyntax.Sparql_1_1);
            try
            {
                SparqlQuery q = parser.ParseFromString(query);
                Assert.Fail("Expected a RdfParseException to be thrown");
            }
            catch (RdfParseException)
            {
                Console.WriteLine("Error thrown as expected");
            } 
            catch 
            {
                Assert.Fail("Expected a RdfParseException");
            }
        }
        static void AddExistingItems(IGraph graph, IDictionary<string, IGraph> items)
        {
            TripleStore store = new TripleStore();
            store.Add(graph, true);

            string inlinePackageSparql = Utils.GetResource("sparql.SelectInlinePackage.rq");

            SparqlResultSet rows = SparqlHelpers.Select(store, inlinePackageSparql);
            foreach (SparqlResult row in rows)
            {
                string packageUri = ((IUriNode)row["catalogPackage"]).Uri.AbsoluteUri;
                string jsonFileName = packageUri.Substring(packageUri.LastIndexOf("/") + 1);
                
                //If items already has that version, then skip it
                //Add only the new ones
                if (!existingVersionsWithID.Contains(jsonFileName))
                {
                    items[packageUri] = graph;
                }
            }
        }
Exemple #39
0
        public void RunTest(String[] args)
        {
            if (args.Length < 2)
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: 2 Arguments are required in order to use the -test mode");
                return;
            }

            if (!File.Exists(args[1]))
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: Cannot test " + args[1] + " since the file does not exist");
                return;
            }

            Graph g = new Graph();
            try
            {
                FileLoader.Load(g, args[1]);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: Cannot parse the configuration file");
                Console.Error.WriteLine("rdfWebDeploy: Error: " + ex.Message);
                return;
            }
            Console.WriteLine("rdfWebDeploy: Opened the configuration file successfully");

            Graph vocab = new Graph();
            try
            {
                TurtleParser ttlparser = new TurtleParser();
                ttlparser.Load(vocab, new StreamReader(Assembly.GetAssembly(typeof(IGraph)).GetManifestResourceStream("VDS.RDF.Configuration.configuration.ttl")));
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: Cannot parse the configuration vocabulary");
                Console.Error.WriteLine("rdfWebDeploy: Error: " + ex.Message);
                return;
            }
            Console.WriteLine("rdfWebDeploy: Loaded the configuration vocabulary successfully");
            Console.WriteLine();
            Console.WriteLine("rdfWebDeploy: Tests Started...");
            Console.WriteLine();

            //Now make some tests against it
            int warnings = 0, errors = 0;
            IInMemoryQueryableStore store = new TripleStore();
            store.Add(vocab);
            if (g.BaseUri == null) g.BaseUri = new Uri("dotnetrdf:config");
            store.Add(g);
            Object results;
            SparqlResultSet rset;

            //Unknown vocabulary term test
            Console.WriteLine("rdfWebDeploy: Testing for URIs in the vocabulary namespace which are unknown");
            results = store.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + UnknownVocabularyTermsTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.Error.WriteLine("rdfWebDeploy: Error: The configuration file uses the URI '" + r["term"] + "' for a property/type and this does not appear to be a valid term in the Configuration vocabulary");
                    errors++;
                }
            }
            Console.WriteLine();

            #region General dnr:type Tests

            //Missing dnr:type test
            Console.WriteLine("rdfWebDeploy: Testing for missing dnr:type properties");
            results = g.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + MissingConfigurationTypeTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.Error.WriteLine("rdfWebDeploy: Warning: The Node '" + r["s"].ToString() + "' has an rdf:type but no dnr:type which may be needed by the Configuration Loader");
                    warnings++;
                }
            }
            Console.WriteLine();

            //Invalid dnr:type test
            Console.WriteLine("rdfWebDeploy: Testing that values given for dnr:type property are literals");
            results = g.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + InvalidTypePropertyTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.Error.WriteLine("rdfWebDeploy: Error: The node '" + r["s"].ToString() + "' has a dnr:type of '" + r["type"].ToString() + "' which is not given as a string literal");
                    errors++;
                }
            }
            Console.WriteLine();

            //Multiple dnr:type test
            Console.WriteLine("rdfWebDeploy: Testing that no object has multiple dnr:type values");
            results = g.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + MultipleTypeTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.Error.WriteLine("rdfWebDeploy: Error: The node '" + r["s"].ToString() + "' has multiple dnr:type values which is not valid");
                    errors++;
                }
            }
            Console.WriteLine();

            //Unknown Library Types test
            Console.WriteLine("rdfWebDeploy: Testing that values given for dnr:type property in the VDS.RDF namespace are valid");
            results = g.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + LibraryTypesTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                Assembly dotnetrdf = Assembly.GetAssembly(typeof(IGraph));
                foreach (SparqlResult r in rset)
                {
                    Type t = dotnetrdf.GetType(((ILiteralNode)r["type"]).Value);
                    if (t == null)
                    {
                        Console.Error.WriteLine("rdfWebDeploy: Error: The node '" + r["s"].ToString() + "' has a dnr:type of '" + r["type"].ToString() + "' which does not appear to be a valid type in dotNetRDF");
                        errors++;
                    }
                }
            }
            Console.WriteLine();

            #endregion

            #region dnr:HttpHandler Tests including specific dnr:type Tests

            //Bad Handler URI test
            Console.WriteLine("rdfWebDeploy: Testing for bad URIs given the rdf:type of dnr:HttpHandler");
            results = g.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + BadHandlerUriTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.Error.WriteLine("rdfWebDeploy: Error: The Handler node '" + r["s"].ToString() + "' is not a URI of the form <dotnetrdf:/path> which is required for correct detection of handler configuration");
                    errors++;
                }
            }
            Console.WriteLine();

            //Missing Handler type test
            Console.WriteLine("rdfWebDeploy: Testing for missing dnr:type for dnr:HttpHandler objects");
            results = g.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + MissingHandlerTypeTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.Error.WriteLine("rdfWebDeploy: Error: The Handler node '" + r["s"].ToString() + "' has an rdf:type but no dnr:type which is requiring for automated deployment via this tool");
                    errors++;
                }
            }
            Console.WriteLine();

            //Invalid Handler Type test
            Console.WriteLine("rdfWebDeploy: Testing that values given for dnr:type for dnr:HttpHandler objects in the VDS.RDF namespace are valid IHttpHandlers");
            results = g.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + InvalidHandlerTypeTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                Assembly dotnetrdf = Assembly.GetAssembly(typeof(IGraph));
                foreach (SparqlResult r in rset)
                {
                    Type t = dotnetrdf.GetType(((ILiteralNode)r["type"]).Value);
                    if (t != null)
                    {
                        if (!t.GetInterfaces().Any(i => i.Equals(typeof(System.Web.IHttpHandler))))
                        {
                            Console.Error.WriteLine("rdfWebDeploy: Error: The node '" + r["s"].ToString() + "' has a dnr:type of '" + r["type"].ToString() + "' which does not appear to be a valid IHttpHandler implementation in dotNetRDF");
                            errors++;
                        }
                    }
                }
            }
            Console.WriteLine();

            #endregion

            #region Property Tests

            //Range test
            Console.WriteLine("rdfWebDeploy: Testing for bad ranges for properties");
            results = store.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + InvalidRangeTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    SparqlParameterizedString hasValidRange = new SparqlParameterizedString();
                    hasValidRange.QueryText = RdfWebDeployHelper.NamespacePrefixes + ValidRangeTest;
                    hasValidRange.SetParameter("property", r["property"]);
                    hasValidRange.SetParameter("s", r["s"]);
                    Object temp = store.ExecuteQuery(hasValidRange.ToString());
                    if (temp is SparqlResultSet)
                    {
                        if (!((SparqlResultSet)temp).Result)
                        {
                            Console.Error.WriteLine("rdfWebDeploy: Error: The Node '" + r["s"].ToString() + "' has a value for the property '" + r["property"].ToString() + "' which is '" + r["obj"].ToString() + "' which does not appear to be valid for the range of this property which is '" + r["range"].ToString() + "'");
                            errors++;
                        }
                    }
                }
            }
            Console.WriteLine();

            //Domain test
            Console.WriteLine("rdfWebDeploy: Testing for bad domains for properties");
            results = store.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + InvalidDomainTest);
            if (results is SparqlResultSet)
            {
                rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    SparqlParameterizedString hasValidDomain = new SparqlParameterizedString();
                    hasValidDomain.QueryText = RdfWebDeployHelper.NamespacePrefixes + ValidDomainTest;
                    hasValidDomain.SetParameter("property", r["property"]);
                    hasValidDomain.SetParameter("s", r["s"]);
                    Object temp = store.ExecuteQuery(hasValidDomain.ToString());
                    if (temp is SparqlResultSet)
                    {
                        if (!((SparqlResultSet)temp).Result)
                        {
                            Console.Error.WriteLine("rdfWebDeploy: Error: The Node '" + r["s"].ToString() + "' has a value for the property '" + r["property"].ToString() + "' and the type given is '" + r["type"].ToString() + "' which does not match the domain of this property which is '" + r["domain"].ToString() + "'");
                            errors++;
                        }
                    }
                }
            }
            Console.WriteLine();

            #endregion

            #region Clear Text Password Tests

            Console.WriteLine("rdfWebDeploy: Testing for clear text passwords used with dnr:password property");
            results = store.ExecuteQuery(RdfWebDeployHelper.NamespacePrefixes + ClearTextPasswordTest);
            if (results is SparqlResultSet)
            {
                foreach (SparqlResult r in (SparqlResultSet)results)
                {
                    Console.Error.WriteLine("rdfWebDeploy: Warning: The Node '" + r["s"].ToString() + "' has a value for the dnr:password property specified as a Literal in clear text.  It is recommended that you specify any passwords as AppSetting URIs e.g. <appsetting:MyPassword> and then create an AppSetting in the <appSettings> section of your Web.config file to store your password.  The Web.config file can then have the <appSettings> section encrypted to help protect your password");
                    warnings++;
                }
            }
            Console.WriteLine();

            #endregion

            //Show Test Results
            Console.WriteLine("rdfWedDeploy: Tests Completed - " + warnings + " Warning(s) - " + errors + " Error(s)");
        }
        public void SparqlOrderByComplexLazy()
        {
            String query = "SELECT * WHERE { ?s ?p ?o . } ORDER BY ?s DESC(?p) LIMIT 5";

            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);

            Console.WriteLine(q.ToAlgebra().ToString());
            Assert.IsTrue(q.ToAlgebra().ToString().Contains("LazyBgp"), "Should have been optimised to use a Lazy BGP");
            Console.WriteLine();

            Object results = q.Evaluate(store);
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count == 5, "Expected exactly 5 results");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
        }
        public void SparqlOrderByComplexLazyPerformance()
        {
            String query = "SELECT * WHERE { ?s ?p ?o . } ORDER BY ?s DESC(?p) LIMIT 5";

            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "dataset_50.ttl");
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();

            //First do with Optimisation
            Stopwatch timer = new Stopwatch();
            SparqlQuery q = parser.ParseFromString(query);

            Console.WriteLine(q.ToAlgebra().ToString());
            Assert.IsTrue(q.ToAlgebra().ToString().Contains("LazyBgp"), "Should have been optimised to use a Lazy BGP");
            Console.WriteLine();

            timer.Start();
            Object results = q.Evaluate(store);
            timer.Stop();
            Console.WriteLine("Took " + timer.Elapsed + " to execute when Optimised");
            timer.Reset();
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count == 5, "Expected exactly 5 results");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }

            //Then do without optimisation
            Options.AlgebraOptimisation = false;
            timer.Start();
            results = q.Evaluate(store);
            timer.Stop();
            Console.WriteLine("Took " + timer.Elapsed + " to execute when Unoptimised");
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count == 5, "Expected exactly 5 results");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
            Options.AlgebraOptimisation = true;
        }
        public void SparqlBindToExistingVariableLazy()
        {
            String query = "PREFIX fn: <" + XPathFunctionFactory.XPathFunctionsNamespace + "> SELECT * WHERE { ?s ?p ?o . BIND(?s AS ?p) } LIMIT 1";

            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();
            try
            {
                SparqlQuery q = parser.ParseFromString(query);

                Console.WriteLine(q.ToAlgebra().ToString());
                Assert.IsTrue(q.ToAlgebra().ToString().Contains("LazyBgp"), "Should have been optimised to use a Lazy BGP");
                Console.WriteLine();

                store.ExecuteQuery(q);
                Assert.Fail("Expected a RdfParseException/RdfQueryException to be thrown");
            }
            catch (RdfParseException parseEx)
            {
                Console.WriteLine("Parsing Error thrown as expected");
                TestTools.ReportError("Parser Error", parseEx, false);
            }
            catch (RdfQueryException queryEx)
            {
                Console.WriteLine("Query Error thrown as expected");
                TestTools.ReportError("Query Error", queryEx, false);
            }
            catch (Exception ex)
            {
                TestTools.ReportError("Unexpected Error", ex, false);
                Assert.Fail("Did not get a RdfParseException/RdfQueryException as expected");
            }
        }
        private IEnumerable<EntityQuad> GetQuads(string fileName, bool useNQuads = true)
        {
            var store = new TripleStore();
            if (useNQuads)
            {
                new NQuadsParser().Load(store, fileName);
            }
            else
            {
                IGraph graph = new Graph();
                new Notation3Parser().Load(graph, fileName);
                store.Add(graph);
            }

            IDictionary<string, string> bnodes = CreateGraphMap(store, fileName, useNQuads);

            return from triple in store.Triples
                   let graphNode = (triple.Graph == null) || (triple.Graph.BaseUri == null) ? null :
                                   (Regex.IsMatch(triple.Graph.BaseUri.AbsoluteUri, "[a-zA-Z0-9_]+://") ? Node.ForUri(triple.Graph.BaseUri) : Node.ForBlank(bnodes[triple.Graph.BaseUri.AbsoluteUri], null, null))
                   let entityId = (triple.Subject is IUriNode ? new EntityId(((IUriNode)triple.Subject).Uri) : new BlankId(((IBlankNode)triple.Subject).InternalID))
                   select
                       new EntityQuad(
                       entityId,
                       WrapNode(triple.Subject),
                       WrapNode(triple.Predicate),
                       WrapNode(triple.Object),
                       graphNode);
        }