public void Execute() { //First define a SPARQL Endpoint for DBPedia SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql")); //Next define our query //We're going to ask DBPedia to describe the first thing it finds which is a Person String query = "DESCRIBE ?person WHERE {?person a <http://dbpedia.org/ontology/Person>} LIMIT 1"; //Get the result var graph = endpoint.QueryWithResultGraph(query); if (!graph.IsEmpty) { foreach (Triple t in graph.Triples) { Console.WriteLine(t.ToString()); Console.WriteLine("\n\n"); } } }
/// <summary> /// Processes a SPARQL Query against the Knowledge Base passing the results to the RDF or Results handler as appropriate /// </summary> /// <param name="rdfHandler">RDF Handler</param> /// <param name="resultsHandler">Results Handler</param> /// <param name="sparqlQuery">SPARQL Query</param> /// <param name="callback">Callback to invoke once handling of results has completed</param> /// <param name="state">State to pass to the callback</param> public void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String sparqlQuery, QueryCallback callback, Object state) { SparqlQueryParser parser = new SparqlQueryParser(); SparqlQuery q = parser.ParseFromString(sparqlQuery); SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(UriFactory.Create(this._sparqlUri)); switch (q.QueryType) { case SparqlQueryType.Ask: case SparqlQueryType.Select: case SparqlQueryType.SelectAll: case SparqlQueryType.SelectAllDistinct: case SparqlQueryType.SelectAllReduced: case SparqlQueryType.SelectDistinct: case SparqlQueryType.SelectReduced: endpoint.QueryWithResultSet(sparqlQuery, (rs, _) => { resultsHandler.Apply(rs); callback(rdfHandler, resultsHandler, state); }, state); break; case SparqlQueryType.Construct: case SparqlQueryType.Describe: case SparqlQueryType.DescribeAll: endpoint.QueryWithResultGraph(sparqlQuery, (g, _) => { rdfHandler.Apply(g); callback(rdfHandler, resultsHandler, state); }, state); break; default: throw new RdfQueryException("Cannot execute unknown query types against Pellet Server"); } }
public IGraph QueryTripleStoreGraphResult(SparqlParameterizedString queryString) { queryString.AddAllColidNamespaces(); return(_queryEndpoint.QueryWithResultGraph(queryString.ToString())); }
public Response Pull(string scope, string app, string graph, Request request) { Response response = new Response(); response.Level = StatusLevel.Success; Status status = new Status(); status.Messages = new Messages(); try { status.Identifier = String.Format("{0}.{1}", scope, app); InitializeScope(scope, app); if (_settings["ReadOnlyDataLayer"] != null && _settings["ReadOnlyDataLayer"].ToString().ToLower() == "true") { string message = "Can not perform post on read-only data layer of [" + scope + "." + app + "]."; _logger.Error(message); status.Level = StatusLevel.Error; status.Messages.Add(message); } else { InitializeDataLayer(); DateTime startTime = DateTime.Now; #region move this portion to dotNetRdfEngine? if (!request.ContainsKey("targetEndpointUri")) { throw new Exception("Target Endpoint Uri is required"); } string targetEndpointUri = request["targetEndpointUri"]; if (!request.ContainsKey("targetGraphBaseUri")) { throw new Exception("Target graph uri is required"); } string targetGraphBaseUri = request["targetGraphBaseUri"]; _settings["TargetGraphBaseUri"] = targetGraphBaseUri; if (targetGraphBaseUri.ToLower() == "[default graph]") { targetGraphBaseUri = String.Empty; } SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri(targetEndpointUri), targetGraphBaseUri); if (request.ContainsKey("targetCredentials")) { string targetCredentialsXML = request["targetCredentials"]; WebCredentials targetCredentials = Utility.Deserialize <WebCredentials>(targetCredentialsXML, true); if (targetCredentials.isEncrypted) { targetCredentials.Decrypt(); } endpoint.SetCredentials(targetCredentials.GetNetworkCredential().UserName, targetCredentials.GetNetworkCredential().Password, targetCredentials.GetNetworkCredential().Domain); } string proxyHost = _settings["ProxyHost"]; string proxyPort = _settings["ProxyPort"]; string proxyCredsToken = _settings["ProxyCredentialToken"]; if (!String.IsNullOrEmpty(proxyHost) && !String.IsNullOrEmpty(proxyPort) && !String.IsNullOrEmpty(proxyCredsToken)) { WebProxyCredentials proxyCreds = _settings.GetWebProxyCredentials(); endpoint.Proxy = proxyCreds.GetWebProxy() as WebProxy; endpoint.ProxyCredentials = proxyCreds.GetNetworkCredential(); } VDS.RDF.IGraph resultGraph = endpoint.QueryWithResultGraph("CONSTRUCT {?s ?p ?o} WHERE {?s ?p ?o}"); #endregion if (resultGraph != null && resultGraph.Triples.Count > 0) { // call RdfProjectionEngine to fill data objects from a given graph _projectionEngine = _kernel.Get <IProjectionLayer>("rdf"); System.Text.StringBuilder sb = new System.Text.StringBuilder(); TextWriter textWriter = new StringWriter(sb); VDS.RDF.Writing.RdfXmlWriter rdfWriter = new VDS.RDF.Writing.RdfXmlWriter(); rdfWriter.Save(resultGraph, textWriter); XDocument xDocument = XDocument.Parse(sb.ToString()); if (xDocument != null && xDocument.Root != null) { _logger.Debug(xDocument.Root.ToString()); _dataObjects = _projectionEngine.ToDataObjects(graph, ref xDocument); if (_dataObjects != null && _dataObjects.Count > 0) { status.Messages.Add("Query target endpoint completed successfully."); status.Messages.Add(String.Format("Number of data objects created [{0}].", _dataObjects.Count)); // post data objects to data layer response.Append(_dataLayer.Post(_dataObjects)); DateTime endTime = DateTime.Now; TimeSpan duration = endTime.Subtract(startTime); status.Messages.Add(String.Format("Execution time [{0}:{1}.{2}] minutes.", duration.Minutes, duration.Seconds, duration.Milliseconds)); } else { status.Messages.Add(string.Format("No data objects being created.")); } } else { throw new Exception("Facade document is empty."); } } else { throw new Exception("Facade graph is empty."); } } } catch (Exception ex) { _logger.Error("Error in Pull(): ", ex); status.Level = StatusLevel.Error; status.Messages.Add(string.Format("Error pulling graph: {0}", ex)); } response.Append(status); return(response); }
public Response Pull(string projectName, string applicationName, string graphName, Request request) { Status status = new Status(); status.Messages = new Messages(); try { status.Identifier = String.Format("{0}.{1}", projectName, applicationName); InitializeScope(projectName, applicationName); InitializeDataLayer(); DateTime startTime = DateTime.Now; if (!request.ContainsKey("targetEndpointUri")) { throw new Exception("Target Endpoint Uri is required"); } string targetEndpointUri = request["targetEndpointUri"]; if (!request.ContainsKey("targetGraphBaseUri")) { throw new Exception("Target graph uri is required"); } string targetGraphBaseUri = request["targetGraphBaseUri"]; _settings["TargetGraphBaseUri"] = targetGraphBaseUri; SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri(targetEndpointUri), targetGraphBaseUri); if (request.ContainsKey("targetCredentials")) { string targetCredentialsXML = request["targetCredentials"]; WebCredentials targetCredentials = Utility.Deserialize <WebCredentials>(targetCredentialsXML, true); if (targetCredentials.isEncrypted) { targetCredentials.Decrypt(); } endpoint.SetCredentials( targetCredentials.GetNetworkCredential().UserName, targetCredentials.GetNetworkCredential().Password, targetCredentials.GetNetworkCredential().Domain); } string proxyHost = _settings["ProxyHost"]; string proxyPort = _settings["ProxyPort"]; if (!String.IsNullOrEmpty(proxyHost) && !String.IsNullOrEmpty(proxyPort)) { WebProxy webProxy = new WebProxy(proxyHost, Int32.Parse(proxyPort)); WebProxyCredentials proxyCrendentials = _settings.GetWebProxyCredentials(); if (proxyCrendentials != null) { webProxy.Credentials = _settings.GetProxyCredential(); } endpoint.SetProxyCredentials(proxyCrendentials.userName, proxyCrendentials.password, proxyCrendentials.domain); endpoint.SetProxy(webProxy.Address); } String query = "CONSTRUCT {?s ?p ?o} WHERE {?s ?p ?o}"; VDS.RDF.IGraph graph = endpoint.QueryWithResultGraph(query); System.Text.StringBuilder sb = new System.Text.StringBuilder(); TextWriter textWriter = new StringWriter(sb); VDS.RDF.Writing.RdfXmlWriter rdfWriter = new VDS.RDF.Writing.RdfXmlWriter(); rdfWriter.Save(graph, textWriter); XDocument xDocument = XDocument.Parse(sb.ToString()); // call RdfProjectionEngine to fill data objects from a given graph _projectionEngine = _kernel.Get <IProjectionLayer>("rdf"); _dataObjects = _projectionEngine.ToDataObjects(graphName, ref xDocument); // post data objects to data layer _dataLayer.Post(_dataObjects); DateTime endTime = DateTime.Now; TimeSpan duration = endTime.Subtract(startTime); status.Messages.Add(string.Format("Graph [{0}] has been posted to legacy system successfully.", graphName)); status.Messages.Add(String.Format("Execution time [{0}:{1}.{2}] minutes.", duration.Minutes, duration.Seconds, duration.Milliseconds)); } catch (Exception ex) { _logger.Error("Error in Pull(): ", ex); status.Level = StatusLevel.Error; status.Messages.Add(string.Format("Error pulling graph: {0}", ex)); } _response.Append(status); return(_response); }
static void Main(string[] args) { // tipos de graph e hello world //IGraph g = new Graph(); //IUriNode dotnetRDF = g.CreateUriNode(UriFactory.Create("http://www.dotnetrdf.org")); //IUriNode says = g.CreateUriNode(UriFactory.Create("http://example.org/says")); //ILiteralNode helloWorld = g.CreateLiteralNode("Hello World"); //ILiteralNode bonjourMonde = g.CreateLiteralNode("Bonjour tout le Monde", "fr"); //g.Assert(new Triple(dotnetRDF, says, helloWorld)); //g.Assert(new Triple(dotnetRDF, says, bonjourMonde)); // somente para debug //foreach (Triple t in graph.Triples) //{ // Console.WriteLine(t); //} // formato NT válido //NTriplesWriter nTWriter = new NTriplesWriter(); //nTWriter.Save(g, "HelloWorld.nt"); // definição XML //RdfXmlWriter rdfXmlWriter = new RdfXmlWriter(); //rdfXmlWriter.Save(g, "HelloWorld.rdf"); // não funcionou //IGraph g = new Graph(); //var a = new TripleStore(); //UriLoader.Load(graph2, new Uri("http://dbpedia.org/resource/Barack_Obama")); //UriLoader.Load(graph2, new Uri("http://dbpedia.org/page/Barack_Obama")); //UriLoader.Load(a, new Uri("http://dbpedia.org/page/Battle_of_Waterloo")); // funcionou //NTriplesParser nTriplesParser = new NTriplesParser(); //nTriplesParser.Load(graph2, "Barack_Obama.ntriples"); // working with graph //Graph g = new Graph(); //g.BaseUri = new Uri("http://example.org/base"); //var isEmpty = g.IsEmpty; //var triples = g.Triples; //First define a SPARQL Endpoint for DBPedia SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql")); //Next define our query //We're going to ask DBPedia to describe the first thing it finds which is a Person String query = "DESCRIBE ?person WHERE {?person a <http://dbpedia.org/ontology/Person>} LIMIT 1"; //Get the result var g = endpoint.QueryWithResultGraph(query); TripleStore store = new TripleStore(); Graph graph = new Graph(); var nTriplesParser = new NTriplesParser(); UriLoader.Load(graph, new Uri("http://dbpedia.org/resource/List_of_ongoing_armed_conflicts"), nTriplesParser); store.Add(graph); // store.Triples as the conflicts itself? Console.ReadKey(); }
public void WorkingWithGraphs() { // 1. Insert Triples ------------------------------------------------------------ Graph g = new Graph(); IUriNode dotNetRDF = g.CreateUriNode(UriFactory.Create("http://www.dotnetrdf.org")); IUriNode says = g.CreateUriNode(UriFactory.Create("http://example.org/says")); IUriNode label = g.CreateUriNode(UriFactory.Create("http://example.org/label")); ILiteralNode dotNetRdfName = g.CreateLiteralNode("dotNetRdf"); ILiteralNode helloWorld = g.CreateLiteralNode("Hello World"); ILiteralNode bonjourMonde = g.CreateLiteralNode("Bonjour tout le Monde", "fr"); g.Assert(new Triple(dotNetRDF, says, helloWorld)); g.Assert(new Triple(dotNetRDF, says, bonjourMonde)); g.Assert(new Triple(dotNetRDF, label, dotNetRdfName)); Assert.AreEqual(3, g.Triples.Count); // asserting an existing triple will not add a new one g.Assert(new Triple(dotNetRDF, says, bonjourMonde)); Assert.AreEqual(3, g.Triples.Count); // We can also create a triple by just passing in the subject, predicate and object g.Assert(dotNetRDF, says, g.CreateLiteralNode("Welcome")); Assert.AreEqual(4, g.Triples.Count); // ------------------------------------------------------------------------------ // 2. Remove Triples ------------------------------------------------------------ // Triple removal is done BY VALUE. g.Retract(dotNetRDF, says, g.CreateLiteralNode("Welcome")); Assert.AreEqual(3, g.Triples.Count); // There is no notion of updating a triple, they can be removed and added. That's it. // e.g. we can't update a Node's value. // says.Uri = new Uri(""); // no setter for Uri // ------------------------------------------------------------------------------ // 3. Lookup Triples ------------------------------------------------------------ // We quite often need to find a set of triples to display, delete, process. // get all triples with a given predicate var matches = g.GetTriplesWithPredicate(says); Assert.AreEqual(2, matches.Count()); // get all the triples whose subject matches a given INode matches = g.GetTriplesWithSubject(dotNetRDF); Assert.AreEqual(3, matches.Count()); // get all the triples whose subject and predicate matches the given INodes matches = g.GetTriplesWithSubjectPredicate(dotNetRDF, says); Assert.AreEqual(2, matches.Count()); // Note: Nodes have no identity beyond their value. var n = g.CreateLiteralNode("Hello World"); Assert.AreNotSame(n, helloWorld); matches = g.GetTriplesWithObject(n); Assert.AreEqual(1, matches.Count()); // ------------------------------------------------------------------------------ // 4. Loading Data -------------------------------------------------------------- // RDF data comes in many different syntaxes. Data can be loaded into graphs by using // the appropriate parser. Many different syntaxes are supported. g = new Graph(); NTriplesParser parser = new NTriplesParser(); parser.Load(g, new StringReader("<http://example.org/a> <http://example.org/b> <http://example.org/c>.")); Assert.AreEqual(1, g.Triples.Count); // ------------------------------------------------------------------------------ // 5. Loading Data from SPARQL -------------------------------------------------- // RDF data can also be loaded into a graph from the result of a SPARQL query that returns RDF XML. // DESCRIBE or CONSTRUCT return RDF. SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql")); // Ask DBPedia to describe the first thing it finds which is a Person var query = "DESCRIBE ?person WHERE {?person a <http://dbpedia.org/ontology/Person>} LIMIT 1"; //Get the result var dbpGraph = endpoint.QueryWithResultGraph(query); Assert.IsTrue(dbpGraph.Triples.Count > 0); // ------------------------------------------------------------------------------ // 6. Writing Data -------------------------------------------------------------- // Again there are writers for different syntaxes. The data can be written to files, // streams, strings as needed. RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(dbpGraph, Console.Out); // view test result details for output. // ------------------------------------------------------------------------------ }