public static void Main(String[] args) { //Fill in the code shown on this page here to build your hello world application 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"); }
public Stream ExecuteQuery(string queryExpression, IList <string> datasetGraphUris) { var parser = new SparqlQueryParser(); var query = parser.ParseFromString(queryExpression); var sparqlResults = _queryProcessor.ProcessQuery(query); var memoryStream = new MemoryStream(); using (var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8)) { if (sparqlResults is SparqlResultSet) { var resultSet = sparqlResults as SparqlResultSet; var writer = new SparqlXmlWriter(); writer.Save(resultSet, streamWriter); } else if (sparqlResults is IGraph) { var g = sparqlResults as IGraph; var writer = new RdfXmlWriter(); writer.Save(g, streamWriter); } } return(new MemoryStream(memoryStream.ToArray())); //return new MemoryStream(Encoding.UTF8.GetBytes(buff.ToString()), false); }
public void WriteToFile(IGraph graph, String path) { logger.LogFunction("WriteToFile"); RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(graph, path); }
public static void Main(String[] args) { //Fill in the code shown on this page here to build your hello world application 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"); }
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 void WriteSchema() { var writer = new RdfXmlWriter(); string path = @"E:\3 курс\WeB\Lab4\RDF_Lab4\StaticFiles\rabotaSchema.rdf"; writer.Save(_graph, path); }
public void WriteGraph(IGraph g) { var writer = new RdfXmlWriter(); string path = @"E:\3 курс\WeB\Lab4\RDF_Lab4\StaticFiles\rabota.rdf"; writer.Save(g, path); }
public void ParsingBaseUriAssignmentRdfXml() { Graph g = new Graph(); g.BaseUri = new Uri("http://example.org/RdfXml"); System.IO.StringWriter strWriter = new System.IO.StringWriter(); RdfXmlWriter writer = new RdfXmlWriter(); writer.Save(g, strWriter); Console.WriteLine("Original Base URI: " + ShowBaseUri(g.BaseUri)); Console.WriteLine("Output using RdfXmlWriter:"); Console.WriteLine(strWriter.ToString()); Console.WriteLine(); Graph h = new Graph(); RdfXmlParser parser = new RdfXmlParser(); parser.Load(h, new System.IO.StringReader(strWriter.ToString())); Console.WriteLine("Base URI after round-trip using RdfXmlWriter: " + ShowBaseUri(h.BaseUri)); Assert.IsNotNull(h.BaseUri, "Base URI should not be null"); }
protected void createrdf(string filename) { Graph g = new Graph(); Session["ggraph"] = g; RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(g, path_user + filename + ".rdf"); }
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"); }
public void Save() { logger.LogFunction("WriteToFile"); RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(situation, path); }
public static void WriteGraph(IGraph graph) { lock (Locks.GetLock((object)"rdflock")) { var rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(graph, RdfFilePath); } }
/// <summary> /// Obtiene el RDF del dataGraph /// </summary> /// <returns></returns> public string GetDataGraphRDF() { System.IO.StringWriter sw = new System.IO.StringWriter(); RdfXmlWriter rdfXmlWriter = new RdfXmlWriter(); rdfXmlWriter.Save(dataGraph, sw); return(sw.ToString()); }
public void SaveOntology(string path) { //Assume that the Graph to be saved has already been loaded into a Ontology Propertie RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); //Save to a File rdfxmlwriter.Save(Ontology, path); }
protected void createPublic() { Graph g = new Graph(); Session["ugraph"] = g; RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(g, path_public); }
protected void addRDFTriple() { var list = (List <string[]>)Session["PersonalList"]; int numberOfRows = 0; if (list.Count() > 0) { numberOfRows = int.Parse(list[list.Count() - 1][0].ToString().Split('/')[6].ToString()); } for (int cv01 = 0; cv01 < list.Count; cv01++) { if (numberOfRows < int.Parse(list[cv01][0].ToString().Split('/')[6].ToString())) { numberOfRows = int.Parse(list[cv01][0].ToString().Split('/')[6].ToString()); } } //System.Diagnostics.Debug.WriteLine(list.Count() + " " + numberOfRows); //int numberOfRows = GridView2.Rows.Count; numberOfRows++; String dataid = numberOfRows.ToString(); Session["Sdataid"] = dataid; Graph g = (Graph)Session["ggraph"]; var g = new Graph(); IUriNode personID = g.CreateUriNode(UriFactory.Create("http://www.phonebook.co.uk/Person/" + numberOfRows)); IUriNode Title = g.CreateUriNode(UriFactory.Create("http://xmlns.com/foaf/0.1/Title")); IUriNode Name = g.CreateUriNode(UriFactory.Create("http://xmlns.com/foaf/0.1/Name")); IUriNode Surname = g.CreateUriNode(UriFactory.Create("http://xmlns.com/foaf/0.1/Surname")); IUriNode Email = g.CreateUriNode(UriFactory.Create("http://xmlns.com/foaf/0.1/Email")); IUriNode Phone = g.CreateUriNode(UriFactory.Create("http://xmlns.com/foaf/0.1/Phone")); IUriNode Comments = g.CreateUriNode(UriFactory.Create("http://xmlns.com/foaf/0.1/Comments")); ILiteralNode NTitle = g.CreateLiteralNode(Session["Stitle"].ToString()); ILiteralNode NName = g.CreateLiteralNode(Session["Sname"].ToString()); ILiteralNode NSurname = g.CreateLiteralNode(Session["Ssurname"].ToString()); ILiteralNode NEmail = g.CreateLiteralNode(Session["Semail"].ToString().Split('>')[1].Split('<')[0].ToString()); ILiteralNode NPhone = g.CreateLiteralNode(Session["Snumber"].ToString()); ILiteralNode NComments = g.CreateLiteralNode(" "); g.Assert(personID, Title, NTitle); g.Assert(personID, Name, NName); g.Assert(personID, Surname, NSurname); g.Assert(personID, Email, NEmail); g.Assert(personID, Phone, NPhone); g.Assert(personID, Comments, NComments); RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(g, "C:/Users/panayiotis/master/MSC PROJECT/db/" + Session["UserId"].ToString() + ".rdf"); }
/// <summary> /// Saves a Graph to the Protocol Server /// </summary> /// <param name="g">Graph to save</param> public virtual void SaveGraph(IGraph g) { String saveUri = this._serviceUri; if (g.BaseUri != null) { saveUri += "?graph=" + Uri.EscapeDataString(g.BaseUri.ToString()); } else { saveUri += "?default"; } try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(UriFactory.Create(saveUri)); request.Method = "PUT"; request.ContentType = MimeTypesHelper.RdfXml[0]; request = base.GetProxiedRequest(request); 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 here 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 StorageSparqlUniformHttpProtocolPostCreateMultiple() { SparqlHttpProtocolConnector connector = SparqlGraphStoreProtocolTest.GetConnection(); Graph g = new Graph(); FileLoader.Load(g, "resources\\InferenceTest.ttl"); List <Uri> uris = new List <Uri>(); for (int i = 0; i < 10; i++) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(TestConfigManager.GetSetting(TestConfigManager.LocalGraphStoreUri)); request.Method = "POST"; request.ContentType = "application/rdf+xml"; using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) { RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(g, writer); writer.Close(); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { //Should get a 201 Created response if (response.StatusCode == HttpStatusCode.Created) { if (response.Headers["Location"] == null) { Assert.Fail("A Location: Header containing the URI of the newly created Graph should have been returned"); } Uri graphUri = new Uri(response.Headers["Location"]); uris.Add(graphUri); Console.WriteLine("New Graph URI is " + graphUri.ToString()); Console.WriteLine("Now attempting to retrieve this Graph from the Store"); Graph h = new Graph(); connector.LoadGraph(h, graphUri); Assert.AreEqual(g, h, "Graphs should have been equal"); Console.WriteLine("Graphs were equal as expected"); } else { Assert.Fail("A 201 Created response should have been received but got a " + (int)response.StatusCode + " response"); } response.Close(); } Console.WriteLine(); } Assert.IsTrue(uris.Distinct().Count() == 10, "Should have generated 10 distinct URIs"); }
protected void addUserInRDF() { var list = (List <string[]>)Session["UserList"]; int numberOfRows = 0; if (list.Count() > 0) { numberOfRows = int.Parse(list[list.Count() - 1][0].ToString().Split('/')[4].ToString()); } for (int cv01 = 0; cv01 < list.Count; cv01++) { if (numberOfRows < int.Parse(list[cv01][0].ToString().Split('/')[4].ToString())) { numberOfRows = int.Parse(list[cv01][0].ToString().Split('/')[4].ToString()); } } //System.Diagnostics.Debug.WriteLine(list.Count() + " " + numberOfRows); //int numberOfRows = GridView2.Rows.Count; numberOfRows++; String dataid = numberOfRows.ToString(); Session["Sdataid"] = dataid; Graph g = (Graph)Session["ugraph"]; g.NamespaceMap.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/0.1/")); IUriNode Username = g.CreateUriNode("foaf:accountName"); IUriNode rdftype = g.CreateUriNode("rdf:type"); //FOAFPERSON IUriNode foafPerson = g.CreateUriNode("foaf:OnlineAccount"); //FOAFPERSON IUriNode personID = g.CreateUriNode(UriFactory.Create("http://www.phonebook.co.uk/Person/" + numberOfRows)); ILiteralNode NUsername = g.CreateLiteralNode(Session["UserId"].ToString()); g.Assert(personID, Username, NUsername); g.Assert(personID, rdftype, foafPerson);//FOAFPERSON RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(g, path_public); LoadPersonalData(); }
public void Write(System.Xml.XmlWriter writer) { RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(0, false); System.IO.StringWriter tw = new System.IO.StringWriter(); System.Xml.XmlReader nr; rdfxmlwriter.Save(this, tw); string str = tw.ToString().Remove(0, @"<?xml version=""1.0"" encoding=""utf-16"">".Length + 3); nr = System.Xml.XmlNodeReader.Create(new System.IO.MemoryStream(System.Text.Encoding.Unicode.GetBytes(str))); writer.WriteNode(nr, true); }
private void GenerateRdfXmlFile(Uri subject, string targetPath, IGraph graph) { try { var rdfXmlTargetPath = targetPath + ".rdf"; var rdfWriter = new RdfXmlWriter(); rdfWriter.Save(graph, rdfXmlTargetPath); } catch (Exception ex) { _progressLog.Exception(ex, "Error generating RDF/XML file for subject {0}: {1}", subject, ex.Message); } }
/// <summary> /// https://github.com/dotnetrdf/dotnetrdf/wiki/UserGuide-Writing-RDF /// </summary> public void TesPlayWithWritingRdft() { #region Basic Usage IGraph g = CreateGraph(); //Assume that the Graph to be saved has already been loaded into a variable g RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); //Save to a File rdfxmlwriter.Save(g, "Example.rdf"); //Save to a Stream rdfxmlwriter.Save(g, Console.Out); #region Writing to Strings //Assume that the Graph to be saved has already been loaded into a variable g //RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); String data1 = VDS.RDF.Writing.StringWriter.Write(g, rdfxmlwriter); // or //Assume that the Graph to be saved has already been loaded into a variable g //RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); System.IO.StringWriter sw = new System.IO.StringWriter(); //Call the Save() method to write to the StringWriter rdfxmlwriter.Save(g, sw); //We can now retrieve the written RDF by using the ToString() method of the StringWriter String data2 = sw.ToString(); #endregion #endregion }
protected void addRDFTriple() { var list = (List<string[]>)Session["PersonalList"]; int numberOfRows = 0; if (list.Count() > 0) numberOfRows = int.Parse(list[list.Count() - 1][0].ToString().Split('/')[6].ToString()); for (int cv01 = 0; cv01 < list.Count; cv01++) { if (numberOfRows < int.Parse(list[cv01][0].ToString().Split('/')[6].ToString())) { numberOfRows = int.Parse(list[cv01][0].ToString().Split('/')[6].ToString()); } } //System.Diagnostics.Debug.WriteLine(list.Count() + " " + numberOfRows); //int numberOfRows = GridView2.Rows.Count; numberOfRows++; String dataid = numberOfRows.ToString(); Session["Sdataid"] = dataid; Graph g = (Graph)Session["ggraph"]; IUriNode personID = g.CreateUriNode(UriFactory.Create("http://www.phonebook.co.uk/Person/" + numberOfRows)); IUriNode Title = g.CreateUriNode(UriFactory.Create("http://xmlns.com/foaf/0.1/Title")); IUriNode Name = g.CreateUriNode(UriFactory.Create("http://xmlns.com/foaf/0.1/Name")); IUriNode Surname = g.CreateUriNode(UriFactory.Create("http://xmlns.com/foaf/0.1/Surname")); IUriNode Email = g.CreateUriNode(UriFactory.Create("http://xmlns.com/foaf/0.1/Email")); IUriNode Phone = g.CreateUriNode(UriFactory.Create("http://xmlns.com/foaf/0.1/Phone")); IUriNode Comments = g.CreateUriNode(UriFactory.Create("http://xmlns.com/foaf/0.1/Comments")); ILiteralNode NTitle = g.CreateLiteralNode(Session["Stitle"].ToString()); ILiteralNode NName = g.CreateLiteralNode(Session["Sname"].ToString()); ILiteralNode NSurname = g.CreateLiteralNode(Session["Ssurname"].ToString()); ILiteralNode NEmail = g.CreateLiteralNode(Session["Semail"].ToString().Split('>')[1].Split('<')[0].ToString()); ILiteralNode NPhone = g.CreateLiteralNode(Session["Snumber"].ToString()); ILiteralNode NComments = g.CreateLiteralNode(" "); g.Assert(personID, Title, NTitle); g.Assert(personID, Name, NName); g.Assert(personID, Surname, NSurname); g.Assert(personID, Email, NEmail); g.Assert(personID, Phone, NPhone); g.Assert(personID, Comments, NComments); RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(g, "C:/Users/panayiotis/master/MSC PROJECT/db/" + Session["UserId"].ToString() + ".rdf"); }
/// <summary> /// Updates a Graph on the Protocol Server /// </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> /// <remarks> /// <strong>Note:</strong> The SPARQL Graph Store HTTP Protocol for Graph Management only supports the addition of Triples to a Graph and does not support removal of Triples from a Graph. If you attempt to remove Triples then an <see cref="RdfStorageException">RdfStorageException</see> will be thrown /// </remarks> public virtual void UpdateGraph(string graphUri, IEnumerable <Triple> additions, IEnumerable <Triple> removals) { if (removals != null && removals.Any()) { throw new RdfStorageException("Unable to Update a Graph since this update requests that Triples be removed from the Graph which the SPARQL Graph Store HTTP Protocol for Graph Management does not support"); } if (additions == null || !additions.Any()) { return; } String updateUri = this._serviceUri; if (graphUri != null && !graphUri.Equals(String.Empty)) { updateUri += "?graph=" + Uri.EscapeDataString(graphUri); } else { updateUri += "?default"; } try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(UriFactory.Create(updateUri)); request.Method = "POST"; request.ContentType = MimeTypesHelper.RdfXml[0]; request = base.ApplyRequestOptions(request); RdfXmlWriter writer = new RdfXmlWriter(); Graph g = new Graph(); g.Assert(additions); writer.Save(g, new StreamWriter(request.GetRequestStream())); Tools.HttpDebugRequest(request); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { Tools.HttpDebugResponse(response); // If we get here then it was OK response.Close(); } } catch (WebException webEx) { throw StorageHelper.HandleHttpError(webEx, "updating a Graph in"); } }
/// <summary> /// Internal implementation of adding a Graphs content to the Store /// </summary> /// <param name="g">Graph to add to the Store</param> /// <param name="servicePath">Service at the Store to add to</param> private void AddInternal(IGraph g, String servicePath) { HttpWebRequest request = null; HttpWebResponse response = null; try { //Create the Request request = this.CreateRequest(servicePath, new Dictionary <string, string>()); request.Method = "POST"; request.ContentType = MimeTypesHelper.RdfXml[0]; //Write the RDF/XML to the Request Stream RdfXmlWriter writer = new RdfXmlWriter(); writer.Save(g, new StreamWriter(request.GetRequestStream())); #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugRequest(request); } #endif //Make the Request using (response = (HttpWebResponse)request.GetResponse()) { #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugResponse(response); } #endif //OK if we get here! response.Close(); } } catch (WebException webEx) { if (webEx.Response != null) { //Got a Response so we can analyse the Response Code response = (HttpWebResponse)webEx.Response; int code = (int)response.StatusCode; throw Error(code, webEx); } //Didn't get a Response throw; } }
public void StorageSparqlUniformHttpProtocolPostCreate() { SparqlHttpProtocolConnector connector = SparqlGraphStoreProtocolTest.GetConnection(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(TestConfigManager.GetSetting(TestConfigManager.LocalGraphStoreUri)); request.Method = "POST"; request.ContentType = "application/rdf+xml"; Graph g = new Graph(); FileLoader.Load(g, "resources\\InferenceTest.ttl"); using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) { RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(g, writer); writer.Close(); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { //Should get a 201 Created response if (response.StatusCode == HttpStatusCode.Created) { if (response.Headers["Location"] == null) { Assert.True(false, "A Location: Header containing the URI of the newly created Graph should have been returned"); } Uri graphUri = new Uri(response.Headers["Location"]); Console.WriteLine("New Graph URI is " + graphUri.ToString()); Console.WriteLine("Now attempting to retrieve this Graph from the Store"); Graph h = new Graph(); connector.LoadGraph(h, graphUri); TestTools.ShowGraph(h); Assert.Equal(g, h); } else { Assert.True(false, "A 201 Created response should have been received but got a " + (int)response.StatusCode + " response"); } response.Close(); } }
public void TestWriteSimpleRdf() { var g = new Graph(); g.Assert(g.CreateUriNode(new Uri("http://example.org/s")), g.CreateUriNode(new Uri("http://example.org/p")), g.CreateLiteralNode("o")); //g.Assert(g.CreateUriNode(new Uri("http://example.org/s")), // g.CreateUriNode(new Uri("http://example.org/ns2/p")), // g.CreateLiteralNode("Another o")); using (var stringWriter = new System.IO.StringWriter()) { var writer = new RdfXmlWriter(); writer.Save(g, stringWriter); var buff = stringWriter.ToString(); XDocument doc = XDocument.Parse(buff); // Fails } }
static void Main(string[] args) { InitContext(); CreateThingsTopology(); IGraph g = new Graph(); IList graphList = store.Graphs.ToList(); foreach (IGraph currentGraph in graphList) { g.Merge(currentGraph); } RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(g, "C:\\output.rdf"); }
public void WritingSerializeOwnOneOf() { //Create the Graph for the Test and Generate a List of URIs Graph g = new Graph(); List<IUriNode> nodes = new List<IUriNode>(); for (int i = 1; i <= 10; i++) { nodes.Add(g.CreateUriNode(new Uri("http://example.org/Class" + i))); } //Use the thingOneOf to generate the Triples thingOneOf(g, nodes.ToArray()); //Dump as NTriples to the Console NTriplesFormatter formatter = new NTriplesFormatter(); foreach (Triple t in g.Triples) { Console.WriteLine(t.ToString(formatter)); } Console.WriteLine(); //Now try to save as RDF/XML IRdfWriter writer = new RdfXmlWriter(); writer.Save(g, "owl-one-of.rdf"); Console.WriteLine("Saved OK using RdfXmlWriter"); Console.WriteLine(); writer = new FastRdfXmlWriter(); writer.Save(g, "owl-one-of-fast.rdf"); Console.WriteLine("Saved OK using FastRdfXmlWriter"); Console.WriteLine(); //Now check that the Graphs are all equivalent Graph h = new Graph(); FileLoader.Load(h, "owl-one-of.rdf"); Assert.AreEqual(g, h, "Graphs should be equal (RdfXmlWriter)"); Console.WriteLine("RdfXmlWriter serialization was OK"); Console.WriteLine(); Graph j = new Graph(); FileLoader.Load(j, "owl-one-of-fast.rdf"); Assert.AreEqual(g, j, "Graphs should be equal (FastRdfXmlWriter)"); Console.WriteLine("FastRdfXmlWriter serialization was OK"); }
protected void addRDFTriple() { var list = (List <string[]>)Session["PersonalList"]; Graph g = (Graph)Session["ggraph"]; g.NamespaceMap.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/0.1/")); g.NamespaceMap.AddNamespace("rdfs", new Uri("http://www.w3.org/2000/01/rdf-schema#")); g.NamespaceMap.AddNamespace("v", new Uri("http://www.w3.org/2006/vcard/ns#")); IUriNode personID = g.CreateUriNode(UriFactory.Create(Session["Sdataid"].ToString())); IUriNode Title = g.CreateUriNode("foaf:title"); IUriNode Name = g.CreateUriNode("foaf:name"); IUriNode Surname = g.CreateUriNode("foaf:familyName"); IUriNode Email = g.CreateUriNode("foaf:mbox"); IUriNode Phone = g.CreateUriNode("foaf:phone"); IUriNode Faculty = g.CreateUriNode("rdfs:label"); IUriNode Comments = g.CreateUriNode("rdfs:comment"); IUriNode rdftype = g.CreateUriNode("rdf:type"); //FOAFPERSON IUriNode foafPerson = g.CreateUriNode("foaf:Person"); //FOAFPERSON ILiteralNode NTitle = g.CreateLiteralNode(Session["Stitle"].ToString()); ILiteralNode NName = g.CreateLiteralNode(Session["Sname"].ToString()); ILiteralNode NSurname = g.CreateLiteralNode(Session["Ssurname"].ToString()); IUriNode NPhone = g.CreateUriNode(UriFactory.Create("tel:" + Session["Snumber"].ToString())); IUriNode NEmail = g.CreateUriNode(UriFactory.Create("mailto:" + Session["Semail"].ToString().Split('>')[1].Split('<')[0].ToString())); ILiteralNode NFaculty = g.CreateLiteralNode(Session["Sfaculty"].ToString()); ILiteralNode NComments = g.CreateLiteralNode(" "); g.Assert(personID, Title, NTitle); g.Assert(personID, Name, NName); g.Assert(personID, Surname, NSurname); g.Assert(personID, Email, NEmail); g.Assert(personID, Phone, NPhone); g.Assert(personID, Faculty, NFaculty); g.Assert(personID, Comments, NComments); g.Assert(personID, rdftype, foafPerson); //FOAFPERSON RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(g, path_user + Session["UserId"].ToString() + ".rdf"); LoadPersonalData(); }
/// <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 TestWriteSimpleRdf() { var g = new Graph(); g.Assert(g.CreateUriNode(new Uri("http://example.org/s")), g.CreateUriNode(new Uri("http://example.org/p")), g.CreateLiteralNode("o")); //g.Assert(g.CreateUriNode(new Uri("http://example.org/s")), // g.CreateUriNode(new Uri("http://example.org/ns2/p")), // g.CreateLiteralNode("Another o")); using (var stringWriter = new StringWriter()) { var writer = new RdfXmlWriter(); writer.Save(g, stringWriter); var buff = stringWriter.ToString(); XDocument doc = XDocument.Parse(buff); // Fails } }
protected void addUserInRDF() { var list = (List<string[]>)Session["UserList"]; int numberOfRows = 0; if (list.Count() > 0) numberOfRows = int.Parse(list[list.Count() - 1][0].ToString().Split('/')[4].ToString()); for (int cv01 = 0; cv01 < list.Count; cv01++) { if (numberOfRows < int.Parse(list[cv01][0].ToString().Split('/')[4].ToString())) { numberOfRows = int.Parse(list[cv01][0].ToString().Split('/')[4].ToString()); } } //System.Diagnostics.Debug.WriteLine(list.Count() + " " + numberOfRows); //int numberOfRows = GridView2.Rows.Count; numberOfRows++; String dataid = numberOfRows.ToString(); Session["Sdataid"] = dataid; Graph g = (Graph)Session["ugraph"]; g.NamespaceMap.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/0.1/")); IUriNode Username = g.CreateUriNode("foaf:accountName"); IUriNode rdftype = g.CreateUriNode("rdf:type");//FOAFPERSON IUriNode foafPerson = g.CreateUriNode("foaf:OnlineAccount");//FOAFPERSON IUriNode personID = g.CreateUriNode(UriFactory.Create("http://www.phonebook.co.uk/Person/" + numberOfRows)); ILiteralNode NUsername = g.CreateLiteralNode(Session["UserId"].ToString()); g.Assert(personID, Username, NUsername); g.Assert(personID, rdftype, foafPerson);//FOAFPERSON RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(g, path_public); LoadPersonalData(); }
protected void addRDFTriple() { var list = (List<string[]>)Session["PersonalList"]; Graph g = (Graph)Session["ggraph"]; g.NamespaceMap.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/0.1/")); g.NamespaceMap.AddNamespace("rdfs", new Uri("http://www.w3.org/2000/01/rdf-schema#")); g.NamespaceMap.AddNamespace("v", new Uri("http://www.w3.org/2006/vcard/ns#")); IUriNode personID = g.CreateUriNode(UriFactory.Create(Session["Sdataid"].ToString())); IUriNode Title = g.CreateUriNode("foaf:title"); IUriNode Name = g.CreateUriNode("foaf:name"); IUriNode Surname = g.CreateUriNode("foaf:familyName"); IUriNode Email = g.CreateUriNode("foaf:mbox"); IUriNode Phone = g.CreateUriNode("foaf:phone"); IUriNode Faculty = g.CreateUriNode("rdfs:label"); IUriNode Comments = g.CreateUriNode("rdfs:comment"); IUriNode rdftype = g.CreateUriNode("rdf:type");//FOAFPERSON IUriNode foafPerson = g.CreateUriNode("foaf:Person");//FOAFPERSON ILiteralNode NTitle = g.CreateLiteralNode(Session["Stitle"].ToString()); ILiteralNode NName = g.CreateLiteralNode(Session["Sname"].ToString()); ILiteralNode NSurname = g.CreateLiteralNode(Session["Ssurname"].ToString()); IUriNode NPhone = g.CreateUriNode(UriFactory.Create("tel:" + Session["Snumber"].ToString())); IUriNode NEmail = g.CreateUriNode(UriFactory.Create("mailto:" + Session["Semail"].ToString().Split('>')[1].Split('<')[0].ToString())); ILiteralNode NFaculty = g.CreateLiteralNode(Session["Sfaculty"].ToString()); ILiteralNode NComments = g.CreateLiteralNode(" "); g.Assert(personID, Title, NTitle); g.Assert(personID, Name, NName); g.Assert(personID, Surname, NSurname); g.Assert(personID, Email, NEmail); g.Assert(personID, Phone, NPhone); g.Assert(personID, Faculty, NFaculty); g.Assert(personID, Comments, NComments); g.Assert(personID, rdftype, foafPerson); //FOAFPERSON RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(g, path_user + Session["UserId"].ToString() + ".rdf"); LoadPersonalData(); }
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> /// Saves a Graph to the Store /// </summary> /// <param name="g">Graph to save</param> public void SaveGraph(IGraph g) { HttpWebRequest request; Dictionary <String, String> requestParams = new Dictionary <string, string>(); if (g.BaseUri != null) { requestParams.Add("context", g.BaseUri.ToString()); request = this.CreateRequest("/statements", MimeTypesHelper.Any, "PUT", requestParams); } else { request = this.CreateRequest("/statements", MimeTypesHelper.Any, "POST", requestParams); } IRdfWriter rdfWriter = new RdfXmlWriter(); request.ContentType = MimeTypesHelper.RdfXml[0]; using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) { rdfWriter.Save(g, writer); writer.Close(); } #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 here then operation completed OK response.Close(); } }
public void ParsingBaseUriAssignmentRdfXml() { Graph g = new Graph(); g.BaseUri = new Uri("http://example.org/RdfXml"); System.IO.StringWriter strWriter = new System.IO.StringWriter(); RdfXmlWriter writer = new RdfXmlWriter(); writer.Save(g, strWriter); Console.WriteLine("Original Base URI: " + ShowBaseUri(g.BaseUri)); Console.WriteLine("Output using RdfXmlWriter:"); Console.WriteLine(strWriter.ToString()); Console.WriteLine(); Graph h = new Graph(); RdfXmlParser parser = new RdfXmlParser(); parser.Load(h, new System.IO.StringReader(strWriter.ToString())); Console.WriteLine("Base URI after round-trip using RdfXmlWriter: " + ShowBaseUri(h.BaseUri)); Assert.IsNotNull(h.BaseUri, "Base URI should not be null"); strWriter = new System.IO.StringWriter(); FastRdfXmlWriter fastWriter = new FastRdfXmlWriter(); fastWriter.Save(g, strWriter); Console.WriteLine("Output using FastRdfXmlWriter:"); Console.WriteLine(strWriter.ToString()); Console.WriteLine(); Graph i = new Graph(); parser.Load(i, new System.IO.StringReader(strWriter.ToString())); Console.WriteLine("Base URI after round-trip to FastRdfXmlWriter: " + ShowBaseUri(h.BaseUri)); Assert.IsNotNull(i.BaseUri, "Base URI should not be null"); }
public Stream ExecuteQuery(string queryExpression, IList<string> datasetGraphUris) { var parser = new SparqlQueryParser(); var query = parser.ParseFromString(queryExpression); var sparqlResults = _queryProcessor.ProcessQuery(query); var memoryStream = new MemoryStream(); using (var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8)) { if (sparqlResults is SparqlResultSet) { var resultSet = sparqlResults as SparqlResultSet; var writer = new SparqlXmlWriter(); writer.Save(resultSet, streamWriter); } else if (sparqlResults is IGraph) { var g = sparqlResults as IGraph; var writer = new RdfXmlWriter(); writer.Save(g, streamWriter); } } return new MemoryStream(memoryStream.ToArray()); //return new MemoryStream(Encoding.UTF8.GetBytes(buff.ToString()), false); }
/// <summary> /// Saves a Graph to the Protocol Server /// </summary> /// <param name="g">Graph to save</param> public virtual void SaveGraph(IGraph g) { String saveUri = this._serviceUri; if (g.BaseUri != null) { saveUri += "?graph=" + Uri.EscapeDataString(g.BaseUri.ToString()); } else { saveUri += "?default"; } try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(saveUri)); request.Method = "PUT"; 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 here 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 WriteToXML(IList<RDFTriple> triples, string outputFile) { Graph graph = CreateGraph(triples); var rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(graph, outputFile); }
/// <summary> /// Saves a Graph to the Store /// </summary> /// <param name="g">Graph to save</param> public void SaveGraph(IGraph g) { HttpWebRequest request; Dictionary<String, String> requestParams = new Dictionary<string, string>(); if (g.BaseUri != null) { requestParams.Add("context", g.BaseUri.ToString()); request = this.CreateRequest("/statements", MimeTypesHelper.Any, "PUT", requestParams); } else { request = this.CreateRequest("/statements", MimeTypesHelper.Any, "POST", requestParams); } IRdfWriter rdfWriter = new RdfXmlWriter(); request.ContentType = MimeTypesHelper.RdfXml[0]; using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) { rdfWriter.Save(g, writer); writer.Close(); } #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 here then operation completed OK response.Close(); } }
protected void RemoveFavorClick(object sender, EventArgs e) { GridViewRow gvRow = (GridViewRow)(sender as Control).Parent.Parent; int index = gvRow.RowIndex; DataTable dt2Datas = (DataTable)ViewState["dt2Datas"]; //delete from rdf Graph g = new Graph(); FileLoader.Load(g, path_user + Session["UserId"].ToString() + ".rdf"); string Title = dt2Datas.Rows[index]["Title"].ToString(); string Name = dt2Datas.Rows[index]["Name"].ToString(); string Surname = dt2Datas.Rows[index]["Surname"].ToString(); string Email = dt2Datas.Rows[index]["E-mail"].ToString(); Email = "mailto:" + Email; string Phone = dt2Datas.Rows[index]["Phone"].ToString(); Phone = "tel:" + Phone; string dataid = dt2Datas.Rows[index]["dataid"].ToString(); string Comments = dt2Datas.Rows[index]["Comments"].ToString(); string Faculty = dt2Datas.Rows[index]["Faculty"].ToString(); g.NamespaceMap.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/0.1/")); g.NamespaceMap.AddNamespace("rdfs", new Uri("http://www.w3.org/2000/01/rdf-schema#")); g.NamespaceMap.AddNamespace("v", new Uri("http://www.w3.org/2006/vcard/ns#")); IUriNode person = g.CreateUriNode(UriFactory.Create(dataid)); IUriNode ITitle = g.CreateUriNode("foaf:title"); IUriNode IName = g.CreateUriNode("foaf:name"); IUriNode ISurname = g.CreateUriNode("foaf:familyName"); IUriNode IEmail = g.CreateUriNode("foaf:mbox"); IUriNode IPhone = g.CreateUriNode("foaf:phone"); IUriNode IFaculty = g.CreateUriNode("rdfs:label"); IUriNode IComments = g.CreateUriNode("rdfs:comment"); IUriNode rdftype = g.CreateUriNode("rdf:type");//FOAFPERSON IUriNode foafPerson = g.CreateUriNode("foaf:Person");//FOAFPERSON // IUriNode NPhone = g.CreateUriNode(UriFactory.Create("tel:" + Session["Snumber"].ToString())); // IUriNode NEmail = g.CreateUriNode(UriFactory.Create("mailto:" + Session["Semail"].ToString().Split('>')[1].Split('<')[0].ToString())); g.Retract(person, ITitle, g.CreateLiteralNode(Title)); g.Retract(person, IName, g.CreateLiteralNode(Name)); g.Retract(person, ISurname, g.CreateLiteralNode(Surname)); g.Retract(person, IEmail, g.CreateUriNode(UriFactory.Create((Email)))); g.Retract(person, IPhone, g.CreateUriNode(UriFactory.Create((Phone)))); g.Retract(person, IComments, g.CreateLiteralNode(Comments)); g.Retract(person, IFaculty, g.CreateLiteralNode(Faculty)); g.Retract(new Triple(person, rdftype, foafPerson));//FOAFPERSON RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(g, path_user + Session["UserId"].ToString() + ".rdf"); //remove from datatable dt2Datas.Rows[index].Delete(); dt2Datas.AcceptChanges(); GridView2.DataSource = dt2Datas; GridView2.DataBind(); /* if (faculty.Equals(" ")) faculty = ""; else if (faculty.Contains("&")) faculty = faculty.Replace("&", "&"); */ if (GridView1.Enabled) { for (int rows = 0; rows < GridView1.Rows.Count; rows++) { //System.Diagnostics.Debug.WriteLine("AHA! AHAAAAAAAAA" + Phone + "=" + GridView1.Rows[rows].Cells[4].Text + "=" + GridView1.Rows[rows].Cells[5].Text.Replace(" ", "")); if ((Title == GridView1.Rows[rows].Cells[0].Text) &&//title (Name == GridView1.Rows[rows].Cells[1].Text) && //name (Surname == GridView1.Rows[rows].Cells[2].Text) &&//surname (Phone.Split(':')[1] == GridView1.Rows[rows].Cells[4].Text) && //phone (Email == GridView1.Rows[rows].Cells[3].Text.Split('=')[1].Split('>')[0]) &&//email ((Faculty == GridView1.Rows[rows].Cells[5].Text.Replace("&", "&")) || (Faculty == GridView1.Rows[rows].Cells[5].Text.Replace(" ", "")) ) //faculty */ ) { // System.Diagnostics.Debug.WriteLine("AHA! AHAAAAAAAAA" + rows); (GridView1.Rows[rows].FindControl("btnAddFavor") as Button).Enabled = true; } } } }
public override Stream GetFragment(string id, string contentType) { // need to see which definition we match ResourcePublishingDefinition definition = null; UriTemplateMatch match = null; foreach (var resourcePublishingDefinition in _publishingDefinitions) { var newuri = new Uri(id); match = resourcePublishingDefinition.UriTemplate.Match(resourcePublishingDefinition.ResourcePrefix, newuri); if (match != null) { definition = resourcePublishingDefinition; break; } } if (definition == null) { throw new Exception("Unable to find matching definition for uri " + id); } var sb = new StringBuilder(); foreach (var generationDefinition in definition.FragmentGenerationDefinitions) { try { var data = ExecuteQuery(_dataSourceConnectionString, generationDefinition.FragmentQuery.Replace("[[id]]", match.BoundVariables["id"])); foreach (DataRow row in data.Rows) { var dra = new DbDataRow(row); foreach (var line in generationDefinition.RdfTemplateLines) { var linePattern = new NTripleLinePattern(line); linePattern.GenerateNTriples(sb, dra, generationDefinition.GenericTemplateExcludeColumns, contentType.Equals("xml")); } } } catch (Exception ex) { Logging.LogError(1, "Error processing definition {0} {1} {2} {3}", ex.Message, generationDefinition.SnapshotQuery, _dataSourceConnectionString, ex.StackTrace); } } try { var g = new Graph(); var parser = new NTriplesParser(TokenQueueMode.SynchronousBufferDuringParsing); var triplesStr = sb.ToString(); parser.Load(g, new StringReader(triplesStr)); if (contentType.Equals("xml")) { var ms = new MemoryStream(); var sw = new StreamWriter(ms, Encoding.UTF8); var rdfxmlwriter = new RdfXmlWriter(); var strw = new System.IO.StringWriter(); rdfxmlwriter.Save(g, strw); var data = strw.ToString(); data = data.Replace("~~~2B~~~", "%2B"); data = data.Replace("~~~SLASH~~~", "%2F"); data = data.Replace("utf-16", "utf-8"); sw.Write(data); sw.Flush(); ms.Seek(0, SeekOrigin.Begin); return ms; } else { var ms = new MemoryStream(); var sw = new StreamWriter(ms); sw.Write(triplesStr); sw.Flush(); ms.Seek(0, SeekOrigin.Begin); return ms; } } catch (Exception ex) { Logging.LogError(1, "Error getting fragment {0} {1}", ex.Message, ex.StackTrace); throw; } }
/// <summary> /// Internal implementation of Updating a Store by POSTing a ChangeSet to it /// </summary> /// <param name="additions">Triples to be added</param> /// <param name="removals">Triples to be removed</param> /// <param name="servicePath">Service to post ChangeSet to</param> /// <returns></returns> private TalisUpdateResult UpdateInternal(IEnumerable<Triple> additions, IEnumerable<Triple> removals, String servicePath) { HttpWebRequest request = null; HttpWebResponse response = null; try { //Generate the ChangeSet Batch IGraph g = this.GenerateChangeSet(additions, removals); if (g == null) return TalisUpdateResult.NotRequired; //Null so no changes need persisting if (g.IsEmpty) return TalisUpdateResult.NotRequired; //Empty so no changes need persisting //Create the Request request = this.CreateRequest(servicePath, new Dictionary<string, string>()); request.Method = "POST"; request.ContentType = TalisChangeSetMIMEType; //Write the RDF/XML to the Request Stream RdfXmlWriter writer = new RdfXmlWriter(); writer.Save(g, new StreamWriter(request.GetRequestStream())); #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugRequest(request); } #endif //Make the Request using (response = (HttpWebResponse)request.GetResponse()) { #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugResponse(response); } #endif //What sort of Update Result did we get? int code = (int)response.StatusCode; response.Close(); if (code == 200 || code == 201) { return TalisUpdateResult.Synchronous; } else if (code == 202) { return TalisUpdateResult.Asynchronous; } else if (code == 204) { return TalisUpdateResult.Done; } else { return TalisUpdateResult.Unknown; } } } catch (WebException webEx) { if (webEx.Response != null) { //Got a Response so we can analyse the Response Code response = (HttpWebResponse)webEx.Response; int code = (int)response.StatusCode; throw Error(code, webEx); } //Didn't get a Response throw; } }
protected void GV2_RowUpdating(object sender, GridViewUpdateEventArgs e) { GridViewRow row = GridView2.Rows[e.RowIndex]; string UpdatedComments = ((TextBox)(row.Cells[7].Controls[0])).Text; if (UpdatedComments.Length > 30) { string script = "alert(\"Please use fewer than 30 letters for your comments\");"; ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true); return; } Graph g = new Graph(); FileLoader.Load(g, path_user + Session["UserId"].ToString() + ".rdf"); //Retrieve the table from the session object. DataTable dt2Datas = (DataTable)ViewState["dt2Datas"]; //Update the values. dt2Datas.Rows[row.DataItemIndex]["Comments"] = ((TextBox)(row.Cells[7].Controls[0])).Text; //RDF string Title = Session["STitle"].ToString(); string Name = Session["SName"].ToString(); string Surname = Session["SSurname"].ToString(); string Email = Session["SE-mail"].ToString(); Email = "mailto:" + Email; string Phone = Session["SPhone"].ToString(); Phone = "tel:" + Phone; string dataid = Session["Sdataid"].ToString(); string Comments = Session["SComments"].ToString(); string Faculty = Session["SFaculty"].ToString(); //System.Diagnostics.Debug.WriteLine(" Comments1=" + Comments); g.NamespaceMap.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/0.1/")); g.NamespaceMap.AddNamespace("rdfs", new Uri("http://www.w3.org/2000/01/rdf-schema#")); g.NamespaceMap.AddNamespace("v", new Uri("http://www.w3.org/2006/vcard/ns#")); IUriNode person = g.CreateUriNode(UriFactory.Create(dataid)); IUriNode ITitle = g.CreateUriNode("foaf:title"); IUriNode IName = g.CreateUriNode("foaf:name"); IUriNode ISurname = g.CreateUriNode("foaf:familyName"); IUriNode IEmail = g.CreateUriNode("foaf:mbox"); IUriNode IPhone = g.CreateUriNode("foaf:phone"); IUriNode IFaculty = g.CreateUriNode("rdfs:label"); IUriNode IComments = g.CreateUriNode("rdfs:comment"); IUriNode rdftype = g.CreateUriNode("rdf:type");//FOAFPERSON IUriNode foafPerson = g.CreateUriNode("foaf:Person");//FOAFPERSON g.Retract(person, ITitle, g.CreateLiteralNode(Title)); g.Retract(person, IName, g.CreateLiteralNode(Name)); g.Retract(person, ISurname, g.CreateLiteralNode(Surname)); g.Retract(person, IEmail, g.CreateUriNode(UriFactory.Create((Email)))); g.Retract(person, IPhone, g.CreateUriNode(UriFactory.Create((Phone)))); g.Retract(person, IComments, g.CreateLiteralNode(Comments)); g.Retract(person, IFaculty, g.CreateLiteralNode(Faculty)); g.Retract(person, rdftype, foafPerson); //FOAFPERSON RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(g, path_user + Session["UserId"].ToString() + ".rdf"); g.Assert(person, ITitle, g.CreateLiteralNode(Title)); g.Assert(person, IName, g.CreateLiteralNode(Name)); g.Assert(person, ISurname, g.CreateLiteralNode(Surname)); g.Assert(person, IEmail, g.CreateUriNode(UriFactory.Create((Email)))); g.Assert(person, IPhone, g.CreateUriNode(UriFactory.Create((Phone)))); g.Assert(person, IFaculty, g.CreateLiteralNode(Faculty)); g.Assert(person, rdftype, foafPerson); //FOAFPERSON g.Assert(person, IComments, g.CreateLiteralNode(UpdatedComments)); // System.Diagnostics.Debug.WriteLine(" Comments2=" + UpdatedComments); rdfxmlwriter.Save(g, path_user + Session["UserId"].ToString() + ".rdf"); LoadPersonalData(); //END RDF //Reset the edit index. GridView2.EditIndex = -1; GridView2.DataSource = dt2Datas; //Bind data to the GridView control. GridView2.DataBind(); //ViewState["dt2Datas"] = dt2Datas; }
public void StorageSparqlUniformHttpProtocolPostCreateMultiple() { SparqlHttpProtocolConnector connector = new SparqlHttpProtocolConnector("http://localhost/demos/server/"); Graph g = new Graph(); FileLoader.Load(g, "InferenceTest.ttl"); List<Uri> uris = new List<Uri>(); for (int i = 0; i < 10; i++) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/demos/server/"); request.Method = "POST"; request.ContentType = "application/rdf+xml"; using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) { RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(g, writer); writer.Close(); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { //Should get a 201 Created response if (response.StatusCode == HttpStatusCode.Created) { if (response.Headers["Location"] == null) Assert.Fail("A Location: Header containing the URI of the newly created Graph should have been returned"); Uri graphUri = new Uri(response.Headers["Location"]); uris.Add(graphUri); Console.WriteLine("New Graph URI is " + graphUri.ToString()); Console.WriteLine("Now attempting to retrieve this Graph from the Store"); Graph h = new Graph(); connector.LoadGraph(h, graphUri); Assert.AreEqual(g, h, "Graphs should have been equal"); Console.WriteLine("Graphs were equal as expected"); } else { Assert.Fail("A 201 Created response should have been received but got a " + (int)response.StatusCode + " response"); } response.Close(); } Console.WriteLine(); } Assert.IsTrue(uris.Distinct().Count() == 10, "Should have generated 10 distinct URIs"); }
static void DoProtocol(Dictionary<String, String> arguments) { String method; SparqlHttpProtocolConnector endpoint; bool verbose = arguments.ContainsKey("verbose") || arguments.ContainsKey("v"); if (verbose) Options.HttpDebugging = true; Options.UriLoaderCaching = !arguments.ContainsKey("nocache"); String dataFile; //First Argument must be HTTP Method if (arguments.ContainsKey("$1") && !arguments["$1"].Equals(String.Empty)) { method = arguments["$1"].ToUpper(); } else { Console.Error.WriteLine("soh: Error: First argument must be one of head, get, put or post - type soh --help for details"); Environment.Exit(-1); return; } try { if (arguments.ContainsKey("$2") && !arguments["$2"].Equals(String.Empty)) { endpoint = new SparqlHttpProtocolConnector(new Uri(arguments["$2"])); } else { Console.Error.WriteLine("soh: Error: Second argument is required and must be the Dataset URI"); Environment.Exit(-1); return; } } catch (UriFormatException uriEx) { Console.Error.WriteLine("soh: Error: Malformed SPARQL Endpoint URI"); Console.Error.WriteLine(uriEx.Message); Environment.Exit(-1); return; } if (verbose) Console.Error.WriteLine("soh: Connection to SPARQL Uniform HTTP Protocol endpoint created OK"); Uri graphUri; try { if (arguments.ContainsKey("$3") && !arguments["$3"].Equals(String.Empty)) { if (arguments["$3"].Equals("default")) { graphUri = null; if (verbose) Console.Error.WriteLine("soh: Graph URI for Protocol request is 'default' (indicates the default unnamed graph)"); } else { graphUri = new Uri(arguments["$3"]); if (verbose) Console.Error.WriteLine("soh: Graph URI for Protocol request is '" + graphUri.ToString() + "'"); } } else { Console.Error.WriteLine("soh: Error: Third argument is required and must be the Graph URI or default to indicate the default unnamed Graph"); Environment.Exit(-1); return; } } catch (UriFormatException uriEx) { Console.Error.WriteLine("soh: Error: Malformed Graph URI"); Console.Error.WriteLine(uriEx.Message); Environment.Exit(-1); return; } try { switch (method) { case "GET": if (arguments.ContainsKey("$4")) { Console.Error.WriteLine("soh: Error: Optional file argument for protocol mode is not permitted with the get method"); Environment.Exit(-1); return; } if (verbose) Console.Error.WriteLine("soh: Making a GET request to the Protocol endpoint"); Graph g = new Graph(); endpoint.LoadGraph(g, graphUri); if (verbose) Console.Error.WriteLine("soh: Received a Graph with " + g.Triples.Count + " Triples"); //Use users choice of output format otherwise RDF/XML MimeTypeDefinition definition = null; if (arguments.ContainsKey("accept")) { definition = MimeTypesHelper.GetDefinitions(arguments["accept"]).FirstOrDefault(d => d.CanWriteRdf); } if (definition != null) { Console.OutputEncoding = definition.Encoding; IRdfWriter writer = definition.GetRdfWriter(); writer.Save(g, new StreamWriter(Console.OpenStandardOutput(), definition.Encoding)); } else { if (arguments.ContainsKey("accept") && verbose) Console.Error.WriteLine("soh: Warning: You wanted output in format '" + arguments["accept"] + "' but dotNetRDF does not support this format so RDF/XML will be returned instead"); RdfXmlWriter rdfXmlWriter = new RdfXmlWriter(); rdfXmlWriter.Save(g, new StreamWriter(Console.OpenStandardOutput(), Encoding.UTF8)); } break; case "HEAD": if (arguments.ContainsKey("$4")) { Console.Error.WriteLine("soh: Error: Optional file argument for protocol mode is not permitted with the head method"); Environment.Exit(-1); return; } if (verbose) Console.Error.WriteLine("soh: Making a HEAD request to the Protocol endpoint"); bool exists = endpoint.GraphExists(graphUri); Console.WriteLine(exists.ToString().ToLower()); break; case "PUT": //Parse in the Graph to be PUT first if (arguments.ContainsKey("$4") && !arguments["$4"].Equals(String.Empty)) { dataFile = arguments["$4"]; } else { Console.Error.WriteLine("soh: Error: The file argument for protocol mode is required when using the put method"); Environment.Exit(-1); return; } Graph toPut = new Graph(); FileLoader.Load(toPut, dataFile); toPut.BaseUri = graphUri; if (verbose) { Console.Error.WriteLine("soh: Graph to be uploaded has " + toPut.Triples.Count + " Triples"); Console.Error.WriteLine("soh: Making a PUT request to the Protocol endpoint"); } endpoint.SaveGraph(toPut); Console.WriteLine("soh: Graph saved to Protocol endpoint OK"); break; case "POST": //Parse in the Graph to be PUT first if (arguments.ContainsKey("$4") && !arguments["$4"].Equals(String.Empty)) { dataFile = arguments["$4"]; } else { Console.Error.WriteLine("soh: Error: The file argument for protocol mode is required when using the post method"); Environment.Exit(-1); return; } Graph toPost = new Graph(); FileLoader.Load(toPost, dataFile); if (verbose) { Console.Error.WriteLine("soh: Graph to be uploaded has " + toPost.Triples.Count + " Triples"); Console.Error.WriteLine("soh: Making a POST request to the Protocol endpoint"); } endpoint.UpdateGraph(graphUri, toPost.Triples, null); Console.WriteLine("soh: Graph updated to Protocol endpoint OK"); break; case "DELETE": if (arguments.ContainsKey("$4")) { Console.Error.WriteLine("soh: Error: Optional file argument for protocol mode is not permitted with the head method"); Environment.Exit(-1); return; } endpoint.DeleteGraph(graphUri); Console.WriteLine("soh: Graph deleted from Protocol endpoint OK"); break; default: Console.Error.WriteLine("soh: Error: " + method + " is not a HTTP Method supported by this tool"); Environment.Exit(-1); return; } } catch (Exception ex) { Console.Error.WriteLine("soh: Error: Error processing HTTP Protocol request"); Console.Error.WriteLine(ex.Message); while (ex.InnerException != null) { Console.Error.WriteLine(); Console.Error.WriteLine(ex.InnerException.Message); Console.Error.WriteLine(ex.InnerException.StackTrace); ex = ex.InnerException; } Environment.Exit(-1); return; } }
public override Stream GetFragment(string id, string mimeType) { try { var g = new Graph(); // id is the url var odataQuery = id; var xmlReader = XmlReader.Create(odataQuery, new XmlReaderSettings() { CloseInput = true}); var syndicationItem = SyndicationItem.Load(xmlReader); xmlReader.Close(); if (syndicationItem != null) { // add the title g.Assert(g.CreateUriNode(new Uri(id)), g.CreateUriNode(new Uri(_rdfsNamespacePrefix + "label")), g.CreateLiteralNode(syndicationItem.Title.Text)); // process basic properties var xmlContent = syndicationItem.Content as XmlSyndicationContent; if (xmlContent != null) { var odataEntityXml = XDocument.Load(xmlContent.GetReaderAtContent()); // get properties var odataProperties = odataEntityXml.Descendants().Where(elem => elem.Name.Namespace.Equals(DataServicesNamespace)); foreach (var odataProperty in odataProperties) { var propertyName = odataProperty.Name.LocalName; var propertyValue = odataProperty.Value; // remove later propertyValue = propertyValue.Replace("ø", "ø"); propertyValue = propertyValue.Replace("å", "å"); propertyValue = propertyValue.Replace("&", ""); if (string.IsNullOrEmpty(propertyValue)) continue; // see if there is a data type if (odataProperty.Attribute(MetadataNamespace + "type") != null) { g.Assert(g.CreateUriNode(new Uri(id)), g.CreateUriNode(new Uri(_defaultSchemaNamespacePrefix + propertyName)), g.CreateLiteralNode(propertyValue, ConvertEdmToXmlSchemaDataType(odataProperty.Attribute(MetadataNamespace + "type").Value))); } else { g.Assert(g.CreateUriNode(new Uri(id)), g.CreateUriNode(new Uri(_defaultSchemaNamespacePrefix + propertyName)), g.CreateLiteralNode(propertyValue)); } } } } // add a instance-of relationship in to the graph for the entity foreach (var category in syndicationItem.Categories) { var term = _defaultSchemaNamespacePrefix + category.Name.Replace('.', '/'); g.Assert(g.CreateUriNode(new Uri(id)), g.CreateUriNode(new Uri(_rdfNamespacePrefix + "type")), g.CreateUriNode(new Uri(term))); } // process relationships var links = syndicationItem.Links.Where(l => l.RelationshipType.StartsWith(OdataRelationshipRelTypePrefix)); foreach (var syndicationLink in links) { // property name var propertyName = syndicationLink.RelationshipType.Substring(OdataRelationshipRelTypePrefix.Length); // go fetch the related entities // todo: we might look to use expand here but as there is no wildcard its a bit of a pain right now unless we pull the schema. // need to check if we need to load an entry or a feed IEnumerable<SyndicationItem> items = null; try { if (syndicationLink.MediaType.ToLower().Contains("type=entry")) { xmlReader = XmlReader.Create(id + "/" + propertyName, new XmlReaderSettings() { CloseInput = true}); items = new List<SyndicationItem>() {SyndicationItem.Load(xmlReader)}; xmlReader.Close(); } else { xmlReader = XmlReader.Create(id + "/" + propertyName, new XmlReaderSettings() { CloseInput = true}); items = SyndicationFeed.Load(xmlReader).Items; xmlReader.Close(); } } catch (Exception) { // log and carry on xmlReader.Close(); } if (items != null) { foreach (var item in items) { // predicate value g.Assert(g.CreateUriNode(new Uri(id)), g.CreateUriNode(new Uri(_defaultSchemaNamespacePrefix + propertyName)), g.CreateUriNode(new Uri(item.Id))); } } } // return data var rdfxmlwriter = new RdfXmlWriter(); var strw = new System.IO.StringWriter(); rdfxmlwriter.Save(g, strw); var data = strw.ToString(); data = data.Replace("utf-16", "utf-8"); var ms = new MemoryStream(); var sw = new StreamWriter(ms, Encoding.UTF8); sw.Write(data); sw.Flush(); ms.Seek(0, SeekOrigin.Begin); return ms; } catch(Exception ex) { Logging.LogError(1, "Unable to fetch fragment for {0}. {1} {2}", id, ex.Message, ex.StackTrace); } return null; }
/// <summary> /// Updates a Graph on the Protocol Server /// </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> /// <remarks> /// <strong>Note:</strong> The SPARQL Graph Store HTTP Protocol for Graph Management only supports the addition of Triples to a Graph and does not support removal of Triples from a Graph. If you attempt to remove Triples then an <see cref="RdfStorageException">RdfStorageException</see> will be thrown /// </remarks> public virtual void UpdateGraph(string graphUri, IEnumerable<Triple> additions, IEnumerable<Triple> removals) { if (removals != null && removals.Any()) throw new RdfStorageException("Unable to Update a Graph since this update requests that Triples be removed from the Graph which the SPARQL Graph Store HTTP Protocol for Graph Management does not support"); if (additions == null || !additions.Any()) return; String updateUri = this._serviceUri; if (graphUri != null && !graphUri.Equals(String.Empty)) { updateUri += "?graph=" + Uri.EscapeDataString(graphUri); } else { updateUri += "?default"; } try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(updateUri)); request.Method = "POST"; request.ContentType = MimeTypesHelper.RdfXml[0]; RdfXmlWriter writer = new RdfXmlWriter(); Graph g = new Graph(); g.Assert(additions); 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 here 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 Write(System.Xml.XmlWriter writer) { RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(0,false); System.IO.StringWriter tw = new System.IO.StringWriter(); System.Xml.XmlReader nr; rdfxmlwriter.Save(this,tw); string str = tw.ToString().Remove(0, @"<?xml version=""1.0"" encoding=""utf-16"">".Length+3); nr = System.Xml.XmlNodeReader.Create(new System.IO.MemoryStream(System.Text.Encoding.Unicode.GetBytes(str))); writer.WriteNode(nr, true); }
/// <summary> /// Internal implementation of adding a Graphs content to the Store /// </summary> /// <param name="g">Graph to add to the Store</param> /// <param name="servicePath">Service at the Store to add to</param> private void AddInternal(IGraph g, String servicePath) { HttpWebRequest request = null; HttpWebResponse response = null; try { //Create the Request request = this.CreateRequest(servicePath, new Dictionary<string, string>()); request.Method = "POST"; request.ContentType = MimeTypesHelper.RdfXml[0]; //Write the RDF/XML to the Request Stream RdfXmlWriter writer = new RdfXmlWriter(); writer.Save(g, new StreamWriter(request.GetRequestStream())); #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugRequest(request); } #endif //Make the Request using (response = (HttpWebResponse)request.GetResponse()) { #if DEBUG if (Options.HttpDebugging) { Tools.HttpDebugResponse(response); } #endif //OK if we get here! response.Close(); } } catch (WebException webEx) { if (webEx.Response != null) { //Got a Response so we can analyse the Response Code response = (HttpWebResponse)webEx.Response; int code = (int)response.StatusCode; throw Error(code, webEx); } //Didn't get a Response throw; } }