public static IEnumerable <Triple> GetContextualGraph(this SparqlRemoteEndpoint endpoint, UriNode uriNode, HashSet <UriNode> processed, int rank) { if (rank == 0) { return(new List <Triple>()); } rank--; var triples = endpoint.GetTriples(uriNode).ToList(); var triplesToAdd = new List <Triple>(); foreach (var triple in triples) { var subject = triple.Subject.NodeType == NodeType.Uri ? (UriNode)triple.Subject : null; if (!processed.Contains(subject)) { processed.Add(subject); triplesToAdd.AddRange(GetContextualGraph(endpoint, subject, processed, rank)); } var obj = triple.Object.NodeType == NodeType.Uri ? (UriNode)triple.Object : null; if (obj != null && !processed.Contains(obj)) { processed.Add(obj); triplesToAdd.AddRange(GetContextualGraph(endpoint, obj, processed, rank)); } } triples.AddRange(triplesToAdd); return(triples.Distinct()); }
/// <summary> /// Makes a SPARQL Query against the Knowledge Base /// </summary> /// <param name="sparqlQuery">SPARQL Query</param> /// <returns></returns> public Object Query(String sparqlQuery) { SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri(this._sparqlUri)); using (HttpWebResponse response = endpoint.QueryRaw(sparqlQuery)) { try { ISparqlResultsReader sparqlParser = MimeTypesHelper.GetSparqlParser(response.ContentType); SparqlResultSet results = new SparqlResultSet(); sparqlParser.Load(results, new StreamReader(response.GetResponseStream())); response.Close(); return results; } catch (RdfParserSelectionException) { IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType); Graph g = new Graph(); parser.Load(g, new StreamReader(response.GetResponseStream())); response.Close(); return g; } } }
/// <summary> /// Creates a new 4store connector which manages access to the services provided by a 4store server. /// </summary> /// <param name="baseUri">Base Uri of the 4store.</param> /// <remarks> /// <strong>Note:</strong> As of the 0.4.0 release 4store support defaults to Triple Level updates enabled as all recent 4store releases have supported this. You can still optionally disable this with the two argument version of the constructor. /// </remarks> public FourStoreConnector(String baseUri) { // Determine the appropriate actual Base Uri if (baseUri.EndsWith("sparql/")) { _baseUri = baseUri.Substring(0, baseUri.IndexOf("sparql/")); } else if (baseUri.EndsWith("data/")) { _baseUri = baseUri.Substring(0, baseUri.IndexOf("data/")); } else if (!baseUri.EndsWith("/")) { _baseUri = baseUri + "/"; } else { _baseUri = baseUri; } _endpoint = new SparqlRemoteEndpoint(UriFactory.Create(_baseUri + "sparql/")); _updateEndpoint = new SparqlRemoteUpdateEndpoint(UriFactory.Create(_baseUri + "update/")); _endpoint.Timeout = 60000; _updateEndpoint.Timeout = 60000; }
/// <summary> /// Search by disease name - Disease /// </summary> /// <param name="diseaseName"></param> public IActionResult GetDiseaseByDiseaseName(string diseaseName) { Dictionary <string, string> resultsObject = new Dictionary <string, string>(); SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("https://query.wikidata.org/sparql"), "https://query.wikidata.org"); SparqlResultSet results = endpoint.QueryWithResultSet(@" PREFIX wd: <http://www.wikidata.org/entity/> PREFIX wdt: <http://www.wikidata.org/prop/direct/> SELECT ?ID ?disease WHERE { ?ID wdt:P699 ?doid . ?ID rdfs:label ?disease filter (lang(?disease) = 'en'). filter regex(str(?disease), '" + diseaseName + "' )}" + " limit 50"); foreach (SparqlResult result in results) { string id = result["ID"].ToString(); id = id.Remove(0, 31); string name = result["disease"].ToString(); name = name.Remove(name.Length - 3); resultsObject.Add(id, name); // richTextBox1.Text += wikidata_id + "\n"; } // TODO: implement Get - route: search/countries/{countryName} return(new ObjectResult(resultsObject)); // TODO: implement GetDiseaseByDiseaseName - route: search/disease/{diseaseName} }
private void btnOpenQueryResults_Click(object sender, RoutedEventArgs e) { try { Uri u = new Uri(this.txtEndpoint.Text); String defGraph = this.txtDefaultGraph.Text; SparqlRemoteEndpoint endpoint; if (defGraph.Equals(String.Empty)) { endpoint = new SparqlRemoteEndpoint(u); } else { endpoint = new SparqlRemoteEndpoint(u, defGraph); } String data; using (HttpWebResponse response = endpoint.QueryRaw(this._editor.DocumentManager.ActiveDocument.Text)) { data = new StreamReader(response.GetResponseStream()).ReadToEnd(); try { this._parser = MimeTypesHelper.GetSparqlParser(response.ContentType); } catch (RdfParserSelectionException) { //Ignore here we'll try other means of getting a parser after this } response.Close(); } this._data = data; if (this._parser == null) { try { this._parser = StringParser.GetResultSetParser(this._data); } catch (RdfParserSelectionException) { this._parser = null; } } this.DialogResult = true; this.Close(); } catch (UriFormatException) { MessageBox.Show("You have failed to enter a valid Endpoint URI", "Invalid URI"); } catch (WebException webEx) { MessageBox.Show("A HTTP error occurred making the Query: " + webEx.Message, "Open Query Results Failed"); } catch (Exception ex) { MessageBox.Show("An error occurred while making the Query: " + ex.Message, "Open Query Results Failed"); } }
public static IGraph GetContextualGraphV2(this SparqlRemoteEndpoint endpoint, string uri, HashSet <string> processed, int rank) { if (rank <= 0) { return(new Graph()); } rank--; var graph = endpoint.GetContextualGraph(uri); processed.Add(uri); var graphToMerge = new List <IGraph>(); foreach (var uriString in graph.Triples.GetAllUriNodeToString()) { if (processed.Contains(uriString)) { continue; } var tmpGraph = endpoint.GetContextualGraphV2(uriString, processed, rank); if (!tmpGraph.IsEmpty) { graphToMerge.Add(tmpGraph); } } foreach (var g in graphToMerge) { graph.Merge(g); } return(graph); }
public void rdfRemoteEndpointToKB(string endpointURI, string graphKBName, string query, string assertTemplate) { //Define a remote endpoint //Use the DBPedia SPARQL endpoint with the default Graph set to DBPedia SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri(endpointURI)); var focus = FindOrCreateKB(graphKBName); RdfRules ruleDefs = new RdfRules(focus.RdfStore.rdfGraph); StringWriter miniMt = new StringWriter(); //Use the extension method ExecuteQuery() to make the query against the Graph try { //Object results = g.ExecuteQuery(query); //Make a SELECT query against the Endpoint SparqlResultSet results = endpoint.QueryWithResultSet(query); GetMiniMt(results, assertTemplate, graphKBName, focus.RdfStore, show, null, miniMt, ruleDefs); } catch (RdfQueryException queryEx) { //There was an error executing the query so handle it here Warn("While endpointURI={0}\n\n{1}", endpointURI, queryEx); } insertKB(miniMt.ToString(), graphKBName); }
public AotSparqlExecutor(string dataSetUri, INamespaceMapper namespaceMapper, Func <Uri, string> uriSerializer, ILogger logger) { if (dataSetUri == null) { throw new ArgumentNullException(nameof(dataSetUri)); } this.namespaceMapper = namespaceMapper ?? throw new ArgumentNullException(nameof(namespaceMapper)); this.uriSerializer = uriSerializer ?? throw new ArgumentNullException(nameof(uriSerializer)); var uri = new Uri(new Uri(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar, UriKind.Absolute), dataSetUri); if (uri.IsFile) { underlyingGraph = new Graph(); underlyingGraph.LoadFromFile(uri.LocalPath); logger.Information("Loaded {Count} triples.", underlyingGraph.Triples.Count); var dataset = new InMemoryDataset(underlyingGraph); queryProcessor = new LeviathanQueryProcessor(dataset); } else { var endpoint = new SparqlRemoteEndpoint(uri); queryProcessor = new RemoteQueryProcessor(endpoint); logger.Information("Using SPARQL endpoint from {Host}.", uri.Host); } queryParser = new SparqlQueryParser(); this.logger = logger; }
private static IDataObjectContext MakeSparqlDataObjectContext(ConnectionString connectionString) { var queryEndpoint = new SparqlRemoteEndpoint(new Uri(connectionString.DnrQuery)); if (!String.IsNullOrEmpty(connectionString.UserName) && !String.IsNullOrEmpty(connectionString.Password)) { queryEndpoint.SetCredentials(connectionString.UserName, connectionString.Password); } var queryProcessor = new RemoteQueryProcessor(queryEndpoint); ISparqlUpdateProcessor updateProcessor = null; if (!String.IsNullOrEmpty(connectionString.DnrUpdate)) { #if PORTABLE || SILVERLIGHT throw new NotSupportedException("The PCL and mobile builds of BrightstarDB do not currently support stores that use SPARQL Update. The store may be opened as a read-only store by removing the update= parameter in the connection string."); #else var updateEndpoint = new SparqlRemoteUpdateEndpoint(new Uri(connectionString.DnrUpdate)); if (!String.IsNullOrEmpty(connectionString.UserName) && !String.IsNullOrEmpty(connectionString.Password)) { updateEndpoint.SetCredentials(connectionString.UserName, connectionString.Password); } updateProcessor = new RemoteUpdateProcessor(updateEndpoint); #endif } return(new SparqlDataObjectContext(queryProcessor, updateProcessor, connectionString.OptimisticLocking)); }
protected void Button12_Click(object sender, EventArgs e) { //Kalamoon Label1.Text = "University of Kalamoon English Information"; Label1.Visible = true; SparqlRemoteEndpoint endpoint1 = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"), "http://dbpedia.org"); SparqlResultSet results1 = endpoint1.QueryWithResultSet(@"PREFIX dbo: <http://dbpedia.org/ontology/> PREFIX dbp: <http://dbpedia.org/property/> PREFIX dbr: <http://dbpedia.org/resource/> PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT DISTINCT ?name ?info WHERE { <http://dbpedia.org/resource/University_of_Kalamoon> rdfs:comment ?info.filter langMatches(lang(?info),'en'). <http://dbpedia.org/resource/University_of_Kalamoon> rdfs:label ?name.filter langMatches(lang(?name),'en'). }"); DataTable DT1 = new DataTable(); if (results1 is SparqlResultSet) { SparqlResultSet rset1 = (SparqlResultSet)results1; DT1 = FillDataTable(rset1); } GridView1.DataSource = DT1; GridView1.DataBind(); GridView1.Visible = true; Label2.Visible = false; GridView2.Visible = false; }
protected void Button1_Click(object sender, EventArgs e) { Label1.Visible = false; Label2.Visible = false; GridView2.Visible = false; //Define a remote endpoint //Use the DBPedia SPARQL endpoint with the default Graph set to DBPedia SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"), "http://dbpedia.org"); string q = @"PREFIX dct: <http://purl.org/dc/terms/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX ont: <http://dbpedia.org/ontology/> SELECT DISTINCT ?AllSyrianUniversities WHERE { ?AllSyrianUniversities dct:subject <http://dbpedia.org/resource/Category:Universities_in_Syria>. }"; //Make a SELECT query against the Endpoint SparqlResultSet results = endpoint.QueryWithResultSet(q); DataTable DT1 = new DataTable(); SparqlResultSet rset = (SparqlResultSet)results; DT1 = FillDataTable(rset); GridView1.DataSource = DT1; GridView1.DataBind(); GridView1.Visible = true; }
protected void Button13_Click(object sender, EventArgs e) { //Alandalus Label1.Text = "Al-Andalus University for Medical Sciences Information"; Label1.Visible = true; SparqlRemoteEndpoint endpoint1 = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"), "http://dbpedia.org"); SparqlResultSet results1 = endpoint1.QueryWithResultSet(@"PREFIX dbo: <http://dbpedia.org/ontology/> PREFIX dbp: <http://dbpedia.org/property/> PREFIX dbr: <http://dbpedia.org/resource/> PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT DISTINCT ?name ?info (str(?Pr)as ?president ) ?homepage WHERE { <http://dbpedia.org/resource/Al-Andalus_University_for_Medical_Sciences> rdfs:comment ?info.filter langMatches(lang(?info),'en'). <http://dbpedia.org/resource/Al-Andalus_University_for_Medical_Sciences> rdfs:label ?name.filter langMatches(lang(?name),'en'). <http://dbpedia.org/resource/Al-Andalus_University_for_Medical_Sciences> dbp:president ?Pr . <http://dbpedia.org/resource/Al-Andalus_University_for_Medical_Sciences> foaf:homepage ?homepage . }"); DataTable DT1 = new DataTable(); if (results1 is SparqlResultSet) { SparqlResultSet rset1 = (SparqlResultSet)results1; DT1 = FillDataTable(rset1); } GridView1.DataSource = DT1; GridView1.DataBind(); GridView1.Visible = true; Label2.Visible = false; GridView2.Visible = false; }
protected static object ExecuteList(SparqlParameterizedString query, string endpointUri = null) { // TODO: This should move to controller action var queryString = query.ToString(); SparqlRemoteEndpoint endpoint = null; if (string.IsNullOrWhiteSpace(endpointUri)) { endpoint = new GraphDBSparqlEndpoint(); } else { endpoint = new SparqlRemoteEndpoint(new Uri(endpointUri)); } using (var connector = new SparqlConnector(endpoint)) { var results = connector.Query(queryString); if (results is IGraph) { AddNamespaces(results as IGraph); } return(results); } }
/// <summary> /// Makes a SPARQL Query against the Knowledge Base /// </summary> /// <param name="sparqlQuery">SPARQL Query</param> /// <returns></returns> public Object Query(String sparqlQuery) { SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(UriFactory.Create(this._sparqlUri)); using (HttpWebResponse response = endpoint.QueryRaw(sparqlQuery)) { try { IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType); Graph g = new Graph(); parser.Load(g, new StreamReader(response.GetResponseStream())); response.Close(); return(g); } catch (RdfParserSelectionException) { ISparqlResultsReader sparqlParser = MimeTypesHelper.GetSparqlParser(response.ContentType); SparqlResultSet results = new SparqlResultSet(); sparqlParser.Load(results, new StreamReader(response.GetResponseStream())); response.Close(); return(results); } } }
public void doIt() { _logger.LogInformation("quering dbpedia"); var prefix = string.Join("\n", Prefixes); var query = prefix + "\nSELECT ?comment WHERE {\n" + "?body a ont:CelestialBody .\n" + "?body foaf:name \"Vega\"@en .\n" + "?body rdfs:comment ?comment .\n" + "FILTER ( lang(?comment) = \"en\")\n" + "}"; //Define a remote endpoint //Use the DBPedia SPARQL endpoint with the default Graph set to DBPedia var endpoint = new SparqlRemoteEndpoint(new Uri(DbPediaEndpoint), DbPediaGraphUri); //Make a SELECT query against the Endpoint //var results = endpoint.QueryWithResultSet("SELECT DISTINCT ?Concept WHERE {[] a ?Concept}"); var results = endpoint.QueryWithResultSet(query); foreach (var result in results) { var comment = result["comment"]; _logger.LogInformation("queried result {@comment}", comment); } }
public TripleStoreRepository(IOptionsMonitor <ColidTripleStoreOptions> options) { var updateEndpoint = new SparqlRemoteUpdateEndpoint(options.CurrentValue.UpdateUrl); updateEndpoint.SetCredentials(options.CurrentValue.Username, options.CurrentValue.Password); _queryEndpoint = new SparqlRemoteEndpoint(options.CurrentValue.ReadUrl);; _updateEndpoint = updateEndpoint; }
public VisDataSet Query(Uri endpointUri, string sparqlQuery) { var endpoint = new SparqlRemoteEndpoint(endpointUri); var result = endpoint.QueryWithResultGraph(sparqlQuery); return(Convert(result)); }
public PredicateResultWrapper(INode node, SparqlRemoteEndpoint endpoint) : base(node, endpoint) { if (node.NodeType != NodeType.Uri) { /*TODO: remove this exception*/ throw new Exception("This predicate is not IRI!"); } }
protected void FindData() { Resetdatalist(); var list = (List <string[]>)Session["datalist"]; //Define a remote endpoint //Use the DBPedia SPARQL endpoint with the default Graph set to DBPedia SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint( new Uri("http://sparql.data.southampton.ac.uk/"), "http://data.southampton.ac.uk/"); var name = namepicker.Value; var surname = surnamepicker.Value; var title = titlepicker.Value; var email = emailpicker.Value; var number = numberpicker.Value; var faculty = facultypicker.Value; //UNIT SEARCH TEST /* name ="Nigel Richard"; * surname = "Shadbolt"; * title = "Prof"; * email = "*****@*****.**"; * number = "+442380597682"; * faculty = "Electronics & computer Science";*/ //END UNIT SEARCH TEST number = number.Replace("+", ""); SparqlResultSet results = endpoint.QueryWithResultSet("PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX soton: <http://id.southampton.ac.uk/ns/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT ?title ?name ?surname ?mbox ?phone ?person ?education WHERE { GRAPH <http://id.southampton.ac.uk/dataset/phonebook/latest> { ?person a foaf:Person ; foaf:familyName ?surname ; foaf:givenName ?name ; foaf:mbox ?mbox ; foaf:phone ?phone ; foaf:title ?title . } OPTIONAL{ ?division foaf:member ?person ; rdfs:label ?education . FILTER regex(?education, '" + faculty + "' , 'i') } FILTER regex(?name, '" + name + "' , 'i') FILTER regex(?surname, '" + surname + "', 'i') FILTER regex(?title, '" + title + "' , 'i') FILTER(regex(str(?mbox), '" + email + "')) FILTER(regex(str(?phone), '" + number + "')) . } LIMIT 10"); string[] table1; foreach (SparqlResult result in results) { string[] phonebookdata = new string[7]; table1 = result.ToString().Split(','); for (int cv01 = 0; cv01 < 7; cv01++) { phonebookdata[cv01] = table1[cv01].Split('=')[1]; if (cv01 == 4 || cv01 == 3) { phonebookdata[cv01] = phonebookdata[cv01].Split(':')[1].Remove(phonebookdata[cv01].Split(':')[1].Length - 1, 1); } else if (cv01 == 6) { phonebookdata[cv01] = phonebookdata[cv01].Remove(0, 1); } else if (cv01 == 5) { phonebookdata[cv01] = phonebookdata[cv01].Replace(" ", ""); } else { string temp = phonebookdata[cv01].Remove(phonebookdata[cv01].Length - 1, 1); phonebookdata[cv01] = temp.Remove(0, 1); } } list.Add(phonebookdata); } var list2 = (List <string[]>)Session["datalist2"]; }
public async Task <IActionResult> Show(string id) { var endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"), "http://dbpedia.org"); var query = "PREFIX dbo: <http://dbpedia.org/ontology/>\r\n" + "PREFIX dct: <http://purl.org/dc/terms/>\r\n" + "PREFIX dbc: <http://dbpedia.org/resource/Category:>\r\n" + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\r\n" + "SELECT ?food ?stripped_name ?stripped_abstract ?thumb ?ings ?cats\r\n" + "WHERE{\r\n" + "?food a dbo:Food.\r\n" + "?food rdfs:label ?name.\r\n" + "?food dbo:abstract ?abstract.\r\n" + "?food dbo:thumbnail ?thumb.\r\n" + "?food dbo:ingredient ?ings.\r\n" + "?food dct:subject ?cats.\r\n" + $"?food dbo:wikiPageID {id}\r\n" + "FILTER(LANGMATCHES(LANG(?name), 'en') && LANGMATCHES(LANG(?abstract), 'en'))\r\n" + "BIND(STR(?name) AS ?stripped_name)\r\n" + "BIND(STR(?abstract) AS ?stripped_abstract)\r\n" + "}"; var results = endpoint.QueryWithResultSet(query); if (!results.Any()) { return(NotFound()); } var evaluation = await _evaluationService.GetAll().FirstOrDefaultAsync(e => e.RecipeId == id); var isFavorited = await _favoritedRecipeService.GetAll().AnyAsync(fr => fr.RecipeId == id && fr.ApplicationUserId == User.FindFirstValue(ClaimTypes.NameIdentifier)); var recipeViewModel = new RecipeViewModel { Categories = results.Select(r => r["cats"].ToString()).Distinct().ToList(), Description = results.First()["stripped_abstract"].ToString(), Evaluation = evaluation != null ? evaluation.Value : 0, FavoritedRecipe = isFavorited, Ingredients = results.Select(r => r["ings"].ToString()).Distinct().ToList(), Name = results.First()["stripped_name"].ToString(), Picture = results.First()["thumb"].ToString(), RecipeId = id, Reviews = evaluation?.Evaluations.Select(e => new ReviewViewModel { Comment = e.Comment, CurrentUserReview = User.Identity.IsAuthenticated ? e.ApplicationUserId == User.FindFirstValue(ClaimTypes.NameIdentifier) : false, Date = e.Date, Evaluation = e.Value, UserName = e.ApplicationUser.UserName.Split('@')[0], }), UserHasReview = User.Identity.IsAuthenticated && evaluation != null? evaluation.Evaluations.Any(e => e.ApplicationUserId == User.FindFirstValue(ClaimTypes.NameIdentifier)) : false }; return(View(recipeViewModel)); }
/// <summary> /// Creates a new SPARQL Connector which uses the given SPARQL Endpoint /// </summary> /// <param name="endpoint">Endpoint</param> public SparqlConnector(SparqlRemoteEndpoint endpoint) { if (endpoint == null) { throw new ArgumentNullException("endpoint", "A valid Endpoint must be specified"); } this._endpoint = endpoint; this._timeout = endpoint.Timeout; }
/// <summary> /// Creates a new connection /// </summary> /// <param name="queryEndpoint">Query Endpoint</param> /// <param name="updateEndpoint">Update Endpoint</param> /// <param name="mode">Method for loading graphs</param> public ReadWriteSparqlConnector(SparqlRemoteEndpoint queryEndpoint, SparqlRemoteUpdateEndpoint updateEndpoint, SparqlConnectorLoadMethod mode) : base(queryEndpoint, mode) { if (updateEndpoint == null) { throw new ArgumentNullException("updateEndpoint", "Update Endpoint cannot be null, if you require a read-only SPARQL connector use the base class SparqlConnector instead"); } this._updateEndpoint = updateEndpoint; }
/// <summary> /// Opens the connection /// </summary> /// <returns></returns> protected override IStorageProvider OpenConnectionInternal() { SparqlRemoteEndpoint endpoint = String.IsNullOrEmpty(this.DefaultGraphUri) ? new SparqlRemoteEndpoint(new Uri(this.EndpointUri)) : new SparqlRemoteEndpoint(new Uri(this.EndpointUri), this.DefaultGraphUri); if (this.UseProxy) { endpoint.Proxy = this.GetProxy(); } return(new SparqlConnector(endpoint, this.LoadMode)); }
public OnBehalfOfMsGraphAuthenticationProvider(IHttpContextAccessor httpContextAccessor, IConfidentialClientApplicationProvider applicationProvider, IOptions <SparqlConfiguration> sparqlConfiguration, ILogger <OnBehalfOfMsGraphAuthenticationProvider> logger) { _httpContextAccessor = httpContextAccessor; _applicationProvider = applicationProvider; _sparqlEndpoint = new SparqlRemoteEndpoint(new Uri(sparqlConfiguration.Value.Endpoint)); _logger = logger; }
protected override int DoCount(LambdaExpression securityFilterExpression, string filterPredicate, object[] filterArguments, IObjectsDataSet context, Dictionary <string, object> parameters) { int count; var regex = new Regex("Name\\.Contains\\(\"(.*)\"\\)"); string nameFilter = null; var match = regex.Match(filterPredicate); if (match.Success) { nameFilter = match.Groups[1].Value; } SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"), "http://dbpedia.org"); //Make a SELECT query against the Endpoint string query = @"SELECT count(?place) WHERE { {?place a <http://dbpedia.org/ontology/HistoricPlace>} UNION {?place a <http://dbpedia.org/ontology/Monument>} UNION {?place a <http://dbpedia.org/ontology/Garden>} UNION {?place a <http://dbpedia.org/ontology/Cemetery>} UNION {?place a <http://dbpedia.org/ontology/ArchitecturalStructure>} UNION {?place a <http://dbpedia.org/ontology/Park>} UNION {?place a <http://dbpedia.org/ontology/NaturalPlace>} ?place rdfs:label ?name . FILTER langMatches(lang(?name), 'en') "; if (!String.IsNullOrEmpty(nameFilter)) { query += $"FILTER regex(?name,\"{nameFilter}\",\"i\")"; } query += "}"; //Make a SELECT query against the Endpoint SparqlResultSet results = endpoint.QueryWithResultSet(query); var res = results.Single(); count = Convert.ToInt32((res.Single().Value as BaseLiteralNode).Value); return(count); }
public IActionResult RequestSparql(List <Data> data) { //Define a remote endpoint //Use the DBPedia SPARQL endpoint with the default Graph set to DBPedia SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"), "http://dbpedia.org"); //Make a SELECT query against the Endpoint SparqlResultSet results = endpoint.QueryWithResultSet("SELECT * WHERE {?iri a schema:Movie . ?iri foaf:name ?name .} Limit 100"); foreach (SparqlResult result in results) { //Console.WriteLine(result.ToString()); //IEnumerator<KeyValuePair<String, INode>> result2=result.GetEnumerator(); Data _d = new Data(); foreach (KeyValuePair <string, INode> kvp in result) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); if (kvp.Key == "iri") { _d.URL = kvp.Value.ToString(); } else if (kvp.Key == "name") { string chaineModif = kvp.Value.ToString(); string toRemove = "@"; int i = chaineModif.IndexOf(toRemove); if (i >= 0) { _d.Name = chaineModif.Remove(i, chaineModif.Length - i); } } } data.Add(_d); } Console.WriteLine("------------------------------------------------------------------"); /* * //Make a DESCRIBE query against the Endpoint * IGraph g = endpoint.QueryWithResultGraph("DESCRIBE"); * foreach (Triple t in g.Triples) * { * Console.WriteLine(t.ToString()); * } */ //BingAPI("Gilet jaune"); return(View(data)); }
protected void Button6_Click(object sender, EventArgs e) { //teshreen Label1.Text = "Tishreen University English Information"; Label1.Visible = true; SparqlRemoteEndpoint endpoint1 = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"), "http://dbpedia.org"); SparqlResultSet results1 = endpoint1.QueryWithResultSet(@"PREFIX dbo: <http://dbpedia.org/ontology/> PREFIX dbp: <http://dbpedia.org/property/> PREFIX dbr: <http://dbpedia.org/resource/> PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT DISTINCT ?name ?info (str(?Pr)as ?president ) (str(?typ )as ?type) ?homepage WHERE { <http://dbpedia.org/resource/Tishreen_University> rdfs:comment ?info.filter langMatches(lang(?info),'en'). <http://dbpedia.org/resource/Tishreen_University> rdfs:label ?name.filter langMatches(lang(?name),'en'). OPTIONAL { <http://dbpedia.org/resource/Tishreen_University> dbp:president ?Pr . <http://dbpedia.org/resource/Tishreen_University> dbp:type ?typ . <http://dbpedia.org/resource/Tishreen_University> foaf:homepage ?homepage . } }"); DataTable DT1 = new DataTable(); if (results1 is SparqlResultSet) { SparqlResultSet rset1 = (SparqlResultSet)results1; DT1 = FillDataTable(rset1); } GridView1.DataSource = DT1; GridView1.DataBind(); GridView1.Visible = true; Label2.Text = "Tishreen University Arabic Information"; Label2.Visible = true; SparqlRemoteEndpoint endpoint2 = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"), "http://dbpedia.org"); SparqlResultSet results2 = endpoint2.QueryWithResultSet(@"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT DISTINCT ?Name ?Information WHERE { <http://dbpedia.org/resource/Tishreen_University> rdfs:comment ?Information.filter langMatches(lang(?Information),'ar'). <http://dbpedia.org/resource/Tishreen_University> rdfs:label ?Name.filter langMatches(lang(?Name),'ar'). }"); DataTable DT2 = new DataTable(); if (results2 is SparqlResultSet) { SparqlResultSet rset2 = (SparqlResultSet)results2; DT2 = FillDataTable(rset2); } GridView2.DataSource = DT2; GridView2.DataBind(); GridView2.Visible = true; }
/// <summary> /// Method to Query Dbpedia and return a Sparql Result set /// </summary> /// <param name="query">The SPARQL query</param> /// <returns>SparqlResutSet containing results from DBpedia</returns> public static SparqlResultSet QueryDbpedia(string query) { //Define a remote endpoint //Use the DBPedia SPARQL endpoint with the default Graph set to DBPedia SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"), "http://dbpedia.org"); //Make a SELECT query against the Endpoint SparqlResultSet results = endpoint.QueryWithResultSet(query); return(results); }
public void InsertPredicateWrapper(string subjectIri, string predicateIri, SparqlRemoteEndpoint endpoint, int expectedObjects = 0) { Config.AssertAbsoluteUri(subjectIri); Config.AssertAbsoluteUri(predicateIri); IUriNode node = new Graph().CreateUriNode(new Uri(predicateIri)); var wrapper = new PredicateResultWrapper(node, endpoint); wrapper.ExpectedObjectCount = expectedObjects; wrapper.SubjectIri = subjectIri; list.Add(wrapper); }
public static SparqlResult GetResultValue(this Uri uri, Uri property, Uri endPointUri) { var endPoint = new SparqlRemoteEndpoint(endPointUri); var querySb = new StringBuilder(); querySb.AppendLine("select ?value where {"); querySb.AppendLine($" <{uri}> <{property}> ?value ."); querySb.AppendLine("} limit 1"); var query = querySb.ToString(); return(endPoint.QueryWithResultSet(query)[0]); }
public async Task <IActionResult> Index() { if (!User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Home")); } var nameIdentifier = User.FindFirstValue(ClaimTypes.NameIdentifier); var recipesId = await _favoritedRecipeService.GetAll().Where(fr => fr.ApplicationUserId == nameIdentifier).Select(fr => fr.RecipeId).ToListAsync(); var endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"), "http://dbpedia.org"); var favoritedRecipes = new List <RecipeViewModel>(); foreach (var recipeId in recipesId) { var query = "PREFIX dbo: <http://dbpedia.org/ontology/>\r\n" + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\r\n" + "SELECT ?food ?stripped_name ?stripped_abstract ?thumb\r\n" + "WHERE{\r\n" + "?food a dbo:Food.\r\n" + "?food rdfs:label ?name.\r\n" + "?food dbo:abstract ?abstract.\r\n" + "?food dbo:thumbnail ?thumb.\r\n" + $"?food dbo:wikiPageID {recipeId}\r\n" + "FILTER(LANGMATCHES(LANG(?name), 'en') && LANGMATCHES(LANG(?abstract), 'en'))\r\n" + "BIND(STR(?name) AS ?stripped_name)\r\n" + "BIND(STR(?abstract) AS ?stripped_abstract)\r\n" + "}"; var results = endpoint.QueryWithResultSet(query); if (results.Any()) { favoritedRecipes.Add(new RecipeViewModel { Description = results.First()["stripped_abstract"].ToString(), Evaluation = 0, //recipe.Evaluation != null ? recipe.Evaluation.Value : 0, FavoritedRecipe = false, // recipe.ApplicationUsersRecipes.Any(aur => aur.ApplicationUserId == User.FindFirstValue(ClaimTypes.NameIdentifier)), Name = results.First()["stripped_name"].ToString(), Picture = results.First()["thumb"].ToString(), RecipeId = recipeId }); } } var recipesViewModel = new RecipesViewModel { Recipes = favoritedRecipes }; return(View(recipesViewModel)); }
/// <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"); } }
/// <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> public void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String sparqlQuery) { SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(UriFactory.Create(this._sparqlUri)); using (HttpWebResponse response = endpoint.QueryRaw(sparqlQuery)) { try { ISparqlResultsReader sparqlParser = MimeTypesHelper.GetSparqlParser(response.ContentType); sparqlParser.Load(resultsHandler, new StreamReader(response.GetResponseStream())); } catch (RdfParserSelectionException) { IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType); parser.Load(rdfHandler, new StreamReader(response.GetResponseStream())); } response.Close(); } }
/// <summary> /// Evaluates the Service Clause by generating instance(s) of <see cref="SparqlRemoteEndpoint">SparqlRemoteEndpoint</see> as required and issuing the query to the remote endpoint(s) /// </summary> /// <param name="context">Evaluation Context</param> /// <returns></returns> public BaseMultiset Evaluate(SparqlEvaluationContext context) { bool bypassSilent = false; try { #if SILVERLIGHT throw new PlatformNotSupportedException("SERVICE is not currently supported under Silverlight"); #else SparqlRemoteEndpoint endpoint; Uri endpointUri; String baseUri = (context.Query.BaseUri == null) ? String.Empty : context.Query.BaseUri.ToString(); SparqlParameterizedString sparqlQuery = new SparqlParameterizedString("SELECT * WHERE "); String pattern = this._pattern.ToString(); pattern = pattern.Substring(pattern.IndexOf('{')); sparqlQuery.CommandText += pattern; //Pass through LIMIT and OFFSET to the remote service if (context.Query.Limit >= 0) { //Calculate a LIMIT which is the LIMIT plus the OFFSET //We'll apply OFFSET locally so don't pass that through explicitly int limit = context.Query.Limit; if (context.Query.Offset > 0) limit += context.Query.Offset; sparqlQuery.CommandText += " LIMIT " + limit; } //Select which service to use if (this._endpointSpecifier.TokenType == Token.URI) { endpointUri = UriFactory.Create(Tools.ResolveUri(this._endpointSpecifier.Value, baseUri)); endpoint = new SparqlRemoteEndpoint(endpointUri); } else if (this._endpointSpecifier.TokenType == Token.VARIABLE) { //Get all the URIs that are bound to this Variable in the Input String var = this._endpointSpecifier.Value.Substring(1); if (!context.InputMultiset.ContainsVariable(var)) throw new RdfQueryException("Cannot evaluate a SERVICE clause which uses a Variable as the Service specifier when the Variable is unbound"); List<IUriNode> services = new List<IUriNode>(); foreach (ISet s in context.InputMultiset.Sets) { if (s.ContainsVariable(var)) { if (s[var].NodeType == NodeType.Uri) { services.Add((IUriNode)s[var]); } } } services = services.Distinct().ToList(); //Now generate a Federated Remote Endpoint List<SparqlRemoteEndpoint> serviceEndpoints = new List<SparqlRemoteEndpoint>(); services.ForEach(u => serviceEndpoints.Add(new SparqlRemoteEndpoint(u.Uri))); endpoint = new FederatedSparqlRemoteEndpoint(serviceEndpoints); } else { //Note that we must bypass the SILENT operator in this case as this is not an evaluation failure //but a query syntax error bypassSilent = true; throw new RdfQueryException("SERVICE Specifier must be a URI/Variable Token but a " + this._endpointSpecifier.GetType().ToString() + " Token was provided"); } //Where possible do substitution and execution to get accurate and correct SERVICE results context.OutputMultiset = new Multiset(); List<String> existingVars = (from v in this._pattern.Variables where context.InputMultiset.ContainsVariable(v) select v).ToList(); if (existingVars.Any() || context.Query.Bindings != null) { //Pre-bound variables/BINDINGS clause so do substitution and execution //Build the set of possible bindings HashSet<ISet> bindings = new HashSet<ISet>(); if (context.Query.Bindings != null && !this._pattern.Variables.IsDisjoint(context.Query.Bindings.Variables)) { //Possible Bindings comes from BINDINGS clause //In this case each possibility is a distinct binding tuple defined in the BINDINGS clause foreach (BindingTuple tuple in context.Query.Bindings.Tuples) { bindings.Add(new Set(tuple)); } } else { //Possible Bindings get built from current input (if there was a BINDINGS clause the variables it defines are not in this SERVICE clause) //In this case each possibility only contains Variables bound so far foreach (ISet s in context.InputMultiset.Sets) { Set t = new Set(); foreach (String var in existingVars) { t.Add(var, s[var]); } bindings.Add(t); } } //Execute the Query for every possible Binding and build up our Output Multiset from all the results foreach (ISet s in bindings) { //Q: Should we continue processing here if and when we hit an error? foreach (String var in s.Variables) { sparqlQuery.SetVariable(var, s[var]); } SparqlResultSet results = endpoint.QueryWithResultSet(sparqlQuery.ToString()); context.CheckTimeout(); foreach (SparqlResult r in results) { Set t = new Set(r); foreach (String var in s.Variables) { t.Add(var, s[var]); } context.OutputMultiset.Add(t); } } return context.OutputMultiset; } else { //No pre-bound variables/BINDINGS clause so just execute the query //Try and get a Result Set from the Service SparqlResultSet results = endpoint.QueryWithResultSet(sparqlQuery.ToString()); //Transform this Result Set back into a Multiset foreach (SparqlResult r in results.Results) { context.OutputMultiset.Add(new Set(r)); } return context.OutputMultiset; } #endif } catch (Exception ex) { if (this._silent && !bypassSilent) { //If Evaluation Errors are SILENT is specified then a Multiset containing a single set with all values unbound is returned //Unless some of the SPARQL queries did return results in which we just return the results we did obtain if (context.OutputMultiset.IsEmpty) { Set s = new Set(); foreach (String var in this._pattern.Variables.Distinct()) { s.Add(var, null); } context.OutputMultiset.Add(s); } return context.OutputMultiset; } else { throw new RdfQueryException("Query execution failed because evaluating a SERVICE clause failed - this may be due to an error with the remote service", ex); } } }