public override StorageContent CreateContent(CatalogContext context)
        {
            using (IGraph graph = new Graph())
            {
                INode entry = graph.CreateUriNode(GetItemAddress());

                //  catalog infrastructure fields
                graph.Assert(entry, graph.CreateUriNode(Schema.Predicates.Type), graph.CreateUriNode(GetItemType()));
                graph.Assert(entry, graph.CreateUriNode(Schema.Predicates.Type), graph.CreateUriNode(Schema.DataTypes.Permalink));
                graph.Assert(entry, graph.CreateUriNode(Schema.Predicates.CatalogTimeStamp), graph.CreateLiteralNode(TimeStamp.ToString("O"), Schema.DataTypes.DateTime));
                graph.Assert(entry, graph.CreateUriNode(Schema.Predicates.CatalogCommitId), graph.CreateLiteralNode(CommitId.ToString()));

                graph.Assert(entry, graph.CreateUriNode(Schema.Predicates.Published), graph.CreateLiteralNode(_published.ToString("O"), Schema.DataTypes.DateTime));

                graph.Assert(entry, graph.CreateUriNode(Schema.Predicates.Id), graph.CreateLiteralNode(_id));
                graph.Assert(entry, graph.CreateUriNode(Schema.Predicates.OriginalId), graph.CreateLiteralNode(_id));
                graph.Assert(entry, graph.CreateUriNode(Schema.Predicates.Version), graph.CreateLiteralNode(_version));

                SetIdVersionFromGraph(graph);

                //  create JSON content
                JObject frame = context.GetJsonLdContext("context.Catalog.json", GetItemType());
                StorageContent content = new StringStorageContent(Utils.CreateArrangedJson(graph, frame), "application/json", "no-store");
               
                return content;
            }
        }
Esempio 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);
        }
        public static IGraph CreateCommitMetadata(Uri indexUri, CommitMetadata commitMetadata)
        {
            IGraph graph = new Graph();

            if (commitMetadata.LastCreated != null)
            {
                graph.Assert(
                    graph.CreateUriNode(indexUri), 
                    graph.CreateUriNode(Schema.Predicates.LastCreated), 
                    graph.CreateLiteralNode(commitMetadata.LastCreated.Value.ToString("O"), Schema.DataTypes.DateTime));
            }
            if (commitMetadata.LastEdited != null)
            {
                graph.Assert(
                    graph.CreateUriNode(indexUri),
                    graph.CreateUriNode(Schema.Predicates.LastEdited),
                    graph.CreateLiteralNode(commitMetadata.LastEdited.Value.ToString("O"), Schema.DataTypes.DateTime));
            }
            if (commitMetadata.LastDeleted != null)
            {
                graph.Assert(
                    graph.CreateUriNode(indexUri), 
                    graph.CreateUriNode(Schema.Predicates.LastDeleted), 
                    graph.CreateLiteralNode(commitMetadata.LastDeleted.Value.ToString("O"), Schema.DataTypes.DateTime));
            }

            return graph;
        }
 public void TestCreateAssociationLinks()
 {
     var testGraph = new Graph {BaseUri = new Uri("http://dbpedia.org/resource/")};
     var film = testGraph.CreateUriNode(UriFactory.Create("http://dbpedia.org/resource/Un_Chien_Andalou"));
     var rdfType = testGraph.CreateUriNode(UriFactory.Create("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"));
     testGraph.Assert(film,
                      rdfType,
                      testGraph.CreateUriNode(UriFactory.Create("http://dbpedia.org/ontology/Film")));
     testGraph.Assert(film,
                      testGraph.CreateUriNode(UriFactory.Create("http://xmlns.com/foaf/0.1/name")),
                      testGraph.CreateLiteralNode("Un Chien Andalou"));
     var director = testGraph.CreateUriNode(UriFactory.Create("http://dbpedia.org/resource/Luis_Bunuel"));
     testGraph.Assert(director, rdfType, testGraph.CreateUriNode(UriFactory.Create("http://dbpedia.org/ontology/Person")));
     testGraph.Assert(film, testGraph.CreateUriNode(UriFactory.Create("http://dbpedia.org/property/director")), director);
     var mockRequest = new Mock<IODataRequestMessage>();
     mockRequest.Setup(m => m.Url).Returns(new Uri("http://example.org/odata/Films('Un_Chien_Andalou')"));
     var mock = new Mock<IODataResponseMessage>();
     var mockStream = new MemoryStream();
     mock.Setup(m => m.GetStream()).Returns(mockStream);
     var generator = new ODataFeedGenerator(mockRequest.Object, mock.Object, _dbpediaMap, "http://example.org/odata/", new ODataMessageWriterSettings { Indent = true });
     generator.CreateEntryFromGraph(testGraph, film.Uri.ToString(), "DBPedia.Film");
     mockStream.Seek(0, SeekOrigin.Begin);
     var streamXml = XDocument.Load(mockStream);
     Assert.IsNotNull(streamXml);
     Assert.IsNotNull(streamXml.Root);
     Assert.AreEqual(XName.Get("entry", "http://www.w3.org/2005/Atom"), streamXml.Root.Name);
     Console.WriteLine(streamXml.ToString());
 }
Esempio n. 5
0
        public static IGraph CreateNuspecGraph(XDocument nuspec, string baseAddress)
        {
            nuspec = NormalizeNuspecNamespace(nuspec);

            XslCompiledTransform transform = CreateTransform("xslt.nuspec.xslt");

            XsltArgumentList arguments = new XsltArgumentList();
            arguments.AddParam("base", "", baseAddress + "packages/");
            arguments.AddParam("extension", "", ".json");

            arguments.AddExtensionObject("urn:helper", new XsltHelper());

            XDocument rdfxml = new XDocument();
            using (XmlWriter writer = rdfxml.CreateWriter())
            {
                transform.Transform(nuspec.CreateReader(), arguments, writer);
            }

            RdfXmlParser rdfXmlParser = new RdfXmlParser();
            XmlDocument doc = new XmlDocument();
            doc.Load(rdfxml.CreateReader());
            IGraph graph = new Graph();
            rdfXmlParser.Load(graph, doc);

            return graph;
        }
Esempio n. 6
0
        public static dynamic GetDyno(string data, bool autoquotation = true, 
            bool treatUri = true,
            bool skipTriplesWithEmptyObject = false,
            bool mindAsterisk = false,
            bool useStore = false,
            string defaultGraphUri = "http://test.org/defaultgraph")
        {
            DynamicSPARQLSpace.dotNetRDF.Connector connector = null;

            if (useStore)
            {
                var store = new VDS.RDF.TripleStore();
                store.LoadFromString(data);
                connector =  new Connector(new InMemoryDataset(store, new Uri(defaultGraphUri)));
            }
            else
            {
                var graph = new VDS.RDF.Graph();
                graph.LoadFromString(data);
                connector =  new Connector(new InMemoryDataset(graph));
            }

            dynamic dyno = DynamicSPARQL.CreateDyno(connector.GetQueryingFunction(),
                updateFunc: connector.GetUpdateFunction(),
                autoquotation: autoquotation,
                treatUri: treatUri,
                skipTriplesWithEmptyObject:skipTriplesWithEmptyObject,
                mindAsterisk:mindAsterisk);

            return dyno;
        }
Esempio n. 7
0
        public void SparqlBindLazy()
        {
            String query = "PREFIX fn: <" + XPathFunctionFactory.XPathFunctionsNamespace + "> SELECT ?triple WHERE { ?s ?p ?o . BIND(fn:concat(STR(?s), ' ', STR(?p), ' ', STR(?o)) AS ?triple) } LIMIT 1";

            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);

            Console.WriteLine(q.ToAlgebra().ToString());
            Assert.IsTrue(q.ToAlgebra().ToString().Contains("LazyBgp"), "Should have been optimised to use a Lazy BGP");
            Console.WriteLine();

            Object results = q.Evaluate(store);
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count == 1, "Expected exactly 1 results");
                Assert.IsTrue(rset.All(r => r.HasValue("triple")), "All Results should have had a value for ?triple");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
        }
        public fclsGraphBrowser()
        {
            InitializeComponent();

            //Connect to Virtuoso
            this._manager = new VirtuosoManager(Properties.Settings.Default.Server, Properties.Settings.Default.Port, VirtuosoQuadStoreDB, Properties.Settings.Default.Username, Properties.Settings.Default.Password);

            //Add some fake test data
            DataTable data = new DataTable();
            data.Columns.Add("Subject");
            data.Columns.Add("Predicate");
            data.Columns.Add("Object");
            data.Columns["Subject"].DataType = typeof(INode);
            data.Columns["Predicate"].DataType = typeof(INode);
            data.Columns["Object"].DataType = typeof(INode);

            Graph g = new Graph();
            DataRow row = data.NewRow();
            row["Subject"] = g.CreateUriNode(new Uri("http://example.org/subject"));
            row["Predicate"] = g.CreateUriNode(new Uri("http://example.org/predicate"));
            row["Object"] = g.CreateUriNode(new Uri("http://example.org/object"));
            data.Rows.Add(row);

            this.BindGraph(data);
        }
        public static void Main(String[] args)
        {
            try
            {
                String server = "localhost";
                Console.WriteLine("Enter Database Server: ");
                server = Console.ReadLine();
                if (server.Equals(String.Empty)) server = "localhost";
                String db = "bbcdemo";
                Console.WriteLine("Enter Database to check: ");
                db = Console.ReadLine();
                if (db.Equals(String.Empty)) db = "bbcdemo";

                Console.WriteLine("Checking Node Hash Codes for Database '" + db + "' on Server '" + server + "'");

                MicrosoftSqlStoreManager manager = new MicrosoftSqlStoreManager(server, db, "example", "password");

                DataTable nodeData = manager.ExecuteQuery("SELECT nodeID, nodeHash FROM NODES");
                Graph g = new Graph();

                int valid = 0;
                int invalid = 0;
                foreach (DataRow r in nodeData.Rows)
                {
                    INode n = manager.LoadNode(g, r["nodeID"].ToString());
                    int hash = Int32.Parse(r["nodeHash"].ToString());

                    if (hash == n.GetHashCode())
                    {
                        valid++;
                    }
                    else
                    {
                        invalid++;
                    }
                }

                manager.Dispose();

                Console.WriteLine(valid + " Nodes had Valid Hash Codes");
                Console.WriteLine(invalid + " Nodes had Invalid Hash Codes");

                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                Exception innerEx = ex.InnerException;
                while (innerEx != null)
                {
                    Console.WriteLine();
                    Console.WriteLine(innerEx.Message);
                    Console.WriteLine(innerEx.StackTrace);
                    innerEx = innerEx.InnerException;
                }

                Console.ReadLine();
            }
        }
        public override bool Execute(PipelinePackage package, PackagePipelineContext context)
        {
            DateTime? commitTimeStamp = PackagePipelineHelpers.GetCommitTimeStamp(context);
            Guid? commitId = PackagePipelineHelpers.GetCommitId(context);

            IGraph graph = new Graph();

            INode resource = graph.CreateUriNode(context.Uri);

            if (commitTimeStamp != null)
            {
                graph.Assert(
                    resource,
                    graph.CreateUriNode(Schema.Predicates.CatalogTimeStamp),
                    graph.CreateLiteralNode(commitTimeStamp.Value.ToString("O"), Schema.DataTypes.DateTime));
            }

            if (commitId != null)
            {
                graph.Assert(
                    resource,
                    graph.CreateUriNode(Schema.Predicates.CatalogCommitId),
                    graph.CreateLiteralNode(commitId.Value.ToString()));
            }

            context.StageResults.Add(new GraphPackageMetadata(graph));

            return true;
        }
Esempio n. 11
0
        public void RunVocab(String[] args)
        {
            if (args.Length < 2)
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: 2 Arguments are required in order to use the -vocab mode");
                return;
            }

            if (File.Exists(args[1]))
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: Cannot output the configuration vocabulary to " + args[1] + " as a file already exists at that location");
                return;
            }

            TurtleParser ttlparser = new TurtleParser();
            StreamReader reader = new StreamReader(Assembly.GetAssembly(typeof(IGraph)).GetManifestResourceStream("VDS.RDF.Configuration.configuration.ttl"));
            Graph g = new Graph();
            ttlparser.Load(g, reader);

            IRdfWriter writer;
            try
            {
                writer = MimeTypesHelper.GetWriter(MimeTypesHelper.GetMimeType(Path.GetExtension(args[1])));
            }
            catch (RdfWriterSelectionException)
            {
                writer = new CompressingTurtleWriter(WriterCompressionLevel.High);
            }
            writer.Save(g, args[1]);
            Console.WriteLine("rdfWebDeploy: Configuration Vocabulary output to " + args[1]);
        }
Esempio n. 12
0
        public void ProcessRequest(HttpContext context)
        {
            String uri = context.Request.QueryString["uri"];
            if (uri == null)
            {
                context.Response.Write("Bad request");
            }
            else
            {
                //Load the Graph from that URI
                Graph g = new Graph();
                try
                {
                    UriLoader.Load(g, new Uri(uri));
                }
                catch (Exception)
                {
                    //Supress the exception
                    //TODO: Show an error message to the end user
                }

                //Write out as a HTML page
                HtmlWriter writer = new HtmlWriter();
                writer.Stylesheet = "../sparql.css";
                writer.UriPrefix = "?uri=";

                context.Response.ContentType = "text/html";
                writer.Save(g, context.Response.Output);
            }
        }
Esempio n. 13
0
        public void SparqlBind()
        {
            String query = "PREFIX fn: <" + XPathFunctionFactory.XPathFunctionsNamespace + "> SELECT ?triple WHERE { ?s ?p ?o . BIND(fn:concat(STR(?s), ' ', STR(?p), ' ', STR(?o)) AS ?triple) }";

            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);

            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(query);

            Object results = q.Evaluate(store);
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult r in rset)
                {
                    Console.WriteLine(r.ToString());
                }
                Assert.IsTrue(rset.Count > 0, "Expected 1 or more results");
            }
            else
            {
                Assert.Fail("Expected a SPARQL Result Set");
            }
        }
Esempio n. 14
0
        public void WritingBlankNodeOutput()
        {
            //Create a Graph and add a couple of Triples which when serialized have
            //potentially colliding IDs

            Graph g = new Graph();
            g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org"));
            IUriNode subj = g.CreateUriNode("ex:subject");
            IUriNode pred = g.CreateUriNode("ex:predicate");
            IUriNode name = g.CreateUriNode("ex:name");
            IBlankNode b1 = g.CreateBlankNode("autos1");
            IBlankNode b2 = g.CreateBlankNode("1");

            g.Assert(subj, pred, b1);
            g.Assert(b1, name, g.CreateLiteralNode("First Triple"));
            g.Assert(subj, pred, b2);
            g.Assert(b2, name, g.CreateLiteralNode("Second Triple"));

            TurtleWriter ttlwriter = new TurtleWriter();
            ttlwriter.Save(g, "bnode-output-test.ttl");

            TestTools.ShowGraph(g);

            TurtleParser ttlparser = new TurtleParser();
            Graph h = new Graph();
            ttlparser.Load(h, "bnode-output-test.ttl");

            TestTools.ShowGraph(h);

            Assert.AreEqual(g.Triples.Count, h.Triples.Count, "Expected same number of Triples after serialization and reparsing");

        }
        public static IGraph ReplaceResourceUris(IGraph original, IDictionary<string, Uri> replacements)
        {
            IGraph modified = new Graph();
            foreach (Triple triple in original.Triples)
            {
                Uri subjectUri;
                if (!replacements.TryGetValue(triple.Subject.ToString(), out subjectUri))
                {
                    subjectUri = ((IUriNode)triple.Subject).Uri;
                }

                INode subjectNode = modified.CreateUriNode(subjectUri);
                INode predicateNode = triple.Predicate.CopyNode(modified);

                INode objectNode;
                if (triple.Object is IUriNode)
                {
                    Uri objectUri;
                    if (!replacements.TryGetValue(triple.Object.ToString(), out objectUri))
                    {
                        objectUri = ((IUriNode)triple.Object).Uri;
                    }
                    objectNode = modified.CreateUriNode(objectUri);
                }
                else
                {
                    objectNode = triple.Object.CopyNode(modified);
                }

                modified.Assert(subjectNode, predicateNode, objectNode);
            }

            return modified;
        }
Esempio n. 16
0
 private void ProcessManifest()
 {
     var baseGraph = new Graph();
     FileLoader.Load(baseGraph, ManifestFilePath);
     ProcessIncludes(baseGraph);
     ProcessEntries(baseGraph);
 }
Esempio n. 17
0
        public void Arrange(string sparqlQuery, out TripleStore store, out SparqlQuery query)
        {
            IGraph g = new VDS.RDF.Graph();                 //Load triples from file OWL

            g.LoadFromFile(@"D:\Stud\4 course\II semester\!Diploma work\Software\Code\SPARQLtoSQL\SPARQLtoSQL\bin\Debug\combined.owl");
            g.BaseUri = null;                           //!

            RdfsReasoner reasoner = new RdfsReasoner(); //Apply reasoner

            reasoner.Initialise(g);
            reasoner.Apply(g);

            g.BaseUri = null;   //!!!!!!!!
            store     = new TripleStore();
            store.Add(g);

            SparqlParameterizedString queryString = new SparqlParameterizedString();

            queryString.CommandText = sparqlQuery;

            SparqlQueryParser parser = new SparqlQueryParser();

            //SparqlQuery query = parser.ParseFromString(queryString.ToString());
            query = parser.ParseFromString(queryString.ToString());

            Dictionary <string, string> dbURIs = new Dictionary <string, string>();

            dbURIs.Add("http://www.semanticweb.org/KMS/", @"Data Source = ASUS\SQLEXPRESS; Initial Catalog = KMS; Integrated Security = True");
            dbURIs.Add("http://www.semanticweb.org/LMS/", @"Data Source = ASUS\SQLEXPRESS; Initial Catalog = LMS; Integrated Security = True");
            Program.ResolveBGPsFromDB(query.ToAlgebra(), g, dbURIs);

            Console.WriteLine(query.ToAlgebra());
            Console.WriteLine(query.ToString());
        }
Esempio n. 18
0
        private void btnCadUser_Click(object sender, EventArgs e)
        {
            Graph g = new Graph();
            UserContextModel ctx = new UserContextModel();
            SingletonStarDog dog = SingletonStarDog.getDbInstance();

            //ctx.userID = txtAlunoID.Text;
            //ctx.ComunidadeMoodle = txtAlunoComunidade.Text;
            HardwareModel device = new HardwareModel();
            //device.Device_ID = txtDeviceID.Text;
            //ctx.DeviceList.Add(device);

            OntoStudent obj = new OntoStudent(ctx, device);
            dog.GetDBConnection().Begin();
            obj.insertStudent(ref g);
            dog.GetDBConnection().SaveGraph(g);
               // obj.insertHasDevice(ref g);
            dog.GetDBConnection().SaveGraph(g);
            obj.insertComunidadeMoodle(ref g);
            dog.GetDBConnection().SaveGraph(g);
            dog.GetDBConnection().Commit();

            Ontology.Ontology.ListAllDevices(txtComunidades.Text);

            Ontology.Ontology onto2 = new Ontology.Ontology();
            onto2.ListAllUserDevice();
        }
    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 ParsingN3Reasoner()
        {
            String rules = "@prefix rdfs: <" + NamespaceMapper.RDFS + "> . { ?s rdfs:subClassOf ?class } => { ?s a ?class } .";

            Graph rulesGraph = new Graph();
            StringParser.Parse(rulesGraph, rules, new Notation3Parser());

            Graph data = new Graph();
            FileLoader.Load(data, "InferenceTest.ttl");

            Console.WriteLine("Original Graph - " + data.Triples.Count + " Triples");
            int origCount = data.Triples.Count;
            foreach (Triple t in data.Triples)
            {
                Console.WriteLine(t.ToString());
            }

            SimpleN3RulesReasoner reasoner = new SimpleN3RulesReasoner();
            reasoner.Initialise(rulesGraph);

            reasoner.Apply(data);

            Console.WriteLine("Graph after Reasoner application - " + data.Triples.Count + " Triples");
            foreach (Triple t in data.Triples)
            {
                Console.WriteLine(t.ToString());
            }

            Assert.IsTrue(data.Triples.Count > origCount, "Number of Triples should have increased after the reasoner was run");
        }
Esempio n. 21
0
 public MetadataSource(Options opts)
 {
     if (!String.IsNullOrEmpty(opts.EndpointUri))
     {
         if (String.IsNullOrEmpty(opts.DefaultGraphUri))
         {
             this._processor = new RemoteQueryProcessor(new SparqlRemoteEndpoint(new Uri(opts.EndpointUri)));
         }
         else
         {
             this._processor = new RemoteQueryProcessor(new SparqlRemoteEndpoint(new Uri(opts.EndpointUri), opts.DefaultGraphUri));
         }
     }
     else if (!String.IsNullOrEmpty(opts.SourceFile))
     {
         TripleStore store = new TripleStore();
         Graph g = new Graph();
         FileLoader.Load(g, opts.SourceFile);
         store.Add(g);
         this._processor = new LeviathanQueryProcessor(store);
     }
     else
     {
         throw new Exception("Must specify an endpoint or a file to query");
     }
 }
        public IEnumerable<IDataObject> BindRdfDataObjects(XDocument rdfXmlDocument,
                                                           IList<OrderingDirection> orderingDirections)
        {
            var g = new Graph();
#if PORTABLE || WINDOWS_PHONE
			var parser = new RdfXmlParser(RdfXmlParserMode.Streaming);
			// This is pretty nasty, having to deserialize only to go through parsing again
			parser.Load(g, new System.IO.StringReader(rdfXmlDocument.ToString()));
#else
			var parser = new RdfXmlParser(RdfXmlParserMode.DOM);
            parser.Load(g, rdfXmlDocument.AsXmlDocument());
#endif
            var p = new VDS.RDF.Query.LeviathanQueryProcessor(new InMemoryDataset(g));
            var queryString = MakeOrderedResourceQuery(orderingDirections);
            var sparqlParser = new SparqlQueryParser();
            var query = sparqlParser.ParseFromString(queryString);
            var queryResultSet = p.ProcessQuery(query) as VDS.RDF.Query.SparqlResultSet;
            foreach (var row in queryResultSet.Results)
            {
                INode uriNode;
                if (row.TryGetBoundValue("x", out uriNode) && uriNode is IUriNode)
                {
                    yield return BindRdfDataObject(uriNode as IUriNode, g);
                }
            }
        } 
Esempio n. 23
0
        /// <summary>
        /// Adds the literal triple to a graph.
        /// </summary>
        /// <param name="graph">The graph.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="predicate">The predicate.</param>
        /// <param name="obj">The object (resource).</param>
        /// <remarks></remarks>
        public static void AddTripleLiteral(Graph graph, string subject, string predicate, string obj, string datatype)
        {
            string xmlSchemaDatatype;
            switch (datatype)
            {
                case "Url":
                    xmlSchemaDatatype = XmlSpecsHelper.XmlSchemaDataTypeAnyUri;
                    break;
                case "Date":
                    xmlSchemaDatatype = XmlSpecsHelper.XmlSchemaDataTypeDateTime;
                    break;
                case "Integer":
                    xmlSchemaDatatype = XmlSpecsHelper.XmlSchemaDataTypeInteger;
                    break;
                case "Ntext":
                    xmlSchemaDatatype = XmlSpecsHelper.XmlSchemaDataTypeString;
                    break;
                case "Nvarchar":
                    xmlSchemaDatatype = XmlSpecsHelper.XmlSchemaDataTypeString;
                    break;
                default:
                    xmlSchemaDatatype = XmlSpecsHelper.XmlSchemaDataTypeString;
                    break;
            }

            Triple triple = null;
            if (subject.StartsWith("http") && predicate.StartsWith("http"))
            {
                triple = new Triple(
                        graph.CreateUriNode(new Uri(subject)),
                        graph.CreateUriNode(new Uri(predicate)),
                        graph.CreateLiteralNode(obj, new Uri(xmlSchemaDatatype))
                        );
            }
            else if (!subject.StartsWith("http") && predicate.StartsWith("http"))
            {
                triple = new Triple(
                        graph.CreateUriNode(subject),
                        graph.CreateUriNode(new Uri(predicate)),
                        graph.CreateLiteralNode(obj, new Uri(xmlSchemaDatatype))
                        );
            }
            else if (subject.StartsWith("http") && !predicate.StartsWith("http"))
            {
                triple = new Triple(
                        graph.CreateUriNode(new Uri(subject)),
                        graph.CreateUriNode(predicate),
                        graph.CreateLiteralNode(obj, new Uri(xmlSchemaDatatype))
                        );
            }
            else if (!subject.StartsWith("http") && !predicate.StartsWith("http"))
            {
                triple = new Triple(
                        graph.CreateUriNode(subject),
                        graph.CreateUriNode(predicate),
                        graph.CreateLiteralNode(obj, new Uri(xmlSchemaDatatype))
                        );
            }
            graph.Assert(triple);
        }
 public static void LoadTestFile(this ITripleStore store, string fileName, Uri graphUri)
 {
     var graph = new Graph();
     graph.BaseUri = graphUri;
     graph.LoadTestFile(fileName);
     store.Add(graph);
 }
Esempio n. 25
0
		private void ImportData(string dataPath, string defaultGraphUri = null)
        {
            var g = new Graph();
            FileLoader.Load(g, dataPath);
            foreach (var t in g.Triples)
            {
                if (t.Object.NodeType == NodeType.Literal)
                {
                    var litNode = t.Object as LiteralNode;
                    _store.InsertTriple(
                        GetNodeString(t.Subject),
                        GetNodeString(t.Predicate),
                        litNode.Value,
                        true,
                        litNode.DataType == null ? null : litNode.DataType.ToString(),
                        litNode.Language,
                        defaultGraphUri ?? Constants.DefaultGraphUri
                        );
                }
                else
                {
                    _store.InsertTriple(
                        GetNodeString(t.Subject),
                        GetNodeString(t.Predicate),
                        GetNodeString(t.Object),
                        false,
                        null,
                        null,
                        defaultGraphUri ?? Constants.DefaultGraphUri
                        );
                }
            }
            _store.Commit(Guid.Empty);
        }
Esempio n. 26
0
 public static IGraph Load(string name)
 {
     TurtleParser parser = new TurtleParser();
     IGraph g = new Graph();
     parser.Load(g, new StreamReader(Utils.GetResourceStream(name)));
     return g;
 }
 /// <summary>
 /// Construictir for MyLoFacebookContextReader
 /// </summary>
 /// <param name="gpsl">A GPSLookup instance implementing IGPSlookup</param>
 public MyLoFacebookContextReader(IGPSlookup gpsl)
 {
     _store = new TripleStore();
     _g = new Graph();
     _g.BaseUri = new Uri("http://facebook.MyLo.com");
     _store.Add(_g);
     gpsLookup = gpsl;
 }
Esempio n. 28
0
		private static IInMemoryQueryableStore CreateMemoryStore()
		{
			TripleStore result = new TripleStore();
			string serialisedLocation = Settings.Default.testStoreLocation;
            Graph g = new Graph();
            FileLoader.Load(g, serialisedLocation);
            result.Add(g);
			return result;
		}
        protected static IInMemoryQueryableStore CreateMemoryStore()
		{
            string musicOntology = Settings.Default.testStoreLocation;
            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, musicOntology);
			store.Add(g);
            return store;
		}
Esempio n. 30
0
		private static void CreateIInMemoryQueryableStore()
		{
			string serialisedLocation = Settings.Default.testStoreLocation;
			store = new TripleStore();
//			store.AddReasoner(new Euler(new N3Reader(MusicConstants.OntologyURL)));
            VDS.RDF.Graph g = new VDS.RDF.Graph();
            FileLoader.Load(g, serialisedLocation);
            store.Add(g);
		}
Esempio n. 31
0
        public static IGraph GraphFromJson(JToken compacted)
        {
            JToken flattened = JsonLdProcessor.Flatten(compacted, new JsonLdOptions());

            IRdfReader rdfReader = new JsonLdReader();
            IGraph graph = new Graph();
            rdfReader.Load(graph, new StringReader(flattened.ToString()));

            return graph;
        }
        public void WritingRdfXmlLiteralsWithLanguageTags()
        {
            Graph g = new Graph();
            INode s = g.CreateUriNode(new Uri("http://example.org/subject"));
            INode p = g.CreateUriNode(new Uri("http://example.org/predicate"));
            INode o = g.CreateLiteralNode("string", "en");
            g.Assert(s, p, o);

            this.CheckRoundTrip(g);
        }
Esempio n. 33
0
        static void CustomQuery()
        {
            Uri prefixRDF  = new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#");
            Uri prefixFilm = new Uri("http://www.semprog.com/film#");

            //IGraph g = new Graph();                 //Load triples from file OWL
            //g.LoadFromFile("film-ontology.owl");
            //g.BaseUri = null; //!
            IGraph g = new VDS.RDF.Graph();             //Load triples from server (OWL)

            RdfsReasoner reasoner = new RdfsReasoner(); //Apply reasoner

            reasoner.Initialise(g);
            reasoner.Apply(g);


            g.BaseUri = null;   //!!!!!!!!
            TripleStore store = new TripleStore();

            store.Add(g);

            SparqlParameterizedString queryString = new SparqlParameterizedString();

            queryString.Namespaces.AddNamespace("rdf", prefixRDF);
            queryString.Namespaces.AddNamespace("film", prefixFilm);
            queryString.CommandText = "SELECT ?who WHERE { ?who rdf:type film:Person }";

            string sparql = "";

            sparql = File.ReadAllText("sparql1.txt");

            SparqlQueryParser parser = new SparqlQueryParser();
            //SparqlQuery query = parser.ParseFromString(queryString.ToString());
            SparqlQuery query = parser.ParseFromString(sparql);

            Console.WriteLine(query.ToAlgebra());
            Console.WriteLine(query.ToString());

            //ISparqlQueryProcessor processor = new LeviathanQueryProcessor(store);   //process query
            //SparqlResultSet results = processor.ProcessQuery(query) as SparqlResultSet;

            ISparqlQueryProcessor processor = new MirageQueryProcessor(mapping);//new LeviathanQueryProcessor(store);   //process query
            string results = processor.ProcessQuery(query) as string;

            Console.WriteLine(results);
            //if (results is SparqlResultSet)
            //{
            //    SparqlResultSet rset = (SparqlResultSet)results;
            //    foreach (SparqlResult result in rset)
            //    {
            //        Console.WriteLine(result);
            //    }
            //}
        }
Esempio n. 34
0
        private Uri ReadRemoteTripleFormat(Uri graph, Uri location, RdfSerializationFormat format)
        {
            using (VDS.RDF.Storage.VirtuosoManager m = new VDS.RDF.Storage.VirtuosoManager(CreateConnectionString()))
            {
                using (VDS.RDF.Graph g = new VDS.RDF.Graph())
                {
                    UriLoader.Load(g, location);
                    g.BaseUri = graph;
                    m.SaveGraph(g);
                }
            }

            return(graph);
        }
        private VDS.RDF.TripleStore CreateNewTripleStore(IDictionary <string, string> graphs)
        {
            var store = new VDS.RDF.TripleStore();

            foreach (var graph in graphs)
            {
                var g = new VDS.RDF.Graph();

                g.BaseUri = new Uri(graph.Value);

                var ttlparser = new TurtleParser();
                ttlparser.Load(g, AppDomain.CurrentDomain.BaseDirectory + $"Setup/Graphs/{graph.Key}");
                store.Add(g);
            }
            ;

            // TODO: Check if usesGraph is in graphGraph
            return(store);
        }
Esempio n. 36
0
        public string AsString(SparqlResultsFormat format)
        {
            var g       = new VDS.RDF.Graph();
            var results = new List <SparqlResult>();

            foreach (var graphUri in Graphs)
            {
                var s = new Set();
                s.Add(SparqlResultVariableName, g.CreateUriNode(new Uri(graphUri)));
                results.Add(new SparqlResult(s));
            }
            var rs     = new SparqlResultSet(results);
            var writer = GetWriter(format);
            var sw     = new StringWriter();

            writer.Save(rs, sw);
            sw.Flush();
            return(sw.ToString());
        }
Esempio n. 37
0
        private Uri ReadTripleFormat(TextReader reader, Uri graphUri, RdfSerializationFormat format, bool update)
        {
            using (VDS.RDF.Storage.VirtuosoManager m = new VDS.RDF.Storage.VirtuosoManager(CreateConnectionString()))
            {
                using (VDS.RDF.Graph graph = new VDS.RDF.Graph())
                {
                    IRdfReader parser = dotNetRDFStore.GetReader(format);
                    parser.Load(graph, reader);
                    graph.BaseUri = graphUri;
                    if (update)
                    {
                        m.UpdateGraph(graphUri, graph.Triples, new Triple[] {});
                    }
                    else
                    {
                        m.SaveGraph(graph);
                    }
                }
            }

            return(graphUri);
        }
Esempio n. 38
0
        public void Write(Stream fs, Uri graph, RdfSerializationFormat format)
        {
            using (VDS.RDF.Storage.VirtuosoManager m = new VDS.RDF.Storage.VirtuosoManager(CreateConnectionString()))
            {
                using (VDS.RDF.Graph g = new VDS.RDF.Graph())
                {
                    m.LoadGraph(g, graph);

                    StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);

                    switch (format)
                    {
                    case RdfSerializationFormat.RdfXml:
                    {
                        VDS.RDF.Writing.RdfXmlWriter wr = new VDS.RDF.Writing.RdfXmlWriter();
                        wr.Save(g, sw);
                        break;
                    }
                    }
                }
            }
        }
Esempio n. 39
0
        private void AddResources(IModel model, Stream stream)
        {
            string connectionString = "Server=localhost:1111;uid=dba;pwd=dba;Charset=utf-8";

            using (StreamReader reader = new StreamReader(stream))
            {
                string data = reader.ReadToEnd();

                using (VDS.RDF.Storage.VirtuosoManager m = new VDS.RDF.Storage.VirtuosoManager(connectionString))
                {
                    using (VDS.RDF.Graph graph = new VDS.RDF.Graph())
                    {
                        IRdfReader parser = dotNetRDFStore.GetReader(RdfSerializationFormat.N3);
                        parser.Load(graph, new StringReader(data));

                        graph.BaseUri = model.Uri;

                        m.UpdateGraph(model.Uri, graph.Triples, new List <Triple>());
                    }
                }
            }
        }
Esempio n. 40
0
        public static ISPARQLQueryable <T> GetQuerable <T>(string data,
                                                           bool autoquotation              = true,
                                                           bool treatUri                   = true,
                                                           IEnumerable <Prefix> prefixes   = null,
                                                           bool skipTriplesWithEmptyObject = false,
                                                           bool mindAsterisk               = false,
                                                           bool useStore                   = false,
                                                           string defaultGraphUri          = "http://test.org/defaultgraph")
        {
            DynamicSPARQLSpace.dotNetRDF.Connector connector = null;

            if (useStore)
            {
                var store = new VDS.RDF.TripleStore();
                store.LoadFromString(data);
                connector = new Connector(new InMemoryDataset(store, new Uri(defaultGraphUri)));

                // var store2 = new VDS.RDF.Query.SparqlRemoteEndpoint(new Uri("http://10.109.219.4:9999/blazegraph/"));

                //store2.SetCredentials("");
            }
            else
            {
                var graph = new VDS.RDF.Graph();
                graph.LoadFromFile(data);
                connector = new Connector(new InMemoryDataset(graph));
            }


            dynamic dyno = DynamicSPARQL.CreateDyno(connector.GetQueryingFunction(),
                                                    updateFunc: connector.GetUpdateFunction(),
                                                    autoquotation: autoquotation,
                                                    treatUri: treatUri,
                                                    prefixes: prefixes,
                                                    skipTriplesWithEmptyObject: skipTriplesWithEmptyObject,
                                                    mindAsterisk: mindAsterisk);

            return(new SPARQLQuery <T>(dyno));
        }
Esempio n. 41
0
        private Uri ReadTripleFormat(TextReader reader, Uri graphUri, RdfSerializationFormat format, bool update)
        {
            using (VirtuosoManager manager = new VirtuosoManager(CreateConnectionString()))
            {
                using (VDS.RDF.Graph graph = new VDS.RDF.Graph())
                {
                    dotNetRDFStore.TryParse(reader, graph, format);

                    graph.BaseUri = graphUri;

                    if (update)
                    {
                        manager.UpdateGraph(graphUri, graph.Triples, new Triple[] { });
                    }
                    else
                    {
                        manager.SaveGraph(graph);
                    }
                }
            }

            return(graphUri);
        }
Esempio n. 42
0
        public override void Write(Stream fs, Uri graph, RdfSerializationFormat format)
        {
            using (VirtuosoManager manager = new VirtuosoManager(CreateConnectionString()))
            {
                using (VDS.RDF.Graph g = new VDS.RDF.Graph())
                {
                    manager.LoadGraph(g, graph);

                    StreamWriter streamWriter = new StreamWriter(fs, Encoding.UTF8);

                    switch (format)
                    {
                    case RdfSerializationFormat.RdfXml:
                    {
                        VDS.RDF.Writing.RdfXmlWriter xmlWriter = new VDS.RDF.Writing.RdfXmlWriter();

                        xmlWriter.Save(g, streamWriter);

                        break;
                    }
                    }
                }
            }
        }
Esempio n. 43
0
        static void CustomQueryLMS_KMS()
        {
            IGraph g = new VDS.RDF.Graph();                 //Load triples from file OWL

            g.LoadFromFile("combined.owl");
            g.BaseUri = null; //!

            //INode subj = g.CreateUriNode(new Uri("http://www.semanticweb.org/KMS/User/1"));
            //INode pred = g.CreateUriNode(new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"));
            //INode obj = g.CreateUriNode(new Uri("http://www.semanticweb.org/KMS/User"));
            //g.Assert(new Triple(subj,pred,obj));


            RdfsReasoner reasoner = new RdfsReasoner(); //Apply reasoner

            reasoner.Initialise(g);
            reasoner.Apply(g);



            g.BaseUri = null;   //!!!!!!!!
            TripleStore store = new TripleStore();

            store.Add(g);

            SparqlParameterizedString queryString = new SparqlParameterizedString();

            //queryString.CommandText = @"SELECT * WHERE { ?user <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.semanticweb.org/KMS/User>.
            //                                             OPTIONAL {?user <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.semanticweb.org/LMS/User>}}";
            // queryString.CommandText = @"SELECT *
            //WHERE { ?usr <http://www.semanticweb.org/LMS/User#EMAIL> ?email.
            //                                ?usr1 <http://www.semanticweb.org/KMS/User#EMAIL> ?email}";
            //queryString.CommandText = @"SELECT *
            //WHERE { ?usr <http://www.semanticweb.org/LMS/User#ROLE_ID> ?roleID.
            //                                ?role <http://www.semanticweb.org/LMS/Role#ID> ?roleID.
            //                                ?role <http://www.semanticweb.org/LMS/Role#NAME> ""Teacher""}";

            //queryString.Namespaces.AddNamespace("owl", new Uri("http://www.w3.org/2002/07/owl#"));
            //queryString.CommandText = @"SELECT * WHERE {
            //                                            ?property owl:equivalentProperty ?property1
            //                                            filter regex(str(?property), '^http://www.semanticweb.org/FEDERATED/Kunde#NAME$')}";

            queryString.CommandText = @"SELECT *
								        WHERE { ?s <http://www.semanticweb.org/FEDERATED/Kunde#EMAIL> ?email.
                                                ?s1 <http://www.semanticweb.org/LMS/User#EMAIL> ?email}";

            SparqlQueryParser parser = new SparqlQueryParser();
            //SparqlQuery query = parser.ParseFromString(queryString.ToString());
            SparqlQuery query = parser.ParseFromString(queryString.ToString());

            Dictionary <string, string> dbURIs = new Dictionary <string, string>();

            dbURIs.Add("http://www.semanticweb.org/KMS/", @"Data Source = ASUS\SQLEXPRESS; Initial Catalog = KMS; Integrated Security = True");
            dbURIs.Add("http://www.semanticweb.org/LMS/", @"Data Source = ASUS\SQLEXPRESS; Initial Catalog = LMS; Integrated Security = True");
            ResolveBGPsFromDB(query.ToAlgebra(), g, dbURIs);

            Console.WriteLine(query.ToAlgebra());
            Console.WriteLine(query.ToString());

            //ISparqlQueryProcessor processor = new LeviathanQueryProcessor(store);   //process query
            //SparqlResultSet results = processor.ProcessQuery(query) as SparqlResultSet;

            ISparqlQueryProcessor processor = new QuantumQueryProcessor(store);//new LeviathanQueryProcessor(store);   //process query
            var results = processor.ProcessQuery(query) as SparqlResultSet;

            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                foreach (SparqlResult result in rset)
                {
                    Console.WriteLine(result);
                }
            }
        }
Esempio n. 44
0
        public void NodeCompareToMixedNodes3()
        {
            Graph g = new Graph();
            Graph h = new Graph();

            IBlankNode b = g.CreateBlankNode();
            ILiteralNode plain = g.CreateLiteralNode("plain");
            IUriNode u = g.CreateUriNode("rdf:type");
            List<INode> nodes = new List<INode>()
            {
                b,
                g.CreateBlankNode(),
                g.CreateBlankNode("id"),
                g.CreateLiteralNode("1.2e3", new Uri(XmlSpecsHelper.XmlSchemaDataTypeFloat)),
                g.CreateLiteralNode("1.2", new Uri(XmlSpecsHelper.XmlSchemaDataTypeFloat)),
                g.CreateLiteralNode("1.2e1", new Uri(XmlSpecsHelper.XmlSchemaDataTypeFloat)),
                g.CreateLiteralNode("10", new Uri(XmlSpecsHelper.XmlSchemaDataTypeShort)),
                g.CreateLiteralNode("-3", new Uri(XmlSpecsHelper.XmlSchemaDataTypeShort)),
                g.CreateLiteralNode("1.2E4", new Uri(XmlSpecsHelper.XmlSchemaDataTypeFloat)),
                g.CreateLiteralNode("http://example.org:8080", new Uri(XmlSpecsHelper.XmlSchemaDataTypeAnyUri)),
                g.CreateLiteralNode("http://example.org/path", new Uri(XmlSpecsHelper.XmlSchemaDataTypeAnyUri)),
                g.CreateLiteralNode("ftp://ftp.example.org", new Uri(XmlSpecsHelper.XmlSchemaDataTypeAnyUri)),
                g.CreateLiteralNode("1.2e0", new Uri(XmlSpecsHelper.XmlSchemaDataTypeFloat)),
                DateTime.Now.ToLiteral(g),
                DateTime.Now.AddYears(3).AddDays(1).ToLiteral(g),
                DateTime.Now.AddYears(-25).AddMinutes(-17).ToLiteral(g),
                g.CreateLiteralNode("1.2e-1", new Uri(XmlSpecsHelper.XmlSchemaDataTypeFloat)),
                g.CreateLiteralNode("10", new Uri(XmlSpecsHelper.XmlSchemaDataTypeFloat)),
                g.CreateLiteralNode("10e14", new Uri(XmlSpecsHelper.XmlSchemaDataTypeFloat)),
                h.CreateBlankNode(),
                h.CreateBlankNode("id"),
                b,
                plain,
                g.CreateLiteralNode("plain english","en"),
                g.CreateLiteralNode("1", new Uri(XmlSpecsHelper.XmlSchemaDataTypeInteger)),
                g.CreateLiteralNode("10", new Uri(XmlSpecsHelper.XmlSchemaDataTypeInteger)),
                g.CreateLiteralNode("plain french","fr"),
                g.CreateLiteralNode("typed", new Uri(XmlSpecsHelper.XmlSchemaDataTypeString)),
                (1234).ToLiteral(g),
                (12.34m).ToLiteral(g),
                (12.34d).ToLiteral(g),
                (false).ToLiteral(g),
                g.CreateLiteralNode((1).ToString("X2"), new Uri(XmlSpecsHelper.XmlSchemaDataTypeHexBinary)),
                g.CreateLiteralNode((10).ToString("X2"), new Uri(XmlSpecsHelper.XmlSchemaDataTypeHexBinary)),
                (true).ToLiteral(g),
                plain,
                u,
                g.CreateUriNode(new Uri("http://example.org")),
                g.CreateUriNode(new Uri("http://example.org:8080")),
                g.CreateLiteralNode("1", new Uri(XmlSpecsHelper.XmlSchemaDataTypeByte)),
                g.CreateLiteralNode("10", new Uri(XmlSpecsHelper.XmlSchemaDataTypeByte)),
                g.CreateLiteralNode("-3", new Uri(XmlSpecsHelper.XmlSchemaDataTypeByte)),
                g.CreateUriNode(new Uri("http://www.dotnetrdf.org")),
                g.CreateUriNode(new Uri("http://www.dotnetrdf.org/configuration#")),
                g.CreateUriNode(new Uri("http://www.dotnetrdf.org/Configuration#")),
                g.CreateUriNode(new Uri("mailto:[email protected]")),
                u
            };

            this.ShowOrdering(nodes);

            this.CheckCombinations(nodes);
        }
Esempio n. 45
0
        public void ParsingUriLoader()
        {
            if (!TestConfigManager.GetSettingAsBoolean(TestConfigManager.UseRemoteParsing))
            {
                Assert.Inconclusive("Test Config marks Remote Parsing as unavailable, test cannot be run");
            }

            int defaultTimeout = Options.UriLoaderTimeout;

            try
            {
#if !NO_URICACHE
                Options.UriLoaderCaching = false;
#endif
                Options.UriLoaderTimeout = 45000;

                List <Uri> testUris = new List <Uri>()
                {
#if !NO_HTMLAGILITYPACK // Resource returns RDFa
                    new Uri("http://www.bbc.co.uk/programmes/b0080bbs#programme"),
#endif
                    new Uri("http://dbpedia.org/resource/Southampton"),
#if !NO_FILE // file: urls not supported
                    new Uri("file:///resources\\MergePart1.ttl"),
#endif
                    new Uri("http://www.dotnetrdf.org/configuration#")
                };

                Console.WriteLine("## URI Loader Test Suite");

                foreach (Uri u in testUris)
                {
                    Console.WriteLine("# Testing URI '" + u.AbsoluteUri + "'");

                    //Load the Test RDF
                    Graph g = new Graph();
                    Assert.IsNotNull(g);
                    VDS.RDF.Parsing.UriLoader.Load(g, u);

                    if (!u.IsFile)
                    {
                        Assert.AreEqual(u, g.BaseUri);
                    }

                    Console.WriteLine();

                    Console.WriteLine("Following Triples were generated");
                    foreach (Triple t in g.Triples)
                    {
                        Console.WriteLine(t.ToString());
                    }
                    Console.WriteLine();
                }
            }
            finally
            {
#if !NO_URICACHE
                Options.UriLoaderCaching = true;
#endif
                Options.UriLoaderTimeout = defaultTimeout;
            }
        }
Esempio n. 46
0
        public void GraphEquality()
        {
            if (!TestConfigManager.GetSettingAsBoolean(TestConfigManager.UseRemoteParsing))
            {
                Assert.Inconclusive("Test Config marks Remote Parsing as unavailable, test cannot be run");
            }

            try
            {
#if !NO_URICACHE
                Options.UriLoaderCaching = false;
#endif
                Console.WriteLine("Going to get two copies of a Graph from DBPedia and compare");
                Console.WriteLine("Using the DBPedia Graph for Barack Obama");

                Graph g      = new Graph();
                Graph h      = new Graph();
                Uri   target = new Uri("http://dbpedia.org/resource/Barack_Obama");

                VDS.RDF.Parsing.UriLoader.Load(g, target);
                Console.WriteLine("Loaded first copy OK - " + g.Triples.Count + " Triples");
                VDS.RDF.Parsing.UriLoader.Load(h, target);
                Console.WriteLine("Loaded second copy OK - " + h.Triples.Count + " Triples");

                //Should have same Base Uri
                Assert.AreEqual(g.BaseUri, h.BaseUri, "Should have the same Base URI after being loaded from the same URI via the URILoader");

                //Do equality check
                Console.WriteLine("Checking the Equality of the Graphs");
                //TestTools.CompareGraphs(g, h, true);
                Dictionary <INode, INode> mapping;
                bool equals = g.Equals(h, out mapping);
                Assert.IsTrue(equals, "Graphs should have been equal");
                if (mapping != null)
                {
                    Console.WriteLine("Blank Node Mapping was:");
                    foreach (KeyValuePair <INode, INode> pair in mapping)
                    {
                        Console.WriteLine(pair.Key.ToString() + " => " + pair.Value.ToString());
                    }
                }
                Console.WriteLine();

                //Get a third graph of something different
                Console.WriteLine("Going to get a third Graph of something different and check it is non-equal");
                Uri   target2 = new Uri("http://dbpedia.org/resource/Nottingham");
                Graph i       = new Graph();
                VDS.RDF.Parsing.UriLoader.Load(i, target2);

                //Should have different Base URIs and be non-equal
                Assert.AreNotEqual(g.BaseUri, i.BaseUri, "Graphs retrieved from different URIs via the URILoader should have different Base URIs");
                Assert.AreNotEqual(h.BaseUri, i.BaseUri, "Graphs retrieved from different URIs via the URILoader should have different Base URIs");
                Assert.IsFalse(g.Equals(i));
                Assert.IsFalse(h.Equals(i));
                //TestTools.CompareGraphs(g, i, false);
                //TestTools.CompareGraphs(h, i, false);
            }
            catch (WebException webEx)
            {
                TestTools.ReportError("Web Exception", webEx);
                Console.WriteLine();
                Console.WriteLine("Unable to retrieve the Graphs from the Web successfully!");
                Assert.Inconclusive();
            }
            catch (RdfParseException parseEx)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
#if !NO_URICACHE
                Options.UriLoaderCaching = true;
#endif
            }
        }
 public ComparisonHelperTests()
 {
     _graph = new Graph();
 }