private Response GetLatestVersionUri() { Logger.LogRequest(HttpStatusCode.OK, Request); string url = GetUri(Request.Query.latestVersion); string queryString = @" PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX prov: <http://www.w3.org/ns/prov#> PREFIX nfo: <http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#> SELECT DISTINCT ?uri WHERE { ?uri prov:specializationOf ?f . ?f nfo:fileUrl """ + url + "\" . ?uri prov:qualifiedGeneration ?g . ?g prov:atTime ?time . } ORDER BY DESC(?time) LIMIT 1"; IModel model = Models.GetActivities(); SparqlQuery query = new SparqlQuery(queryString); ISparqlQueryResult result = model.ExecuteQuery(query); if (result.GetBindings().Any()) { BindingSet binding = result.GetBindings().First(); string uri = binding["uri"].ToString(); if (!string.IsNullOrEmpty(uri)) { return(Response.AsJson(uri)); } } return(""); }
private Response GetFileUri() { Logger.LogRequest(HttpStatusCode.OK, Request); string url = GetUri(Request.Query.file); string queryString = @" PREFIX prov: <http://www.w3.org/ns/prov#> PREFIX nfo: <http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#> SELECT DISTINCT ?uri WHERE { ?v prov:specializationOf ?uri . ?uri nfo:fileUrl """ + url + "\" . } LIMIT 1"; IModel model = Models.GetActivities(); SparqlQuery query = new SparqlQuery(queryString); ISparqlQueryResult result = model.ExecuteQuery(query); if (result.GetBindings().Any()) { BindingSet binding = result.GetBindings().First(); string uri = binding["uri"].ToString(); if (!string.IsNullOrEmpty(uri)) { return(Response.AsJson(uri)); } } return(""); }
/// <summary> /// Lists all models in the store. /// </summary> /// <returns>All handles to existing models.</returns> public override IEnumerable <IModel> ListModels() { ISparqlQuery query = new SparqlQuery("SELECT DISTINCT ?g WHERE { GRAPH ?g { ?s ?p ?o } }"); ISparqlQueryResult result = ExecuteQuery(query); foreach (BindingSet b in result.GetBindings()) { IModel model = null; try { var x = b["g"]; model = new Model(this, new UriRef(x.ToString())); } catch (Exception) { continue; } if (model != null) { yield return(model); } } }
private void CreateSeriesPoints(ISparqlQueryResult result) { AreaSeries series = CreateSeries("Facts x 1000", OxyColor.Parse("#119eda")); int d = 0; int n = 0; double y0 = 0; double y1 = 0; foreach (BindingSet binding in result.GetBindings()) { DateTime x = DateTime.Parse(binding["time"].ToString()); double y = Convert.ToInt32(binding["facts"]); if (n == 0) { y0 = y; } if (d != x.DayOfYear) { d = x.DayOfYear; n++; } y1 = y; series.Points.Add(DateTimeAxis.CreateDataPoint(x, y / 1000)); } AverageDelta = n > 0 ? (y1 - y0) / n : 0; Model.Series.Add(series); }
private static void QuerySPARQLPhysicalLocation() { string sparql = "Select ?a from <http://www.example.com/> " + "{ ?a a<http://www.example.com/PhysicalLocation>. }"; ISparqlQuery sparqlQuery = new SparqlQuery(sparql, false); Console.WriteLine("SPARQL QueryPhysicalLocation .. start"); //Executing Query with inference, hence the true statement ISparqlQueryResult locations = context.ExecuteQuery(sparqlQuery, true); var bindings = locations.GetBindings().ToList(); if (bindings.FirstOrDefault() != null) { foreach (var binding in bindings) { Console.WriteLine(" - Found: " + binding.Values.FirstOrDefault().ToString()); } } else { Console.WriteLine("====> No inferred results found, did you upload the ontology model?"); } Console.WriteLine("SPARQL QueryPhysicalLocation .. done"); }
public void Refresh() { string queryString = @" PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX nfo: <http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#> PREFIX prov: <http://www.w3.org/ns/prov#> PREFIX dces: <http://purl.org/dc/elements/1.1/> SELECT ?agent ?startTime ?endTime ?fileUrl WHERE { ?activity prov:used ?entity . ?activity prov:startedAtTime ?startTime . ?activity prov:endedAtTime ?endTime . ?activity prov:qualifiedAssociation ?association . ?association prov:agent ?agent . ?entity nfo:fileUrl ?fileUrl . } ORDER BY DESC(?startTime)"; IModel model = Models.GetActivities(); SparqlQuery query = new SparqlQuery(queryString); ISparqlQueryResult result = model.ExecuteQuery(query); LoadBindings(result.GetBindings()); }
private void CreateSeriesPoints(ISparqlQueryResult result) { AreaSeries series = CreateSeries("Size / MB", OxyColors.Orange); int d = 0; int n = 0; double y0 = 0; double y1 = 0; foreach (BindingSet binding in result.GetBindings()) { DateTime x = DateTime.Parse(binding["time"].ToString()); double y = Convert.ToDouble(binding["size"]); if (n == 0) { y0 = y; } if (d != x.DayOfYear) { d = x.DayOfYear; n++; } y1 = y; series.Points.Add(DateTimeAxis.CreateDataPoint(x, ToMegaByte(y, 2))); } AverageDelta = n > 0 ? ToKiloByte((y0 - y1) / n, 2) : 0; Model.Series.Add(series); }
public void TestSelectCount() { SparqlQuery query = new SparqlQuery("SELECT COUNT(?s) AS ?count WHERE { ?s rdf:type nfo:Document. }"); ISparqlQueryResult result = Model.ExecuteQuery(query); var bindings = result.GetBindings(); Assert.AreEqual(1, bindings.Count()); Assert.AreEqual(3, bindings.First()["count"]); }
private void CreateRows(ISparqlQueryResult result) { _items.Clear(); foreach (BindingSet binding in result.GetBindings()) { ActivityLogItem item = new ActivityLogItem(); item.Activity = new UriRef(binding["activity"].ToString()); item.Agent = new UriRef(binding["agent"].ToString()); if (_agents.ContainsKey(item.Agent)) { item.AgentColour = _agents[item.Agent].ColourCode; } item.Date = (DateTime)binding["influenceTime"]; if (!(binding["influenceType"] is DBNull)) { item.InfluenceType = ToDisplayString(binding["influenceType"].ToString()); } if (!(binding["description"] is DBNull)) { item.Description = binding["description"].ToString(); } UriRef entityType = new UriRef(binding["entityType"].ToString()); if (entityType == nfo.FileDataObject.Uri) { string value = binding["value"].ToString(); item.Data = value; } else { UriRef entityUri = new UriRef(binding["entity"].ToString()); item.Data = entityUri.Host; } if (!(binding["bounds"] is DBNull)) { item.InfluencedRegion = binding["bounds"].ToString(); } _items.Add(item); } DataStore = _items; }
private void LoadActivities(string fileUrl) { SuspendLayout(); string queryString = @" PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX nfo: <http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#> PREFIX prov: <http://www.w3.org/ns/prov#> SELECT ?agent ?startTime ?endTime WHERE { ?activity prov:qualifiedAssociation ?association . ?activity prov:startedAtTime ?startTime . ?activity prov:endedAtTime ?endTime . ?activity prov:used ?entity . ?association prov:agent ?agent . ?entity nfo:fileUrl """ + Uri.EscapeUriString(fileUrl) + @""" . } ORDER BY DESC(?startTime)"; IModel model = Models.GetAllActivities(); SparqlQuery query = new SparqlQuery(queryString); ISparqlQueryResult result = model.ExecuteQuery(query, true); foreach (BindingSet binding in result.GetBindings()) { Agent agent = new Agent(new Uri(binding["agent"].ToString())); DateTime startTime = ((DateTime)binding["startTime"]).RoundToMinute(); DateTime endTime = ((DateTime)binding["endTime"]).RoundToMinute(); OxyColor color = _palette[agent]; // Since we're going backward in time, we see the close activities first. PolygonAnnotation annotation = new PolygonAnnotation(); annotation.Layer = AnnotationLayer.BelowAxes; annotation.Fill = OxyColor.FromArgb(125, color.R, color.G, color.B); annotation.Points.Add(DateTimeAxis.CreateDataPoint(startTime, 0)); annotation.Points.Add(DateTimeAxis.CreateDataPoint(startTime, 2)); annotation.Points.Add(DateTimeAxis.CreateDataPoint(endTime, 2)); annotation.Points.Add(DateTimeAxis.CreateDataPoint(endTime, 0)); Model.Annotations.Add(annotation); } ResumeLayout(); }
private void InitializeMonitoredFiles() { // We order by start time so that we get the latest version of a file, // just in case there exist previous (deleted) versions. string queryString = @" PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX prov: <http://www.w3.org/ns/prov#> PREFIX nfo: <http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#> SELECT DISTINCT ?uri ?url WHERE { ?activity prov:used ?uri . ?activity prov:startedAtTime ?startTime . ?uri a nfo:FileDataObject . ?uri nfo:fileUrl ?url . FILTER(!ISIRI(?url)) } ORDER BY DESC(?startTime)"; SparqlQuery query = new SparqlQuery(queryString); ISparqlQueryResult result = _model.ExecuteQuery(query); foreach (BindingSet binding in result.GetBindings()) { string u = binding["url"].ToString(); if (!Uri.IsWellFormedUriString(u, UriKind.Absolute)) { continue; } Uri url = new Uri(u); if (_monitoredFileUris.ContainsKey(url) || !File.Exists(url.LocalPath)) { continue; } Uri uri = new Uri(binding["uri"].ToString()); _monitoredFileUris[url] = uri; _monitoredFiles[url.LocalPath] = new FileInfoCache(url.LocalPath); } }
private FileInfoCache CreateFileDataObject(string path) { FileInfoCache file = new FileInfoCache(path); string queryString = @" PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX nfo: <http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#> SELECT ?uri WHERE { ?uri a nfo:FileDataObject . ?uri nfo:fileUrl """ + file.Url.AbsoluteUri + @""" . } LIMIT 1"; SparqlQuery query = new SparqlQuery(queryString); ISparqlQueryResult result = _model.ExecuteQuery(query); BindingSet bindings = result.GetBindings().FirstOrDefault(); if (bindings == null) { FileDataObject f = _model.CreateResource <FileDataObject>(); f.CreationTime = file.CreationTime; f.LastAccessTime = file.LastAccessTime; f.LastModificationTime = file.LastWriteTime; f.Url = file.Url.AbsoluteUri; f.Commit(); _monitoredFileUris[file.Url] = f.Uri; Logger.LogInfo("Created {0}", file.FullName); } else { _monitoredFileUris[file.Url] = new Uri(bindings["uri"].ToString()); Logger.LogInfo("Updating {0}", file.FullName); } return(file); }
public void TestSelect() { // Retrieving bound variables using the SELECT query form. SparqlQuery query = new SparqlQuery("SELECT ?name ?birthday WHERE { ?x nco:fullname ?name. ?x nco:birthDate ?birthday. }"); ISparqlQueryResult result = Model.ExecuteQuery(query); Assert.AreEqual(1, result.GetBindings().Count()); // Retrieving resoures using the SELECT or DESCRIBE query form. query = new SparqlQuery("SELECT ?s ?p ?o WHERE { ?s ?p ?o. ?s nco:fullname 'Hans Wurscht'. }"); result = Model.ExecuteQuery(query); Assert.AreEqual(1, result.GetResources().Count()); // Test SELECT with custom defined PREFIXes query = new SparqlQuery("PREFIX nco: <http://www.semanticdesktop.org/ontologies/2007/03/22/nco#> SELECT ?s ?p ?o WHERE { ?s ?p ?o. ?s nco:fullname 'Hans Wurscht'. }"); result = Model.ExecuteQuery(query); Assert.AreEqual(1, result.GetResources().Count()); // Check if the select statement only works on the given model. query = new SparqlQuery("SELECT * WHERE { ?s ?p ?o. }"); result = Model.ExecuteQuery(query); Assert.AreEqual(5, result.GetResources().Count()); // Check that resource creation is done correctly for Resources containing dashes. IResource r0 = Model.CreateResource(new Uri("http://example.org/Something#0")); r0.AddProperty(new Property(new Uri("http://example.org/fullName")), "Something"); r0.Commit(); IResource r1 = Model.CreateResource(new Uri("http://example.org/Something#1")); r1.AddProperty(new Property(new Uri("http://example.org/fullName")), "Anotherthing"); r1.Commit(); query = new SparqlQuery("SELECT * WHERE { ?s ?p ?o. }"); result = Model.ExecuteQuery(query); Assert.AreEqual(7, result.GetResources().Count()); }
public int Count() { SparqlQuery query = new SparqlQuery(SparqlSerializer.SerializeCount(_model, _query)); ISparqlQueryResult result = _model.ExecuteQuery(query, _inferenceEnabled); IEnumerable <BindingSet> bindings = result.GetBindings(); if (bindings != null) { foreach (BindingSet b in bindings) { if (b.ContainsKey("count")) { return((int)b["count"]); } } } return(-1); }
public T ExecuteScalar <T>(QueryModel queryModel) { Type t = typeof(T); if (t == typeof(bool)) { // Generate and execute ASK query. SparqlQueryModelVisitor <T> visitor = new SparqlQueryModelVisitor <T>(new AskQueryGenerator()); visitor.VisitQueryModel(queryModel); ISparqlQuery query = visitor.GetQuery(); ISparqlQueryResult result = Model.ExecuteQuery(query, _inferenceEnabled); return(new object[] { result.GetAnwser() }.OfType <T>().First()); } else if (queryModel.ResultOperators.Any(o => o is CountResultOperator)) { SparqlQueryModelVisitor <T> visitor = new SparqlQueryModelVisitor <T>(new SelectBindingsQueryGenerator()); visitor.VisitQueryModel(queryModel); ISparqlQuery query = visitor.GetQuery(); ISparqlQueryResult result = Model.ExecuteQuery(query, _inferenceEnabled); BindingSet b = result.GetBindings().FirstOrDefault(); if (b != null && b.Any()) { return(new object[] { b.First().Value }.OfType <T>().First()); } else { return(new object[] { 0 }.OfType <T>().First()); } } else { // Unknown scalar type. throw new NotImplementedException(); } }
private data.Canvas TryGetCanvas(string filePath) { if (string.IsNullOrEmpty(filePath)) { return(null); } IModel model = data.Models.GetActivities(); string queryString = @" PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX nfo: <http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#> PREFIX prov: <http://www.w3.org/ns/prov#> PREFIX art: <http://semiodesk.com/artivity/1.0/> SELECT DISTINCT ?canvas WHERE { ?activity prov:used ?file . ?activity prov:startedAtTime ?startTime . ?file rdf:type nfo:FileDataObject . ?file nfo:fileUrl ""file://" + Uri.EscapeUriString(filePath) + @""" . ?file art:canvas ?canvas . } ORDER BY DESC(?startTime) LIMIT 1"; SparqlQuery query = new SparqlQuery(queryString); ISparqlQueryResult result = model.ExecuteQuery(query); BindingSet bindings = result.GetBindings().FirstOrDefault(); if (bindings == null || !bindings.ContainsKey("canvas")) { return(null); } UriRef canvasUri = new UriRef(bindings["canvas"].ToString()); return(model.GetResource <data.Canvas>(canvasUri)); }
public IEnumerable <T> ExecuteCollection <T>(QueryModel queryModel) { Type t = queryModel.SelectClause.Selector.Type; if (typeof(Resource).IsAssignableFrom(t)) { // Handle queries which return instances of resources. SparqlQueryModelVisitor <T> visitor = new SparqlQueryModelVisitor <T>(new SelectTriplesQueryGenerator()); visitor.VisitQueryModel(queryModel); MethodInfo getResources = _getResourceMethod.MakeGenericMethod(typeof(T)); object[] args = new object[] { visitor.GetQuery(), _inferenceEnabled, null }; foreach (T value in getResources.Invoke(Model, args) as IEnumerable <T> ) { yield return(value); } } else { // Handle queries which return value type objects. SparqlQueryModelVisitor <T> visitor = new SparqlQueryModelVisitor <T>(new SelectBindingsQueryGenerator()); visitor.VisitQueryModel(queryModel); ISparqlQuery query = visitor.GetQuery(); ISparqlQueryResult result = Model.ExecuteQuery(query, _inferenceEnabled); // TODO: This works correctly for single bindings, check with multiple bindings. foreach (BindingSet bindings in result.GetBindings()) { foreach (var value in bindings.Values.OfType <T>()) { yield return(value); } } } }
private BackgroundWorker GetWriteCsvWorker(string filename) { BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += (object sender, DoWorkEventArgs e) => { using (TextWriter writer = File.CreateText(filename)) { try { string queryString = @" PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX nfo: <http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#> PREFIX prov: <http://www.w3.org/ns/prov#> PREFIX dces: <http://purl.org/dc/elements/1.1/> PREFIX art: <http://semiodesk.com/artivity/1.0/> SELECT ?activity ?agent ?influenceTime ?influenceType ?entity ?entityType ?description ?value ?bounds WHERE { ?activity prov:qualifiedAssociation ?association . ?association prov:agent ?agent . { ?activity prov:used ?file ; prov:generated ?entity . ?entity a ?entityType ; prov:qualifiedGeneration ?generation . ?generation a ?influenceType ; prov:atTime ?influenceTime . OPTIONAL { ?generation art:hadBoundaries ?bounds . } OPTIONAL { ?generation dces:description ?description . } OPTIONAL { ?generation prov:value ?value . } } UNION { ?editing prov:used ?file; prov:startedAtTime ?startTime ; prov:endedAtTime ?endTime . ?activity prov:startedAtTime ?time ; prov:qualifiedUsage ?usage . ?usage a ?influenceType ; prov:entity ?entity ; prov:atTime ?influenceTime . ?entity a ?entityType . FILTER(?startTime <= ?time && ?time <= ?endTime) . } } ORDER BY DESC(?influenceTime)"; IModel model = Models.GetAllActivities(); SparqlQuery query = new SparqlQuery(queryString); ISparqlQueryResult result = model.ExecuteQuery(query); foreach (BindingSet binding in result.GetBindings()) { writer.WriteLine(String.Join(",", binding.Values)); } e.Result = true; } catch (Exception ex) { Console.WriteLine(ex); e.Result = false; } } }; return(worker); }
private void CreateSeriesPoints(ISparqlQueryResult result) { DateTime previousTime; foreach (BindingSet binding in result.GetBindings()) { UriRef uri = new UriRef(binding["agent"].ToString()); Agent agent = _agents.ContainsKey(uri) ? _agents[uri] : new Agent(uri); // We initialize one series per agent. LineSeries series; if (!_series.ContainsKey(agent)) { series = CreateSeries(agent); Model.Series.Add(series); _series[agent] = series; previousTime = DateTime.MinValue; } else { series = _series[agent]; previousTime = DateTimeAxis.ToDateTime(series.Points.Last().X); } DateTime currentTime = (DateTime)binding["influenceTime"]; currentTime = currentTime.RoundToMinute(); if (previousTime != DateTime.MinValue) { if (DateTime.Equals(currentTime, previousTime)) { // We increment the current data point's value.. DataPoint p = series.Points.Last(); series.Points.Remove(p); p.Y++; series.Points.Add(p); _maxY = Math.Max(_maxY, p.Y); } else { // We fill up the gapping minutes between the current time value and the previous one.. double delta = (previousTime - currentTime).TotalMinutes; if (delta > 1) { DateTime t = previousTime.Subtract(TimeSpan.FromMinutes(1)); series.Points.Add(DateTimeAxis.CreateDataPoint(t, 0)); } if (delta > 2) { DateTime t = currentTime.Add(TimeSpan.FromMinutes(1)); series.Points.Add(DateTimeAxis.CreateDataPoint(t, 0)); } // ..and add the new point at the end. series.Points.Add(DateTimeAxis.CreateDataPoint(currentTime, 1)); } } else { // If there are no points in the series, we add this one. DateTime zeroTime = currentTime.Add(TimeSpan.FromMinutes(1)); series.Points.Add(DateTimeAxis.CreateDataPoint(zeroTime, 0)); series.Points.Add(DateTimeAxis.CreateDataPoint(currentTime, 1)); } previousTime = currentTime; } // Add a zero to the end of each line series. foreach (LineSeries series in _series.Values) { if (!series.Points.Any()) { continue; } previousTime = DateTimeAxis.ToDateTime(series.Points.Last().X); DateTime t = previousTime.Subtract(TimeSpan.FromMinutes(1)); series.Points.Add(DateTimeAxis.CreateDataPoint(t, 0)); } }