public void NodeToLiteralCultureInvariant2() { CultureInfo sysCulture = CultureInfo.CurrentCulture; try { INodeFactory factory = new NodeFactory(); CultureInfo culture = CultureInfo.CurrentCulture; culture = (CultureInfo)culture.Clone(); culture.NumberFormat.NegativeSign = "!"; #if NET40 Thread.CurrentThread.CurrentCulture = culture; #else CultureInfo.CurrentCulture = culture; #endif TurtleFormatter formatter = new TurtleFormatter(); String fmtStr = formatter.Format((-1).ToLiteral(factory)); Assert.Equal("-1 ", fmtStr); fmtStr = formatter.Format((-1.2m).ToLiteral(factory)); Assert.Equal("-1.2", fmtStr); } finally { #if NET40 Thread.CurrentThread.CurrentCulture = sysCulture; #else CultureInfo.CurrentCulture = sysCulture; #endif } }
static void Main(string[] args) { try { PlayWithGraph p = new PlayWithGraph(); p.PlayWithOverview(); p.PlayWithHelloWorld(); p.PlayWithReadingRdf(); p.TesPlayWithWritingRdft(); p.TestCompressingTurtleWriter(); p.TestHtmlWriter(); WorkingWithGraphs w = new WorkingWithGraphs(); w.TestBaseUri(); w.TestGetNodes(); w.SelectingTriples(); w.MergingGraphs(); Test1(); IGraph g = new Graph(); TurtleParser ttlparser = new TurtleParser(); //Load using a Filename ttlparser.Load(g, @"C:\Users\philippe\Documents\GitHub\DotNetRDFExample\DotNetRDFExample\Files\Test12.ttl"); //First we need an instance of the SparqlQueryParser SparqlQueryParser parser = new SparqlQueryParser(); //Then we can parse a SPARQL string into a query string query = File.ReadAllText(@"C:\Users\philippe\Documents\GitHub\DotNetRDFExample\DotNetRDFExample\Files\query1.txt"); SparqlQuery q = parser.ParseFromString(query); SparqlResultSet o = g.ExecuteQuery(q) as SparqlResultSet; //Create a formatter INodeFormatter formatter = new TurtleFormatter(); foreach (SparqlResult result in o) { Console.WriteLine(result.ToString(formatter)); } } catch (RdfParseException parseEx) { //This indicates a parser error e.g unexpected character, premature end of input, invalid syntax etc. Console.WriteLine("Parser Error"); Console.WriteLine(parseEx.Message); } catch (RdfException rdfEx) { //This represents a RDF error e.g. illegal triple for the given syntax, undefined namespace Console.WriteLine("RDF Error"); Console.WriteLine(rdfEx.Message); } }
/// <summary> /// Processes a POST operation /// </summary> /// <param name="context">HTTP Context</param> public override void ProcessPost(IHttpContext context) { //Get the payload assuming there is one IGraph g = this.ParsePayload(context); if (g == null) { //Q: What should the behaviour be when the payload is null for a POST? Assuming a 200 OK response return; } //Get the Graph URI of the Graph to be added Uri graphUri = this.ResolveGraphUri(context, g); //First we need a //Generate an INSERT DATA command for the POST StringBuilder insert = new StringBuilder(); if (graphUri != null) { insert.AppendLine("INSERT DATA { GRAPH @graph {"); } else { insert.AppendLine("INSERT DATA {"); } TurtleFormatter formatter = new TurtleFormatter(g.NamespaceMap); foreach (Triple t in g.Triples) { insert.AppendLine(t.ToString(formatter)); } if (graphUri != null) { insert.AppendLine("} }"); } else { insert.AppendLine("}"); } //Parse and evaluate the command SparqlParameterizedString insertCmd = new SparqlParameterizedString(insert.ToString()); insertCmd.Namespaces = g.NamespaceMap; if (graphUri != null) { insertCmd.SetUri("graph", graphUri); } SparqlUpdateCommandSet cmds = this._parser.ParseFromString(insertCmd); this._updateProcessor.ProcessCommandSet(cmds); this._updateProcessor.Flush(); }
public static void Main(string[] args) { // Create a Console Logger: log = LoggerFactory .Create(builder => builder.AddConsole().SetMinimumLevel(LogLevel.Debug)) .CreateLogger <Program>(); // We don't want to use a Graph to prevent Memory // from exploding while writing the Data: nodeFactory = new NodeFactory(); // We don't want to write the full URL for every // triple, because that will lead to a large TTL // file with redundant data: namespaceMapper = new NamespaceMapper(); namespaceMapper.AddNamespace("ge", Constants.NsAviationGeneral); namespaceMapper.AddNamespace("ap", Constants.NsAviationAirport); namespaceMapper.AddNamespace("ac", Constants.NsAviationtAircraft); namespaceMapper.AddNamespace("ca", Constants.NsAviationCarrier); namespaceMapper.AddNamespace("fl", Constants.NsAviationFlight); namespaceMapper.AddNamespace("we", Constants.NsAviationWeather); namespaceMapper.AddNamespace("st", Constants.NsAviationWeatherStation); // There is a memory-leak when using the default QNameOutputMapper, // which adds all URIs encountered to a cache for speedup. This leads // to problems with millions of unique URIs, so we define a // a QNameOutputMapper with the Cache removed: var outputMapper = new NonCachingQNameOutputMapper(namespaceMapper); // Create the TurtleFormatter with the Namespace Mappings: turtleFormatter = new TurtleFormatter(outputMapper); // Load the Base Data: log.LogDebug("Loading Base Data ..."); var aircrafts = GetAircraftData(csvAircraftsFile).ToList(); var carriers = GetCarrierData(csvCarriersFile).ToList(); var airports = GetAirportData(csvAirportFile).ToList(); var stations = GetWeatherStationData(csvWeatherStationsFileName).ToList(); using (FileStream fileStream = File.Create(@"G:\aviation_2014.ttl")) { using (StreamWriter writer = new StreamWriter(fileStream)) { WriteNamespaces(writer); WriteAircrafts(writer, aircrafts); WriteAirports(writer, airports); WriteCarriers(writer, carriers); WriteFlights(writer, aircrafts, airports, carriers); WriteWeatherStations(writer, stations, airports); WriteWeatherDatas(writer, stations); } } }
/// <summary> /// Gets a String representation of a Triple in the form 'Subject , Predicate , Object' with optional compression of URIs to QNames. /// </summary> /// <param name="compress">Controls whether URIs will be compressed to QNames in the String representation.</param> /// <returns></returns> public string ToString(bool compress) { if (!compress || _g == null) { return(ToString()); } else { TurtleFormatter formatter = new TurtleFormatter(_g.NamespaceMap); return(formatter.Format(this)); } }
/// <summary> /// Processes a POST operation which adds triples to a new Graph in the Store and returns the URI of the newly created Graph /// </summary> /// <param name="context">HTTP Context</param> /// <remarks> /// <para> /// This operation allows clients to POST data to an endpoint and have it create a Graph and assign a URI for them. /// </para> /// </remarks> public override void ProcessPostCreate(IHttpContext context) { //Get the payload assuming there is one IGraph g = this.ParsePayload(context); //Mint a URI for the Graph Uri graphUri = this.MintGraphUri(context, g); //First generate a CREATE to ensure that the Graph exists //We don't do a CREATE SILENT as this operation is supposed to generate a new Graph URI //so if MintGraphUri() fails to deliver a unused Graph URI then the operation should fail StringBuilder insert = new StringBuilder(); insert.AppendLine("CREATE GRAPH @graph ;"); //Then Generate an INSERT DATA command for the actual POST //Note that if the payload is empty this still has the effect of creating a Graph if (g != null) { insert.AppendLine("INSERT DATA { GRAPH @graph {"); TurtleFormatter formatter = new TurtleFormatter(g.NamespaceMap); foreach (Triple t in g.Triples) { insert.AppendLine(t.ToString(formatter)); } insert.AppendLine("} }"); } //Parse and evaluate the command SparqlParameterizedString insertCmd = new SparqlParameterizedString(insert.ToString()); insertCmd.Namespaces = g.NamespaceMap; insertCmd.SetUri("graph", graphUri); SparqlUpdateCommandSet cmds = this._parser.ParseFromString(insertCmd); this._updateProcessor.ProcessCommandSet(cmds); this._updateProcessor.Flush(); //Finally return a 201 Created and a Location header with the new Graph URI context.Response.StatusCode = (int)HttpStatusCode.Created; try { context.Response.Headers.Add("Location", graphUri.AbsoluteUri); } catch (PlatformNotSupportedException) { context.Response.AddHeader("Location", graphUri.AbsoluteUri); } }
/// <summary> /// Processes a PUT operation /// </summary> /// <param name="context">HTTP Context</param> public override void ProcessPut(IHttpContext context) { //Get the payload assuming there is one IGraph g = this.ParsePayload(context); //Get the Graph URI of the Graph to be added Uri graphUri = this.ResolveGraphUri(context, g); //Determine whether the Graph already exists or not, if it doesn't then we have to send a 201 Response bool created = false; try { SparqlQueryParser parser = new SparqlQueryParser(); SparqlParameterizedString graphExistsQuery = new SparqlParameterizedString(); graphExistsQuery.CommandText = "ASK WHERE { GRAPH @graph { } }"; graphExistsQuery.SetUri("graph", graphUri); Object temp = this._queryProcessor.ProcessQuery(parser.ParseFromString(graphExistsQuery)); if (temp is SparqlResultSet) { created = !((SparqlResultSet)temp).Result; } } catch { //If any error occurs assume the Graph doesn't exist and so we'll return a 201 created created = true; } //Generate a set of commands based upon this StringBuilder cmdSequence = new StringBuilder(); if (graphUri != null) { cmdSequence.AppendLine("DROP SILENT GRAPH @graph ;"); cmdSequence.Append("CREATE SILENT GRAPH @graph"); } else { cmdSequence.Append("DROP SILENT DEFAULT"); } if (g != null) { cmdSequence.AppendLine(" ;"); if (graphUri != null) { cmdSequence.AppendLine("INSERT DATA { GRAPH @graph {"); } else { cmdSequence.AppendLine("INSERT DATA { "); } TurtleFormatter formatter = new TurtleFormatter(g.NamespaceMap); foreach (Triple t in g.Triples) { cmdSequence.AppendLine(t.ToString(formatter)); } if (graphUri != null) { cmdSequence.AppendLine("} }"); } else { cmdSequence.AppendLine("}"); } } SparqlParameterizedString put = new SparqlParameterizedString(cmdSequence.ToString()); put.Namespaces = g.NamespaceMap; if (graphUri != null) { put.SetUri("graph", graphUri); } SparqlUpdateCommandSet putCmds = this._parser.ParseFromString(put); this._updateProcessor.ProcessCommandSet(putCmds); this._updateProcessor.Flush(); //Return a 201 if required, otherwise the default behaviour of returning a 200 will occur automatically if (created) { context.Response.StatusCode = (int)HttpStatusCode.Created; } }
public TurtleRdfWriter(Stream outputStream) { _outputStream = new StreamWriter(outputStream, new UTF8Encoding(false), 64 * 1024, true); _turtleFormatter = new TurtleFormatter(); }
public IActionResult Index(SearchViewModel model) { // Load ontology file IGraph g = new Graph(); var file = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "food-nt.owl"); FileLoader.Load(g, file); // Spartql query SparqlParameterizedString query = new SparqlParameterizedString(); query.Namespaces.AddNamespace("rdfs", new Uri("http://www.w3.org/2000/01/rdf-schema#")); query.Namespaces.AddNamespace("rdf", new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#")); query.Namespaces.AddNamespace("uni", new Uri("http://www.semanticweb.org/nnt/ontologies/2019/10/food-nt#")); string type = ""; string type_declare = ""; if (model.Type != 0) { type_declare = " ?food rdf:type ?type . "; } if (model.Type == 1) { type = " && ?type=uni:Ngu_coc "; } if (model.Type == 2) { type = " && ?type=uni:Khoai_cu "; } if (model.Type == 3) { type = " && ?type=uni:Hat_qua "; } query.CommandText = "SELECT ?food WHERE " + "{ ?food uni:hasEnergyPer100g ?en ." + " ?food uni:hasProteinPer100g ?pr ." + " ?food uni:hasFatPer100g ?fat ." + " ?food uni:hasCarbPer100g ?ca ." + type_declare + "FILTER(?en>=" + model.Energy + "&& ?pr>=" + model.Protein + "&& ?fat>=" + model.Fat + "&& ?ca>=" + model.Carb + type + ")}"; SparqlQueryParser parser = new SparqlQueryParser(); SparqlQuery queryEx = parser.ParseFromString(query); // Execute query Object result = g.ExecuteQuery(queryEx); string data = ""; if (result is SparqlResultSet) { SparqlResultSet rset = (SparqlResultSet)result; INodeFormatter formatter = new TurtleFormatter(g); foreach (SparqlResult r in rset) { String d; INode n; if (r.TryGetValue("food", out n)) { switch (n.NodeType) { case NodeType.Uri: d = ((IUriNode)n).Uri.Fragment; break; case NodeType.Literal: d = ((ILiteralNode)n).Value; break; default: throw new RdfOutputException("Unexpected Node Type"); } } else { d = String.Empty; } data = data + d.Replace("#", "").Replace("_", " ") + "\n"; model.Result.Add(d.Replace("#", "").Replace("_", " ")); } } else { data += "NO RESULT!"; } return(PartialView("_Result", model.Result)); }
protected void Button1_Click1(object sender, EventArgs e) { string filename = @"\RestaurantScenerio.rdf-xml.owl"; //get the owl file path string owlfilepath = AppDomain.CurrentDomain.BaseDirectory + filename; //var content = File.ReadAllText(owlfilepath); //var graph = new VDS.RDF.Graph(); //var xml = new XmlDocument(); //xml.LoadXml(content); //var parser = new RdfXmlParser(); //parser.Load(graph, xml); IGraph graph = new Graph(); graph.LoadFromFile(owlfilepath); string query = TextBox1.Text; string str = "PREFIX Res: <http://www.cs.le.ac.uk/rdf#>" + "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>" + query; Object res = graph.ExecuteQuery(str); SparqlResultSet results = (SparqlResultSet)res; DataTable table = new DataTable(); DataRow row; INodeFormatter formatter = new TurtleFormatter(); switch (results.ResultsType) { case SparqlResultsType.VariableBindings: foreach (String var in results.Variables) { table.Columns.Add(new DataColumn(var, typeof(INode))); } foreach (SparqlResult r in results) { row = table.NewRow(); r.ToString(formatter); foreach (String var in results.Variables) { if (r.HasValue(var)) { row[var] = r[var]; } else { row[var] = null; } } table.Rows.Add(row); } break; case SparqlResultsType.Boolean: table.Columns.Add(new DataColumn("ASK", typeof(bool))); row = table.NewRow(); row["ASK"] = results.Result; table.Rows.Add(row); break; case SparqlResultsType.Unknown: default: throw new InvalidCastException("Unable to cast a SparqlResultSet to a DataTable as the ResultSet has yet to be filled with data and so has no SparqlResultsType which determines how it is cast to a DataTable"); } populatedata(table); }