private void LoadButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.InitialDirectory = Environment.CurrentDirectory;
                ofd.Filter           = "RDF Files (*.rdf)|*.rdf|Turtle Files (*.ttl)|*.ttl|All Files (*.*)|*.*";
                if (ofd.ShowDialog().Value)
                {
                    string filePath = ofd.FileName;

                    switch (ModeComboBox.SelectedIndex)
                    {
                    case 0:     // RDF/XML
                        RdfXmlParser rdfXmlParser = new RdfXmlParser(RdfXmlParserMode.Streaming);
                        myGraph = new Graph();
                        rdfXmlParser.Load(myGraph, filePath);
                        break;

                    case 1:     // NTriples
                        NTriplesParser ntp = new NTriplesParser();
                        myGraph = new Graph();
                        ntp.Load(myGraph, filePath);
                        break;
                    }

                    MessageBox.Show("Graph Loaded From File Successfully", "Connected", MessageBoxButton.OK,
                                    MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n" + ex.StackTrace, "ERROR", MessageBoxButton.OK);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Returns all metadata and the stored instances as graph.
        /// There are some adjustments to the data to make the metadata compatible with the Shacl validator.
        /// </summary>
        /// <returns></returns>
        private IGraph GetShapesGraph()
        {
            var shapes = _cacheService.GetOrAdd($"shapes-graph", () =>
            {
                var store = new TripleStore();
                var data  = _metadataService.GetAllShaclAsGraph();

                store.Add(data);

                ModifiyShapesForTargetClass(store);
                ModifyShapesForShaclClass(store);

                var dataGraph = store.Graphs.FirstOrDefault(t => t.BaseUri?.OriginalString == data.BaseUri.OriginalString);

                if (dataGraph == null)
                {
                    throw new ArgumentNullException("Shapes graph is null");
                }

                NTriplesWriter writer = new NTriplesWriter(NTriplesSyntax.Original);
                var shapes            = VDS.RDF.Writing.StringWriter.Write(dataGraph, writer);

                return(shapes);
            });

            var shapesGraph = new VDS.RDF.Graph(true);
            var reader      = new StringReader(shapes);

            var nTriplesParser = new NTriplesParser();

            nTriplesParser.Load(shapesGraph, reader);

            return(shapesGraph);
        }
Ejemplo n.º 3
0
        public void LoadFromFile(string filePath, DatasourceFileType fileType)
        {
            try
            {
                switch (fileType)
                {
                case DatasourceFileType.Rdfxml:     // RDF/XML
                    RdfXmlParser rdfXmlParser = new RdfXmlParser(RdfXmlParserMode.Streaming);
                    myGraph = new Graph();
                    rdfXmlParser.Load(myGraph, filePath);
                    break;

                case DatasourceFileType.NTriples:     // NTriples
                    NTriplesParser ntp = new NTriplesParser();
                    myGraph = new Graph();
                    ntp.Load(myGraph, filePath);
                    break;
                }
            }
            catch (Exception ex)
            {
                MySoapFault fault = new MySoapFault();
                fault.Operation   = "LoadFromFile";
                fault.Reason      = "Error in loading datasource file into graph .";
                fault.Details     = ex.Message;
                fault.MoreDetails = ex.StackTrace;
                throw new FaultException <MySoapFault>(fault);
            }
        }
Ejemplo n.º 4
0
        private void ConnectButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (RemoteRadio.IsChecked != null)
                {
                    if (RemoteRadio.IsChecked.Value) // Remote Endpoint Mode
                    {
                        config.endpoint = new SparqlRemoteEndpoint(new Uri(UrlTextBox.Text));

                        MessageBox.Show("Application Connected To Endpoint Successfully", "Connected", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    else // File Mode
                    {
                        config.endpoint = null;

                        NTriplesParser ntp = new NTriplesParser();
                        config.myGraph.Clear();
                        ntp.Load(config.myGraph, PathTextBox.Text);

                        MessageBox.Show("Graph Loaded From File Successfully", "Connected", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ERROR6", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Ejemplo n.º 5
0
        public void SparqlQuery()
        {
            TripleStore store = new TripleStore();
            var         g     = new Graph();

            var parser = new NTriplesParser();

            parser.Load(g, new StringReader(
                            @"<http://example.org/a> <http://example.org/b> <http://example.org/c>.
  <http://example.org/a> <http://example.org/b> <http://example.org/d>.
  <http://example.org/a> <http://example.org/b> <http://example.org/e>.
  <http://example.org/d> <http://example.org/f> <http://example.org/g>."));

            store.Add(g);

            // Normal SPARQL results ARE NOT rdf data. But a rows of bindings.
            Object results = store.ExecuteQuery("SELECT * WHERE {?s ?p ?o}");

            if (results is SparqlResultSet)
            {
                var rset = (SparqlResultSet)results;
                Assert.AreEqual(4, rset.Count);

                foreach (SparqlResult result in rset)
                {
                    Console.WriteLine(result.ToString());
                }
            }

            // SPARQL can be used to construct RDF as a result of the query. This can be loaded into a graph
            SparqlQueryParser sparqlparser = new SparqlQueryParser();
            SparqlQuery       query        = sparqlparser.ParseFromString("CONSTRUCT { ?s ?p ?o } WHERE {?s ?p ?o}");

            results = store.ExecuteQuery(query);
            if (results is IGraph)
            {
                IGraph gr = (IGraph)results;
                foreach (Triple t in gr.Triples)
                {
                    Console.WriteLine(t.ToString());
                }
            }

            // SPARQL works by matching patterns
            results = store.ExecuteQuery("SELECT * WHERE {<http://example.org/a> ?p ?o}");
            if (results is SparqlResultSet)
            {
                var rset = (SparqlResultSet)results;
                Assert.AreEqual(3, rset.Count);

                foreach (SparqlResult result in rset)
                {
                    Console.WriteLine(result.ToString());
                }
            }
        }
Ejemplo n.º 6
0
        private static IGraph Load(string source)
        {
            var result           = new Graph();
            var graphHandler     = new GraphHandler(result);
            var strippingHandler = new StripStringHandler(graphHandler);
            var parser           = new NTriplesParser();

            using (var reader = new StringReader(source))
            {
                parser.Load(strippingHandler, reader);
            }

            return(result);
        }
        private void LoadButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                NTriplesParser ntp = new NTriplesParser();
                myGraph = new Graph();
                ntp.Load(myGraph, dbpeidaNtFileName);

                MessageBox.Show("Loaded", "Done", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ERROR5", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Ejemplo n.º 8
0
        public IActionResult LoadFileG()
        {
            TripleStore store = new TripleStore();


            IGraph g = new Graph();

            NTriplesParser ntparser = new NTriplesParser();

            //Load using Filename
            ntparser.Load(g, new StreamReader("Data/anime_dataset.nt"));
            g.NamespaceMap.AddNamespace("schema", new Uri("http://schema.org/"));
            store.Add(g);

            /*
             * ITripleFormatter formatter = new TurtleFormatter(g);
             * Console.WriteLine("------------------------");
             * //Print triples with this formatter
             * foreach (Triple t in g.Triples)
             * {
             *  Console.WriteLine(t.ToString());
             * }
             */


            //Execute a raw SPARQL Query
            //Should get a SparqlResultSet back from a SELECT query

            Object results = store.ExecuteQuery("PREFIX schema: <http://schema.org/> SELECT * WHERE {?iri a schema:TVSeries .?iri schema:image ?image.}LIMIT 10");


            if (results is SparqlResultSet)
            {
                //Print out the Results
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult result in rset)
                {
                    Console.WriteLine(result.ToString());
                }
            }


            return(View());
        }
Ejemplo n.º 9
0
        // srcFn stazeno z https://wiki.dbpedia.org/downloads-2016-10, Raw html tables
        public static void parseTTL()
        {
            void parseTTLLow(string lang)
            {
                var srcFn = $"{Dirs.wikiesDbpedia}raw_tables_{lang}.ttl";

                if (!File.Exists(srcFn))
                {
                    return;
                }
                Console.WriteLine(srcFn);
                var destFn    = $"{Dirs.root}dbpedia\\{lang}.txt";
                var ttlparser = new NTriplesParser();

                using (var graph = new MyGraph(destFn))
                    using (var rdr = new StreamReader(srcFn))
                        ttlparser.Load(graph, rdr);
            }

            //foreach (var lang in langs) parseTTLLow(lang);
            Parallel.ForEach(langs, new ParallelOptions {
                MaxDegreeOfParallelism = 4
            }, parseTTLLow);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// https://github.com/dotnetrdf/dotnetrdf/wiki/UserGuide-Reading-RDF
        /// </summary>
        public void PlayWithReadingRdf()
        {
            #region Reading RDF from Files
            IGraph       g         = new Graph();
            IGraph       h         = new Graph();
            TurtleParser ttlparser = new TurtleParser();

            // Load using a Filename
            ttlparser.Load(g, "HelloWorld.ttl");

            // Load using a StreamReader
            ttlparser.Load(h, new StreamReader("HelloWorld.ttl"));

            try
            {
                IGraph         g2       = new Graph();
                NTriplesParser ntparser = new NTriplesParser();

                //Load using Filename
                ntparser.Load(g2, "HelloWorld.nt");
            }
            catch (RdfParseException parseEx)
            {
                //This indicates a parser error e.g unexpected character, premature end of input, invalid syntax etc.
                Console.WriteLine("Parser Error");
                Console.WriteLine(parseEx.Message);
            }
            catch (RdfException rdfEx)
            {
                //This represents a RDF error e.g. illegal triple for the given syntax, undefined namespace
                Console.WriteLine("RDF Error");
                Console.WriteLine(rdfEx.Message);
            }
            #endregion

            #region Reading RDF from URIs

            try
            {
                IGraph g3 = new Graph();
                //UriLoader.Load(g3, new Uri("http://dbpedia.org/resource/Barack_Obama"));
            }
            catch (RdfParseException parseEx)
            {
                //This indicates a parser error e.g unexpected character, premature end of input, invalid syntax etc.
                Console.WriteLine("Parser Error");
                Console.WriteLine(parseEx.Message);
            }
            catch (RdfException rdfEx)
            {
                //This represents a RDF error e.g. illegal triple for the given syntax, undefined namespace
                Console.WriteLine("RDF Error");
                Console.WriteLine(rdfEx.Message);
            }
            #endregion

            #region Reading RDF from Embedded Resources

            try
            {
                IGraph g4 = new Graph();
                EmbeddedResourceLoader.Load(g4, "embedded.ttl, PlayWithDotNetRDF");
                Console.WriteLine(g4.IsEmpty);
            }
            catch (RdfParseException parseEx)
            {
                //This indicates a parser error e.g unexpected character, premature end of input, invalid syntax etc.
                Console.WriteLine("Parser Error");
                Console.WriteLine(parseEx.Message);
            }
            catch (RdfException rdfEx)
            {
                //This represents a RDF error e.g. illegal triple for the given syntax, undefined namespace
                Console.WriteLine("RDF Error");
                Console.WriteLine(rdfEx.Message);
            }
            #endregion

            #region Reading RDF from Strings

            Graph g5 = new Graph();
            StringParser.Parse(g5, "<http://example.org/a> <http://example.org/b> <http://example.org/c>.");

            Graph          g6     = new Graph();
            NTriplesParser parser = new NTriplesParser();
            parser.Load(g6, new StringReader("<http://example.org/a> <http://example.org/b> <http://example.org/c>."));

            #endregion

            #region Store Parsers

            /*
             * TripleStore store = new TripleStore();
             * TriGParser trigparser = new TriGParser();
             *
             * //Load the Store
             * trigparser.Load(store, "Example.trig");
             */

            #endregion

            #region Advanced Parsing

            // Create a Handler and use it for parsing
            CountHandler handler      = new CountHandler();
            TurtleParser turtleParser = new TurtleParser();
            turtleParser.Load(handler, "HelloWorld.ttl");

            //Print the resulting count
            Console.WriteLine(handler.Count + " Triple(s)");

            // https://github.com/dotnetrdf/dotnetrdf/wiki/UserGuide-Handlers-API
            #endregion

            /*
             * Parser Class         Supported Input
             * NTriplesParser       NTriples
             * Notation3Parser  Notation 3, Turtle, NTriples, some forms of TriG
             * NQuadsParser         NQuads, NTriples
             * RdfAParser           RDFa 1.0 embedded in (X)HTML, some RDFa 1.1 support
             * RdfJsonParser        RDF/JSON (Talis specification)
             * RdfXmlParser         RDF/XML
             * TriGParser           TriG
             * TriXParser           TriX
             * TurtleParser         Turtle, NTriples
             * JsonLdParser         JSON-LD
             */
        }
Ejemplo n.º 11
0
        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;
            }
        }
Ejemplo n.º 12
0
        public static Object LoadFromReader(Reader r, string baseUri, org.openrdf.rio.RDFFormat rdff)
        {
            Object obj;

            if (rdff == dotSesameFormats.RDFFormat.N3)
            {
                obj = new Graph();
                if (baseUri != null)
                {
                    ((IGraph)obj).BaseUri = new Uri(baseUri);
                }
                Notation3Parser parser = new Notation3Parser();
                parser.Load((IGraph)obj, r.ToDotNetReadableStream());
            }
            else if (rdff == dotSesameFormats.RDFFormat.NTRIPLES)
            {
                obj = new Graph();
                if (baseUri != null)
                {
                    ((IGraph)obj).BaseUri = new Uri(baseUri);
                }
                NTriplesParser parser = new NTriplesParser();
                parser.Load((IGraph)obj, r.ToDotNetReadableStream());
            }
            else if (rdff == dotSesameFormats.RDFFormat.RDFXML)
            {
                obj = new Graph();
                if (baseUri != null)
                {
                    ((IGraph)obj).BaseUri = new Uri(baseUri);
                }
                RdfXmlParser parser = new RdfXmlParser();
                parser.Load((IGraph)obj, r.ToDotNetReadableStream());
            }
            else if (rdff == dotSesameFormats.RDFFormat.TRIG)
            {
                obj = new TripleStore();
                TriGParser trig = new TriGParser();
                trig.Load((ITripleStore)obj, new StreamParams(r.ToDotNetReadableStream().BaseStream));
            }
            else if (rdff == dotSesameFormats.RDFFormat.TRIX)
            {
                obj = new TripleStore();
                TriXParser trix = new TriXParser();
                trix.Load((ITripleStore)obj, new StreamParams(r.ToDotNetReadableStream().BaseStream));
            }
            else if (rdff == dotSesameFormats.RDFFormat.TURTLE)
            {
                obj = new Graph();
                if (baseUri != null)
                {
                    ((IGraph)obj).BaseUri = new Uri(baseUri);
                }
                TurtleParser parser = new TurtleParser();
                parser.Load((IGraph)obj, r.ToDotNetReadableStream());
            }
            else
            {
                throw new RdfParserSelectionException("The given Input Format is not supported by dotNetRDF");
            }

            return(obj);
        }
Ejemplo n.º 13
0
        public void WorkingWithGraphs()
        {
            // 1. Insert Triples ------------------------------------------------------------
            Graph g = new Graph();

            IUriNode dotNetRDF = g.CreateUriNode(UriFactory.Create("http://www.dotnetrdf.org"));
            IUriNode says      = g.CreateUriNode(UriFactory.Create("http://example.org/says"));
            IUriNode label     = g.CreateUriNode(UriFactory.Create("http://example.org/label"));

            ILiteralNode dotNetRdfName = g.CreateLiteralNode("dotNetRdf");
            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));
            g.Assert(new Triple(dotNetRDF, label, dotNetRdfName));

            Assert.AreEqual(3, g.Triples.Count);

            // asserting an existing triple will not add a new one
            g.Assert(new Triple(dotNetRDF, says, bonjourMonde));
            Assert.AreEqual(3, g.Triples.Count);

            // We can also create a triple by just passing in the subject, predicate and object
            g.Assert(dotNetRDF, says, g.CreateLiteralNode("Welcome"));

            Assert.AreEqual(4, g.Triples.Count);
            // ------------------------------------------------------------------------------


            // 2. Remove Triples ------------------------------------------------------------
            // Triple removal is done BY VALUE.
            g.Retract(dotNetRDF, says, g.CreateLiteralNode("Welcome"));

            Assert.AreEqual(3, g.Triples.Count);

            // There is no notion of updating a triple, they can be removed and added. That's it.
            // e.g. we can't update a Node's value.
            // says.Uri = new Uri(""); // no setter for Uri

            // ------------------------------------------------------------------------------

            // 3. Lookup Triples ------------------------------------------------------------
            // We quite often need to find a set of triples to display, delete, process.

            // get all triples with a given predicate
            var matches = g.GetTriplesWithPredicate(says);

            Assert.AreEqual(2, matches.Count());

            // get all the triples whose subject matches a given INode
            matches = g.GetTriplesWithSubject(dotNetRDF);
            Assert.AreEqual(3, matches.Count());

            // get all the triples whose subject and predicate matches the given INodes
            matches = g.GetTriplesWithSubjectPredicate(dotNetRDF, says);
            Assert.AreEqual(2, matches.Count());

            // Note: Nodes have no identity beyond their value.
            var n = g.CreateLiteralNode("Hello World");

            Assert.AreNotSame(n, helloWorld);
            matches = g.GetTriplesWithObject(n);
            Assert.AreEqual(1, matches.Count());

            // ------------------------------------------------------------------------------

            // 4. Loading Data --------------------------------------------------------------
            // RDF data comes in many different syntaxes. Data can be loaded into graphs by using
            // the appropriate parser. Many different syntaxes are supported.
            g = new Graph();
            NTriplesParser parser = new NTriplesParser();

            parser.Load(g, new StringReader("<http://example.org/a> <http://example.org/b> <http://example.org/c>."));

            Assert.AreEqual(1, g.Triples.Count);
            // ------------------------------------------------------------------------------

            // 5. Loading Data from SPARQL --------------------------------------------------
            // RDF data can also be loaded into a graph from the result of a SPARQL query that returns RDF XML.
            // DESCRIBE or CONSTRUCT return RDF.
            SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"));

            // Ask DBPedia to describe the first thing it finds which is a Person
            var query = "DESCRIBE ?person WHERE {?person a <http://dbpedia.org/ontology/Person>} LIMIT 1";

            //Get the result
            var dbpGraph = endpoint.QueryWithResultGraph(query);

            Assert.IsTrue(dbpGraph.Triples.Count > 0);
            // ------------------------------------------------------------------------------


            // 6. Writing Data --------------------------------------------------------------
            // Again there are writers for different syntaxes. The data can be written to files,
            // streams, strings as needed.

            RdfXmlWriter rdfxmlwriter = new RdfXmlWriter();

            rdfxmlwriter.Save(dbpGraph, Console.Out); // view test result details for output.

            // ------------------------------------------------------------------------------
        }