private static void SaveResults(MemoryStore store, Path file) { using (var writer = new RdfXmlWriter(file.FullPath)) writer.Write(store); Console.WriteLine("Wrote {0} statements.", store.StatementCount); }
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 newNamespacesAreAssignedNewPrefixes() { XmlWriterStore xmlWriter = new XmlWriterStore(); RdfXmlWriter rdfWriter = new RdfXmlWriter(xmlWriter); rdfWriter.StartOutput(); rdfWriter.StartSubject(); rdfWriter.WriteUriRef("http://example.com/subj"); rdfWriter.StartPredicate(); rdfWriter.WriteUriRef("http://foo.example.com/name"); rdfWriter.StartObject(); rdfWriter.WriteUriRef("http://example.com/obj"); rdfWriter.EndObject(); rdfWriter.EndPredicate(); rdfWriter.StartPredicate(); rdfWriter.WriteUriRef("http://bar.example.com/name"); rdfWriter.StartObject(); rdfWriter.WriteUriRef("http://example.com/obj"); rdfWriter.EndObject(); rdfWriter.EndPredicate(); rdfWriter.EndSubject(); rdfWriter.EndOutput(); Assert.IsTrue(xmlWriter.WasWriteStartElementCalledWith("ns1", "name", "http://foo.example.com/"), "first new namespace assigned"); Assert.IsTrue(xmlWriter.WasWriteStartElementCalledWith("ns2", "name", "http://bar.example.com/"), "second new namespace assigned"); }
public void Save() { logger.LogFunction("WriteToFile"); RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(situation, path); }
/// <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> /// <param name="callback">Callback</param> /// <param name="state">State to pass to the callback</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 override void UpdateGraph(string graphUri, IEnumerable <Triple> additions, IEnumerable <Triple> removals, AsyncStorageCallback callback, Object state) { if (removals != null && removals.Any()) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri.ToSafeUri(), 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")), state); return; } if (additions == null || !additions.Any()) { callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri.ToSafeUri()), state); return; } String updateUri = this._serviceUri; if (graphUri != null && !graphUri.Equals(String.Empty)) { updateUri += "?graph=" + Uri.EscapeDataString(graphUri); } else { updateUri += "?default"; } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(UriFactory.Create(updateUri)); request.Method = "POST"; request.ContentType = MimeTypesHelper.RdfXml[0]; request = base.ApplyRequestOptions(request); RdfXmlWriter writer = new RdfXmlWriter(); this.UpdateGraphAsync(request, writer, graphUri.ToSafeUri(), additions, callback, state); }
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"); }
public string GetString(SparqlResultsFormat format, IRdfWriter graphWriter = null) { switch (ResultType) { case BrightstarSparqlResultsType.VariableBindings: case BrightstarSparqlResultsType.Boolean: var stringWriter = new System.IO.StringWriter(); var sparqlXmlWriter = GetSparqlWriter(format); sparqlXmlWriter.Save(_resultSet, stringWriter); return stringWriter.GetStringBuilder().ToString(); case BrightstarSparqlResultsType.Graph: if (graphWriter == null) { #if WINDOWS_PHONE // Cannot use DTD because the mobile version of XmlWriter doesn't support writing a DOCTYPE. graphWriter = new RdfXmlWriter(WriterCompressionLevel.High, false); #else graphWriter = new RdfXmlWriter(); #endif } return StringWriter.Write(_graph, graphWriter); default: throw new BrightstarInternalException( String.Format("Unrecognized result type when serializing results string: {0}", ResultType)); } }
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 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"); }
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() { Store store = new MemoryStore(); store.Import(RdfReader.LoadFromUri(new Uri(example_foaf_file))); // Dump out the data, for fun using (RdfWriter writer = new RdfXmlWriter(Console.Out)) { writer.Write(store); } Console.WriteLine("These are the people in the file:"); foreach (Statement s in store.Select(new Statement(null, rdftype, foafPerson))) { foreach (Resource r in store.SelectObjects(s.Subject, foafname)) { Console.WriteLine(r); } } Console.WriteLine(); Console.WriteLine("And here's RDF/XML just for some of the file:"); using (RdfWriter w = new RdfXmlWriter(Console.Out)) { store.Select(new Statement(null, foafname, null), w); store.Select(new Statement(null, foafknows, null), w); } Console.WriteLine(); }
public void subjectUsedTypedNodeIfRdfTypeSpecified() { XmlWriterStore xmlWriter = new XmlWriterStore(); RdfXmlWriter rdfWriter = new RdfXmlWriter(xmlWriter); rdfWriter.RegisterNamespacePrefix("http://example.com/", "ex"); rdfWriter.StartOutput(); rdfWriter.StartSubject(); rdfWriter.WriteUriRef("http://example.com/subj"); rdfWriter.StartPredicate(); rdfWriter.WriteUriRef("http://foo.example.com/name"); rdfWriter.StartObject(); rdfWriter.WriteUriRef("http://example.com/obj"); rdfWriter.EndObject(); rdfWriter.EndPredicate(); rdfWriter.StartPredicate(); rdfWriter.WriteUriRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"); rdfWriter.StartObject(); rdfWriter.WriteUriRef("http://example.com/Thing"); rdfWriter.EndObject(); rdfWriter.EndPredicate(); rdfWriter.EndSubject(); rdfWriter.EndOutput(); Assert.IsTrue(xmlWriter.WasWriteStartElementCalledWith("ex", "Thing", "http://example.com/")); }
public void newNamespacePrefixesAreRememberedAndReused() { XmlWriterStore xmlWriter = new XmlWriterStore(); RdfXmlWriter rdfWriter = new RdfXmlWriter(xmlWriter); rdfWriter.StartOutput(); rdfWriter.StartSubject(); rdfWriter.WriteUriRef("http://example.com/subj"); rdfWriter.StartPredicate(); rdfWriter.WriteUriRef("http://foo.example.com/name"); rdfWriter.StartObject(); rdfWriter.WriteUriRef("http://example.com/obj"); rdfWriter.EndObject(); rdfWriter.EndPredicate(); rdfWriter.StartPredicate(); rdfWriter.WriteUriRef("http://bar.example.com/name"); rdfWriter.StartObject(); rdfWriter.WriteUriRef("http://example.com/obj"); rdfWriter.EndObject(); rdfWriter.EndPredicate(); rdfWriter.StartPredicate(); rdfWriter.WriteUriRef("http://foo.example.com/place"); rdfWriter.StartObject(); rdfWriter.WriteUriRef("http://example.com/obj"); rdfWriter.EndObject(); rdfWriter.EndPredicate(); rdfWriter.EndSubject(); rdfWriter.EndOutput(); Assert.IsTrue(xmlWriter.WasWriteStartElementCalledWith("ns1", "place", "http://foo.example.com/"), "first new namespace reused"); }
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 subjectUsesOnlyFirstRdfTypePropertyToDetermineTypedNode() { XmlWriterStore xmlWriter = new XmlWriterStore(); RdfXmlWriter rdfWriter = new RdfXmlWriter(xmlWriter); rdfWriter.RegisterNamespacePrefix("http://example.com/", "ex"); rdfWriter.StartOutput(); rdfWriter.StartSubject(); rdfWriter.WriteUriRef("http://example.com/subj"); rdfWriter.StartPredicate(); rdfWriter.WriteUriRef("http://foo.example.com/name"); rdfWriter.StartObject(); rdfWriter.WriteUriRef("http://example.com/obj"); rdfWriter.EndObject(); rdfWriter.EndPredicate(); rdfWriter.StartPredicate(); rdfWriter.WriteUriRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"); rdfWriter.StartObject(); rdfWriter.WriteUriRef("http://example.com/Thing"); rdfWriter.EndObject(); rdfWriter.EndPredicate(); rdfWriter.StartPredicate(); rdfWriter.WriteUriRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"); rdfWriter.StartObject(); rdfWriter.WriteUriRef("http://example.com/Other"); rdfWriter.EndObject(); rdfWriter.EndPredicate(); rdfWriter.EndSubject(); rdfWriter.EndOutput(); Assert.IsFalse(xmlWriter.WasWriteStartElementCalledWith("ex", "Other", "http://example.com/")); }
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 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 void Run() { IPlugin plugin = PluginManager.FindPlugin("SemanticLib.OpenXmlSdkPlugin.dll"); if (plugin != null) { ITextPlugin textPlugin = plugin.TextPlugin; if (textPlugin != null) { ITextDocument textDocument = textPlugin.CreateTextDocument("Test.docx"); if (textDocument != null) { try { RdfXmlWriter rdfXmlWriter = new RdfXmlWriter(); IMetadataFile metadataFile = textDocument.MetadataManifest.MetadataFiles.Add("resources.rdf"); foreach (Triple triple in textDocument.MetadataManifest.Graph.Triples) { Console.WriteLine(triple.ToString()); } Console.WriteLine(VDS.RDF.Writing.StringWriter.Write(textDocument.MetadataManifest.Graph, rdfXmlWriter)); } finally { textDocument.Dispose(); } } } } }
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 WriteToFile(IGraph graph, String path) { logger.LogFunction("WriteToFile"); RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(graph, path); }
public void WriteSchema() { var writer = new RdfXmlWriter(); string path = @"E:\3 курс\WeB\Lab4\RDF_Lab4\StaticFiles\rabotaSchema.rdf"; writer.Save(_graph, path); }
public void Run(IComponentsConfig config, string targetFile) { var rdfStore = new MemoryStore(); rdfStore.Add(new Statement(NS.CSO.classEntity, NS.Rdfs.subClassOf, NS.Rdfs.ClassEntity)); rdfStore.Add(new Statement(NS.CSO.interfaceEntity, NS.Rdfs.subClassOf, NS.Rdfs.ClassEntity)); var assemblyExtractor = new AssemblyMetadata(); assemblyExtractor.Extract(System.Web.HttpRuntime.BinDirectory, rdfStore); var configExtractor = new WinterMetadata(); var baseUri = String.IsNullOrEmpty(BaseUri) ? "file:///" + System.Web.HttpRuntime.AppDomainAppPath.Replace('\\', '/') + "#" : BaseUri; configExtractor.BaseNs = baseUri; configExtractor.Extract(config, rdfStore); using (RdfXmlWriter wr = new RdfXmlWriter(targetFile)) { wr.BaseUri = NS.NrMeta; wr.Namespaces.AddNamespace(NS.DotNet.Type, "type"); wr.Namespaces.AddNamespace(NS.DotNet.Property, "prop"); wr.Namespaces.AddNamespace(NS.NrMetaTerms, "nr"); wr.Write(rdfStore); } }
private static IRdfWriter CreateWriter(string mediaType) { IRdfWriter result; switch (mediaType) { case TextTurtle: result = new CompressingTurtleWriter(); break; case ApplicationRdfXml: case ApplicationOwlXml: result = new RdfXmlWriter(); break; case ApplicationLdJson: result = new JsonLdWriter(Context); break; default: throw new InvalidOperationException(String.Format("Media type '{0}' is not supported.", mediaType)); } if (!(result is INamespaceWriter)) { return(result); } var namespaceWriter = (INamespaceWriter)result; namespaceWriter.DefaultNamespaces.AddNamespace("owl", new Uri(Owl.BaseUri)); namespaceWriter.DefaultNamespaces.AddNamespace("hydra", Hydra); namespaceWriter.DefaultNamespaces.AddNamespace("ursa", DescriptionController <IController> .VocabularyBaseUri); return(result); }
public string GetString(SparqlResultsFormat format, IRdfWriter graphWriter = null) { switch (ResultType) { case BrightstarSparqlResultsType.VariableBindings: case BrightstarSparqlResultsType.Boolean: var stringWriter = new System.IO.StringWriter(); var sparqlXmlWriter = GetSparqlWriter(format); sparqlXmlWriter.Save(_resultSet, stringWriter); return(stringWriter.GetStringBuilder().ToString()); case BrightstarSparqlResultsType.Graph: if (graphWriter == null) { #if WINDOWS_PHONE // Cannot use DTD because the mobile version of XmlWriter doesn't support writing a DOCTYPE. graphWriter = new RdfXmlWriter(WriterCompressionLevel.High, false); #else graphWriter = new RdfXmlWriter(); #endif } return(StringWriter.Write(_graph, graphWriter)); default: throw new BrightstarInternalException( String.Format("Unrecognized result type when serializing results string: {0}", ResultType)); } }
public RdfXmlWriterTestHarness() { itsOutputWriter = new StringWriter(); XmlTextWriter xmlWriter = new XmlTextWriter(itsOutputWriter); itsRdfWriter = new RdfXmlWriter(xmlWriter); itsVerifier = new NTripleListVerifier(); }
public void writerWritesPredicateElement() { XmlWriterStore xmlWriter = new XmlWriterStore(); RdfXmlWriter rdfWriter = new RdfXmlWriter(xmlWriter); writeSingleUUUTriple(rdfWriter); Assert.IsTrue(xmlWriter.WasWriteStartElementCalledWith("ns1", "pred", "http://example.com/")); }
public static void WriteGraph(IGraph graph) { lock (Locks.GetLock((object)"rdflock")) { var rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(graph, RdfFilePath); } }
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); }
/// <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 writerWritesEndDocument() { XmlWriterCounter xmlWriter = new XmlWriterCounter(); RdfXmlWriter rdfWriter = new RdfXmlWriter(xmlWriter); writeSingleUUUTriple(rdfWriter); Assert.AreEqual(1, xmlWriter.WriteEndDocumentCalled); }
public RohGraph Clone() { RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); string rdf = VDS.RDF.Writing.StringWriter.Write(this, rdfxmlwriter); RohGraph rohGraphClone = new RohGraph(); rohGraphClone.LoadFromString(rdf, new RdfXmlParser()); return(rohGraphClone); }
public void writerWritesRdfDescriptionForUntypedSubject() { XmlWriterStore xmlWriter = new XmlWriterStore(); RdfXmlWriter rdfWriter = new RdfXmlWriter(xmlWriter); writeSingleUUUTriple(rdfWriter); Assert.IsTrue(xmlWriter.WasWriteStartElementCalledWith("rdf", "Description", "http://www.w3.org/1999/02/22-rdf-syntax-ns#")); }
public void writerStartsRdfRootElement() { XmlWriterStore xmlWriter = new XmlWriterStore(); RdfXmlWriter rdfWriter = new RdfXmlWriter(xmlWriter); writeSingleUUUTriple(rdfWriter); Assert.IsTrue(xmlWriter.WasWriteStartElementCalledWith("rdf", "RDF", "http://www.w3.org/1999/02/22-rdf-syntax-ns#")); }
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"); }
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 } }
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(); }
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 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 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 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"); }
protected void createPublic() { Graph g = new Graph(); Session["ugraph"] = g; RdfXmlWriter rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(g, path_public); }
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> /// 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 WriteToXML(IList<RDFTriple> triples, string outputFile) { Graph graph = CreateGraph(triples); var rdfxmlwriter = new RdfXmlWriter(); rdfxmlwriter.Save(graph, outputFile); }
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; } } } }
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; } }
/// <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; } }
/// <summary> /// Internal Method which performs multi-threaded writing of data /// </summary> private void SaveGraphs(FolderStoreWriterContext context) { //Create the relevant Writer IRdfWriter writer; switch (context.Format) { case FolderStoreFormat.Turtle: writer = new TurtleWriter(); break; case FolderStoreFormat.Notation3: writer = new Notation3Writer(); break; case FolderStoreFormat.RdfXml: #if !NO_XMLDOM writer = new FastRdfXmlWriter(); #else writer = new RdfXmlWriter(); #endif break; default: writer = new TurtleWriter(); break; } try { Uri u = context.GetNextURI(); while (u != null) { //Get the Graph from the Store IGraph g = context.Store.Graphs[u]; //Write to Disk String destFile = Path.Combine(context.Folder, u.GetSha256Hash()); switch (context.Format) { case FolderStoreFormat.Turtle: destFile += ".ttl"; break; case FolderStoreFormat.Notation3: destFile += ".n3"; break; case FolderStoreFormat.RdfXml: destFile += ".rdf"; break; default: destFile += ".ttl"; break; } writer.Save(g, destFile); //Get the Next Uri u = context.GetNextURI(); } } catch (ThreadAbortException) { //We've been terminated, don't do anything #if !SILVERLIGHT Thread.ResetAbort(); #endif } catch (Exception ex) { throw new RdfStorageException("Error in Threaded Writer in Thread ID " + Thread.CurrentThread.ManagedThreadId, ex); } }
/// <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); } }
/// <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 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> /// 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 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; }