Example #1
0
        internal SparqlResult(object resultObject, SparqlQueryContext sparqlQueryContext)
        {
            if (resultObject == null) throw new ArgumentNullException(nameof(resultObject));
            if (sparqlQueryContext == null) throw new ArgumentNullException(nameof(sparqlQueryContext));
            SourceSparqlQueryContext = sparqlQueryContext;

            ResultGraph = resultObject as IGraph;
            if (ResultGraph == null)
            {
                ResultSet = resultObject as SparqlResultSet;
                if (ResultSet == null)
                {
                    throw new ArgumentException(
                        $"Result object must be either a {typeof (IGraph).FullName} or a {typeof (SparqlResultSet).FullName} instance. Got a {resultObject.GetType().FullName}");
                }
                ResultFormat = sparqlQueryContext.SparqlResultsFormat ?? SparqlResultsFormat.Xml;
            }

            
            if (resultObject is IGraph)
            {
                ResultGraph = resultObject as IGraph;
                ResultFormat = sparqlQueryContext.GraphResultsFormat ?? RdfFormat.RdfXml;
            }
        }
Example #2
0
 public void Fill(SparqlResultSet results)
 {
     foreach (SparqlResult result in results)
     {
         this.ProcessResult(result);
     }
 }
        /// <summary>
        /// Validates the syntax to see if it is valid SPARQL Results
        /// </summary>
        /// <param name="data">Data to validate</param>
        /// <returns></returns>
        public ISyntaxValidationResults Validate(string data)
        {
            String message;
            try
            {
                SparqlResultSet results = new SparqlResultSet();
                StringParser.ParseResultSet(results, data);
                message = "Valid SPARQL Results - " + results.Count + " Results - Parser: " + this._parser.GetType().Name;

                return new SyntaxValidationResults(true, message, results);
            }
            catch (RdfParseException parseEx)
            {
                message = "Invalid SPARQL Results - Parsing Error from Parser: " + this._parser.GetType().Name + " - " + parseEx.Message;
                return new SyntaxValidationResults(message, parseEx);
            }
            catch (RdfException rdfEx)
            {
                message = "Invalid SPARQL Results - RDF Error from Parser: " + this._parser.GetType().Name + " - " + rdfEx.Message;
                return new SyntaxValidationResults(message, rdfEx);
            }
            catch (Exception ex)
            {
                message = "Invalid SPARQL Results - Error from Parser: " + this._parser.GetType().Name + " - " + ex.Message;
                return new SyntaxValidationResults(message, ex);
            }
        }
Example #4
0
        /// <summary>
        /// Makes a SPARQL Query against the Knowledge Base
        /// </summary>
        /// <param name="sparqlQuery">SPARQL Query</param>
        /// <returns></returns>
        public Object Query(String sparqlQuery)
        {
            SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri(this._sparqlUri));

            using (HttpWebResponse response = endpoint.QueryRaw(sparqlQuery))
            {
                try
                {
                    ISparqlResultsReader sparqlParser = MimeTypesHelper.GetSparqlParser(response.ContentType);
                    SparqlResultSet results = new SparqlResultSet();
                    sparqlParser.Load(results, new StreamReader(response.GetResponseStream()));

                    response.Close();
                    return results;
                }
                catch (RdfParserSelectionException)
                {
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    Graph g = new Graph();
                    parser.Load(g, new StreamReader(response.GetResponseStream()));

                    response.Close();
                    return g;
                }
            }
        }
        public void SparqlXmlWriter()
        {
            try
            {
                Graph g = new Graph();
                FileLoader.Load(g, "InferenceTest.ttl");

                Object results = g.ExecuteQuery("SELECT * WHERE {?s ?p ?o}");
                if (results is SparqlResultSet)
                {
                    TestTools.ShowResults(results);
                }

                StringBuilder output = new StringBuilder();
                System.IO.StringWriter writer = new System.IO.StringWriter(output);
                SparqlXmlWriter sparqlWriter = new SparqlXmlWriter();
                sparqlWriter.Save((SparqlResultSet)results, writer);

                Console.WriteLine();
                Console.WriteLine(output.ToString());
                Console.WriteLine();

                SparqlXmlParser parser = new SparqlXmlParser();
                SparqlResultSet results2 = new SparqlResultSet();
                StringParser.ParseResultSet(results2, output.ToString());

                Assert.AreEqual(((SparqlResultSet)results).Count, results2.Count, "Result Sets should have contained same number of Results");
                Assert.IsTrue(((SparqlResultSet)results).Equals(results2), "Result Sets should have been equal");
            }
            catch (Exception ex)
            {
                TestTools.ReportError("Error", ex, true);
            }
        }
        public ResultSetWindow(SparqlResultSet results)
        {
            InitializeComponent();
            this._formatter = new SparqlFormatter();
            this._grid = this.gridResults;

            this.RenderResultSet(results);
        }
 public BrightstarSparqlResultSet(object o)
 {
     if (o is SparqlResultSet)
     {
         _resultSet = o as SparqlResultSet;
         ResultType = _resultSet.ResultsType == SparqlResultsType.VariableBindings
                          ? BrightstarSparqlResultsType.VariableBindings
                          : BrightstarSparqlResultsType.Boolean;
     }
     else if (o is IGraph)
     {
         _graph = o as IGraph;
         ResultType = BrightstarSparqlResultsType.Graph;
     }
 }
Example #8
0
        /// <summary>
        /// overload of Execute query
        /// </summary>
        /// <param name="input">the query text as string</param>
        /// <returns></returns>
        public static SparqlResultSet ExecuteQueryWithString(string input)
        {
            //list to hold the results
            SparqlResultSet resultSet = new SparqlResultSet();
            try
            {

                //making the query
                Object result = manager.Query(input);
                resultSet = (SparqlResultSet)result;

            }
            catch { }
            return resultSet;
        }
Example #9
0
        /// <summary>
        /// Loads a Result Set from an Input Stream
        /// </summary>
        /// <param name="results">Result Set to load into</param>
        /// <param name="input">Input Stream to read from</param>
        public void Load(SparqlResultSet results, StreamReader input)
        {
            if (input == null) throw new RdfParseException("Cannot parse SPARQL Results from a null input stream");

            //Check Encoding
            if (input.CurrentEncoding != Encoding.UTF8)
            {
            #if !SILVERLIGHT
                this.RaiseWarning("Expected Input Stream to be encoded as UTF-8 but got a Stream encoded as " + input.CurrentEncoding.EncodingName + " - Please be aware that parsing errors may occur as a result");
            #else
                this.RaiseWarning("Expected Input Stream to be encoded as UTF-8 but got a Stream encoded as " + input.CurrentEncoding.GetType().Name + " - Please be aware that parsing errors may occur as a result");
            #endif
            }

            this.Load(results, (TextReader)input);
        }
Example #10
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();
 }
        public void ParsingResultSetHandlerImplicitSparqlRdfNTriples()
        {
            this.EnsureTestData("test.sparql.nt", new SparqlRdfWriter(new NTriplesWriter()));

            SparqlRdfParser parser = new SparqlRdfParser(new NTriplesParser());
            SparqlResultSet results = new SparqlResultSet();
            parser.Load(results, "test.sparql.nt");

            NTriplesFormatter formatter = new NTriplesFormatter();
            foreach (SparqlResult r in results)
            {
                Console.WriteLine(r.ToString(formatter));
            }

            Assert.IsFalse(results.IsEmpty, "Result Set should not be empty");
            Assert.AreEqual(SparqlResultsType.VariableBindings, results.ResultsType, "Results Type should be VariableBindings");
        }
Example #12
0
        public static SparqlResultSet RequestWithHTTP(string request)
        {
            SparqlResultSet toreturn = new SparqlResultSet();
            try
            {
                StreamReader sr = new StreamReader("endpointURI.txt");
                SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri(sr.ReadLine()));
                sr.Close();
                endpoint.Timeout = 999999;
                toreturn = endpoint.QueryWithResultSet(request);
            }
            catch (Exception e)
            {

                util.log(request + e.Message + "==>" + e.Data);
            }
            return toreturn;
        }
        /// <summary>
        /// Displays the given SPARQL Result Set
        /// </summary>
        /// <param name="results">SPARQL Result to display</param>
        public ResultSetViewerForm(SparqlResultSet results)
        {
            InitializeComponent();
            if (Constants.WindowIcon != null)
            {
                this.Icon = Constants.WindowIcon;
            }

            //Load Formatters
            List<INodeFormatter> formatters = new List<INodeFormatter>();
            Type targetType = typeof(INodeFormatter);
            foreach (Type t in Assembly.GetAssembly(targetType).GetTypes())
            {
                if (t.Namespace == null) continue;

                if (t.Namespace.Equals("VDS.RDF.Writing.Formatting"))
                {
                    if (t.GetInterfaces().Contains(targetType))
                    {
                        try
                        {
                            INodeFormatter formatter = (INodeFormatter)Activator.CreateInstance(t);
                            formatters.Add(formatter);
                            if (formatter.GetType().Equals(this._formatter.GetType())) this._formatter = formatter;
                        }
                        catch
                        {
                            //Ignore this Formatter
                        }
                    }
                }
            }
            formatters.Sort(new ToStringComparer<INodeFormatter>());
            this.cboFormat.DataSource = formatters;
            this.cboFormat.SelectedItem = this._formatter;
            this.cboFormat.SelectedIndexChanged += new System.EventHandler(this.cboFormat_SelectedIndexChanged);

            this.dgvResults.CellFormatting += new DataGridViewCellFormattingEventHandler(dgvTriples_CellFormatting);
            this.dgvResults.CellContentClick += new DataGridViewCellEventHandler(dgvTriples_CellClick);

            this._results = results;

            this.Text = this.GetTitle();
        }
        /// <summary>
        /// Returns whether the Knowledge Base is consistent
        /// </summary>
        public bool IsConsistent()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.Endpoint.Uri);
            request.Method = this.Endpoint.HttpMethods.First();
            request.ContentType = MimeTypesHelper.HttpSparqlAcceptHeader;

#if DEBUG
            if (Options.HttpDebugging)
            {
                Tools.HttpDebugRequest(request);
            }
#endif

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
#endif
                    ISparqlResultsReader parser = MimeTypesHelper.GetSparqlParser(response.ContentType);
                    SparqlResultSet results = new SparqlResultSet();
                    parser.Load(results, new StreamReader(response.GetResponseStream()));

                    //Expect a boolean result set
                    return results.Result;
                }
            }
            catch (WebException webEx)
            {
#if DEBUG
                if (Options.HttpDebugging)
                {
                    if (webEx.Response != null) Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                }
#endif
                throw new RdfReasoningException("A HTTP error occurred while communicating with the Pellet Server", webEx);
            }
        }
Example #15
0
        /// <summary>
        /// do a HTTP request using a sparql query from a sparql endpoint stated in a file
        /// </summary>
        /// <param name="request">sparql Query to be executed</param>
        /// <returns>set of results resulted from executing the query</returns>
        public static SparqlResultSet executeSparqlQuery(string request)
        {
            SparqlResultSet toreturn = new SparqlResultSet();
            try
            {
                string path = HttpRuntime.BinDirectory + "endpointURI.txt";
                StreamReader sr = new StreamReader(path);
                string endpointURI = sr.ReadLine();
                SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri (endpointURI));
                sr.Close();
                endpoint.Timeout = 999999;
                toreturn = endpoint.QueryWithResultSet(request);
            }
            catch (Exception e)
            {

                util.log(request + e.Message + "==>" + e.Data);
            }
            return toreturn;
        }
Example #16
0
 /// <summary>
 /// Saves the Result Set to the given Stream in the SPARQL Results JSON Format
 /// </summary>
 /// <param name="results">Result Set to save</param>
 /// <param name="output">Stream to save to</param>
 public void Save(SparqlResultSet results, TextWriter output)
 {
     try
     {
         this.GenerateOutput(results, output);
         output.Close();
     }
     catch
     {
         try
         {
             output.Close();
         }
         catch
         {
             //No Catch Actions
         }
         throw;
     }
 }
Example #17
0
 /// <summary>
 /// Saves the Result Set to the given Stream in the Sparql Results XML Format
 /// </summary>
 /// <param name="results"></param>
 /// <param name="output"></param>
 public virtual void Save(SparqlResultSet results, TextWriter output)
 {
     try
     {
         XmlDocument doc = this.GenerateOutput(results);
         doc.Save(output);
         output.Close();
     }
     catch
     {
         try
         {
             output.Close();
         }
         catch
         {
             //No Catch Actions
         }
         throw;
     }
 }
Example #18
0
 public static IList<CountryDto> GenerateCountriesOfEuropeResponse(SparqlResultSet resultSet)
 {
     var result = resultSet.Results;
     if (result == null) return null;
     var countries = new List<CountryDto>();
     foreach (var value in result)
     {
         var country = new CountryDto
         {
             Id = value.Value(SparqlResources.Country).ToString(),
             Name = value.Value(SparqlResources.CountryLabel).ToString()
                 .Replace(SparqlResources.EnLangQualifier, string.Empty)
         };
         if (value.HasValue(SparqlResources.Thumbnail))
         {
             country.Thumbnail = value.Value(SparqlResources.Thumbnail)?.ToString();
         }
         countries.Add(country);
     }
     return countries;
 }
 public void Apply(SparqlResultSet results)
 {
     switch (this._type)
     {
         case SparqlResultsType.Boolean:
             results.SetResult(this._r);
             break;
         case SparqlResultsType.VariableBindings:
             foreach (String var in this._vars)
             {
                 results.AddVariable(var);
             }
             foreach (SparqlResult res in this._results)
             {
                 results.AddResult(res);
             }
             break;
         default:
             throw new RdfParseException("The type property of a serialized SparqlResultSet did not contain a valid value");
     }
 }
Example #20
0
        public static List<SimpleArtistDto> GetSimpleArtists(SparqlResultSet resultSet)
        {
            var result = resultSet.Results;
            var simpleArtists = new List<SimpleArtistDto>();
            foreach (var entity in result)
            {
                var simpleArtistDto = new SimpleArtistDto
                {
                    Id = entity.Value(SparqlResources.Artist).ToString(),
                    Name = entity.Value(SparqlResources.ArtistName)
                        .ToString()
                        .Replace(SparqlResources.EnLangQualifier, string.Empty)
                };
                if (entity.HasValue(SparqlResources.Thumbnail))
                {
                    simpleArtistDto.Thumbnail = entity.Value(SparqlResources.Thumbnail)?.ToString();
                }
                simpleArtists.Add(simpleArtistDto);
            }

            return simpleArtists;
        }
Example #21
0
        public static void UpdateArtistData(ArtistDto artistDto, SparqlResultSet resultSet)
        {
            var result = resultSet.Results.FirstOrDefault();
            if (result == null) return;

            artistDto.Id = result.Value(SparqlResources.Artist).ToString();
            if (result.HasValue(SparqlResources.Wiki))
            {
                artistDto.Wiki = result.Value(SparqlResources.Wiki)?.ToString();
            }
            if (result.HasValue(SparqlResources.Homepage))
            {
                artistDto.Website = result.Value(SparqlResources.Homepage)?.ToString();
            }
            if (result.HasValue(SparqlResources.Thumbnail))
            {
                artistDto.Thumbnail = result.Value(SparqlResources.Thumbnail)?.ToString();
            }
            if (result.HasValue(SparqlResources.Abstract))
            {
                artistDto.Abstract = result.Value(SparqlResources.Abstract)?.ToString();
            }
        }
        public void WritingSparqlXmlWithNulls()
        {
            TripleStore store = new TripleStore();
            store.Add(new Graph());
            Graph g = new Graph();
            g.BaseUri = new Uri("http://example.org/graph");
            store.Add(g);

            Object results = store.ExecuteQuery("SELECT DISTINCT ?g WHERE { GRAPH ?g { ?s ?p ?o } }");
            if (results is SparqlResultSet)
            {
                SparqlResultSet rset = (SparqlResultSet)results;
                SparqlXmlWriter writer = new SparqlXmlWriter();
                writer.Save(rset, "temp.srx");

                SparqlXmlParser parser = new SparqlXmlParser();
                SparqlResultSet rset2 = new SparqlResultSet();
                parser.Load(rset2, "temp.srx");

                rset.Trim();
                Console.WriteLine("Original Results");
                TestTools.ShowResults(rset);
                Console.WriteLine();

                rset2.Trim();
                Console.WriteLine("Serializes and Parsed Results");
                TestTools.ShowResults(rset2);
                Console.WriteLine();

                Assert.AreEqual(rset, rset2, "Result Sets should be equal");
            }
            else
            {
                Assert.Fail("Query did not return a Result Set as expected");
            }
        }
Example #23
0
 /// <summary>
 /// Saves the SPARQL Result Set to the given Stream
 /// </summary>
 /// <param name="results">Result Set to save</param>
 /// <param name="output">Stream to save to</param>
 public void Save(SparqlResultSet results, TextWriter output)
 {
     this._writer.Save(this.GenerateOutput(results), output);
 }
Example #24
0
 private void CompareSparqlResults(SparqlResultSet actual, SparqlResultSet expected, bool reduced)
 {
     if (expected.ResultsType == SparqlResultsType.Boolean)
     {
         Assert.IsTrue(actual.ResultsType == SparqlResultsType.Boolean);
         Assert.AreEqual(expected.Result, actual.Result);
     }
     else if (expected.ResultsType == SparqlResultsType.VariableBindings)
     {
         if (reduced)
         {
             Assert.IsTrue(actual.Results.Count <= expected.Results.Count,
                           "Too many results returned expected <= {0}, got {1}",
                           expected.Results.Count, actual.Results.Count);
         }
         else
         {
             Assert.AreEqual(expected.Results.Count, actual.Results.Count,
                             "Unexpected number of rows in results. Expected {0}, got {1}",
                             expected.Results.Count, actual.Results.Count);
         }
         foreach (var actualSolution in actual.Results)
         {
             Assert.IsTrue(expected.Results.Any(x => CompareSolutions(actualSolution, x)),
                           "Could not find a match for solution {0} in the expected results set", actualSolution);
         }
     }
     else
     {
         Assert.Fail("Cannot compare results to result set of type {0}", expected.ResultsType);
     }
 }
    protected void Button11_Click(object sender, EventArgs e)
    {
        //Bachelor in Communications Technology Program Details
        TripleStore store = new TripleStore();
        Graph       g1    = new Graph();

        g1.LoadFromFile(Server.MapPath("SVUModeling.rdf"));
        store.Add(g1);
        InMemoryDataset ds = new InMemoryDataset(store);
        //Get the Query processor
        ISparqlQueryProcessor processor = new LeviathanQueryProcessor(ds);

        Label1.Text       = "Bachelor in Communications Technology Program : BACT Details";
        Label1.Visible    = true;
        GridView1.Visible = false;
        Label2.Text       = "Bachelor in Communications Technology Program Informations ";
        Label2.Visible    = true;
        // to select the Communications Technology program's Director Informations
        SparqlQueryParser sparqlparser = new SparqlQueryParser();
        SparqlQuery       query        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                prefix owl: <http://www.w3.org/2002/07/owl#>
                prefix foaf: <http://xmlns.com/foaf/0.1/#>
                SELECT   ?BACTDirectorInfo
                WHERE {
                ?t   owl:TelecommunicationsTechnologyDirectorInfoProperty ?BACTDirectorInfo
                }");
        Object            results      = processor.ProcessQuery(query);
        DataTable         DT2          = new DataTable();
        SparqlResultSet   rset         = (SparqlResultSet)results;

        DT2 = FillDataTable(rset);
        GridView2.DataSource = DT2;
        GridView2.DataBind();
        GridView2.Visible = true;
        //to retrival the Teachers of Bachelor in Communications Technology program
        Label3.Text    = "Teachers Of Bachelor in Communications Technology Program";
        Label3.Visible = true;
        SparqlQueryParser sparqlparser3 = new SparqlQueryParser();
        SparqlQuery       query3        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                prefix foaf: <http://xmlns.com/foaf/0.1/#>
                prefix owl: <http://www.w3.org/2002/07/owl#>
                SELECT   ?BACTTeachers
                WHERE {
                ?t   owl:TeachersOfTelecommunicationsTechnology ?BACTTeachers
                }");
        Object            results3      = processor.ProcessQuery(query3);
        DataTable         DT3           = new DataTable();
        SparqlResultSet   rset3         = (SparqlResultSet)results3;

        DT3 = FillDataTable(rset3);
        GridView3.DataSource = DT3;
        GridView3.DataBind();
        GridView3.Visible = true;
        //to select Courses Of Bachelor in Communications Technology
        Label4.Text    = "Courses of Bachelor in Communications Technology Program";
        Label4.Visible = true;
        SparqlQueryParser sparqlparser4 = new SparqlQueryParser();
        SparqlQuery       query4        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                prefix owl: <http://www.w3.org/2002/07/owl#>
                SELECT   ?BACTCourses
                WHERE {
                ?t   owl:CoursesOfTelecommunicationsTechnology ?BACTCourses
                }");
        Object            results4      = processor.ProcessQuery(query4);
        DataTable         DT4           = new DataTable();
        SparqlResultSet   rset4         = (SparqlResultSet)results4;

        DT4 = FillDataTable(rset4);
        GridView4.DataSource = DT4;
        GridView4.DataBind();
        GridView4.Visible = true;
    }
        /// <summary>
        /// Method which generates the RDF Graph of a SPARQL Result Set
        /// </summary>
        /// <param name="results">Result Set</param>
        /// <returns></returns>
        public IGraph GenerateOutput(SparqlResultSet results)
        {
            //Create the Graph for the Output
            IGraph g = new Graph();

            //Add the relevant namespaces
            g.NamespaceMap.AddNamespace("rs", UriFactory.Create(SparqlSpecsHelper.SparqlRdfResultsNamespace));

            //Create relevant Nodes
            IUriNode rdfType        = g.CreateUriNode("rdf:type");
            IUriNode resultSetClass = g.CreateUriNode("rs:ResultSet");
            IUriNode resultVariable = g.CreateUriNode("rs:resultVariable");
            IUriNode solution       = g.CreateUriNode("rs:solution");
            IUriNode binding        = g.CreateUriNode("rs:binding");
            IUriNode value          = g.CreateUriNode("rs:value");
            IUriNode variable       = g.CreateUriNode("rs:variable");
            IUriNode boolean        = g.CreateUriNode("rs:boolean");

            //First we declare a Result Set
            IBlankNode rset = g.CreateBlankNode();

            g.Assert(new Triple(rset, rdfType, resultSetClass));

            if (results.ResultsType == SparqlResultsType.VariableBindings)
            {
                //Assert a Triple for each Result Variable
                foreach (String v in results.Variables)
                {
                    g.Assert(new Triple(rset, resultVariable, g.CreateLiteralNode(v)));
                }

                //Then we're going to define a solution for each result
                foreach (SparqlResult r in results)
                {
                    IBlankNode sln = g.CreateBlankNode();
                    g.Assert(new Triple(rset, solution, sln));

                    foreach (String v in results.Variables)
                    {
                        //Only define Bindings if there is a value and it is non-null
                        if (r.HasValue(v) && r[v] != null)
                        {
                            IBlankNode bnd = g.CreateBlankNode();
                            g.Assert(new Triple(sln, binding, bnd));
                            g.Assert(new Triple(bnd, variable, g.CreateLiteralNode(v)));
                            switch (r[v].NodeType)
                            {
                            case NodeType.Blank:
                                IBlankNode b = (IBlankNode)r[v];
                                IBlankNode bMapped;
                                if (b.GraphUri == null)
                                {
                                    bMapped = g.CreateBlankNode(b.InternalID + "def");
                                }
                                else
                                {
                                    bMapped = g.CreateBlankNode(b.InternalID + b.GraphUri.GetEnhancedHashCode());
                                }
                                g.Assert(new Triple(bnd, value, bMapped));
                                break;

                            case NodeType.GraphLiteral:
                                throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("SPARQL Results RDF Serialization"));

                            case NodeType.Literal:
                            case NodeType.Uri:
                                g.Assert(new Triple(bnd, value, r[v].CopyNode(g)));
                                break;

                            default:
                                throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("SPARQL Results RDF Serialization"));
                            }
                        }
                    }
                }
            }
            else
            {
                //A Boolean Result Set
                g.Assert(new Triple(rset, boolean, g.CreateLiteralNode(results.Result.ToString(), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeBoolean))));
            }

            return(g);
        }
 /// <summary>
 /// Displays the given SPARQL Result Set and prefixes the Form Title with the given Title
 /// </summary>
 /// <param name="results">SPARQL Result Set to display</param>
 /// <param name="title">Title</param>
 public ResultSetViewerForm(SparqlResultSet results, String title)
     : this(results)
 {
     this.Text = this.GetTitle(title);
 }
        /// <summary>
        /// Internal method which generates the HTML Output for the Graph.
        /// </summary>
        /// <param name="context">Writer Context.</param>
        private void GenerateOutput(HtmlWriterContext context)
        {
            Object results;

            // Add the Namespaces we want to use later on
            context.QNameMapper.AddNamespace("owl", UriFactory.Create(NamespaceMapper.OWL));
            context.QNameMapper.AddNamespace("rdf", UriFactory.Create(NamespaceMapper.RDF));
            context.QNameMapper.AddNamespace("rdfs", UriFactory.Create(NamespaceMapper.RDFS));
            context.QNameMapper.AddNamespace("dc", UriFactory.Create("http://purl.org/dc/elements/1.1/"));
            context.QNameMapper.AddNamespace("dct", UriFactory.Create("http://purl.org/dc/terms/"));
            context.QNameMapper.AddNamespace("vann", UriFactory.Create("http://purl.org/vocab/vann/"));
            context.QNameMapper.AddNamespace("vs", UriFactory.Create("http://www.w3.org/2003/06/sw-vocab-status/ns#"));

            // Find the Node that represents the Schema Ontology
            // Assumes there is exactly one thing given rdf:type owl:Ontology
            IUriNode ontology  = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.OWL + "Ontology"));
            IUriNode rdfType   = context.Graph.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfType));
            IUriNode rdfsLabel = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.RDFS + "label"));
            INode    ontoNode  = context.Graph.GetTriplesWithPredicateObject(rdfType, ontology).Select(t => t.Subject).FirstOrDefault();
            INode    ontoLabel = (ontoNode != null) ? context.Graph.GetTriplesWithSubjectPredicate(ontoNode, rdfsLabel).Select(t => t.Object).FirstOrDefault() : null;

            // Stuff for formatting
            // We'll use the Turtle Formatter to get nice QNames wherever possible
            context.NodeFormatter = new TurtleFormatter(context.QNameMapper);
            context.UriFormatter  = (IUriFormatter)context.NodeFormatter;

            // Page Header
            context.HtmlWriter.Write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML+RDFa 1.0//EN\" \"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd\">");
            context.HtmlWriter.WriteLine();
            context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Html);
            context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Head);
            context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Title);
            context.HtmlWriter.WriteEncodedText("Schema");
            if (ontoNode != null && ontoLabel != null)
            {
                context.HtmlWriter.WriteEncodedText(" - " + ontoLabel.ToSafeString());
            }
            else if (context.Graph.BaseUri != null)
            {
                context.HtmlWriter.WriteEncodedText(" - " + context.Graph.BaseUri.AbsoluteUri);
            }
            context.HtmlWriter.RenderEndTag();
            if (!Stylesheet.Equals(String.Empty))
            {
                context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Href, Stylesheet);
                context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Type, "text/css");
                context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Rel, "stylesheet");
                context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Link);
                context.HtmlWriter.RenderEndTag();
            }
            context.HtmlWriter.RenderEndTag();
            context.HtmlWriter.WriteLine();

            // Start Body
            context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Body);

            // Title
            context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H2);
            context.HtmlWriter.WriteEncodedText("Schema");
            if (ontoNode != null && ontoLabel != null)
            {
                context.HtmlWriter.WriteEncodedText(" - " + ontoLabel.ToSafeString());
            }
            else if (context.Graph.BaseUri != null)
            {
                context.HtmlWriter.WriteEncodedText(" - " + context.Graph.BaseUri.AbsoluteUri);
            }
            context.HtmlWriter.RenderEndTag();
            context.HtmlWriter.WriteLine();

            // Show the Description of the Schema (if any)
            if (ontoNode != null)
            {
                SparqlParameterizedString getOntoDescrip = new SparqlParameterizedString();
                getOntoDescrip.Namespaces  = context.QNameMapper;
                getOntoDescrip.CommandText = "SELECT * WHERE { @onto a owl:Ontology . OPTIONAL { @onto rdfs:comment ?description } . OPTIONAL { @onto vann:preferredNamespacePrefix ?nsPrefix ; vann:preferredNamespaceUri ?nsUri } . OPTIONAL { @onto dc:creator ?creator . ?creator (foaf:name | rdfs:label) ?creatorName } }";
                getOntoDescrip.SetParameter("onto", ontoNode);

                try
                {
                    results = context.Graph.ExecuteQuery(getOntoDescrip);
                    if (results is SparqlResultSet)
                    {
                        if (!((SparqlResultSet)results).IsEmpty)
                        {
                            SparqlResult ontoInfo = ((SparqlResultSet)results)[0];

                            // Show rdfs:comment on the Ontology
                            if (ontoInfo.HasValue("description"))
                            {
                                INode descrip = ontoInfo["description"];
                                if (descrip.NodeType == NodeType.Literal)
                                {
                                    context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P);
                                    context.HtmlWriter.Write(((ILiteralNode)descrip).Value);
                                    context.HtmlWriter.RenderEndTag();
                                    context.HtmlWriter.WriteLine();
                                }
                            }

                            // Show Author Information
                            if (ontoInfo.HasValue("creator"))
                            {
                                INode author     = ontoInfo["creator"];
                                INode authorName = ontoInfo["creatorName"];
                                context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P);
                                context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Em);
                                context.HtmlWriter.WriteEncodedText("Schema created by ");
                                if (author.NodeType == NodeType.Uri)
                                {
                                    context.HtmlWriter.AddAttribute("href", ((IUriNode)author).Uri.AbsoluteUri);
                                    context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, CssClassUri);
                                    context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.A);
                                }
                                switch (authorName.NodeType)
                                {
                                case NodeType.Uri:
                                    context.HtmlWriter.WriteEncodedText(((IUriNode)authorName).Uri.AbsoluteUri);
                                    break;

                                case NodeType.Literal:
                                    context.HtmlWriter.WriteEncodedText(((ILiteralNode)authorName).Value);
                                    break;

                                default:
                                    context.HtmlWriter.WriteEncodedText(authorName.ToString());
                                    break;
                                }
                                if (author.NodeType == NodeType.Uri)
                                {
                                    context.HtmlWriter.RenderEndTag();
                                }
                                context.HtmlWriter.RenderEndTag();
                                context.HtmlWriter.RenderEndTag();
                                context.HtmlWriter.WriteLine();
                            }

                            // Show the Namespace information for the Schema
                            if (ontoInfo.HasValue("nsPrefix"))
                            {
                                if (ontoInfo["nsPrefix"].NodeType == NodeType.Literal && ontoInfo["nsUri"].NodeType == NodeType.Uri)
                                {
                                    // Add this QName to the QName Mapper so we can get nice QNames later on
                                    String prefix = ((ILiteralNode)ontoInfo["nsPrefix"]).Value;
                                    context.QNameMapper.AddNamespace(prefix, ((IUriNode)ontoInfo["nsUri"]).Uri);

                                    context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H4);
                                    context.HtmlWriter.WriteEncodedText("Preferred Namespace Definition");
                                    context.HtmlWriter.RenderEndTag();
                                    context.HtmlWriter.WriteLine();

                                    // Show human readable description of preferred Namespace Settings
                                    context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P);
                                    context.HtmlWriter.WriteEncodedText("Preferred Namespace Prefix is ");
                                    context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Strong);
                                    context.HtmlWriter.WriteEncodedText(prefix);
                                    context.HtmlWriter.RenderEndTag();
                                    context.HtmlWriter.WriteEncodedText(" and preferred Namespace URI is ");
                                    context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Href, context.QNameMapper.GetNamespaceUri(prefix).AbsoluteUri);
                                    context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, CssClassUri);
                                    context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.A);
                                    context.HtmlWriter.WriteEncodedText(context.QNameMapper.GetNamespaceUri(prefix).AbsoluteUri);
                                    context.HtmlWriter.RenderEndTag();
                                    context.HtmlWriter.RenderEndTag();

                                    // RDF/XML Syntax
                                    context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H5);
                                    context.HtmlWriter.WriteEncodedText("RDF/XML Syntax");
                                    context.HtmlWriter.RenderEndTag();
                                    context.HtmlWriter.WriteLine();
                                    context.HtmlWriter.AddStyleAttribute(HtmlTextWriterStyle.Width, "90%");
                                    context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Pre);
                                    int currIndent = context.HtmlWriter.Indent;
                                    context.HtmlWriter.Indent = 0;
                                    context.HtmlWriter.WriteEncodedText("<?xml version=\"1.0\" charset=\"utf-8\"?>");
                                    context.HtmlWriter.WriteLine();
                                    context.HtmlWriter.WriteEncodedText("<rdf:RDF xmlns:rdf=\"" + NamespaceMapper.RDF + "\" xmlns:" + prefix + "=\"" + context.UriFormatter.FormatUri(context.QNameMapper.GetNamespaceUri(prefix)) + "\">");
                                    context.HtmlWriter.WriteLine();
                                    context.HtmlWriter.WriteEncodedText("   <!-- Your RDF here... -->");
                                    context.HtmlWriter.WriteLine();
                                    context.HtmlWriter.WriteEncodedText("</rdf:RDF>");
                                    context.HtmlWriter.Indent = currIndent;
                                    context.HtmlWriter.RenderEndTag();
                                    context.HtmlWriter.WriteLine();

                                    // Turtle/N3 Syntax
                                    context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H5);
                                    context.HtmlWriter.WriteEncodedText("Turtle/N3 Syntax");
                                    context.HtmlWriter.RenderEndTag();
                                    context.HtmlWriter.WriteLine();
                                    context.HtmlWriter.AddStyleAttribute(HtmlTextWriterStyle.Width, "90%");
                                    context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Pre);
                                    currIndent = context.HtmlWriter.Indent;
                                    context.HtmlWriter.Indent = 0;
                                    context.HtmlWriter.WriteEncodedText("@prefix " + prefix + ": <" + context.UriFormatter.FormatUri(context.QNameMapper.GetNamespaceUri(prefix)) + "> .");
                                    context.HtmlWriter.Indent = currIndent;
                                    context.HtmlWriter.RenderEndTag();
                                    context.HtmlWriter.WriteLine();

                                    // SPARQL Syntax
                                    context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H5);
                                    context.HtmlWriter.WriteEncodedText("SPARQL Syntax");
                                    context.HtmlWriter.RenderEndTag();
                                    context.HtmlWriter.WriteLine();
                                    context.HtmlWriter.AddStyleAttribute(HtmlTextWriterStyle.Width, "90%");
                                    context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Pre);
                                    currIndent = context.HtmlWriter.Indent;
                                    context.HtmlWriter.Indent = 0;
                                    context.HtmlWriter.WriteEncodedText("PREFIX " + prefix + ": <" + context.UriFormatter.FormatUri(context.QNameMapper.GetNamespaceUri(prefix)) + ">");
                                    context.HtmlWriter.Indent = currIndent;
                                    context.HtmlWriter.RenderEndTag();
                                    context.HtmlWriter.WriteLine();
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new RdfOutputException("Tried to make a SPARQL Query to determine Schema Information but an unexpected Query Result was returned");
                    }
                }
                catch (RdfQueryException queryEx)
                {
                    throw new RdfOutputException("Tried to make a SPARQL Query to determine Schema Information but a Query Error occurred", queryEx);
                }
            }

            SparqlParameterizedString getPropertyRanges = new SparqlParameterizedString();

            getPropertyRanges.Namespaces = new NamespaceMapper();
            getPropertyRanges.Namespaces.AddNamespace("owl", UriFactory.Create(NamespaceMapper.OWL));
            getPropertyRanges.CommandText = "SELECT ?range WHERE { { @property rdfs:range ?range . FILTER(ISURI(?range)) } UNION { @property rdfs:range ?union . ?union owl:unionOf ?ranges . { ?ranges rdf:first ?range } UNION { ?ranges rdf:rest+/rdf:first ?range } } }";
            SparqlParameterizedString getPropertyDomains = new SparqlParameterizedString();

            getPropertyDomains.Namespaces  = getPropertyRanges.Namespaces;
            getPropertyDomains.CommandText = "SELECT ?domain WHERE { { @property rdfs:domain ?domain . FILTER(ISURI(?domain)) } UNION { @property rdfs:domain ?union . ?union owl:unionOf ?domains . { ?domains rdf:first ?domain } UNION { ?domains rdf:rest+/rdf:first ?domain } } }";

            // Show lists of all Classes and Properties in the Schema
            context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H4);
            context.HtmlWriter.WriteEncodedText("Class and Property Summary");
            context.HtmlWriter.RenderEndTag();
            context.HtmlWriter.WriteLine();

            context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P);
            context.HtmlWriter.WriteEncodedText("This Schema defines the following classes:");
            context.HtmlWriter.RenderEndTag();
            context.HtmlWriter.WriteLine();
            context.HtmlWriter.AddStyleAttribute("width", "90%");
            context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, CssClassBox);
            context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P);

            // Get the Classes and Display
            SparqlParameterizedString getClasses = new SparqlParameterizedString();

            getClasses.Namespaces  = context.QNameMapper;
            getClasses.CommandText = "SELECT DISTINCT ?class WHERE { { ?class a rdfs:Class } UNION { ?class a owl:Class } FILTER(ISURI(?class)) } ORDER BY ?class";
            try
            {
                results = context.Graph.ExecuteQuery(getClasses);
                if (results is SparqlResultSet)
                {
                    SparqlResultSet rs = (SparqlResultSet)results;
                    for (int i = 0; i < rs.Count; i++)
                    {
                        SparqlResult r = rs[i];

                        // Get the QName and output a Link to an anchor that we'll generate later to let
                        // users jump to a Class/Property definition
                        String qname = context.NodeFormatter.Format(r["class"]);
                        context.HtmlWriter.AddAttribute("href", "#" + qname);
                        context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, CssClassUri);
                        context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.A);
                        context.HtmlWriter.WriteEncodedText(qname);
                        context.HtmlWriter.RenderEndTag();

                        if (i < rs.Count - 1)
                        {
                            context.HtmlWriter.WriteEncodedText(" , ");
                        }
                    }
                }
                else
                {
                    throw new RdfOutputException("Tried to make a SPARQL Query to find Classes in the Schema but an unexpected Query Result was returned");
                }
            }
            catch (RdfQueryException queryEx)
            {
                throw new RdfOutputException("Tried to make a SPARQL Query to find Classes in the Schema but a Query Error occurred", queryEx);
            }

            context.HtmlWriter.RenderEndTag();
            context.HtmlWriter.WriteLine();

            context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P);
            context.HtmlWriter.WriteEncodedText("This Schema defines the following properties:");
            context.HtmlWriter.RenderEndTag();
            context.HtmlWriter.WriteLine();
            context.HtmlWriter.AddStyleAttribute("width", "90%");
            context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, CssClassBox);
            context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P);

            // Get the Properties and Display
            SparqlParameterizedString getProperties = new SparqlParameterizedString();

            getProperties.Namespaces  = context.QNameMapper;
            getProperties.CommandText = "SELECT DISTINCT ?property WHERE { { ?property a rdf:Property } UNION { ?property a owl:DatatypeProperty } UNION { ?property a owl:ObjectProperty } FILTER(ISURI(?property)) } ORDER BY ?property";
            try
            {
                results = context.Graph.ExecuteQuery(getProperties);
                if (results is SparqlResultSet)
                {
                    SparqlResultSet rs = (SparqlResultSet)results;
                    for (int i = 0; i < rs.Count; i++)
                    {
                        SparqlResult r = rs[i];

                        // Get the QName and output a Link to an anchor that we'll generate later to let
                        // users jump to a Class/Property definition
                        String qname = context.NodeFormatter.Format(r["property"]);
                        context.HtmlWriter.AddAttribute("href", "#" + qname);
                        context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, CssClassUri);
                        context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.A);
                        context.HtmlWriter.WriteEncodedText(qname);
                        context.HtmlWriter.RenderEndTag();

                        if (i < rs.Count - 1)
                        {
                            context.HtmlWriter.WriteEncodedText(" , ");
                        }
                    }
                }
                else
                {
                    throw new RdfOutputException("Tried to make a SPARQL Query to find Properties in the Schema but an unexpected Query Result was returned");
                }
            }
            catch (RdfQueryException queryEx)
            {
                throw new RdfOutputException("Tried to make a SPARQL Query to find Properties in the Schema but a Query Error occurred", queryEx);
            }

            context.HtmlWriter.RenderEndTag();
            context.HtmlWriter.WriteLine();

            // Show details for each class
            context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H3);
            context.HtmlWriter.WriteEncodedText("Classes");
            context.HtmlWriter.RenderEndTag();
            context.HtmlWriter.WriteLine();

            // Now create the URI Nodes we need for the next stage of Output
            IUriNode rdfsDomain            = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.RDFS + "domain"));
            IUriNode rdfsRange             = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.RDFS + "range"));
            IUriNode rdfsSubClassOf        = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.RDFS + "subClassOf"));
            IUriNode rdfsSubPropertyOf     = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.RDFS + "subPropertyOf"));
            IUriNode owlDisjointClass      = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.OWL + "disjointWith"));
            IUriNode owlEquivalentClass    = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.OWL + "equivalentClass"));
            IUriNode owlEquivalentProperty = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.OWL + "equivalentProperty"));
            IUriNode owlInverseProperty    = context.Graph.CreateUriNode(UriFactory.Create(NamespaceMapper.OWL + "inverseOf"));

            // Alter our previous getClasses query to get additional details
            getClasses.CommandText = "SELECT ?class (SAMPLE(?label) AS ?classLabel) (SAMPLE(?description) AS ?classDescription) WHERE { { ?class a rdfs:Class } UNION { ?class a owl:Class } FILTER(ISURI(?class)) OPTIONAL { ?class rdfs:label ?label } OPTIONAL { ?class rdfs:comment ?description } } GROUP BY ?class ORDER BY ?class";
            try
            {
                results = context.Graph.ExecuteQuery(getClasses);
                if (results is SparqlResultSet)
                {
                    foreach (SparqlResult r in (SparqlResultSet)results)
                    {
                        if (!r.HasValue("class"))
                        {
                            continue;
                        }
                        String qname = context.NodeFormatter.Format(r["class"]);

                        // Use a <div> for each Class
                        context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, CssClassBox);
                        context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Div);

                        // Add the Anchor to which earlier Class summary links to
                        context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Name, qname);
                        context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.A);
                        context.HtmlWriter.RenderEndTag();

                        // Show Basic Class Information
                        context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H4);
                        context.HtmlWriter.WriteEncodedText("Class: " + qname);
                        context.HtmlWriter.RenderEndTag();

                        // Show "Local Name - Label"
                        context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Em);
                        if (TurtleSpecsHelper.IsValidQName(qname))
                        {
                            context.HtmlWriter.WriteEncodedText(qname);
                        }
                        else
                        {
                            Uri temp = new Uri(qname, UriKind.RelativeOrAbsolute);
                            if (!temp.Fragment.Equals(String.Empty))
                            {
                                context.HtmlWriter.WriteEncodedText(temp.Fragment);
                            }
                            else
                            {
                                context.HtmlWriter.WriteEncodedText(temp.Segments.Last());
                            }
                        }
                        context.HtmlWriter.RenderEndTag();
                        if (r.HasValue("classLabel"))
                        {
                            if (r["classLabel"] != null && r["classLabel"].NodeType == NodeType.Literal)
                            {
                                context.HtmlWriter.WriteEncodedText(" - ");
                                context.HtmlWriter.WriteEncodedText(((ILiteralNode)r["classLabel"]).Value);
                            }
                        }
                        context.HtmlWriter.WriteLine();
                        context.HtmlWriter.WriteBreak();
                        context.HtmlWriter.WriteLine();

                        // Output further information about the class
                        IEnumerable <Triple> ts;

                        // Output any Subclasses
                        ts = context.Graph.GetTriplesWithSubjectPredicate(rdfsSubClassOf, r["class"]);
                        GenerateCaptionedInformation(context, "Has Sub Classes", ts, t => t.Object);

                        // Output Properties which have this as domain/range
                        ts = context.Graph.GetTriplesWithPredicateObject(rdfsDomain, r["class"]);
                        GenerateCaptionedInformation(context, "Properties Include", ts, t => t.Subject);
                        ts = context.Graph.GetTriplesWithPredicateObject(rdfsRange, r["class"]);
                        GenerateCaptionedInformation(context, "Used With", ts, t => t.Subject);

                        // Output any Equivalent Classes
                        ts = context.Graph.GetTriplesWithSubjectPredicate(r["class"], owlEquivalentClass).Concat(context.Graph.GetTriplesWithPredicateObject(owlEquivalentClass, r["class"]));
                        GenerateCaptionedInformation(context, "Equivalent Classes", ts, t => t.Subject.Equals(r["class"]) ? t.Object : t.Subject);
                        // Output any Disjoint Classes
                        ts = context.Graph.GetTriplesWithSubjectPredicate(r["class"], owlDisjointClass).Concat(context.Graph.GetTriplesWithPredicateObject(owlDisjointClass, r["class"]));
                        GenerateCaptionedInformation(context, "Disjoint Classes", ts, t => t.Subject.Equals(r["class"]) ? t.Object : t.Subject);

                        // Show the Class Description
                        if (r.HasValue("classDescription"))
                        {
                            if (r["classDescription"] != null && r["classDescription"].NodeType == NodeType.Literal)
                            {
                                context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P);
                                context.HtmlWriter.Write(((ILiteralNode)r["classDescription"]).Value);
                                context.HtmlWriter.RenderEndTag();
                            }
                        }

                        // End the </div> for the Class
                        context.HtmlWriter.RenderEndTag();
                        context.HtmlWriter.WriteLine();
                    }
                }
                else
                {
                    throw new RdfOutputException("Tried to make a SPARQL Query to get Class Information from the Schema but an unexpected Query Result was returned");
                }
            }
            catch (RdfQueryException queryEx)
            {
                throw new RdfOutputException("Tried to make a SPARQL Query to get Class Information from the Schema but a Query Error occurred", queryEx);
            }

            // Show details for each property
            context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H3);
            context.HtmlWriter.WriteEncodedText("Properties");
            context.HtmlWriter.RenderEndTag();
            context.HtmlWriter.WriteLine();

            // Alter our previous getProperties query to get additional details
            getProperties.CommandText = "SELECT ?property (SAMPLE(?label) AS ?propertyLabel) (SAMPLE(?description) AS ?propertyDescription) WHERE { { ?property a rdf:Property } UNION { ?property a owl:ObjectProperty } UNION { ?property a owl:DatatypeProperty } FILTER(ISURI(?property)) OPTIONAL { ?property rdfs:label ?label } OPTIONAL { ?property rdfs:comment ?description } } GROUP BY ?property ORDER BY ?property";
            try
            {
                results = context.Graph.ExecuteQuery(getProperties);
                if (results is SparqlResultSet)
                {
                    foreach (SparqlResult r in (SparqlResultSet)results)
                    {
                        if (!r.HasValue("property"))
                        {
                            continue;
                        }
                        String qname = context.NodeFormatter.Format(r["property"]);

                        // Use a <div> for each Property
                        context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, CssClassBox);
                        context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Div);

                        // Add the Anchor to which earlier Property summary links to
                        context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Name, qname);
                        context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.A);
                        context.HtmlWriter.RenderEndTag();

                        // Show Basic Property Information
                        context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H4);
                        context.HtmlWriter.WriteEncodedText("Property: " + qname);
                        context.HtmlWriter.RenderEndTag();

                        // Show "Local Name - Label"
                        context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.Em);
                        if (TurtleSpecsHelper.IsValidQName(qname))
                        {
                            context.HtmlWriter.WriteEncodedText(qname);
                        }
                        else
                        {
                            Uri temp = new Uri(qname, UriKind.RelativeOrAbsolute);
                            if (!temp.Fragment.Equals(String.Empty))
                            {
                                context.HtmlWriter.WriteEncodedText(temp.Fragment);
                            }
                            else
                            {
                                context.HtmlWriter.WriteEncodedText(temp.Segments.Last());
                            }
                        }
                        context.HtmlWriter.RenderEndTag();
                        if (r.HasValue("propertyLabel"))
                        {
                            if (r["propertyLabel"] != null && r["propertyLabel"].NodeType == NodeType.Literal)
                            {
                                context.HtmlWriter.WriteEncodedText(" - ");
                                context.HtmlWriter.WriteEncodedText(((ILiteralNode)r["propertyLabel"]).Value);
                            }
                        }
                        context.HtmlWriter.WriteLine();
                        context.HtmlWriter.WriteBreak();
                        context.HtmlWriter.WriteLine();

                        // Output further information about the property
                        IEnumerable <Triple> ts;

                        // Output any Subproperties
                        ts = context.Graph.GetTriplesWithSubjectPredicate(rdfsSubPropertyOf, r["property"]);
                        GenerateCaptionedInformation(context, "Has Sub Properties", ts, t => t.Object);

                        // Output Domain and Range
                        // ts = context.Graph.GetTriplesWithSubjectPredicate(r["property"], rdfsDomain);
                        // this.GenerateCaptionedInformation(context, "Has Domain", ts, t => t.Object);
                        // ts = context.Graph.GetTriplesWithSubjectPredicate(r["property"], rdfsRange);
                        // this.GenerateCaptionedInformation(context, "Has Range", ts, t => t.Object);
                        getPropertyDomains.SetParameter("property", r["property"]);
                        GenerateCaptionedInformation(context, "Has Domain", context.Graph.ExecuteQuery(getPropertyDomains) as SparqlResultSet, "domain");
                        getPropertyRanges.SetParameter("property", r["property"]);
                        GenerateCaptionedInformation(context, "Has Range", context.Graph.ExecuteQuery(getPropertyRanges) as SparqlResultSet, "range");

                        // Output any Equivalent Properties
                        ts = context.Graph.GetTriplesWithSubjectPredicate(r["property"], owlEquivalentProperty).Concat(context.Graph.GetTriplesWithPredicateObject(owlEquivalentProperty, r["property"]));
                        GenerateCaptionedInformation(context, "Equivalent Properties", ts, t => t.Subject.Equals(r["property"]) ? t.Object : t.Subject);
                        // Output any Disjoint Classes
                        ts = context.Graph.GetTriplesWithSubjectPredicate(r["property"], owlInverseProperty).Concat(context.Graph.GetTriplesWithPredicateObject(owlInverseProperty, r["property"]));
                        GenerateCaptionedInformation(context, "Inverse Property", ts, t => t.Subject.Equals(r["property"]) ? t.Object : t.Subject);

                        // Show the Property Description
                        if (r.HasValue("propertyDescription"))
                        {
                            if (r["propertyDescription"] != null && r["propertyDescription"].NodeType == NodeType.Literal)
                            {
                                context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P);
                                context.HtmlWriter.Write(((ILiteralNode)r["propertyDescription"]).Value);
                                context.HtmlWriter.RenderEndTag();
                            }
                        }

                        // End the </div> for the Property
                        context.HtmlWriter.RenderEndTag();
                        context.HtmlWriter.WriteLine();
                    }
                }
                else
                {
                    throw new RdfOutputException("Tried to make a SPARQL Query to get Property Information from the Schema but an unexpected Query Result was returned");
                }
            }
            catch (RdfQueryException queryEx)
            {
                throw new RdfOutputException("Tried to make a SPARQL Query to get Property Information from the Schema but a Query Error occurred", queryEx);
            }


            // End of Page
            context.HtmlWriter.RenderEndTag(); //End Body
            context.HtmlWriter.RenderEndTag(); //End Html
        }
 /// <summary>
 /// Saves the SPARQL Result Set to the given File
 /// </summary>
 /// <param name="results">Result Set to save</param>
 /// <param name="filename">File to save to</param>
 public void Save(SparqlResultSet results, string filename)
 {
     this._writer.Save(this.GenerateOutput(results), filename);
 }
Example #30
0
        /// <summary>
        /// Выполнение Sparql-запроса
        /// </summary>
        /// <param name="sparqlCommandText">Текст Sparql-запроса</param>
        /// <returns>Результат запроса в виде текста</returns>
        public string ExecuteQuery(string sparqlCommandText)
        {
            using (Graph baseGraph = new Graph())
            {
                RdfXmlParser fileParser = new RdfXmlParser();
                foreach (string fileName in FilesToQuery)
                {
                    if (String.IsNullOrWhiteSpace(fileName))
                    {
                        continue;
                    }

                    using (Graph g = new Graph())
                    {
                        try
                        {
                            fileParser.Load(g, fileName);
                            baseGraph.Merge(g);
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(String.Format("Ошибка при обработке файла {0}\r\n{1}", fileName, ex.Message), ex);
                        }
                    }
                }

                var resultSet = baseGraph.ExecuteQuery(sparqlCommandText);

                if (resultSet is SparqlResultSet)
                {
                    SparqlResultSet outputSet = resultSet as SparqlResultSet;

                    if (outputSet.IsEmpty)
                    {
                        QueryResult = "Пустой результат";
                    }
                    else
                    {
                        StringBuilder outputString = new StringBuilder();
                        foreach (SparqlResult result in outputSet.Results)
                        {
                            outputString.AppendLine(result.ToString());
                        }

                        QueryResult = outputString.ToString();
                    }
                }
                else if (resultSet is Graph)
                {
                    Graph resultGraph = resultSet as Graph;

                    if (resultGraph.IsEmpty)
                    {
                        QueryResult = "Пустой граф";
                    }
                    else
                    {
                        QueryResult = VDS.RDF.Writing.StringWriter.Write(resultGraph, new RdfXmlWriter());
                    }
                }
                else
                {
                    QueryResult = string.Format("Неизвестный результат: {0}", resultSet.GetType());
                }

                return(QueryResult);
            }
        }
    protected void Button2_Click1(object sender, EventArgs e)
    {
        TripleStore store = new TripleStore();
        Graph       g1    = new Graph();

        g1.LoadFromFile(Server.MapPath("SVUModeling.rdf"));
        store.Add(g1);
        Label1.Text       = "Economic Program Details";
        Label1.Visible    = true;
        GridView1.Visible = false;
        InMemoryDataset ds = new InMemoryDataset(store);
        //Get the Query processor
        ISparqlQueryProcessor processor = new LeviathanQueryProcessor(ds);

        //Use the SparqlQueryParser to give us a SparqlQuery object
        //Should get a Graph back from a CONSTRUCT query
        Label2.Text    = "Economic Director Informations ";
        Label2.Visible = true;
        // to select the Economic Director Informations
        SparqlQueryParser sparqlparser = new SparqlQueryParser();
        SparqlQuery       query        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                prefix owl: <http://www.w3.org/2002/07/owl#>
                prefix foaf: <http://xmlns.com/foaf/0.1/#>
                SELECT   ?EconomicDirectorInfo 
                WHERE {
                ?t   owl:EconomicDirectorInfoProperty ?EconomicDirectorInfo
                }");
        Object            results      = processor.ProcessQuery(query);
        DataTable         DT2          = new DataTable();
        SparqlResultSet   rset         = (SparqlResultSet)results;

        DT2 = FillDataTable(rset);
        GridView2.DataSource = DT2;
        GridView2.DataBind();
        GridView2.Visible = true;
        //to retrival the Teachers Economic program
        Label3.Text    = "Teachers Of Economic Program";
        Label3.Visible = true;
        SparqlQueryParser sparqlparser2 = new SparqlQueryParser();
        SparqlQuery       query2        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                prefix foaf: <http://xmlns.com/foaf/0.1/#>
                prefix owl: <http://www.w3.org/2002/07/owl#>
                SELECT   ?TeachersEconomic 
                WHERE {
                ?t   owl:TeachersOfEconomic ?TeachersEconomic 
                }");
        Object            results2      = processor.ProcessQuery(query2);
        DataTable         DT3           = new DataTable();
        SparqlResultSet   rset5         = (SparqlResultSet)results2;

        DT3 = FillDataTable(rset5);
        GridView3.DataSource = DT3;
        GridView3.DataBind();
        GridView3.Visible = true;
        //to select Courses Of Economic
        Label4.Text    = "Courses of Economic Program";
        Label4.Visible = true;
        SparqlQueryParser sparqlparser4 = new SparqlQueryParser();
        SparqlQuery       query4        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                prefix owl: <http://www.w3.org/2002/07/owl#>
                SELECT   ?CoursesEconomic 
                WHERE {
                ?t   owl:CoursesOfEconomic ?CoursesEconomic 
                }");
        Object            results4      = processor.ProcessQuery(query4);
        DataTable         DT4           = new DataTable();
        SparqlResultSet   rset6         = (SparqlResultSet)results4;

        DT4 = FillDataTable(rset6);
        GridView4.DataSource = DT4;
        GridView4.DataBind();
        GridView4.Visible = true;
    }
Example #32
0
 /// <summary>
 /// Displays the given SPARQL Result Set
 /// </summary>
 /// <param name="results">SPARQL Result to display</param>
 public ResultSetViewerForm(SparqlResultSet results)
     : this(results, null, null)
 {
 }
Example #33
0
 /// <summary>
 /// Displays the given SPARQL Result Set and prefixes the form title with the given title
 /// </summary>
 /// <param name="results">SPARQL Result Set to display</param>
 /// <param name="title">Title prefix</param>
 public ResultSetViewerForm(SparqlResultSet results, String title)
     : this(results, null, title)
 {
 }
Example #34
0
        public IEnumerable <SparqlResult> Run(IEnumerable <SparqlResult> variableBindings, SparqlResultSet resultSet, bool isGrouped)
        {
            Selected = null;

            if (isAll)
            {
                Selected = resultSet.Variables.Values.Where(v => !(v is SparqlBlankNode)).ToList();
            }
            else
            {
                var asExpressions = this.Select(varOrExpr => varOrExpr as SparqlExpressionAsVariable).ToArray();
                if (isGrouped)
                {
                    if (asExpressions.All(exp => exp != null))
                    {
                        if (asExpressions.All(exp =>
                                              exp.sparqlExpression.AggregateLevel == SparqlExpression.VariableDependenceGroupLevel.GroupOfGroups))
                        {
                            return(OneRowResult(variableBindings, asExpressions));
                        }
                    }
                    else
                    {
                        //todo
                    }
                }
                else
                {
                    if (asExpressions.All(exp => exp != null))
                    {
                        //if(asExpressions.All(exp=>exp.sparqlExpression.AggregateLevel==SparqlExpression.VariableDependenceGroupLevel.Const || exp.sparqlExpression.AggregateLevel==SparqlExpression.VariableDependenceGroupLevel.UndependableFunc))
                        if (asExpressions.All(exp =>
                                              exp.sparqlExpression.AggregateLevel == SparqlExpression.VariableDependenceGroupLevel.Group))
                        {
                            return(OneRowResult(variableBindings, asExpressions));
                        }
                    }
                }

                Selected = new List <VariableNode>();

                foreach (IVariableNode variable in this)
                {
                    var expr = variable as SparqlExpressionAsVariable;
                    if (expr != null)
                    {
                        variableBindings = isGrouped ? expr.Run4Grouped(variableBindings) : expr.Run(variableBindings);
                        Selected.Add(expr.variableNode);
                    }
                    else
                    {
                        Selected.Add((VariableNode)variable);
                    }
                }
            }
            variableBindings = variableBindings.Select(result =>
            {
                result.SetSelection(Selected);
                return(result);
            });
            if (IsDistinct)
            {
                variableBindings = Distinct(variableBindings);
            }
            if (IsReduced)
            {
                variableBindings = Reduce(variableBindings);
            }

            return(variableBindings);
        }
Example #35
0
        /// <summary>
        /// Evaluates the Service Clause by generating instance(s) of <see cref="SparqlRemoteEndpoint">SparqlRemoteEndpoint</see> as required and issuing the query to the remote endpoint(s).
        /// </summary>
        /// <param name="context">Evaluation Context.</param>
        /// <returns></returns>
        public BaseMultiset Evaluate(SparqlEvaluationContext context)
        {
            bool bypassSilent = false;

            try
            {
                SparqlRemoteEndpoint endpoint;
                Uri    endpointUri;
                String baseUri = (context.Query.BaseUri == null) ? String.Empty : context.Query.BaseUri.AbsoluteUri;
                SparqlParameterizedString sparqlQuery = new SparqlParameterizedString("SELECT * WHERE ");

                String pattern = _pattern.ToString();
                pattern = pattern.Substring(pattern.IndexOf('{'));
                sparqlQuery.CommandText += pattern;

                // Pass through LIMIT and OFFSET to the remote service
                if (context.Query.Limit >= 0)
                {
                    // Calculate a LIMIT which is the LIMIT plus the OFFSET
                    // We'll apply OFFSET locally so don't pass that through explicitly
                    int limit = context.Query.Limit;
                    if (context.Query.Offset > 0)
                    {
                        limit += context.Query.Offset;
                    }
                    sparqlQuery.CommandText += " LIMIT " + limit;
                }

                // Select which service to use
                if (_endpointSpecifier.TokenType == Token.URI)
                {
                    endpointUri = UriFactory.Create(Tools.ResolveUri(_endpointSpecifier.Value, baseUri));
                    endpoint    = new SparqlRemoteEndpoint(endpointUri);
                }
                else if (_endpointSpecifier.TokenType == Token.VARIABLE)
                {
                    // Get all the URIs that are bound to this Variable in the Input
                    String var = _endpointSpecifier.Value.Substring(1);
                    if (!context.InputMultiset.ContainsVariable(var))
                    {
                        throw new RdfQueryException("Cannot evaluate a SERVICE clause which uses a Variable as the Service specifier when the Variable is unbound");
                    }
                    List <IUriNode> services = new List <IUriNode>();
                    foreach (ISet s in context.InputMultiset.Sets)
                    {
                        if (s.ContainsVariable(var))
                        {
                            if (s[var].NodeType == NodeType.Uri)
                            {
                                services.Add((IUriNode)s[var]);
                            }
                        }
                    }
                    services = services.Distinct().ToList();

                    // Now generate a Federated Remote Endpoint
                    List <SparqlRemoteEndpoint> serviceEndpoints = new List <SparqlRemoteEndpoint>();
                    services.ForEach(u => serviceEndpoints.Add(new SparqlRemoteEndpoint(u.Uri)));
                    endpoint = new FederatedSparqlRemoteEndpoint(serviceEndpoints);
                }
                else
                {
                    // Note that we must bypass the SILENT operator in this case as this is not an evaluation failure
                    // but a query syntax error
                    bypassSilent = true;
                    throw new RdfQueryException("SERVICE Specifier must be a URI/Variable Token but a " + _endpointSpecifier.GetType().ToString() + " Token was provided");
                }

                // Where possible do substitution and execution to get accurate and correct SERVICE results
                context.OutputMultiset = new Multiset();
                List <String> existingVars = (from v in _pattern.Variables
                                              where context.InputMultiset.ContainsVariable(v)
                                              select v).ToList();

                if (existingVars.Any() || context.Query.Bindings != null)
                {
                    // Pre-bound variables/BINDINGS clause so do substitution and execution

                    // Build the set of possible bindings
                    HashSet <ISet> bindings = new HashSet <ISet>();
                    if (context.Query.Bindings != null && !_pattern.Variables.IsDisjoint(context.Query.Bindings.Variables))
                    {
                        // Possible Bindings comes from BINDINGS clause
                        // In this case each possibility is a distinct binding tuple defined in the BINDINGS clause
                        foreach (BindingTuple tuple in context.Query.Bindings.Tuples)
                        {
                            bindings.Add(new Set(tuple));
                        }
                    }
                    else
                    {
                        // Possible Bindings get built from current input (if there was a BINDINGS clause the variables it defines are not in this SERVICE clause)
                        // In this case each possibility only contains Variables bound so far
                        foreach (ISet s in context.InputMultiset.Sets)
                        {
                            Set t = new Set();
                            foreach (String var in existingVars)
                            {
                                t.Add(var, s[var]);
                            }
                            bindings.Add(t);
                        }
                    }

                    // Execute the Query for every possible Binding and build up our Output Multiset from all the results
                    foreach (ISet s in bindings)
                    {
                        // Q: Should we continue processing here if and when we hit an error?

                        foreach (String var in s.Variables)
                        {
                            sparqlQuery.SetVariable(var, s[var]);
                        }
                        SparqlResultSet results = endpoint.QueryWithResultSet(sparqlQuery.ToString());
                        context.CheckTimeout();

                        foreach (SparqlResult r in results)
                        {
                            Set t = new Set(r);
                            foreach (String var in s.Variables)
                            {
                                t.Add(var, s[var]);
                            }
                            context.OutputMultiset.Add(t);
                        }
                    }

                    return(context.OutputMultiset);
                }
                else
                {
                    // No pre-bound variables/BINDINGS clause so just execute the query

                    // Try and get a Result Set from the Service
                    SparqlResultSet results = endpoint.QueryWithResultSet(sparqlQuery.ToString());

                    // Transform this Result Set back into a Multiset
                    foreach (SparqlResult r in results.Results)
                    {
                        context.OutputMultiset.Add(new Set(r));
                    }

                    return(context.OutputMultiset);
                }
            }
            catch (Exception ex)
            {
                if (_silent && !bypassSilent)
                {
                    // If Evaluation Errors are SILENT is specified then a Multiset containing a single set with all values unbound is returned
                    // Unless some of the SPARQL queries did return results in which we just return the results we did obtain
                    if (context.OutputMultiset.IsEmpty)
                    {
                        Set s = new Set();
                        foreach (String var in _pattern.Variables.Distinct())
                        {
                            s.Add(var, null);
                        }
                        context.OutputMultiset.Add(s);
                    }
                    return(context.OutputMultiset);
                }
                else
                {
                    throw new RdfQueryException("Query execution failed because evaluating a SERVICE clause failed - this may be due to an error with the remote service", ex);
                }
            }
        }
Example #36
0
        public void browseFunction(MyWpfRdfResultControl _RdfRes, String browse, bool isPopup)
        {
            if (browse == null)
            {
                return;
            }

            try
            {
                SparqlQueryParser sqp   = new SparqlQueryParser();
                string            query = null;
                int len = TypesComboBox.Text.Length;
                if (len != 0 && browse.Length != 0)
                {
                    query = "SELECT * WHERE { {<" + browse + "> <" + TypesComboBox.Text + "> ?object} UNION {?subject <" + TypesComboBox.Text + "> <" + browse + ">} } ORDER BY ?object";
                }
                else if (len == 0 && browse.Length != 0)
                {
                    query = "SELECT * WHERE { {?subject ?type <" + browse + ">} UNION {<" + browse + "> ?type ?object} } ORDER BY ?type";
                }
                else if (len != 0 && browse.Length == 0)
                {
                    query = "SELECT * WHERE {?subject <" + TypesComboBox.Text + "> ?object} ORDER BY ?subject ?object";
                }
                else if (len == 0 && browse.Length == 0)
                {
                    query = "SELECT * WHERE {?subject ?type ?object} ORDER BY ?subject ?type ?object LIMIT 20";
                }

                if (isPopup)
                {
                    query += " LIMIT " + POPUP_QUERY_LIMIT;
                }

                SparqlQuery     sparqlQuery = sqp.ParseFromString(query);
                SparqlResultSet results     = null;

                if (config.endpoint != null)
                {
                    results = config.endpoint.QueryWithResultSet(query);
                }
                else
                {
                    results = (SparqlResultSet)config.myGraph.ExecuteQuery(sparqlQuery);
                }

                _RdfRes.setResultSet(results);
                _RdfRes.Href_Click = Href_Click;
                _RdfRes._popUp     = popLink;

                if (config.types == BrowsingType.RdfBrowsing)
                {
                    _RdfRes.initForRdfTypeBrowing();
                }
                else      // BrowsingType.TriplesBrowsing
                {
                    _RdfRes.initForTripleBrowing();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ERROR1", MessageBoxButton.OK, MessageBoxImage.Error);
                MessageBox.Show(ex.StackTrace, "ERROR1(StackTrace)", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Example #37
0
        /// <summary>
        /// Saves a SPARQL Result Set to TSV format
        /// </summary>
        /// <param name="results">Result Set</param>
        /// <param name="output">Writer to save to</param>
        public void Save(SparqlResultSet results, TextWriter output)
        {
            try
            {
                if (results.ResultsType == SparqlResultsType.VariableBindings)
                {
                    // Output Variables first
                    String[] vars = results.Variables.ToArray();
                    for (int i = 0; i < vars.Length; i++)
                    {
                        output.Write("?" + vars[i]);
                        if (i < vars.Length - 1)
                        {
                            output.Write('\t');
                        }
                    }
                    output.Write('\n');

                    foreach (SparqlResult result in results)
                    {
                        for (int i = 0; i < vars.Length; i++)
                        {
                            if (result.HasValue(vars[i]))
                            {
                                INode temp = result[vars[i]];
                                if (temp != null)
                                {
                                    switch (temp.NodeType)
                                    {
                                    case NodeType.GraphLiteral:
                                        throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("SPARQL TSV"));

                                    case NodeType.Blank:
                                    case NodeType.Literal:
                                    case NodeType.Uri:
                                        output.Write(this._formatter.Format(temp));
                                        break;

                                    default:
                                        throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("SPARQL TSV"));
                                    }
                                }
                            }
                            if (i < vars.Length - 1)
                            {
                                output.Write('\t');
                            }
                        }
                        output.Write('\n');
                    }
                }
                else
                {
                    output.Write(results.Result.ToString());
                }

                output.Close();
            }
            catch
            {
                try
                {
                    output.Close();
                }
                catch
                {
                    // No error handling, just trying to clean up
                }
                throw;
            }
        }
        public ISparqlQueryResult ExecuteQuery(SparqlQuery query, ITransaction transaction = null)
        {
            SparqlResultSet result = _endpoint.QueryWithResultSet(query.ToString());

            return(new SparqlEndpointQueryResult(result, query));
        }
Example #39
0
        private void RenderResultSet(SparqlResultSet results)
        {
            //First Create the Header Row
            RowDefinition rowDef = new RowDefinition();

            rowDef.Height = new GridLength(27);
            this._grid.RowDefinitions.Add(rowDef);

            //Create the appropriate number of Columns
            int c = 0;
            List <GridSplitter> columnSplitters = new List <GridSplitter>();

            foreach (String var in results.Variables)
            {
                //Create the Column for the Variable
                ColumnDefinition colDef = new ColumnDefinition();
                colDef.Width = new GridLength(100, GridUnitType.Star);
                this._grid.ColumnDefinitions.Add(colDef);

                //Create a Label for the Variable
                Label varLabel = new Label();
                varLabel.Content    = var;
                varLabel.Background = Brushes.LightGray;
                varLabel.HorizontalContentAlignment = HorizontalAlignment.Center;
                varLabel.VerticalContentAlignment   = VerticalAlignment.Center;
                this._grid.Children.Add(varLabel);
                Grid.SetColumn(varLabel, c);
                Grid.SetRow(varLabel, 0);

                c++;

                //Create a Column for a Splitter
                colDef       = new ColumnDefinition();
                colDef.Width = new GridLength(1);
                this._grid.ColumnDefinitions.Add(colDef);

                //Add the Spliiter
                GridSplitter splitter = new GridSplitter();
                splitter.ResizeDirection = GridResizeDirection.Columns;
                splitter.ResizeBehavior  = GridResizeBehavior.PreviousAndNext;
                splitter.Width           = 1;
                splitter.Background      = Brushes.Black;
                splitter.Foreground      = Brushes.Black;
                this._grid.Children.Add(splitter);
                Grid.SetColumn(splitter, c);
                Grid.SetRow(splitter, 0);
                columnSplitters.Add(splitter);

                c++;
            }

            int row = 1;

            c = 0;

            foreach (SparqlResult result in results)
            {
                //Create a new Row
                rowDef        = new RowDefinition();
                rowDef.Height = new GridLength(27, GridUnitType.Star);
                this._grid.RowDefinitions.Add(rowDef);

                //Create Controls for each Value in the appropriate Columns
                //The increment is two because we're skipping the column splitter columns
                foreach (String var in results.Variables)
                {
                    if (result.HasValue(var))
                    {
                        if (result[var] != null)
                        {
                            Control value = this.RenderNode(result[var]);
                            Grid.SetRow(value, row);
                            Grid.SetColumn(value, c);
                            this._grid.Children.Add(value);
                        }
                    }
                    c += 2;
                }


                //Add the Splitter Row
                row++;
                this._grid.RowDefinitions.Add(new RowDefinition());
                GridSplitter rowSplitter = new GridSplitter();
                rowSplitter.HorizontalAlignment = HorizontalAlignment.Stretch;
                rowSplitter.Height          = 1;
                rowSplitter.ResizeDirection = GridResizeDirection.Rows;
                rowSplitter.ResizeBehavior  = GridResizeBehavior.PreviousAndNext;
                rowSplitter.Background      = Brushes.Black;
                rowSplitter.Foreground      = Brushes.Black;
                Grid.SetColumn(rowSplitter, 0);
                Grid.SetRow(rowSplitter, row);
                Grid.SetColumnSpan(rowSplitter, this._grid.ColumnDefinitions.Count);
                this._grid.Children.Add(rowSplitter);

                //Increment Row and Reset Column
                row++;
                c = 0;
            }

            foreach (GridSplitter splitter in columnSplitters)
            {
                Grid.SetRowSpan(splitter, this._grid.RowDefinitions.Count);
            }
        }
Example #40
0
 /// <summary>
 /// Creates a new Merging Result Set Handler
 /// </summary>
 /// <param name="results">Result Set</param>
 public MergingResultSetHandler(SparqlResultSet results)
     : base(results)
 {
 }
 private void GenerateCaptionedInformation(HtmlWriterContext context, String caption, SparqlResultSet results, String var)
 {
     if (results == null)
     {
         return;
     }
     GenerateCaptionedInformation(context, caption, results.Select(r => r[var]).Where(n => n != null));
 }
Example #42
0
 /// <summary>
 /// Dynamically wraps a SPARQL result set.
 /// </summary>
 /// <param name="set">The SPARQL result set to wrap dynamically.</param>
 /// <returns>A dynamic result set that wraps <paramref name="set"/>.</returns>
 public static dynamic AsDynamic(this SparqlResultSet set)
 {
     return(new DynamicSparqlResultSet(set));
 }
 /// <summary>
 /// Saves the SPARQL Result Set to the given Stream
 /// </summary>
 /// <param name="results">Result Set to save</param>
 /// <param name="output">Stream to save to</param>
 public void Save(SparqlResultSet results, TextWriter output)
 {
     this._writer.Save(this.GenerateOutput(results), output);
 }
Example #44
0
 /// <summary>
 /// Creates a new Results Parser Context
 /// </summary>
 /// <param name="results">Result Set</param>
 /// <param name="traceParsing">Whether to trace parsing</param>
 public BaseResultsParserContext(SparqlResultSet results, bool traceParsing)
     : this(new ResultSetHandler(results), traceParsing)
 {
 }
Example #45
0
 /// <summary>
 /// Creates a new Tokenising Parser Context with default settings
 /// </summary>
 /// <param name="results">Result Set to parse into</param>
 /// <param name="tokeniser">Tokeniser to use</param>
 public TokenisingResultParserContext(SparqlResultSet results, ITokeniser tokeniser)
     : base(results)
 {
     this._queue = new TokenQueue(tokeniser);
 }
Example #46
0
 /// <summary>
 /// Loads a Result Set from an Input
 /// </summary>
 /// <param name="results">Result Set to load into</param>
 /// <param name="input">Input to read from</param>
 public void Load(SparqlResultSet results, TextReader input)
 {
     if (results == null) throw new RdfParseException("Cannot parse SPARQL Results into a null Result Set");
     if (input == null) throw new RdfParseException("Cannot parse SPARQL Results from a null input stream");
     this.Load(new ResultSetHandler(results), input);
 }
        /// <summary>
        /// Runs the task
        /// </summary>
        /// <returns></returns>
        protected override object RunTaskInternal()
        {
            try
            {
                //Firstly try and parse the Query
                this.Query = this._parser.ParseFromString(this.QueryString);
            }
            catch
            {
                this.Information = "Query is not valid SPARQL 1.0/1.1 - will attempt to evaluate it but underlying store may reject the originalQuery...";
            }

            // Successfuly parsed originalQuery
            if (this.Query != null)
            {
                //Then apply it to the Manager using the GenericQueryProcessor
                try
                {
                    //Check that paging can be used if it was enabled
                    if (this._usePaging)
                    {
                        if (this.Query.Limit >= 0 || this.Query.Offset > 0)
                        {
                            throw new RdfQueryException("Cannot apply originalQuery paging when the SPARQL Query already contains an explicit LIMIT and/or OFFSET clause");
                        }
                        else if (this.Query.QueryType == SparqlQueryType.Ask)
                        {
                            throw new RdfQueryException("Cannot apply originalQuery paging to an ASK Query");
                        }
                    }

                    int      offset    = 0;
                    TimeSpan totalTime = TimeSpan.Zero;

                    switch (this.Query.QueryType)
                    {
                    case SparqlQueryType.Ask:
                        SparqlResultSet blnResult = this._processor.ProcessQuery(this.Query) as SparqlResultSet;
                        if (blnResult == null)
                        {
                            throw new RdfQueryException("Store did not return a SPARQL Result Set for the ASK originalQuery as was expected");
                        }
                        return(blnResult);

                    case SparqlQueryType.Construct:
                    case SparqlQueryType.Describe:
                    case SparqlQueryType.DescribeAll:
                        Graph g = new Graph();
                        g.NamespaceMap.Import(this.Query.NamespaceMap);

                        do
                        {
                            if (this._usePaging)
                            {
                                this.Query.Limit  = this._pageSize;
                                this.Query.Offset = offset;
                            }
                            Object result = this._processor.ProcessQuery(this.Query);
                            totalTime += this.Query.QueryExecutionTime.HasValue ? this.Query.QueryExecutionTime.Value : TimeSpan.Zero;

                            if (!(result is IGraph))
                            {
                                throw new RdfQueryException("SPARQL Query did not return a RDF Graph as expected");
                            }
                            IGraph temp = (IGraph)result;

                            //If no further results can halt
                            if (temp.Triples.Count == 0)
                            {
                                break;
                            }
                            offset += this._pageSize;

                            //Merge the partial result into the final result
                            g.Merge(temp);
                        } while (this._usePaging);

                        this.Information = "Query Completed OK (Took " + totalTime.ToString() + ")";
                        return(g);

                    case SparqlQueryType.Select:
                    case SparqlQueryType.SelectAll:
                    case SparqlQueryType.SelectAllDistinct:
                    case SparqlQueryType.SelectAllReduced:
                    case SparqlQueryType.SelectDistinct:
                    case SparqlQueryType.SelectReduced:
                        SparqlResultSet  results = new SparqlResultSet();
                        ResultSetHandler handler = new ResultSetHandler(results);
                        try
                        {
                            handler.StartResults();

                            do
                            {
                                if (this._usePaging)
                                {
                                    this.Query.Limit  = this._pageSize;
                                    this.Query.Offset = offset;
                                }
                                Object result = this._processor.ProcessQuery(this.Query);
                                totalTime += this.Query.QueryExecutionTime.HasValue ? this.Query.QueryExecutionTime.Value : TimeSpan.Zero;

                                if (!(result is SparqlResultSet))
                                {
                                    throw new RdfQueryException("SPARQL Query did not return a SPARQL Result Set as expected");
                                }
                                SparqlResultSet rset = (SparqlResultSet)result;
                                foreach (String var in rset.Variables)
                                {
                                    handler.HandleVariable(var);
                                }

                                //If no further results can halt
                                if (rset.Count == 0)
                                {
                                    break;
                                }
                                offset += this._pageSize;

                                //Merge the partial result into the final result
                                foreach (SparqlResult r in rset)
                                {
                                    handler.HandleResult(r);
                                }
                            } while (this._usePaging);

                            handler.EndResults(true);
                        }
                        catch
                        {
                            handler.EndResults(false);
                            throw;
                        }
                        this.Information = "Query Completed OK (Took " + totalTime.ToString() + ")";
                        return(results);

                    default:
                        throw new RdfQueryException("Cannot evaluate an unknown originalQuery type");
                    }
                }
                catch
                {
                    //Try and show the execution time if possible
                    if (this.Query.QueryExecutionTime.HasValue)
                    {
                        this.Information = "Query Failed (Took " + this.Query.QueryExecutionTime.Value + ")";
                    }
                    else
                    {
                        this.Information = "Query Failed";
                    }
                    throw;
                }
            }

            // Unsuccessfully parsed originalQuery - may be using syntax extensions specific to the target store
            DateTime start = DateTime.Now;

            try
            {
                if (this._usePaging)
                {
                    throw new RdfQueryException("Cannot apply paging to a Query that we cannot parse as a valid SPARQL 1.0/1.1 originalQuery");
                }
                Object results = this._storage.Query(this.QueryString);
                this.Information = "Query Completed OK (Took " + (DateTime.Now - start) + ")";
                return(results);
            }
            catch
            {
                //Try and show the execution time if possible
                try
                {
                    this.Information = "Query Failed (Took " + (DateTime.Now - start) + ")";
                }
                catch
                {
                    this.Information = "Query Failed";
                }
                throw;
            }
        }
Example #48
0
        /// <summary>
        /// overload of Execute query
        /// </summary>
        /// <param name="input">the query text as string</param>
        /// <returns></returns>
        public static SparqlResultSet ExecuteQueryWithString(string input)
        {
            //list to hold the results
            SparqlResultSet resultSet = new SparqlResultSet();
            try
            {
                //just in cas someone didn't open the connection
                if (!isConnectionStarted)
                    startConnection();

                //making the query
                Object result = manager.Query(input);
                //Object result = manager.ExecuteQuery(input);
                resultSet = (SparqlResultSet)result;

            }
            catch {

            }
            return resultSet;
        }
Example #49
0
        /// <summary>
        /// returns a string of comma separated uris of given list of keywords, if a keyword doesn't match a uri , a "" is inserted in it's place.
        /// </summary>
        /// <param name="keywords">the list of keywords to get uris for</param>
        /// <returns></returns>
        private static string Find_URIs(List<string> keywords)
        {
            SparqlResultSet result = new SparqlResultSet();
               string query = null;
               List<int> scores=new List<int>();
               List<string> uris = new List<string>();
               string comma_sep_uris;

               for (int i = 0; i < keywords.Count; i++)
               {
               //query = "select distinct * where{" +
               //    "<http://dbpedia.org/resource/Inception> ?x ?y}";

               //here a for loop to query the similar keywords and add found uris to uris List<string>
               //if a uri is not found a "not found" string is put instead of the uri

               query = "select distinct  ?subject ?literal ?redirects where{" +

            "?subject <http://www.w3.org/2000/01/rdf-schema#label> ?literal." +

            "optional {   ?subject <http://dbpedia.org/ontology/wikiPageRedirects> ?redirects}." +
            "optional {?subject <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?type}." +

            "Filter (!bound(?type) || !(?type=<http://www.w3.org/2004/02/skos/core#Concept>))." +

            "?literal bif:contains '\"" + keywords[i] + "\"'.}"+"limit 100";

                   //query = "select distinct * where  {?t1 <http://www.w3.org/2000/01/rdf-schema#label> \"The Dark Knight\"   @en }";

                   result = remoteEndPoint.QueryWithResultSet(query);
                   //QueryProcessor.closeConnection();
                   if (result.Count == 0)
                   {
                       //a panic mode to be added to generate a more generic query with more results
                       uris.Add("");
                       continue;
                   }
                   else if (result.Count == 1)
                   {
                       if ((result[0].Value("redirects") == null))
                           uris.Add(result[0].Value("subject").ToString());
                       else
                           uris.Add(result[0].Value("redirects").ToString());
                       continue;
                   }
                   else
                   {

                       int new_value;
                       int min_value=1000;
                       int max_index=0;
                       for ( int j = 0; j < result.Count; j++)
                       {

                         new_value=(  computeLevenshteinDistance(keywords[i],result[j].Value("literal").ToString()));
                         scores.Add(new_value);
                           if(new_value<min_value)
                           {
                               max_index=j;
                               min_value = new_value;
                           }
                           else if (new_value == min_value)
                           {
                               if (result[j].Value("redirects") == null)
                               {
                                   max_index = j;
                                   min_value = new_value;

                               }
                               else
                               {
                                   min_value = new_value;
                               }

                           }
                       }
                       if ((result[max_index].Value("redirects") == null))
                           uris.Add(result[max_index].Value("subject").ToString());
                       else
                           uris.Add(result[max_index].Value("redirects").ToString());

                       min_value = 0;
                   }

               }

               comma_sep_uris = string.Join(",", uris.ToArray());
               return comma_sep_uris;
        }
        /// <summary>
        /// Internal method which generates the SPARQL Query Results JSON output
        /// </summary>
        /// <param name="results">Result Set to save</param>
        /// <param name="output">Stream to save to</param>
        private void GenerateOutput(SparqlResultSet results, TextWriter output)
        {
            JsonTextWriter writer = new JsonTextWriter(output);

            writer.Formatting = Newtonsoft.Json.Formatting.Indented;

            // Start a Json Object for the Result Set
            writer.WriteStartObject();

            // Create the Head Object
            writer.WritePropertyName("head");
            writer.WriteStartObject();

            if (results.ResultsType == SparqlResultsType.VariableBindings)
            {
                // SELECT query results

                // Create the Variables Object
                writer.WritePropertyName("vars");
                writer.WriteStartArray();
                foreach (String var in results.Variables)
                {
                    writer.WriteValue(var);
                }
                writer.WriteEndArray();

                // End Head Object
                writer.WriteEndObject();

                // Create the Result Object
                writer.WritePropertyName("results");
                writer.WriteStartObject();
                writer.WritePropertyName("bindings");
                writer.WriteStartArray();

                foreach (SparqlResult result in results)
                {
                    // Create a Binding Object
                    writer.WriteStartObject();
                    foreach (String var in results.Variables)
                    {
                        if (!result.HasValue(var))
                        {
                            continue;                        //No output for unbound variables
                        }
                        INode value = result.Value(var);
                        if (value == null)
                        {
                            continue;
                        }

                        // Create an Object for the Variable
                        writer.WritePropertyName(var);
                        writer.WriteStartObject();
                        writer.WritePropertyName("type");

                        switch (value.NodeType)
                        {
                        case NodeType.Blank:
                            // Blank Node
                            writer.WriteValue("bnode");
                            writer.WritePropertyName("value");
                            String id = ((IBlankNode)value).InternalID;
                            id = id.Substring(id.IndexOf(':') + 1);
                            writer.WriteValue(id);
                            break;

                        case NodeType.GraphLiteral:
                            // Error
                            throw new RdfOutputException("Result Sets which contain Graph Literal Nodes cannot be serialized in the SPARQL Query Results JSON Format");

                        case NodeType.Literal:
                            // Literal
                            ILiteralNode lit = (ILiteralNode)value;
                            if (lit.DataType != null)
                            {
                                writer.WriteValue("typed-literal");
                            }
                            else
                            {
                                writer.WriteValue("literal");
                            }
                            writer.WritePropertyName("value");

                            writer.WriteValue(lit.Value);
                            if (!lit.Language.Equals(String.Empty))
                            {
                                writer.WritePropertyName("xml:lang");
                                writer.WriteValue(lit.Language);
                            }
                            else if (lit.DataType != null)
                            {
                                writer.WritePropertyName("datatype");
                                writer.WriteValue(lit.DataType.AbsoluteUri);
                            }
                            break;

                        case NodeType.Uri:
                            // Uri
                            writer.WriteValue("uri");
                            writer.WritePropertyName("value");
                            writer.WriteValue(value.ToString());
                            break;

                        default:
                            throw new RdfOutputException("Result Sets which contain Nodes of unknown Type cannot be serialized in the SPARQL Query Results JSON Format");
                        }

                        // End the Variable Object
                        writer.WriteEndObject();
                    }
                    // End the Binding Object
                    writer.WriteEndObject();
                }

                // End Result Object
                writer.WriteEndArray();
                writer.WriteEndObject();
            }
            else
            {
                // ASK query result

                // Set an empty Json Object in the Head
                writer.WriteEndObject();

                // Create a Boolean Property
                writer.WritePropertyName("boolean");
                writer.WriteValue(results.Result);
            }

            // End the Json Object for the Result Set
            writer.WriteEndObject();
        }
Example #51
0
 /// <summary>
 /// Saves the SPARQL Result Set to the given File
 /// </summary>
 /// <param name="results">Result Set to save</param>
 /// <param name="filename">File to save to</param>
 public void Save(SparqlResultSet results, string filename)
 {
     this._writer.Save(this.GenerateOutput(results), filename);
 }
 /// <summary>
 /// Loads a SPARQL Result Set from RDF contained in the given Input
 /// </summary>
 /// <param name="results">SPARQL Result Set to populate</param>
 /// <param name="input">Input to read from</param>
 /// <remarks>
 /// Uses the <see cref="StringParser">StringParser</see> which will use simple heuristics to 'guess' the format of the RDF unless the parser was instaniated with a specific <see cref="IRdfReader">IRdfReader</see> to use
 /// </remarks>
 public void Load(SparqlResultSet results, TextReader input)
 {
     Load(new ResultSetHandler(results), input);
 }
Example #53
0
        /// <summary>
        /// Method which generates the RDF Graph of a SPARQL Result Set
        /// </summary>
        /// <param name="results">Result Set</param>
        /// <returns></returns>
        public IGraph GenerateOutput(SparqlResultSet results)
        {
            //Create the Graph for the Output
            IGraph g = new Graph();

            //Add the relevant namespaces
            g.NamespaceMap.AddNamespace("rs", new Uri(SparqlSpecsHelper.SparqlRdfResultsNamespace));

            //Create relevant Nodes
            IUriNode rdfType = g.CreateUriNode("rdf:type");
            IUriNode resultSetClass = g.CreateUriNode("rs:ResultSet");
            IUriNode resultVariable = g.CreateUriNode("rs:resultVariable");
            IUriNode solution = g.CreateUriNode("rs:solution");
            IUriNode binding = g.CreateUriNode("rs:binding");
            IUriNode value = g.CreateUriNode("rs:value");
            IUriNode variable = g.CreateUriNode("rs:variable");
            IUriNode boolean = g.CreateUriNode("rs:boolean");

            //First we declare a Result Set
            IBlankNode rset = g.CreateBlankNode();
            g.Assert(new Triple(rset, rdfType, resultSetClass));

            if (results.ResultsType == SparqlResultsType.VariableBindings)
            {
                //Assert a Triple for each Result Variable
                foreach (String v in results.Variables)
                {
                    g.Assert(new Triple(rset, resultVariable, g.CreateLiteralNode(v)));
                }

                //Then we're going to define a solution for each result
                foreach (SparqlResult r in results)
                {
                    IBlankNode sln = g.CreateBlankNode();
                    g.Assert(new Triple(rset, solution, sln));

                    foreach (String v in results.Variables)
                    {
                        //Only define Bindings if there is a value and it is non-null
                        if (r.HasValue(v) && r[v] != null)
                        {
                            IBlankNode bnd = g.CreateBlankNode();
                            g.Assert(new Triple(sln, binding, bnd));
                            g.Assert(new Triple(bnd, variable, g.CreateLiteralNode(v)));
                            switch (r[v].NodeType) 
                            {
                                case NodeType.Blank:
                                    IBlankNode b = (IBlankNode)r[v];
                                    IBlankNode bMapped;
                                    if (b.GraphUri == null)
                                    {
                                        bMapped = g.CreateBlankNode(b.InternalID + "def");
                                    }
                                    else
                                    {
                                        bMapped = g.CreateBlankNode(b.InternalID + b.GraphUri.GetEnhancedHashCode());
                                    }
                                    g.Assert(new Triple(bnd, value, bMapped));
                                    break;
                                case NodeType.GraphLiteral:
                                    throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("SPARQL Results RDF Serialization"));
                                case NodeType.Literal:
                                case NodeType.Uri:
                                    g.Assert(new Triple(bnd, value, r[v].CopyNode(g)));
                                    break;
                                default:
                                    throw new RdfOutputException(WriterErrorMessages.UnknownNodeTypeUnserializable("SPARQL Results RDF Serialization"));
                            }
                        }
                    }
                }
            }
            else
            {
                //A Boolean Result Set
                g.Assert(new Triple(rset, boolean, g.CreateLiteralNode(results.Result.ToString(), new Uri(XmlSpecsHelper.XmlSchemaDataTypeBoolean))));
            }

            return g;
        }
Example #54
0
 /// <summary>
 /// Creates a new Results Parser Context
 /// </summary>
 /// <param name="results">Result Set</param>
 public BaseResultsParserContext(SparqlResultSet results)
     : this(results, false)
 {
 }
Example #55
0
 /// <summary>
 /// Loads a Result Set from a File
 /// </summary>
 /// <param name="results">Result Set to load into</param>
 /// <param name="filename">File to load from</param>
 public void Load(SparqlResultSet results, string filename)
 {
     if (filename == null) throw new RdfParseException("Cannot parse SPARQL Results from a null file");
     this.Load(results, new StreamReader(filename));
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text    = "there is three types of programs at Syrian Virtual University";
        Label1.Visible = true;
        Graph g1 = new Graph();

        g1.LoadFromFile(Server.MapPath("SVUModeling.rdf"));
        TripleStore store = new TripleStore();

        store.Add(g1);
        //Assume that we fill our Store with data from somewhere

        //Create a dataset for our queries to operate over
        //We need to explicitly state our default graph or the unnamed graph is used
        //Alternatively you can set the second parameter to true to use the union of all graphs
        //as the default graph
        InMemoryDataset ds = new InMemoryDataset(store);

        //Get the Query processor
        ISparqlQueryProcessor processor = new LeviathanQueryProcessor(ds);

        //Use the SparqlQueryParser to give us a SparqlQuery object
        //Should get a Graph back from a CONSTRUCT query
        SparqlQueryParser sparqlparser = new SparqlQueryParser();
        SparqlQuery       query        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                                                           prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                                                           prefix owl: <http://www.w3.org/2002/07/owl#>
                                                           SELECT   ?ProgramName 
                                                           WHERE {
                                                           ?t   owl:StudyingAtSVU ?ProgramName 
                                                        }");
        Object            results      = processor.ProcessQuery(query);
        DataTable         DT1          = new DataTable();
        SparqlResultSet   rset         = (SparqlResultSet)results;

        DT1 = FillDataTable(rset);
        GridView1.DataSource = DT1;
        GridView1.DataBind();
        GridView1.Visible = true;


        // to select Bachelor Programs
        Label2.Text    = "Bachelor Programs At SVU";
        Label2.Visible = true;
        SparqlQueryParser sparqlparser2 = new SparqlQueryParser();
        SparqlQuery       query2        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                 prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                 prefix owl: <http://www.w3.org/2002/07/owl#>
                SELECT ?BachelorPrograms
                WHERE {
                ?t   owl:BachelorProgramAtSVU ?BachelorPrograms
                }");
        Object            results2      = processor.ProcessQuery(query2);
        DataTable         DT2           = new DataTable();
        SparqlResultSet   rset2         = (SparqlResultSet)results2;

        DT2 = FillDataTable(rset2);
        GridView2.DataSource = DT2;
        GridView2.DataBind();
        GridView2.Visible = true;

        // to select Master Programs
        Label3.Text    = "Master Programs At SVU";
        Label3.Visible = true;
        SparqlQueryParser sparqlparser3 = new SparqlQueryParser();
        SparqlQuery       query3        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                prefix owl: <http://www.w3.org/2002/07/owl#>
                SELECT ?MasterPrograms 
                WHERE {
                ?t   owl:MasterProgramAtSVU ?MasterPrograms 
                }");
        Object            results3      = processor.ProcessQuery(query3);
        DataTable         DT3           = new DataTable();
        SparqlResultSet   rset3         = (SparqlResultSet)results3;

        DT3 = FillDataTable(rset3);
        GridView3.DataSource = DT3;
        GridView3.DataBind();
        GridView3.Visible = true;

        // to select Training Programs
        Label4.Text    = "Training Programs At SVU";
        Label4.Visible = true;
        SparqlQueryParser sparqlparser4 = new SparqlQueryParser();
        SparqlQuery       query4        = sparqlparser.ParseFromString(@"prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                prefix owl: <http://www.w3.org/2002/07/owl#>
                SELECT   ?TrainingPrograms 
                WHERE {
                ?t   owl:TrainingProgramAtSVU ?TrainingPrograms 
                }");
        Object            results4      = processor.ProcessQuery(query4);
        DataTable         DT4           = new DataTable();
        SparqlResultSet   rset4         = (SparqlResultSet)results4;

        DT4 = FillDataTable(rset4);
        GridView4.DataSource = DT4;
        GridView4.DataBind();
        GridView4.Visible = true;
    }
Example #57
0
        public void SparqlUpdateInsertDeleteWithBlankNodes()
        {
            //This test adapted from a contribution by Tomasz Pluskiewicz
            //It demonstrates an issue in SPARQL Update caused by incorrect Graph
            //references that can result when using GraphPersistenceWrapper in a SPARQL Update
            String initData = @"@prefix ex: <http://www.example.com/>.
@prefix rr: <http://www.w3.org/ns/r2rml#>.

ex:triplesMap rr:predicateObjectMap _:blank .
_:blank rr:object ex:Employee, ex:Worker .";

            String update = @"PREFIX rr: <http://www.w3.org/ns/r2rml#>

DELETE { ?map rr:object ?value . }
INSERT { ?map rr:objectMap [ rr:constant ?value ] . }
WHERE { ?map rr:object ?value }";

            String query = @"prefix ex: <http://www.example.com/>
prefix rr: <http://www.w3.org/ns/r2rml#>

select *
where
{
ex:triplesMap rr:predicateObjectMap ?predObjMap .
?predObjMap rr:objectMap ?objMap .
}";

            String expectedData = @"@prefix ex: <http://www.example.com/>.
@prefix rr: <http://www.w3.org/ns/r2rml#>.

ex:triplesMap rr:predicateObjectMap _:blank.
_:blank rr:objectMap _:autos1.
_:autos1 rr:constant ex:Employee.
_:autos2 rr:constant ex:Worker.
_:blank rr:objectMap _:autos2.";

            // given
            IGraph graph = new Graph();

            graph.LoadFromString(initData);
            IGraph expectedGraph = new Graph();

            expectedGraph.LoadFromString(expectedData);

            Console.WriteLine("Initial Graph:");
            TestTools.ShowGraph(graph);
            Console.WriteLine();

            // when
            TripleStore store = new TripleStore();

            store.Add(graph);

            var dataset = new InMemoryDataset(store, graph.BaseUri);
            ISparqlUpdateProcessor processor = new LeviathanUpdateProcessor(dataset);
            var updateParser = new SparqlUpdateParser();

            processor.ProcessCommandSet(updateParser.ParseFromString(update));

            Console.WriteLine("Resulting Graph:");
            TestTools.ShowGraph(graph);
            Console.WriteLine();

            Triple x         = graph.GetTriplesWithPredicate(graph.CreateUriNode("rr:predicateObjectMap")).FirstOrDefault();
            INode  origBNode = x.Object;

            Assert.IsTrue(graph.GetTriples(origBNode).Count() > 1, "Should be more than one Triple using the BNode");
            IEnumerable <Triple> ys = graph.GetTriplesWithSubject(origBNode);

            foreach (Triple y in ys)
            {
                Assert.AreEqual(origBNode, y.Subject, "Blank Nodes should be equal");
            }

            //Graphs should be equal
            GraphDiffReport diff = graph.Difference(expectedGraph);

            if (!diff.AreEqual)
            {
                TestTools.ShowDifferences(diff);
            }
            Assert.AreEqual(expectedGraph, graph, "Graphs should be equal");

            //Test the Query
            SparqlResultSet results = graph.ExecuteQuery(query) as SparqlResultSet;

            TestTools.ShowResults(results);
            Assert.IsFalse(results.IsEmpty, "Should be some results");
        }
        private void LoopValuesToDatabase(SparqlResultSet resultSetAuthorDetails, SparqlResultSet resultSetAuthorBooks)
        {
            if (resultSetAuthorDetails.IsEmpty && resultSetAuthorBooks.IsEmpty)
            {
                return;
            }
            string authorLink       = resultSetAuthorDetails.Last()["authorLink"].ToString();
            string authorName       = resultSetAuthorDetails.Last()["authorName"].ToString();
            string placeOfBirthLink = resultSetAuthorDetails.Last()["placeOfBirthLink"].ToString();
            string placeOfBirth     = resultSetAuthorDetails.Last()["PlaceOfBirth"].ToString();
            string stringLatitude   = resultSetAuthorDetails.Last().Value("latitude").ToString();
            string stringLongitude  = resultSetAuthorDetails.Last().Value("longitude").ToString();

            //Convert latitude and longitude to float

            float latitude  = float.Parse(Utilities.NumberConverter(stringLatitude));
            float longitude = float.Parse(Utilities.NumberConverter(stringLongitude));

            if (authorName.Length > 3 && placeOfBirth.Length > 3)
            {
                authorName   = authorName.Substring(0, authorName.Length - 3);
                placeOfBirth = placeOfBirth.Substring(0, placeOfBirth.Length - 3);
            }

            //Create a list of all the authors books
            List <BookDetails> authorBooks = new List <BookDetails>();

            foreach (SparqlResult result in resultSetAuthorBooks)
            {
                string bookLink            = result["bookLink"].ToString();
                string name                = result["bookName"].ToString();
                string bookAbstract        = result["bookAbstract"].ToString();
                string stringNumberOfPages = "";
                if (result["numberOfPages"] != null)
                {
                    stringNumberOfPages = result["numberOfPages"].ToString();
                }
                string comment = result["comment"].ToString();

                //Remove @en from the string
                name         = Utilities.RemoveLast3Cahracters(name);
                bookAbstract = Utilities.RemoveLast3Cahracters(bookAbstract);
                comment      = Utilities.RemoveLast3Cahracters(comment);

                //Convert numberOfPages to int
                int numberOfPages = 0;
                if (result["numberOfPages"] != null)
                {
                    numberOfPages = int.Parse(Utilities.NumberConverter(stringNumberOfPages));
                }

                //Create a BookDetails object
                BookDetails book = new BookDetails
                {
                    BookLink      = bookLink,
                    Name          = name,
                    Abstract      = bookAbstract,
                    NumberOfPages = numberOfPages,
                    Comment       = comment
                };
                authorBooks.Add(book);
            }

            //
            AddToDatabase(authorLink, authorName, placeOfBirthLink, placeOfBirth, latitude, longitude, authorBooks);
        }
Example #59
0
        public void SparqlAggregatesMaxBug3()
        {
            try
            {
                Options.AlgebraOptimisation = false;

                TripleStore store = new TripleStore();
                Graph       g     = new Graph();
                g.LoadFromFile("LearningStyles.rdf");
                Assert.IsFalse(g.IsEmpty);
                g.BaseUri = null;
                store.Add(g);

                var graph = (IGraph)store.ExecuteQuery(@"
                    PREFIX sage: <http://www.semanticsage.home.lc/LearningStyles.owl#>
                    PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
                    PREFIX : <http://www.semanticsage.home.lc/LearningStyles.rdf#>
                    CONSTRUCT 
                    { 
                       ?MTech :max ?maxScore  
                    }
                    WHERE 
                    { 
                       SELECT ?MTech (MAX(?max) AS ?maxScore)
                       WHERE
                       {
                          SELECT ?MTech ?LessonType (SUM(?hasValue) AS ?max)
                          WHERE 
                          {
                             ?MTech sage:attendsLessons ?Lesson. 
                             ?Lesson sage:hasLessonType ?LessonType. 
                             ?MTech sage:undergoesEvaluation ?Quiz. 
                             ?Quiz sage:isForLesson ?Lesson. 
                             ?MTech sage:hasQuizMarks ?QuizMarks. 
                             ?QuizMarks sage:belongsToQuiz ?Quiz. 
                             ?QuizMarks sage:hasValue ?hasValue.
                             ?Lesson sage:inRound '1'^^xsd:int.
                          }
                          GROUP BY ?MTech ?LessonType
                       }
                       GROUP BY ?MTech
                    }");

                Assert.IsFalse(graph.IsEmpty, "CONSTRUCTed graph should not be empty");

                // here a graph name is given to the result graph
                graph.BaseUri = new Uri("http://semanticsage.home.lc/files/LearningStyles.rdf#maxValues");
                store.Add(graph, true);

                SparqlResultSet actualResults = store.ExecuteQuery(@"
                    PREFIX sage: <http://www.semanticsage.home.lc/LearningStyles.owl#>
                    PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
                    PREFIX : <http://www.semanticsage.home.lc/LearningStyles.rdf#>
                    SELECT ?MTech ?LessonType ?max
                    WHERE
                    {
                       GRAPH <http://semanticsage.home.lc/files/LearningStyles.rdf#maxValues>
                       {
                          ?MTech :max ?max
                       }
                       {
                            SELECT ?MTech ?LessonType (SUM(?hasValue) AS ?Score)
                            WHERE 
                            {
                                ?MTech sage:attendsLessons ?Lesson. 
                                ?Lesson sage:hasLessonType ?LessonType. 
                                ?MTech sage:undergoesEvaluation ?Quiz. 
                                ?Quiz sage:isForLesson ?Lesson. 
                                ?MTech sage:hasQuizMarks ?QuizMarks. 
                                ?QuizMarks sage:belongsToQuiz ?Quiz. 
                                ?QuizMarks sage:hasValue ?hasValue.
                                ?Lesson sage:inRound '1'^^xsd:int.
                            }
                            GROUP BY ?MTech ?LessonType
                            ORDER BY ?MTech
                       }
                       FILTER(?Score = ?max)
                    }") as SparqlResultSet;
                Assert.IsNotNull(actualResults);
                Assert.IsFalse(actualResults.IsEmpty, "Final results should not be empty");
            }
            finally
            {
                Options.AlgebraOptimisation = true;
            }
        }
Example #60
0
 /// <summary>
 /// Saves a SPARQL Result Set to the given File
 /// </summary>
 /// <param name="results">Result Set</param>
 /// <param name="filename">File to save to</param>
 public override void Save(SparqlResultSet results, string filename)
 {
     this.Save(results, new StreamWriter(filename, false, new UTF8Encoding(Options.UseBomForUtf8)));
 }