private void SaveButton_Click(object sender, RoutedEventArgs e) { try { SaveFileDialog sfd = new SaveFileDialog(); sfd.InitialDirectory = Environment.CurrentDirectory; sfd.Filter = "RDF Files (*.rdf)|*.rdf|Turtle Files (*.ttl)|*.ttl|All Files (*.*)|*.*"; if (sfd.ShowDialog().Value) { string filePath = sfd.FileName; switch (ModeComboBox.SelectedIndex) { case 0: // RDF/XML FastRdfXmlWriter rxtw = new FastRdfXmlWriter(); rxtw.Save(myGraph, filePath); break; case 1: // NTriples NTriplesWriter wr = new NTriplesWriter(); wr.Save(myGraph, filePath); break; } MessageBox.Show("Your Current Graph Saved Successfully", "Save Graph", MessageBoxButton.OK, MessageBoxImage.Information); } } catch (Exception ex) { MessageBox.Show(ex.Message + "\n" + ex.StackTrace, "ERROR", MessageBoxButton.OK); } }
public void SaveToFile(string filePath, DatasourceFileType fileType) { try { switch (fileType) { case DatasourceFileType.Rdfxml: // RDF/XML FastRdfXmlWriter rxtw = new FastRdfXmlWriter(); rxtw.Save(myGraph, filePath); break; case DatasourceFileType.NTriples: // NTriples NTriplesWriter wr = new NTriplesWriter(); wr.Save(myGraph, filePath); break; } } catch (Exception ex) { MySoapFault fault = new MySoapFault(); fault.Operation = "SaveToFile"; fault.Reason = "Error in saving datasource from graph to file ."; fault.Details = ex.Message; fault.MoreDetails = ex.StackTrace; throw new FaultException <MySoapFault>(fault); } }
/// <summary> /// Returns all metadata and the stored instances as graph. /// There are some adjustments to the data to make the metadata compatible with the Shacl validator. /// </summary> /// <returns></returns> private IGraph GetShapesGraph() { var shapes = _cacheService.GetOrAdd($"shapes-graph", () => { var store = new TripleStore(); var data = _metadataService.GetAllShaclAsGraph(); store.Add(data); ModifiyShapesForTargetClass(store); ModifyShapesForShaclClass(store); var dataGraph = store.Graphs.FirstOrDefault(t => t.BaseUri?.OriginalString == data.BaseUri.OriginalString); if (dataGraph == null) { throw new ArgumentNullException("Shapes graph is null"); } NTriplesWriter writer = new NTriplesWriter(NTriplesSyntax.Original); var shapes = VDS.RDF.Writing.StringWriter.Write(dataGraph, writer); return(shapes); }); var shapesGraph = new VDS.RDF.Graph(true); var reader = new StringReader(shapes); var nTriplesParser = new NTriplesParser(); nTriplesParser.Load(shapesGraph, reader); return(shapesGraph); }
public void mtest() { if (mtestRan > 0) { Warn("Running mtest() twice might expose some bugs with creating two instances of the same graph that will not be fixed this week!"); return; } mtestRan++; var g = NewGraph("mtest", UriOfMt("mtest"), true, false); g.BaseUri = UriFactory.Create(RoboKindURI); IUriNode dotNetRDF = g.CreateUriNode(UriFactory.Create("http://www.dotnetrdf.org")); IUriNode says = g.CreateUriNode(UriFactory.Create("http://example.org/says")); ILiteralNode helloWorld = g.CreateLiteralNode("Hello World"); ILiteralNode bonjourMonde = g.CreateLiteralNode("Bonjour tout le Monde", "fr"); rdfGraphAssert(g, MakeTriple(dotNetRDF, says, helloWorld)); rdfGraphAssert(g, MakeTriple(dotNetRDF, says, bonjourMonde)); foreach (Triple t in g.Triples) { ConsoleWriteLine(t.ToString()); ConsoleWriteLine("TRIPLE: triple(\"{0}\",\"{1}\",\"{2}\").", t.Subject.ToString(), t.Predicate.ToString(), t.Object.ToString()); } NTriplesWriter ntwriter = new NTriplesWriter(); ntwriter.Save(g, "HelloWorld.nt"); RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(g, "HelloWorld.rdf"); FindOrCreateKB("testRDF").SourceKind = ContentBackingStore.Prolog; if (RdfDeveloperSanityChecks < 3) { return; } rdfImportToKB(g, "testRDF", "SELECT * WHERE { ?s ?p ?o }", null); foreach (var nameAndEndp in new[] { //new[] {"http://budapest.rkbexplorer.com/sparql"}, new[] { "dbpedia", "http://dbpedia.org/sparql" }, // new[] {"josekiBooks", "http://cogserver:2020"}, // new[] {"cogPoint", "http://cogserver:8181"}, //new[] {"hebis", "http://lod.hebis.de/sparql"}, }) { string prefix = nameAndEndp[0]; string endp = nameAndEndp[1]; CreateTestTriangle(prefix, endp); } return; }
public string GetFormattedOutput(ref Graph graph, string outputFormat) { var writer = new System.IO.StringWriter(); if (outputFormat == "jsonLd") { var jsonLdWriter = new JsonLdWriter(); var store = new TripleStore(); store.Add(graph); jsonLdWriter.Save(store, writer); } else { dynamic formattedWriter = new CompressingTurtleWriter(); if (outputFormat == "rdf/xml") { formattedWriter = new RdfXmlWriter(); } else if (outputFormat == "n triples") { formattedWriter = new NTriplesWriter(); } formattedWriter.Save(graph, writer); } return(writer.ToString()); }
public static void Main(String[] args) { Console.WriteLine(Environment.CurrentDirectory); Graph g = new Graph(); IUriNode dotNetRDF = g.CreateUriNode(new Uri("http://www.dotnetrdf.org")); IUriNode says = g.CreateUriNode(new Uri("http://example.org/says")); ILiteralNode helloWorld = g.CreateLiteralNode("Hello World"); ILiteralNode bonjourMonde = g.CreateLiteralNode("Bonjour tout le Monde", "fr"); g.Assert(new Triple(dotNetRDF, says, helloWorld)); g.Assert(new Triple(dotNetRDF, says, bonjourMonde)); foreach (Triple t in g.Triples) { Console.WriteLine(t.ToString()); } NTriplesWriter ntwriter = new NTriplesWriter(); ntwriter.Save(g, "HelloWorld.nt"); RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(g, "HelloWorld.rdf"); }
private void WriteMolecule(IAtomContainer mol) { Graph g = CreateCDKModel(); var convertor = new Convertor(g); convertor.Molecule2Model(mol); NTriplesWriter ntwriter = new NTriplesWriter(); ntwriter.Save(g, output); }
private void FailedPrecondition(string subject, bool subjectIsBNode, string predicate, bool predicateIsBNode, string obj, bool objIsBNode, bool isLiteral, string dataType, string langCode, string graphUri) { if (_failedPreconditionsWriter == null) { _failedPreconditionsWriter = new StringWriter(); _failedTriplesWriter = new NTriplesWriter(_failedPreconditionsWriter); } _failedTriplesWriter.Triple(subject, subjectIsBNode, predicate, predicateIsBNode, obj, objIsBNode, isLiteral, dataType, langCode, graphUri); FailedPreconditionCount++; }
public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context) { IServiceProvider serviceProvider = context.HttpContext.RequestServices; var response = context.HttpContext.Response; var graph = context.Object as IGraph; var writer = new NTriplesWriter(); var nt = StringWriter.Write(graph, writer); return(response.WriteAsync(nt)); }
/// <summary> /// Creates a new store based on the given template /// </summary> /// <param name="template">Template</param> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</param> /// <remarks> /// <para> /// Template must inherit from <see cref="BaseSesameTemplate"/> /// </para> /// </remarks> public virtual void CreateStore(IStoreTemplate template, AsyncStorageCallback callback, object state) { if (template is BaseSesameTemplate) { // First we need to store the template as a new context in the SYSTEM repository Dictionary <String, String> createParams = new Dictionary <string, string>(); BaseSesameTemplate sesameTemplate = (BaseSesameTemplate)template; if (template.Validate().Any()) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, new RdfStorageException("Template is not valid, call Validate() on the template to see the list of errors")), state); return; } IGraph g = sesameTemplate.GetTemplateGraph(); createParams.Add("context", sesameTemplate.ContextNode.ToString()); HttpWebRequest request = this.CreateRequest(this._repositoriesPrefix + SesameServer.SystemRepositoryID + "/statements", "*/*", "POST", createParams); request.ContentType = MimeTypesHelper.NTriples[0]; NTriplesWriter ntwriter = new NTriplesWriter(); this.EnsureSystemConnection(); this._sysConnection.SaveGraphAsync(request, ntwriter, g, (sender, args, st) => { if (args.WasSuccessful) { // Then we need to declare that said Context is of type rep:RepositoryContext Triple repoType = new Triple(sesameTemplate.ContextNode, g.CreateUriNode("rdf:type"), g.CreateUriNode("rep:RepositoryContext")); this._sysConnection.UpdateGraph(String.Empty, repoType.AsEnumerable(), null, (sender2, args2, st2) => { if (args.WasSuccessful) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, template), state); } else { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, StorageHelper.HandleError(args.Error, "creating a new Store in")), state); } }, st); } else { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, template, StorageHelper.HandleError(args.Error, "creating a new Store in")), state); } }, state); } else { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.CreateStore, template.ID, template, new RdfStorageException("Invalid template, templates must derive from BaseSesameTemplate")), state); } }
/// <summary> /// Deletes a Graph from the Sesame store /// </summary> /// <param name="graphUri">URI of the Graph to delete</param> public virtual void DeleteGraph(String graphUri) { try { HttpWebRequest request; HttpWebResponse response; Dictionary <String, String> serviceParams = new Dictionary <string, string>(); NTriplesWriter ntwriter = new NTriplesWriter(); if (!graphUri.Equals(String.Empty)) { serviceParams.Add("context", "<" + graphUri + ">"); } else { serviceParams.Add("context", "null"); } request = this.CreateRequest(this._repositoriesPrefix + this._store + "/statements", "*/*", "DELETE", serviceParams); #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugRequest(request); } #endif using (response = (HttpWebResponse)request.GetResponse()) { #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugResponse(response); } #endif //If we get here then the Delete worked OK response.Close(); } } catch (WebException webEx) { #if DEBUG if (Options.HttpDebugging) { if (webEx.Response != null) { Tools.HttpDebugResponse((HttpWebResponse)webEx.Response); } } #endif throw new RdfStorageException("A HTTP Error occurred while trying to delete a Graph from the Store", webEx); } }
/// <summary> /// has side effects! updates triplestore /// </summary> /// <param name="entity"></param> /// <param name="metadataProperties"></param> /// <returns></returns> public async Task <ValidationResult> ValidateEntity(Entity entity, IList <MetadataProperty> metadataProperties) { var resourceGraph = GetResourceGraph(entity, metadataProperties); var shapesGraph = GetShapesGraph(); var processor = new ShapesGraph(shapesGraph); var report = processor.Validate(resourceGraph); var validationResult = CreateValidationResult(report); NTriplesWriter rdfNTriplesWriter = new NTriplesWriter(); validationResult.Triples = VDS.RDF.Writing.StringWriter.Write(resourceGraph, rdfNTriplesWriter); return(await Task.FromResult(validationResult)); }
/// <summary> /// Creates a new Store based on the given template /// </summary> /// <param name="template">Template</param> /// <returns></returns> /// <remarks> /// <para> /// Templates must inherit from <see cref="BaseSesameTemplate"/> /// </para> /// </remarks> public virtual bool CreateStore(IStoreTemplate template) { if (template is BaseSesameTemplate) { try { Dictionary <String, String> createParams = new Dictionary <string, string>(); BaseSesameTemplate sesameTemplate = (BaseSesameTemplate)template; if (template.Validate().Any()) { throw new RdfStorageException("Template is not valid, call Validate() on the template to see the list of errors"); } IGraph g = sesameTemplate.GetTemplateGraph(); // Firstly we need to save the Repository Template as a new Context to Sesame createParams.Add("context", sesameTemplate.ContextNode.ToString()); HttpWebRequest request = this.CreateRequest(this._repositoriesPrefix + SesameServer.SystemRepositoryID + "/statements", "*/*", "POST", createParams); request.ContentType = MimeTypesHelper.NTriples[0]; NTriplesWriter ntwriter = new NTriplesWriter(); ntwriter.Save(g, new StreamWriter(request.GetRequestStream())); Tools.HttpDebugRequest(request); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { Tools.HttpDebugResponse(response); // If we get then it was OK response.Close(); } // Then we need to declare that said Context is of type rep:RepositoryContext Triple repoType = new Triple(sesameTemplate.ContextNode, g.CreateUriNode("rdf:type"), g.CreateUriNode("rep:RepositoryContext")); this.EnsureSystemConnection(); this._sysConnection.UpdateGraph(String.Empty, repoType.AsEnumerable(), null); return(true); } catch (WebException webEx) { throw StorageHelper.HandleHttpError(webEx, "creating a new Store in"); } } else { throw new RdfStorageException("Invalid template, templates must derive from BaseSesameTemplate"); } }
/// <summary> /// Obtiene los triples de un RDF /// </summary> /// <param name="pXMLRDF">XML RDF</param> /// <returns>Lista de triples</returns> public static List <string> GetTriplesFromRDF(XmlDocument pXMLRDF) { RohGraph g = new RohGraph(); g.LoadFromString(pXMLRDF.InnerXml, new RdfXmlParser()); System.IO.StringWriter sw = new System.IO.StringWriter(); NTriplesWriter nTriplesWriter = new NTriplesWriter(); nTriplesWriter.Save(g, sw); return(sw.ToString().Split("\n").ToList().Select(x => Regex.Replace( x, @"\\u(?<Value>[a-zA-Z0-9]{4})", m => { return ((char)int.Parse(m.Groups["Value"].Value, NumberStyles.HexNumber)).ToString(); })).ToList()); }
public void Triple(string subject, bool subjectIsBNode, string predicate, bool predicateIsBNode, string obj, bool objIsBNode, bool isLiteral, string dataType, string langCode, string graphUri) { Logging.LogDebug("Try and Match Precondition {0} {1} {2} {3} {4} {5} {6}", subject, predicate, obj, isLiteral, dataType, langCode, graphUri); var triples = _store.Match(subject, predicate, obj, isLiteral, dataType, langCode, graphUri).ToList(); if (triples.Count == 0) { if (_failedPreconditionsWriter == null) { _failedPreconditionsWriter = new StringWriter(); _failedTriplesWriter = new NTriplesWriter(_failedPreconditionsWriter); } _failedTriplesWriter.Triple(subject, subjectIsBNode, predicate, predicateIsBNode, obj, objIsBNode, isLiteral, dataType, langCode, graphUri); _failedTripleCount++; } }
private void SaveButton_Click(object sender, RoutedEventArgs e) { try { SparqlRemoteEndpoint sre = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql")); string query = QueryTextBox.Text; myGraph = sre.QueryWithResultGraph(query); NTriplesWriter wr = new NTriplesWriter(); wr.Save(myGraph, dbpeidaNtFileName); MessageBox.Show("Saved", "Done", MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { MessageBox.Show(ex.Message, "ERROR4", MessageBoxButton.OK, MessageBoxImage.Error); } }
/// <summary> /// https://github.com/dotnetrdf/dotnetrdf/wiki/UserGuide-Hello-World /// </summary> public void PlayWithHelloWorld() { IGraph g = CreateGraph(); // Console.ReadLine(); NTriplesWriter ntwriter = new NTriplesWriter(); ntwriter.Save(g, "HelloWorld.nt"); RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(g, "HelloWorld.rdf"); CompressingTurtleWriter turtleWriter = new CompressingTurtleWriter(); turtleWriter.Save(g, "HelloWorld.ttl"); }
public void HelloWorld() { //Fill in the code shown on this page here to build your hello world application Graph g = new Graph(); IUriNode dotNetRDF = g.CreateUriNode(UriFactory.Create("http://www.dotnetrdf.org")); IUriNode says = g.CreateUriNode(UriFactory.Create("http://example.org/says")); ILiteralNode helloWorld = g.CreateLiteralNode("Hello World"); ILiteralNode bonjourMonde = g.CreateLiteralNode("Bonjour tout le Monde", "fr"); g.Assert(new Triple(dotNetRDF, says, helloWorld)); g.Assert(new Triple(dotNetRDF, says, bonjourMonde)); Console.WriteLine(); Console.WriteLine("Raw Output"); Console.WriteLine(); foreach (Triple t in g.Triples) { Console.WriteLine(t.ToString()); } // RDF is written out using one of the Writer types. // Use the Save method on the graph to serialise the triples in // the specified format to the provided write. Console.WriteLine(); Console.WriteLine("NTriples"); Console.WriteLine(); NTriplesWriter ntwriter = new NTriplesWriter(); var sw = new System.IO.StringWriter(); ntwriter.Save(g, sw); Console.WriteLine(sw.ToString()); Console.WriteLine(); Console.WriteLine("RDF XML"); Console.WriteLine(); RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); sw = new System.IO.StringWriter(); rdfxmlwriter.Save(g, sw); Console.WriteLine(sw.ToString()); // view the Test Results output to see the different serialisations. }
/// <summary> /// Updates the underlying store with this as the new representation of the identified resource /// </summary> /// <param name="resourceUri">The resource for whom this is the representation</param> /// <param name="resourceDescription">The rdf xml document that describes the resource</param> public override void ApplyFragment(string resourceUri, XDocument resourceDescription) { try { var g = new Graph(); var rdfXmlParser = new RdfXmlParser(); rdfXmlParser.Load(g, new StringReader(resourceDescription.ToString())); var ntWriter = new NTriplesWriter(); var data = StringWriter.Write(g, ntWriter); var sparqlUpdate = ""; sparqlUpdate += "DELETE { GRAPH <" + GraphUri + "> { <" + resourceUri + "> ?x ?y }}"; sparqlUpdate += "USING <" + GraphUri + "> WHERE {<" + resourceUri + "> ?x ?y } ;"; sparqlUpdate += "INSERT DATA { GRAPH <" + GraphUri + "> { "; sparqlUpdate += data; sparqlUpdate += " }};"; // execute update var wr = WebRequest.Create(SparqlEndpoint) as HttpWebRequest; wr.ContentType = "application/sparql-update"; wr.Method = "POST"; var ds = wr.GetRequestStream(); var bytes = Encoding.ASCII.GetBytes(sparqlUpdate); ds.Write(bytes, 0, bytes.Length); var resp = wr.GetResponse() as HttpWebResponse; if (resp.StatusCode == HttpStatusCode.OK) { Logging.LogDebug("Update successful"); } else { Logging.LogDebug("Not a 200"); } resp.Close(); } catch (Exception ex) { Logging.LogError(1, "Unable to apply fragment for resourceUri {0} {1}", ex.Message, ex.StackTrace); } }
private void SaveGraphButton_Click(object sender, RoutedEventArgs e) { try { SaveFileDialog sfd = new SaveFileDialog(); sfd.InitialDirectory = Environment.CurrentDirectory; sfd.Filter = "RDF Files (*.rdf)|*.rdf|Turtle Files (*.ttl)|*.ttl|All Files (*.*)|*.*"; if (sfd.ShowDialog().Value) { string savePath = sfd.FileName; NTriplesWriter wr = new NTriplesWriter(); wr.Save(config.myGraph, savePath); MessageBox.Show("Your Current Graph Saved Successfully", "Save Graph", MessageBoxButton.OK, MessageBoxImage.Information); } } catch (Exception ex) { MessageBox.Show(ex.Message, "ERROR2", MessageBoxButton.OK, MessageBoxImage.Error); } }
public void ParsingSuiteRdfA10() { String[] wantOutput = { }; bool outputAll = false; String[] skipTests = { "0002.xhtml", "0003.xhtml", "0004.xhtml", "0005.xhtml", "0016.xhtml", "0022.xhtml", "0024.xhtml", "0028.xhtml", "0043.xhtml", "0044.xhtml", "0045.xhtml", "0095.xhtml", "0096.xhtml", "0097.xhtml", "0098.xhtml", "0122.xhtml", "0123.xhtml", "0124.xhtml", "0125.xhtml", "0126.xhtml" }; String[] skipCheck = { "0011.xhtml", "0092.xhtml", "0094.xhtml", "0100.xhtml", "0101.xhtml", "0102.xhtml", "0103.xhtml" }; String[] falseTests = { "0042.xhtml", "0086.xhtml", "0095.xhtml", "0096.xhtml", "0097.xhtml", "0107.xhtml", "0116.xhtml", "0122.xhtml", "0125.xhtml" }; try { int testsPassed = 0; int testsFailed = 0; String[] files = Directory.GetFiles("resources\\rdfa\\"); RdfAParser parser = new RdfAParser(RdfASyntax.AutoDetectLegacy); //XHtmlPlusRdfAParser parser = new XHtmlPlusRdfAParser(); parser.Warning += parser_Warning; SparqlQueryParser queryparser = new SparqlQueryParser(); bool passed, passDesired; Graph g = new Graph(); Stopwatch timer = new Stopwatch(); long totalTime = 0; long totalTriples = 0; foreach (String file in files) { timer.Reset(); if (skipTests.Contains(Path.GetFileName(file))) { _testOutputHelper.WriteLine("## Skipping Test of File " + Path.GetFileName(file)); _testOutputHelper.WriteLine(""); continue; } if (Path.GetExtension(file) != ".html" && Path.GetExtension(file) != ".xhtml") { continue; } _testOutputHelper.WriteLine("## Testing File " + Path.GetFileName(file)); _testOutputHelper.WriteLine("# Test Started at " + DateTime.Now); passed = false; passDesired = true; try { g = new Graph { BaseUri = new Uri("http://www.w3.org/2006/07/SWD/RDFa/testsuite/xhtml1-testcases/" + Path.GetFileName(file)) }; if (Path.GetFileNameWithoutExtension(file).StartsWith("bad")) { passDesired = false; _testOutputHelper.WriteLine("# Desired Result = Parsing Failed"); } else { _testOutputHelper.WriteLine("# Desired Result = Parses OK"); } timer.Start(); parser.Load(g, file); timer.Stop(); _testOutputHelper.WriteLine("Parsing took " + timer.ElapsedMilliseconds + "ms"); passed = true; _testOutputHelper.WriteLine("Parsed OK"); if (outputAll || wantOutput.Contains(Path.GetFileName(file))) { NTriplesWriter writer = new NTriplesWriter(); writer.Save(g, "rdfa_tests\\" + Path.GetFileNameWithoutExtension(file) + ".out"); } } catch (IOException ioEx) { reportError("IO Exception", ioEx); } catch (RdfParseException parseEx) { reportError("Parsing Exception", parseEx); } catch (RdfException rdfEx) { reportError("RDF Exception", rdfEx); } catch (Exception ex) { reportError("Other Exception", ex); } finally { timer.Stop(); //Write the Triples to the Output foreach (Triple t in g.Triples) { _testOutputHelper.WriteLine(t.ToString()); } //Now we run the Test SPARQL (if present) if (File.Exists("rdfa_tests/" + Path.GetFileNameWithoutExtension(file) + ".sparql")) { if (skipCheck.Contains(Path.GetFileName(file))) { _testOutputHelper.WriteLine("## Skipping Check of File " + Path.GetFileName(file)); _testOutputHelper.WriteLine(""); } else { try { SparqlQuery q = queryparser.ParseFromFile("rdfa_tests/" + Path.GetFileNameWithoutExtension(file) + ".sparql"); Object results = g.ExecuteQuery(q); if (results is SparqlResultSet) { //The Result is the result of the ASK Query if (falseTests.Contains(Path.GetFileName(file))) { passed = !((SparqlResultSet)results).Result; } else { passed = ((SparqlResultSet)results).Result; } } } catch { passed = false; } } } if (passed && passDesired) { //Passed and we wanted to Pass testsPassed++; _testOutputHelper.WriteLine("# Result = Test Passed"); totalTime += timer.ElapsedMilliseconds; totalTriples += g.Triples.Count; } else if (!passed && passDesired) { //Failed when we should have Passed testsFailed++; _testOutputHelper.WriteLine("# Result = Test Failed"); } else if (passed && !passDesired) { //Passed when we should have Failed testsFailed++; _testOutputHelper.WriteLine("# Result = Test Failed"); } else { //Failed and we wanted to Fail testsPassed++; _testOutputHelper.WriteLine("# Result = Test Passed"); } _testOutputHelper.WriteLine("# Triples Generated = " + g.Triples.Count()); _testOutputHelper.WriteLine("# Test Ended at " + DateTime.Now); } _testOutputHelper.WriteLine(""); } _testOutputHelper.WriteLine(testsPassed + " Tests Passed"); _testOutputHelper.WriteLine(testsFailed + " Tests Failed"); _testOutputHelper.WriteLine(""); _testOutputHelper.WriteLine($"Total Parsing Time was {totalTime} ms"); if (totalTime > 1000) { _testOutputHelper.WriteLine(" (" + totalTime / 1000d + " seconds)"); } _testOutputHelper.WriteLine("Average Parsing Speed was " + totalTriples / (totalTime / 1000d) + " triples/second"); if (testsFailed > 0) { Assert.True(false, testsFailed + " Tests Failed"); } } catch (Exception ex) { reportError("Other Exception", ex); throw; } }
/// <summary> /// Saves a Graph into the Store (Warning: Completely replaces any existing Graph with the same URI unless there is no URI - see remarks for details) /// </summary> /// <param name="g">Graph to save</param> /// <remarks> /// If the Graph has no URI then the contents will be appended to the Store, if the Graph has a URI then existing data associated with that URI will be replaced /// </remarks> public virtual void SaveGraph(IGraph g) { try { HttpWebRequest request; Dictionary <String, String> serviceParams = new Dictionary <string, string>(); if (g.BaseUri != null) { if (this._fullContextEncoding) { serviceParams.Add("context", "<" + g.BaseUri.ToString() + ">"); } else { serviceParams.Add("context", g.BaseUri.ToString()); } request = this.CreateRequest(this._repositoriesPrefix + this._store + "/statements", "*/*", "PUT", serviceParams); } else { request = this.CreateRequest(this._repositoriesPrefix + this._store + "/statements", "*/*", "POST", serviceParams); } request.ContentType = MimeTypesHelper.NTriples[0]; NTriplesWriter ntwriter = new NTriplesWriter(); ntwriter.Save(g, new StreamWriter(request.GetRequestStream())); //request.ContentType = MimeTypesHelper.RdfXml[0]; //RdfXmlWriter writer = new RdfXmlWriter(); //writer.Save(g, new StreamWriter(request.GetRequestStream())); #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugRequest(request); } #endif using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugResponse(response); } #endif //If we get then it was OK response.Close(); } } catch (WebException webEx) { #if DEBUG if (Options.HttpDebugging) { if (webEx.Response != null) { Tools.HttpDebugResponse((HttpWebResponse)webEx.Response); } } #endif throw new RdfStorageException("A HTTP Error occurred while trying to save a Graph to the Store", webEx); } }
public void Dispose() { //Create all of the directories required for the file var f = new FileInfo(_outputPath); f.Directory.Create(); if (this._outputFormat == ERdfFormat.RdfXml) { using (XmlTextWriter xmlWriter = new XmlTextWriter(_outputPath, new UTF8Encoding(false))) //Set encoding { _output.Save(xmlWriter); } } else if (this._outputFormat == ERdfFormat.TriG) { string fileNameAsTrig = GetFilePathBasedOnFormat(); var outparams = new StreamParams(fileNameAsTrig); outparams.Encoding = Encoding.UTF8; var writer = new TriGWriter(); if (_store == null) { var g = GetXmlDocumentAsGraph(); _store = new TripleStore(); _store.Add(g, true); } writer.Save(_store, outparams); } else if (this._outputFormat == ERdfFormat.Turtle) { var g = GetXmlDocumentAsGraph(); string filePathForFormat = GetFilePathBasedOnFormat(); var writer = new TurtleWriter(TurtleSyntax.W3C); writer.Save(g, filePathForFormat); } else if (this._outputFormat == ERdfFormat.NTriples) { var g = GetXmlDocumentAsGraph(); string filePathForFormat = GetFilePathBasedOnFormat(); var writer = new NTriplesWriter(); writer.Save(g, filePathForFormat); } else if (this._outputFormat == ERdfFormat.N3) { var g = GetXmlDocumentAsGraph(); string filePathForFormat = GetFilePathBasedOnFormat(); var writer = new Notation3Writer(); writer.Save(g, filePathForFormat); } else if (this._outputFormat == ERdfFormat.NQuads) { string filePathForFormat = GetFilePathBasedOnFormat(); var outparams = new StreamParams(filePathForFormat); outparams.Encoding = Encoding.UTF8; if (_store == null) { var g = GetXmlDocumentAsGraph(); _store = new TripleStore(); _store.Add(g, true); } var writer = new NQuadsWriter(); writer.Save(_store, outparams); } //make sure it's not null - can happen if no graphs have yet to be asserted!! if (_store != null) { foreach (var graph in _store.Graphs) { graph.Dispose(); } _store.Dispose(); GC.Collect(); } }
public Hashtable Validate() { string content = HttpContext.Current.Request.Form["content"]; string format = HttpContext.Current.Request.Form["format"]; if (content == null || content.Trim() == "" || format == null) { HttpContext.Current.Response.Redirect("index.xpd"); throw new InvalidOperationException(); } StringWriter output = new StringWriter(); RdfReader reader; RdfWriter writer; Hashtable response = new Hashtable(); response["InDocument"] = AddLineNumbers(content); if (format == "xml") { reader = new RdfXmlReader(new StringReader(content)); writer = new N3Writer(output); response["InFormat"] = "RDF/XML"; response["OutFormat"] = "Notation 3"; } else if (format == "n3") { reader = new N3Reader(new StringReader(content)); writer = new RdfXmlWriter(output); response["OutFormat"] = "RDF/XML"; response["InFormat"] = "Notation 3"; } else { throw new Exception("Invalid format."); } response["Validation"] = "Syntax validated OK."; response["OutDocument"] = ""; response["Triples"] = ""; MemoryStore data = new MemoryStore(); try { data.Import(reader); } catch (Exception e) { response["Validation"] = "Validation failed: " + e.Message + "."; return(response); } finally { if (reader.Warnings.Count > 0) { response["Validation"] += " There were warnings: "; foreach (string warning in reader.Warnings) { response["Validation"] += " " + warning + "."; } } } writer.Namespaces.AddFrom(reader.Namespaces); try { writer.Write(data); writer.Close(); response["OutDocument"] = output.ToString(); } catch (Exception e) { response["OutDocument"] = e.Message; } StringWriter triplesoutput = new StringWriter(); using (NTriplesWriter tripleswriter = new NTriplesWriter(triplesoutput)) { tripleswriter.Write(data); } response["Triples"] = triplesoutput.ToString(); return(response); }
/// <summary> /// Updates a Graph /// </summary> /// <param name="graphUri">Uri of the Graph to update</param> /// <param name="additions">Triples to be added</param> /// <param name="removals">Triples to be removed</param> public virtual void UpdateGraph(String graphUri, IEnumerable <Triple> additions, IEnumerable <Triple> removals) { try { HttpWebRequest request; HttpWebResponse response; Dictionary <String, String> serviceParams = new Dictionary <string, string>(); NTriplesWriter ntwriter = new NTriplesWriter(); //RdfXmlWriter writer = new RdfXmlWriter(); if (!graphUri.Equals(String.Empty)) { serviceParams.Add("context", "<" + graphUri + ">"); } else { serviceParams.Add("context", "null"); } if (removals != null) { if (removals.Any()) { serviceParams.Add("subj", null); serviceParams.Add("pred", null); serviceParams.Add("obj", null); //Have to do a DELETE for each individual Triple foreach (Triple t in removals.Distinct()) { this._output.Remove(0, this._output.Length); serviceParams["subj"] = this._formatter.Format(t.Subject); serviceParams["pred"] = this._formatter.Format(t.Predicate); serviceParams["obj"] = this._formatter.Format(t.Object); request = this.CreateRequest(this._repositoriesPrefix + this._store + "/statements", "*/*", "DELETE", serviceParams); #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugRequest(request); } #endif using (response = (HttpWebResponse)request.GetResponse()) { #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugResponse(response); } #endif //If we get here then the Delete worked OK response.Close(); } } serviceParams.Remove("subj"); serviceParams.Remove("pred"); serviceParams.Remove("obj"); } } if (additions != null) { if (additions.Any()) { //Add the new Triples request = this.CreateRequest(this._repositoriesPrefix + this._store + "/statements", "*/*", "POST", serviceParams); Graph h = new Graph(); h.Assert(additions); request.ContentType = MimeTypesHelper.NTriples[0]; ntwriter.Save(h, new StreamWriter(request.GetRequestStream())); //request.ContentType = MimeTypesHelper.RdfXml[0]; //writer.Save(h, new StreamWriter(request.GetRequestStream())); #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugRequest(request); } #endif using (response = (HttpWebResponse)request.GetResponse()) { #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugResponse(response); } #endif //If we get then it was OK response.Close(); } } } } catch (WebException webEx) { #if DEBUG if (Options.HttpDebugging) { if (webEx.Response != null) { Tools.HttpDebugResponse((HttpWebResponse)webEx.Response); } } #endif throw new RdfStorageException("A HTTP Error occurred while trying to update a Graph in the Store", webEx); } }
public void ExportNTriples(string filename) { var writer = new NTriplesWriter(); writer.Save(Graph, filename); }