private void RunQuery() { string Query = "SELECT ?person ?name ?surname ?givenName ?abstract (COUNT(?external) AS ?externalCount) (COUNT(?abstract) AS ?abstractCount) " + "FROM <http://dbpedia.org> " + "WHERE { " + " ?person a foaf:Person . " + " ?person foaf:name ?name . " + " ?person dbo:abstract ?abstract . " + " OPTIONAL { " + " ?person foaf:surname ?surname . " + " ?person foaf:givenName ?givenName . " + " ?person dbo:wikiPageExternalLink ?external . " + " } " + " FILTER(lang(?abstract) = \'en\') "; string[] split = Name.Split(' '); foreach (string part in split) { Query += "FILTER(regex(?name, \"" + part.Trim() + "\", \"i\")) "; Query += "FILTER(regex(?abstract, \"" + part.Trim() + "\", \"i\")) "; } Query += "} " + "ORDER BY DESC(?externalCount) DESC(?abstractCount) "; var result = endpoint.QueryWithResultSet(Query); foreach (var i in result) { tryAddPerson(i); } }
// GET: Home public ActionResult Index() { //Decclaramos todos los string necesarios para las consultas string url = Request.QueryString["interaction"]; string nodo = Request.QueryString["class_type"]; //Cargamos el prefijo para usarlo en todas las consultas string prefijos = "PREFIX RO: <http://www.obofoundry.org/ro/ro.owl#>PREFIX SIO: <http://semanticscience.org/resource/>PREFIX EDAM: <http://edamontology.org/>PREFIX PHIO: <http://linkeddata.systems/ontologies/SemanticPHIBase#>PREFIX PUBMED: <http://linkedlifedata.com/resource/pubmed/>PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>PREFIX up: <http://purl.uniprot.org/core/>PREFIX foaf: <http://xmlns.com/foaf/0.1/>PREFIX skos: <http://www.w3.org/2004/02/skos/core#>"; string inicio = "SELECT DISTINCT ?disn_1 ?label ?rel ?valor WHERE { ?disn_1 ?rel ?valor . ?disn_1 rdfs:label ?label FILTER(( ?disn_1 = <"; string fin = ">))}"; Boolean defecto = true; //Se establece el endpoint para las consultas SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://linkeddata.systems:8890/sparql")); try { //Creamos la query de la interaction que proviene de la url string query = prefijos + inicio + url + fin; SparqlResultSet resultQuery1 = endpoint.QueryWithResultSet(query); //recorremos los resultados de esta primera query if (resultQuery1.Results != null) { metodoRecursivo(resultQuery1, padre, level); } json = json.TrimEnd(','); json = json + finTotal; ViewData["Nodos"] = json; if (nodo != null) { string query2 = prefijos + inicio + nodo + fin; SparqlResultSet resultQuery2 = endpoint.QueryWithResultSet(query2); if (resultQuery2.Results != null) { metodoNodoCentral(resultQuery2, defecto); } ViewData["Nodo"] = json2; } if ((nodo == null) && resultQuery1.Results != null) { defecto = false; metodoNodoCentral(resultQuery1, defecto); ViewData["Nodo"] = json2; } } catch (RdfQueryException queryEx) { //There was an error executing the query so handle it here Console.WriteLine(queryEx.Message); } return(View()); }
protected override PlaceDataObject DoGet(PlaceDataObject entity, LambdaExpression securityFilterExpression, List <string> includes, IObjectsDataSet context, Dictionary <string, object> parameters) { var uri = entity.URI; SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"), "http://dbpedia.org"); string queryString = @"SELECT ?name, ?abstract WHERE { ?place rdfs:label ?name . ?place dbo:abstract ?abstract . FILTER langMatches(lang(?name), 'en') FILTER langMatches(lang(?abstract), 'en')}"; queryString = queryString.Replace("?place ", $"<{uri}> "); //Make a SELECT query against the Endpoint SparqlResultSet results = endpoint.QueryWithResultSet(queryString); var result = results.Single(); var place = new PlaceDataObject(); var dataset = ApplicationSettings.Container.Resolve <IObjectsDataSet>(); dataset.AddObject(place); place.URI = entity.URI; place.Name = (result.Where(r => r.Key == "name").Single().Value as BaseLiteralNode).Value; place.Abstract = (result.Where(r => r.Key == "abstract").Single().Value as BaseLiteralNode)?.Value; place.IsNew = false; place.IsDirty = false; return(place); }
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 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; }
public static SparqlResultSet make(string request) { SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("https://query.wikidata.org/sparql"), "https://query.wikidata.org/sparql"); endpoint.UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"; return(endpoint.QueryWithResultSet(request)); }
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 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); } }
/// <summary> /// Makes a Query against the SPARQL Endpoint processing the results with an appropriate handler from those provided. /// </summary> /// <param name="rdfHandler">RDF Handler.</param> /// <param name="resultsHandler">Results Handler.</param> /// <param name="sparqlQuery">SPARQL Query.</param> /// <returns></returns> public void Query(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, String sparqlQuery) { if (!_skipLocalParsing) { // Parse the query locally to validate it and so we can decide what to do // when we receive the Response more easily as we'll know the query type // This also saves us wasting a HttpWebRequest on a malformed query SparqlQueryParser qparser = new SparqlQueryParser(); SparqlQuery q = qparser.ParseFromString(sparqlQuery); switch (q.QueryType) { case SparqlQueryType.Ask: case SparqlQueryType.Select: case SparqlQueryType.SelectAll: case SparqlQueryType.SelectAllDistinct: case SparqlQueryType.SelectAllReduced: case SparqlQueryType.SelectDistinct: case SparqlQueryType.SelectReduced: // Some kind of Sparql Result Set _endpoint.QueryWithResultSet(resultsHandler, sparqlQuery); break; case SparqlQueryType.Construct: case SparqlQueryType.Describe: case SparqlQueryType.DescribeAll: // Some kind of Graph _endpoint.QueryWithResultGraph(rdfHandler, sparqlQuery); break; case SparqlQueryType.Unknown: default: // Error throw new RdfQueryException("Unknown Query Type was used, unable to determine how to process the response"); } } else { // If we're skipping local parsing then we'll need to just make a raw query and process the response using (HttpWebResponse response = _endpoint.QueryRaw(sparqlQuery)) { try { // Is the Content Type referring to a Sparql Result Set format? ISparqlResultsReader sparqlParser = MimeTypesHelper.GetSparqlParser(response.ContentType); sparqlParser.Load(resultsHandler, new StreamReader(response.GetResponseStream())); response.Close(); } catch (RdfParserSelectionException) { // If we get a Parser Selection exception then the Content Type isn't valid for a Sparql Result Set // Is the Content Type referring to a RDF format? IRdfReader rdfParser = MimeTypesHelper.GetParser(response.ContentType); rdfParser.Load(rdfHandler, new StreamReader(response.GetResponseStream())); response.Close(); } } } }
public ISparqlQueryResult ExecuteQuery(ISparqlQuery query, ITransaction transaction = null) { string q = query.ToString(); Log?.Invoke(q); SparqlQueryParser p = new SparqlQueryParser(); var x = p.ParseFromString(q); x.ClearNamedGraphs(); x.ClearDefaultGraphs(); SparqlEndpointQueryResult result = null; if (query.QueryType == SparqlQueryType.Describe || query.QueryType == SparqlQueryType.Construct) { var r = _endpoint.QueryWithResultGraph(x.ToString()); result = new SparqlEndpointQueryResult(r, query); } else { var r = _endpoint.QueryWithResultSet(x.ToString()); result = new SparqlEndpointQueryResult(r, query); } return(result); }
public void ExecuteQuery(string query) { SparqlResultSet results = endpoint.QueryWithResultSet(query); List <string[]> rows = new List <string[]>(); List <String> columns = new List <String>(); foreach (var result in results) { List <String> row = new List <String>(); StringBuilder sb = new StringBuilder(); foreach (var item in result) { if (columns.Count < result.Count) { columns.Add(item.Key); } sb.Append(item.Value.ToString()); sb.Append(" "); row.Add(item.Value.ToString()); } row.Add(sb.ToString()); rows.Add(row.ToArray <String>()); } if (rows.Count > 0) { columns.Add("invisible"); } DeleteFoward(); LL.AddLast(new QueryDM(rows, columns, query)); SaveQuery(); Index++; }
/// <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} }
public static string Rank(this Uri uri, Uri endPointUri) { var endpoint = new SparqlRemoteEndpoint(endPointUri); var querySb = new StringBuilder(); querySb.AppendLine(Prefixes.GetSparqlPrefix("rdfs")); querySb.AppendLine($"select ?rank"); querySb.AppendLine($"where {{"); querySb.AppendLine($" <{uri}> <http://purl.obolibrary.org/obo/ncbitaxon#has_rank> ?r ."); querySb.AppendLine($" ?r rdfs:label ?rank ."); querySb.AppendLine($"}}"); var results = endpoint.QueryWithResultSet(querySb.ToString()); if (results.Count != 1) { throw new Exception("Unexpected results."); } results[0].TryGetValue("rank", out var node); if (!(node is LiteralNode literalNode)) { throw new Exception("Unexpected results."); } return(literalNode.Value); }
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; }
public void Execute(SparqlRemoteEndpoint endpoint, ODataFeedGenerator handler) { if (IsDescribe) { string query = GetSparqlRepresentation(); IGraph resultsGraph = endpoint.QueryWithResultGraph(query); if (!String.IsNullOrEmpty(DescribeResource)) { // Create ODATA entry payload for single resource handler.CreateEntryFromGraph(resultsGraph, DescribeResource, GetEntityType(DescribeResource)); } else { if (IsDescribe) { if (SelectVariables.Count > 1) { throw new Exception( "Cannot create an entity feed from a SPARQL query with multiple DESCRIBE bindings"); } string countQuery = GetSparqlCountQuery(); var countResults = endpoint.QueryWithResultSet(countQuery); var firstResult = countResults.Results.FirstOrDefault(); int resultsCount = 0; if (firstResult != null) { resultsCount = Int32.Parse((firstResult[0] as ILiteralNode).Value); } var selectVarInfo = VariableType[SelectVariables[0]]; if (selectVarInfo.IsCollection) { handler.CreateFeedFromGraph(resultsGraph, selectVarInfo.EntityType, resultsCount, this); } else { handler.CreateEntryFromGraphWithVariable(resultsGraph, SelectVariables[0], selectVarInfo.EntityType); } } } } else { SparqlResultSet resultSet = endpoint.QueryWithResultSet(GetSparqlRepresentation()); handler.CreateFeedFromResultSet(resultSet); } }
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)); }
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 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); }
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 IActionResult ShowAll(IndexViewModel model) { if (!ModelState.IsValid) { return(PartialView("_NoIngredientsPartial")); } var ingredients = model.IngredientsUris.Select(i => $"exists {{ ?food dbo:ingredient dbr:{i.Split('/').Last()} }}"); var ingredients_exists = $"FILTER ({string.Join(" && ", ingredients)})\r\n"; var categories = model.CategoriesUris?.Select(c => $"exists {{ ?food dct:subject dbc:{c.Split(':').Last()} }}"); var categories_exists = categories != null ? $"FILTER ({string.Join(" && ", categories)})\r\n" : ""; var endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"), "http://dbpedia.org"); var query = "PREFIX dbo: <http://dbpedia.org/ontology/>\r\n" + "PREFIX dbr: <http://dbpedia.org/resource/>\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 ?id\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 ?id\r\n" + ingredients_exists + categories_exists + "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); var recipesViewModel = new RecipesViewModel { Recipes = results.Select(r => new RecipeViewModel { Description = r["stripped_abstract"].ToString(), Name = r["stripped_name"].ToString(), Picture = r["thumb"].ToString(), RecipeId = r["id"].ToString().Split("^^").First(), Evaluation = GetEvaluation(r["id"].ToString().Split("^^").First()) }).ToList() }; if (model.Rating.HasValue) { recipesViewModel.Recipes = recipesViewModel.Recipes.Where(r => r.Evaluation >= model.Rating.Value).ToList(); } return(PartialView("_RecipesPartial", recipesViewModel)); }
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)); }
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 static String getPyrometers(int tcpSpeed, int lampPower) // Second Case Scenario (getting all pyrometers from the tcp speed and the lamp power) { SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://localhost:8890/sparql"), "http://localhost:8890/test1"); SparqlResultSet results = endpoint.QueryWithResultSet("SELECT * WHERE {?s <http://bedrock/has_Lamp_N%EF%BF%BD1_(1001)> ?lamp.?s <http://bedrock/has_TCP_Speed_(53)> ?tcp.?s <http://bedrock/has_Pyrometer_N%EF%BF%BD1_(27)> ?p1.?s <http://bedrock/has_Pyrometer_N%EF%BF%BD2_(29)> ?p2.?s <http://bedrock/has_Pyrometer_N%EF%BF%BD3_(31)> ?p3. ?s <http://bedrock/has_Pyrometer_N%EF%BF%BD4_(33)> ?p4.FILTER(?tcp=0 && ?lamp=100).}"); String res = ""; Console.WriteLine(results.Count); foreach (SparqlResult result in results) { res += result.ToString() + "\n"; } return(res); }
public static String getGrandfather(String grandchild) // sparql query to get the grandfather { SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://localhost:8890/sparql"), "http://localhost:8890/test"); ////Make a SELECT query against the Endpoint SparqlResultSet results = endpoint.QueryWithResultSet("SELECT ?grandParent WHERE { <http://bedrock/" + grandchild + "> <http://bedrock/hasParent> ?o. ?o <http://bedrock/hasParent> ?grandParent}"); String res = ""; foreach (SparqlResult result in results) { res += result.ToString().Split('=')[result.ToString().Split('=').Length - 1].Split('/')[result.ToString().Split('=')[result.ToString().Split('=').Length - 1].Split('/').Length - 1]; } return(res); }
private string getDiseaseNameFromCode(string diseaseCode) { string diseaseName = ""; SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"), "http://dbpedia.org"); { string query = @"SELECT * WHERE { ?url <http://dbpedia.org/ontology/icd10> ?ID. ?url rdfs:label ?name. ?url <http://dbpedia.org/ontology/abstract> ?description. filter regex(str(lcase(?ID)), concat(lcase('" + diseaseCode[0] + "'), '[" + diseaseCode[1] + "][" + diseaseCode[2] + "][.]?[0-9]?') )" + "filter(langMatches(lang(?name), 'EN'))" + "filter(langMatches(lang(?description), 'EN'))" + "} limit 1"; SparqlResultSet results = endpoint.QueryWithResultSet(query); if (results.Count > 0) { diseaseName = results[0]["name"].ToString().Remove(results[0]["name"].ToString().Length - 3); } else { query = @"SELECT * WHERE { ?url <http://dbpedia.org/ontology/icd10> ?ID. ?url rdfs:label ?name. ?url <http://dbpedia.org/ontology/abstract> ?description. filter regex(str(lcase(?ID)), concat(lcase('" + diseaseCode[0] + "'), '[" + diseaseCode[1] + "][0-9][.]?[0-9]?') )" + "filter(langMatches(lang(?name), 'EN'))" + "filter(langMatches(lang(?description), 'EN'))" + "} limit 1"; results = endpoint.QueryWithResultSet(query); if (results.Count > 0) { diseaseCode = results[0]["name"].ToString().Remove(results[0]["name"].ToString().Length - 3); } } } return(diseaseName); }
public void SparqlRemoteEndpointAsyncApiQueryWithResultSet() { RegisterSelectQueryGetHandler(); SparqlRemoteEndpoint endpoint = GetQueryEndpoint(); ManualResetEvent signal = new ManualResetEvent(false); endpoint.QueryWithResultSet("SELECT * WHERE {?s ?p ?o}", (r, s) => { signal.Set(); signal.Close(); }, null); signal.WaitOne(10000).Should().BeTrue(); }
protected void Button3_Click(object sender, EventArgs e) { //Higher Institute for Applied Sciences and Technology Label1.Text = " Higher Institute for Applied Sciences and Technology 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(?dir)as ?director ) ?homepage WHERE { <http://dbpedia.org/resource/Higher_Institute_for_Applied_Sciences_and_Technology> rdfs:comment ?info.filter langMatches(lang(?info),'en'). <http://dbpedia.org/resource/Higher_Institute_for_Applied_Sciences_and_Technology> rdfs:label ?name.filter langMatches(lang(?name),'en'). OPTIONAL { <http://dbpedia.org/resource/Higher_Institute_for_Applied_Sciences_and_Technology> dbp:director ?dir. <http://dbpedia.org/resource/Higher_Institute_for_Applied_Sciences_and_Technology> 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 = "Higher Institute for Applied Sciences and Technology 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/Higher_Institute_for_Applied_Sciences_and_Technology> rdfs:comment ?Information.filter langMatches(lang(?Information),'ar'). <http://dbpedia.org/resource/Higher_Institute_for_Applied_Sciences_and_Technology> 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; }
public static String getErrorsInCertainPlaceOfLaneEnhanced(int feedaccess, int programPointer) // Third case Scenario (getting Errors in certain places of lane giving the feed access position and the program counter for exact date ) { SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://localhost:8890/sparql"), "http://localhost:8890/test1"); SparqlResultSet results = endpoint.QueryWithResultSet("SELECT * WHERE {?s <http://bedrock/has_Feed_axis_position_(5100)> ?fa.?s <http://bedrock/has_Program_pointer_(5102)> ?pp. ?s <http://bedrock/hasDate> ?date . ?s1 <http://bedrock/hasStart_date> ?sd.?s1 <http://bedrock/hasDefault> ?error .FILTER(?fa =" + feedaccess + " && ?pp=" + programPointer + " && xsd:dateTime(?date)= xsd:dateTime(?sd))}"); String res = ""; Console.WriteLine(results.Count); foreach (SparqlResult result in results) { // res += result.ToString().Split('=')[result.ToString().Split('=').Length - 1].Split('/')[result.ToString().Split('=')[result.ToString().Split('=').Length - 1].Split('/').Length - 1].ToString() +"\n"; res += result.ToString() + "\n" + "\n"; } return(res); }
/// <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"); } }