コード例 #1
0
        private void Replace(IGraph graph, IUriNode parent, Uri predicate, string jsonField)
        {
            JToken token = null;
            if (_galleryPage.TryGetValue(jsonField, out token))
            {
                JArray array = token as JArray;
                JValue val = token as JValue;

                if (array != null || val != null)
                {
                    var pred = graph.CreateUriNode(predicate);

                    var old = graph.GetTriplesWithSubjectPredicate(parent, pred).ToArray();

                    // remove the old values
                    foreach (var triple in old)
                    {
                        graph.Retract(triple);
                    }

                    if (array != null)
                    {
                        foreach (var child in array)
                        {
                            graph.Assert(parent, pred, graph.CreateLiteralNode(child.ToString()));
                        }
                    }
                    else
                    {
                        graph.Assert(parent, pred, graph.CreateLiteralNode(val.ToString()));
                    }
                }
            }
        }
コード例 #2
0
        public UriNodeControl(IUriNode u, INodeFormatter formatter)
        {
            InitializeComponent();

            this.lnkUri.Text = formatter.Format(u);
            this._u = u.Uri;
        }
コード例 #3
0
ファイル: ExpansionProfile.cs プロジェクト: jbunzel/MvcRQ_git
        protected override void Initialise(IGraph g)
        {
            if (g.BaseUri != null) this._node = g.CreateUriNode();

            //First ensure all the correct namespace prefixes are set to the correct URIs
            g.NamespaceMap.AddNamespace("rdf", new Uri(NamespaceMapper.RDF));
            g.NamespaceMap.AddNamespace("void", new Uri(VoIDNamespace));
            g.NamespaceMap.AddNamespace("foaf", new Uri(FoafNamespace));
            g.NamespaceMap.AddNamespace("dcterms", new Uri(DublinCoreTermsNamespace));
            g.NamespaceMap.AddNamespace("aat", new Uri(AATNamespace));

            //First look for an Expansion Profile description
            Triple profileDescriptor = new Triple(g.CreateUriNode(), g.CreateUriNode("rdf:type"), g.CreateUriNode("aat:ExpansionProfile"));
            if (g.ContainsTriple(profileDescriptor))
            {
                //Does it specify a Max Expansion Depth?
                Triple maxDepthSpecifier = g.GetTriplesWithSubjectPredicate(g.CreateUriNode(), g.CreateUriNode("aat:maxExpansionDepth")).FirstOrDefault();
                if (maxDepthSpecifier != null)
                {
                    if (maxDepthSpecifier.Object.NodeType == NodeType.Literal)
                    {
                        ILiteralNode l = (ILiteralNode)maxDepthSpecifier.Object;
                        if (l.DataType != null && l.DataType.ToString().Equals(XmlSpecsHelper.XmlSchemaDataTypeInteger))
                        {
                            this._maxDepth = Int32.Parse(l.Value);
                        }
                    }
                }
            }

            //Find Datasets
            foreach (Triple t in g.GetTriplesWithPredicateObject(g.CreateUriNode("rdf:type"), g.CreateUriNode("void:Dataset")))
            {
                ExpansionDataset dataset = new ExpansionDataset(g, t.Subject);
                if (this._datasets.ContainsKey(t.Subject))
                {
                    throw new NotImplementedException("Merging Expansion Datasets is not yet implemented");
                }
                else
                {
                    this._datasets.Add(t.Subject, dataset);
                }
            }

            //Find Linksets
            foreach (Triple t in g.GetTriplesWithPredicateObject(g.CreateUriNode("rdf:type"), g.CreateUriNode("void:Linkset")))
            {
                ExpansionLinkset linkset = new ExpansionLinkset(g, t.Subject);
                if (this._linksets.ContainsKey(t.Subject))
                {
                    throw new NotImplementedException("Merging Expansion Linksets is not yet implemented");
                }
                else
                {
                    this._linksets.Add(t.Subject, linkset);
                }
            }

        }
コード例 #4
0
 private IDataObject BindRdfDataObject(IUriNode dataObjectResource, IGraph graph)
 {
     var triples =
         graph.GetTriplesWithSubject(dataObjectResource)
             .Where(t => t.Subject is IUriNode && t.Predicate is IUriNode)
             .Select(t => MakeTriple(t.Subject, t.Predicate, t.Object));
     return MakeDataObject(dataObjectResource.Uri.ToString(), triples);
 }
コード例 #5
0
 /// <summary>
 /// Formats a URI Node
 /// </summary>
 /// <param name="u">URI Node</param>
 /// <param name="segment">Triple Segment</param>
 /// <returns></returns>
 protected override string FormatUriNode(IUriNode u, TripleSegment? segment)
 {
     StringBuilder output = new StringBuilder();
     output.Append('<');
     output.Append(this.FormatUri(u.Uri));
     output.Append('>');
     return output.ToString();
 }
コード例 #6
0
ファイル: SKOSReasoner.cs プロジェクト: jbunzel/MvcRQ_git
 /// <summary>
 /// Creates a new instance of the SKOS Reasoner
 /// </summary>
 public StaticSkosReasoner()
 {
     Graph g = new Graph();
     g.NamespaceMap.AddNamespace("skos", new Uri(SKOSNamespace));
     this._rdfType = g.CreateUriNode("rdf:type");
     this._skosBroader = g.CreateUriNode("skos:broader");
     this._skosConcept = g.CreateUriNode("skos:Concept");
     this._skosNarrower = g.CreateUriNode("skos:narrower");
 }
コード例 #7
0
ファイル: ExpansionContext.cs プロジェクト: jbunzel/MvcRQ_git
        public ExpansionContext(ExpansionProfile profile)
        {
            this._profile = profile;

            this._linkTree.BaseUri = new Uri(VDS.RDF.Writing.WriterHelper.StoreDefaultGraphURIs.First());
            this._linkTree.NamespaceMap.AddNamespace("owl", new Uri(NamespaceMapper.OWL));
            this._sameAs = this._linkTree.CreateUriNode("owl:sameAs");
            this._seeAlso = this._linkTree.CreateUriNode("rdfs:seeAlso");
            this._store.Add(this._linkTree);
        }
コード例 #8
0
        /// <summary>
        /// Add data from nuget.packed.json
        /// </summary>
        public override void ApplyToGraph(IGraph graph, IUriNode mainNode)
        {
            Uri mainUri = mainNode.Uri;
            IUriNode typeNode = graph.CreateUriNode(Schema.Predicates.Type);

            // supported frameworks
            if (SupportedFrameworks != null)
            {
                foreach (string framework in SupportedFrameworks)
                {
                    graph.Assert(new Triple(mainNode, graph.CreateUriNode(Schema.Predicates.SupportedFramework), graph.CreateLiteralNode(framework)));
                }
            }

            // assets
            //if (AssetGroups != null)
            //{
            //    int groupId = 0;
            //    foreach (var group in AssetGroups)
            //    {
            //        // group type and id
            //        var groupNode = GetSubNode(graph, mainUri, "assetGroup", "" + groupId);
            //        graph.Assert(groupNode, typeNode, graph.CreateUriNode(PackageAssetGroupType));
            //        graph.Assert(mainNode, graph.CreateUriNode(AssetGroupPredicate), groupNode);
            //        groupId++;

            //        int propId = 0;

            //        // group properties
            //        foreach (var prop in group.Properties)
            //        {
            //            var propNode = GetSubNode(graph, groupNode, "property", "" + propId);
            //            propId++;
            //            graph.Assert(propNode, typeNode, graph.CreateUriNode(PackageAssetGroupPropertyType));
            //            graph.Assert(groupNode, graph.CreateUriNode(AssetGroupPropertyPredicate), propNode);
            //            graph.Assert(propNode, graph.CreateUriNode(AssetKeyPredicate), graph.CreateLiteralNode(prop.Key));
            //            graph.Assert(propNode, graph.CreateUriNode(AssetValuePredicate), graph.CreateLiteralNode(prop.Value));
            //        }

            //        int assetId = 0;

            //        // group items
            //        foreach (var item in group.Items)
            //        {
            //            var itemNode = GetSubNode(graph, groupNode, "asset", "" + assetId);
            //            assetId++;
            //            graph.Assert(itemNode, typeNode, graph.CreateUriNode(PackageAssetType));
            //            graph.Assert(groupNode, graph.CreateUriNode(AssetPredicate), itemNode);

            //            graph.Assert(itemNode, graph.CreateUriNode(AssetTypePredicate), graph.CreateLiteralNode(item.ArtifactType));
            //            graph.Assert(itemNode, graph.CreateUriNode(AssetPathPredicate), graph.CreateLiteralNode(item.Path));
            //        }
            //    }
            //}
        }
コード例 #9
0
 /// <summary>
 /// Creates a new instance of the Static RdfsReasoner
 /// </summary>
 public StaticRdfsReasoner()
 {
     Graph g = new Graph();
     this._rdfType = g.CreateUriNode("rdf:type");
     this._rdfsClass = g.CreateUriNode("rdfs:Class");
     this._rdfsSubClass = g.CreateUriNode("rdfs:subClassOf");
     this._rdfProperty = g.CreateUriNode("rdf:Property");
     this._rdfsSubProperty = g.CreateUriNode("rdfs:subPropertyOf");
     this._rdfsDomain = g.CreateUriNode("rdfs:domain");
     this._rdfsRange = g.CreateUriNode("rdfs:range");
 }
コード例 #10
0
        public override void ApplyToGraph(IGraph graph, IUriNode parent)
        {
            Replace(graph, parent, Schema.Predicates.ProjectUrl, "projectUrl");
            Replace(graph, parent, Schema.Predicates.Title, "title");
            Replace(graph, parent, Schema.Predicates.IconUrl, "iconUrl");

            //Replace(graph, parent, Schema.Predicates.Summary, "summary");
            //Replace(graph, parent, Schema.Predicates.Author, "authors");
            //Replace(graph, parent, Schema.Predicates.Tag, "tag");
            //Replace(graph, parent, Schema.Predicates.ReleaseNotes, "releaseNotes");
        }
コード例 #11
0
 private static void CompareNodes(IUriNode a, IUriNode b)
 {
     Console.WriteLine("URI Node A has String form: " + a.ToString());
     Console.WriteLine("URI Node B has String form: " + b.ToString());
     Console.WriteLine();
     Console.WriteLine("URI Node A has Hash Code: " + a.GetHashCode());
     Console.WriteLine("URI Node B has Hash Code: " + b.GetHashCode());
     Console.WriteLine();
     Console.WriteLine("Nodes are Equal? " + a.Equals(b));
     Console.WriteLine("Hash Codes are Equal? " + a.GetHashCode().Equals(b.GetHashCode()));
     Console.WriteLine();
 }
コード例 #12
0
        public MetadataManifest(IPackageDocument document, string name)
            : base(document, name)
        {
            Graph.NamespaceMap.AddNamespace("pkg", new Uri("http://docs.oasis-open.org/ns/office/1.2/meta/pkg#"));
            Graph.NamespaceMap.AddNamespace("odf", new Uri("http://docs.oasis-open.org/ns/office/1.2/meta/odf#"));
            Graph.NamespaceMap.AddNamespace("rdf", new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#"));

            _documentNode = Graph.CreateUriNode();
            _rdfTypeNode = Graph.CreateUriNode("rdf:type");
            _hasPartPredicateNode = Graph.CreateUriNode("pkg:hasPart");
            _metadataFileTypeNode = Graph.CreateUriNode("pkg:MetadataFile");

            Graph.Assert(_documentNode, _rdfTypeNode, _hasPartPredicateNode);
        }
コード例 #13
0
        public static bool AreUrisEqual(IUriNode a, IUriNode b)
        {
            if (ReferenceEquals(a, b)) return true;
            if (a == null)
            {
                if (b == null) return true;
                return false;
            }
            else if (b == null)
            {
                return false;
            }

            return EqualityHelper.AreUrisEqual(a.Uri, b.Uri);
        }
コード例 #14
0
 private IDataObject BindRdfDataObject(IUriNode dataObjectResource, IGraph graph)
 {
     var triples = new List<Triple>();
     foreach (var t in graph.GetTriplesWithSubject(dataObjectResource))
     {
         if (t.Subject is IUriNode && t.Predicate is IUriNode)
         {
             // Only handling triples that have a URI predicate
             // subject will always be a UriNode, because that is what we used in the lookup
             var subject = (t.Subject as IUriNode).Uri.ToString();
             var predicate = (t.Predicate as IUriNode).Uri.ToString();
             if (t.Object is ILiteralNode)
             {
                 var lit = t.Object as ILiteralNode;
                 triples.Add(new Triple
                     {
                         Subject = subject,
                         Predicate = predicate,
                         IsLiteral = true,
                         Object = lit.Value,
                         DataType = lit.DataType == null ? Constants.DefaultDatatypeUri : lit.DataType.ToString(),
                         LangCode = lit.Language
                     });
             }
             else if (t.Object is IUriNode)
             {
                 var uriNode = t.Object as IUriNode;
                 triples.Add(new Triple
                     {
                         Subject = subject,
                         Predicate = predicate,
                         IsLiteral = false,
                         Object = uriNode.Uri.ToString()
                     });
             }
         }
     }
     var dataObject = _storeContext.MakeDataObject(dataObjectResource.Uri.ToString()) as DataObject;
     dataObject.BindTriples(triples);
     return dataObject;
 }
コード例 #15
0
ファイル: ManifestGraph.cs プロジェクト: Tenere/Semantic-Lib
        public ManifestGraph(IMetadataManifest metadataManifest)
        {
            if (metadataManifest == null)
            {
                throw new ArgumentNullException("metadataManifest");
            }

            NamespaceMap.AddNamespace("pkg", new Uri("http://docs.oasis-open.org/ns/office/1.2/meta/pkg#"));
            NamespaceMap.AddNamespace("odf", new Uri("http://docs.oasis-open.org/ns/office/1.2/meta/odf#"));
            NamespaceMap.AddNamespace("rdf", new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#"));

            //TODO Use a document URI.
            BaseUri = metadataManifest.Document.Uri;
            //_documentNode = CreateUriNode(new Uri("http://www.example.com"));
            _documentNode = CreateUriNode();
            _rdfTypeNode = CreateUriNode("rdf:type");
            _hasPartPredicateNode = CreateUriNode("pkg:hasPart");
            _metadataFileTypeNode = CreateUriNode("pkg:MetadataFile");
            IUriNode documentTypeNode = CreateUriNode("pkg:Document");

            Assert(new Triple(_documentNode, _rdfTypeNode, documentTypeNode));
        }
コード例 #16
0
ファイル: TestTools.cs プロジェクト: almostEric/DotNetRDF-4.0
        public static void CompareNodes(IUriNode a, IUriNode b, bool expectEquality)
        {
            Console.WriteLine("URI Node A has String form: " + a.ToString());
            Console.WriteLine("URI Node B has String form: " + b.ToString());
            Console.WriteLine();
            Console.WriteLine("URI Node A has Hash Code: " + a.GetHashCode());
            Console.WriteLine("URI Node B has Hash Code: " + b.GetHashCode());
            Console.WriteLine();
            Console.WriteLine("Nodes are Equal? " + a.Equals(b));
            Console.WriteLine("Hash Codes are Equal? " + a.GetHashCode().Equals(b.GetHashCode()));
            Console.WriteLine();

            if (expectEquality)
            {
                Assert.AreEqual(a.GetHashCode(), b.GetHashCode());
                Assert.AreEqual(a, b);
            }
            else
            {
                Assert.AreNotEqual(a.GetHashCode(), b.GetHashCode());
                Assert.AreNotEqual(a, b);
            }
        }
コード例 #17
0
 /// <summary>
 /// Nodes must implement a CompareTo method to allow them to be Sorted
 /// </summary>
 /// <param name="other">Node to compare self to</param>
 /// <returns></returns>
 /// <remarks>
 /// Implementations should use the SPARQL Term Sort Order for ordering nodes (as opposed to value sort order).  Standard implementations of Node type specific comparisons can be found in <see cref="ComparisonHelper">ComparisonHelper</see>
 /// </remarks>
 public abstract int CompareTo(IUriNode other);
コード例 #18
0
ファイル: BaseFormatter.cs プロジェクト: naeemullah/dotnetrdf
 /// <summary>
 /// Formats a URI Node as a String for the given Format.
 /// </summary>
 /// <param name="u">URI Node.</param>
 /// <param name="segment">Triple Segment.</param>
 /// <returns></returns>
 protected abstract String FormatUriNode(IUriNode u, TripleSegment?segment);
コード例 #19
0
 private void GenerateUriOutput(RdfXmlWriterContext context, IUriNode u, String attribute, List<String> tempNamespaceIDs, XmlElement node, XmlDocument doc)
 {
     //Create an attribute
     XmlAttribute attr = doc.CreateAttribute(attribute, NamespaceMapper.RDF);
     //Get a Uri Reference if the Uri can be reduced
     UriRefType rtype;
     String uriref = this.GenerateUriRef(context, u, UriRefType.UriRef, tempNamespaceIDs, out rtype);
     attr.InnerXml = WriterHelper.EncodeForXml(uriref);
     //Append the attribute
     node.Attributes.Append(attr);
 }
コード例 #20
0
 public bool Equals(IUriNode other)
 {
     return(_source.Equals(other));
 }
コード例 #21
0
 public override bool Equals(IUriNode other)
 {
     return Uri.Equals(other.Uri);
 }
コード例 #22
0
 /// <summary>
 /// Creates a new SubClassSelector for the given Graph with the given Target Class
 /// </summary>
 /// <param name="g"></param>
 /// <param name="targetClass"></param>
 public SubClassSelector(IGraph g, IUriNode targetClass)
 {
     this._targetclass = targetClass;
     this._subclassof  = g.CreateUriNode(UriFactory.Create(NamespaceMapper.RDFS + "subClassOf"));
 }
コード例 #23
0
        public void StorageVirtuosoBlankNodePersistence()
        {
            //Create our Test Graph
            Graph g = new Graph();

            g.BaseUri = new Uri("http://example.org/bnodes/");
            g.NamespaceMap.AddNamespace(String.Empty, g.BaseUri);

            IBlankNode b       = g.CreateBlankNode("blank");
            IUriNode   rdfType = g.CreateUriNode("rdf:type");
            IUriNode   bnode   = g.CreateUriNode(":BlankNode");

            g.Assert(new Triple(b, rdfType, bnode));

            Assert.AreEqual(1, g.Triples.Count, "Should only be 1 Triple in the Test Graph");

            //Connect to Virtuoso
            VirtuosoManager manager = VirtuosoTest.GetConnection();

            try
            {
                //Save Graph
                manager.SaveGraph(g);

                //Retrieve
                Graph h = new Graph();
                Graph i = new Graph();
                manager.LoadGraph(h, g.BaseUri);
                manager.LoadGraph(i, g.BaseUri);

                Assert.AreEqual(1, h.Triples.Count, "Retrieved Graph should only contain 1 Triple");
                Assert.AreEqual(1, i.Triples.Count, "Retrieved Graph should only contain 1 Triple");

                Console.WriteLine("Contents of Retrieved Graph:");
                foreach (Triple t in h.Triples)
                {
                    Console.WriteLine(t.ToString());
                }
                Console.WriteLine();

                TestTools.CompareGraphs(h, i, true);

                //Save back again
                manager.SaveGraph(h);

                //Retrieve again
                Graph j = new Graph();
                manager.LoadGraph(j, g.BaseUri);

                Console.WriteLine("Contents of Retrieved Graph (Retrieved after saving original Retrieval):");
                foreach (Triple t in j.Triples)
                {
                    Console.WriteLine(t.ToString());
                }
                Console.WriteLine();

                TestTools.CompareGraphs(h, j, false);
                TestTools.CompareGraphs(i, j, false);

                //Save back yet again
                manager.SaveGraph(j);

                //Retrieve yet again
                Graph k = new Graph();
                manager.LoadGraph(k, g.BaseUri);

                Console.WriteLine("Contents of Retrieved Graph (Retrieved after saving second Retrieval):");
                foreach (Triple t in k.Triples)
                {
                    Console.WriteLine(t.ToString());
                }
                Console.WriteLine();

                TestTools.CompareGraphs(j, k, false);
            }
            finally
            {
                if (manager != null)
                {
                    manager.Dispose();
                }
            }
        }
コード例 #24
0
        /// <summary>
        /// Internal method which actually parses the Result Set by traversing the RDF Graph appropriately
        /// </summary>
        /// <param name="context">Parser Context</param>
        private void Parse(SparqlRdfParserContext context)
        {
            try
            {
                context.Handler.StartResults();

                // Create relevant Nodes
                context.Graph.NamespaceMap.AddNamespace("rdf", UriFactory.Create(NamespaceMapper.RDF));
                context.Graph.NamespaceMap.AddNamespace("rs", UriFactory.Create(SparqlSpecsHelper.SparqlRdfResultsNamespace));
                IUriNode rdfType        = context.Graph.CreateUriNode("rdf:type");
                IUriNode resultSetClass = context.Graph.CreateUriNode("rs:ResultSet");
                IUriNode resultVariable = context.Graph.CreateUriNode("rs:resultVariable");
                IUriNode solution       = context.Graph.CreateUriNode("rs:solution");
                IUriNode binding        = context.Graph.CreateUriNode("rs:binding");
                IUriNode value          = context.Graph.CreateUriNode("rs:value");
                IUriNode variable       = context.Graph.CreateUriNode("rs:variable");
                IUriNode boolean        = context.Graph.CreateUriNode("rs:boolean");

                // Try to get a ResultSet object
                Triple rset = context.Graph.Triples.WithPredicateObject(rdfType, resultSetClass).FirstOrDefault();
                if (rset != null)
                {
                    INode rsetID = rset.Subject;

                    // Find the Variables the Result Set contains or the Boolean Value
                    List <Triple> temp = context.Graph.Triples.WithSubjectPredicate(rsetID, boolean).ToList();
                    if (temp.Count > 0)
                    {
                        if (temp.Count > 1)
                        {
                            throw new RdfParseException("Result Set has more than one boolean result defined for it");
                        }

                        Triple booleanResult = temp.First();
                        INode  result        = booleanResult.Object;
                        if (result.NodeType == NodeType.Literal)
                        {
                            ILiteralNode lit = (ILiteralNode)result;
                            if (lit.DataType != null)
                            {
                                if (lit.DataType.AbsoluteUri.Equals(XmlSpecsHelper.XmlSchemaDataTypeBoolean))
                                {
                                    bool b;
                                    if (Boolean.TryParse(lit.Value, out b))
                                    {
                                        context.Handler.HandleBooleanResult(b);
                                        return;
                                    }
                                    else
                                    {
                                        throw new RdfParseException("Result Set has a boolean result which is a Literal typed as boolean but which does not contain a valid boolean value");
                                    }
                                }
                                else
                                {
                                    throw new RdfParseException("Result Set has a boolean result which is a Literal which is not boolean typed");
                                }
                            }
                            else
                            {
                                throw new RdfParseException("Result Set has a boolean result which is a Literal which is not typed as a boolean");
                            }
                        }
                        else
                        {
                            throw new RdfParseException("Result Set has a boolean result which is not a Literal Node");
                        }
                    }
                    else
                    {
                        // We're expected one/more variables
                        temp = context.Graph.Triples.WithSubjectPredicate(rsetID, resultVariable).ToList();
                        if (temp.Count > 0)
                        {
                            foreach (Triple t in temp)
                            {
                                if (t.Object.NodeType == NodeType.Literal)
                                {
                                    if (!context.Handler.HandleVariable(((ILiteralNode)t.Object).Value))
                                    {
                                        ParserHelper.Stop();
                                    }
                                    context.Variables.Add(((ILiteralNode)t.Object).Value);
                                }
                                else
                                {
                                    throw new RdfParseException("Result Set has a result variable definition which is not a Literal Node");
                                }
                            }
                        }
                        else
                        {
                            throw new RdfParseException("Result Set does not define any result variables or a boolean result");
                        }

                        // Then we're expecting some Solutions
                        temp = context.Graph.Triples.WithSubjectPredicate(rsetID, solution).ToList();
                        foreach (Triple slnTriple in temp)
                        {
                            // Each Solution has some Bindings
                            INode        slnID = slnTriple.Object;
                            bool         ok    = false;
                            SparqlResult r     = new SparqlResult();

                            foreach (Triple bindingTriple in context.Graph.Triples.WithSubjectPredicate(slnID, binding))
                            {
                                // Each Binding has a Variable and a Value
                                ok = true;
                                INode  bindingID = bindingTriple.Object;
                                String var       = String.Empty;
                                INode  val       = null;

                                // Retrieve the Variable and the Bound Value
                                foreach (Triple valueTriple in context.Graph.Triples.WithSubject(bindingID))
                                {
                                    if (valueTriple.Predicate.Equals(variable))
                                    {
                                        if (!var.Equals(String.Empty))
                                        {
                                            throw new RdfParseException("Result Set contains a Binding which refers to more than one Variable");
                                        }
                                        if (valueTriple.Object.NodeType != NodeType.Literal)
                                        {
                                            throw new RdfParseException("Result Set contains a Binding which refers to a Variable but not by a Literal Node as required");
                                        }
                                        var = ((ILiteralNode)valueTriple.Object).Value;
                                    }
                                    else if (valueTriple.Predicate.Equals(value))
                                    {
                                        if (val != null)
                                        {
                                            throw new RdfParseException("Result Set contains a Binding which has more than one Value");
                                        }
                                        val = valueTriple.Object;
                                    }
                                }
                                if (var.Equals(String.Empty) || val == null)
                                {
                                    throw new RdfParseException("Result Set contains a Binding which doesn't contain both a Variable and a Value");
                                }

                                // Check that the Variable was defined in the Header
                                if (!context.Variables.Contains(var))
                                {
                                    throw new RdfParseException("Unable to Parse a SPARQL Result Set since a <binding> element attempts to bind a value to the variable '" + var + "' which is not defined in the <head> by a <variable> element!");
                                }

                                r.SetValue(var, val);
                            }
                            if (!ok)
                            {
                                throw new RdfParseException("Result Set contains a Solution which has no Bindings");
                            }

                            // Check that all Variables are bound for a given result binding nulls where appropriate
                            foreach (String v in context.Variables)
                            {
                                if (!r.HasValue(v))
                                {
                                    r.SetValue(v, null);
                                }
                            }

                            if (!context.Handler.HandleResult(r))
                            {
                                ParserHelper.Stop();
                            }
                        }
                    }
                }
                else
                {
                    throw new RdfParseException("No Result Set object is defined in the Graph");
                }

                context.Handler.EndResults(true);
            }
            catch (RdfParsingTerminatedException)
            {
                context.Handler.EndResults(true);
            }
            catch
            {
                context.Handler.EndResults(false);
                throw;
            }
        }
コード例 #25
0
ファイル: EqualityHelper.cs プロジェクト: jbunzel/MvcRQ_git
        /// <summary>
        /// Compares two URI Nodes
        /// </summary>
        /// <param name="a">First URI Node</param>
        /// <param name="b">Second URI Node</param>
        /// <returns></returns>
        public static int CompareUris(IUriNode a, IUriNode b)
        {
            if (ReferenceEquals(a, b)) return 0;
            if (a == null)
            {
                if (b == null) return 0;
                return -1;
            }
            else if (b == null)
            {
                return 1;
            }

            return ComparisonHelper.CompareUris(a.Uri, b.Uri);
        }
コード例 #26
0
        public static bool HasVersionUri(this Ontology ontology)
        {
            IUriNode versionIri = ontology.Graph.CreateUriNode(VocabularyHelper.OWL.versionIRI);

            return(ontology.GetNodesViaPredicate(versionIri).UriNodes().Any());
        }
コード例 #27
0
ファイル: BasicTests1.cs プロジェクト: keremdemirer/dotnetrdf
        public void NodesHashCodes()
        {
            Console.WriteLine("Tests that Literal and URI Nodes produce different Hashes");
            Console.WriteLine();

            //Create the Nodes
            Graph        g = new Graph();
            IUriNode     u = g.CreateUriNode(new Uri("http://www.google.com"));
            ILiteralNode l = g.CreateLiteralNode("http://www.google.com/");

            Console.WriteLine("Created a URI and Literal Node both referring to 'http://www.google.com'");
            Console.WriteLine("String form of URI Node is:");
            Console.WriteLine(u.ToString());
            Console.WriteLine("String form of Literal Node is:");
            Console.WriteLine(l.ToString());
            Console.WriteLine("Hash Code of URI Node is " + u.GetHashCode());
            Console.WriteLine("Hash Code of Literal Node is " + l.GetHashCode());
            Console.WriteLine("Hash Codes are Equal? " + u.GetHashCode().Equals(l.GetHashCode()));
            Console.WriteLine("Nodes are equal? " + u.Equals(l));

            Assert.NotEqual(u.GetHashCode(), l.GetHashCode());
            Assert.NotSame(u, l);
            //Assert.NotEqual(u, l);

            //Create some plain and typed literals which may have colliding Hash Codes
            ILiteralNode plain = g.CreateLiteralNode("test^^http://example.org/type");
            ILiteralNode typed = g.CreateLiteralNode("test", new Uri("http://example.org/type"));

            Console.WriteLine();
            Console.WriteLine("Created a Plain and Typed Literal where the String representations are identical");
            Console.WriteLine("Plain Literal String form is:");
            Console.WriteLine(plain.ToString());
            Console.WriteLine("Typed Literal String from is:");
            Console.WriteLine(typed.ToString());
            Console.WriteLine("Hash Code of Plain Literal is " + plain.GetHashCode());
            Console.WriteLine("Hash Code of Typed Literal is " + typed.GetHashCode());
            Console.WriteLine("Hash Codes are Equal? " + plain.GetHashCode().Equals(typed.GetHashCode()));
            Console.WriteLine("Nodes are equal? " + plain.Equals(typed));

            Assert.NotEqual(plain.GetHashCode(), typed.GetHashCode());
            Assert.NotEqual(plain, typed);

            //Create Triples
            IBlankNode b = g.CreateBlankNode();
            IUriNode   type = g.CreateUriNode("rdf:type");
            Triple     t1, t2;

            t1 = new Triple(b, type, u);
            t2 = new Triple(b, type, l);

            Console.WriteLine();
            Console.WriteLine("Created two Triples stating a Blank Node has rdf:type of the URI Nodes created earlier");
            Console.WriteLine("String form of Triple 1 (using URI Node) is:");
            Console.WriteLine(t1.ToString());
            Console.WriteLine("String form of Triple 2 (using Literal Node) is:");
            Console.WriteLine(t2.ToString());
            Console.WriteLine("Hash Code of Triple 1 is " + t1.GetHashCode());
            Console.WriteLine("Hash Code of Triple 2 is " + t2.GetHashCode());
            Console.WriteLine("Hash Codes are Equal? " + t1.GetHashCode().Equals(t2.GetHashCode()));
            Console.WriteLine("Triples are Equal? " + t1.Equals(t2));

            Assert.NotEqual(t1.GetHashCode(), t2.GetHashCode());
            Assert.NotEqual(t1, t2);

            //Create Triples from the earlier Literal Nodes
            t1 = new Triple(b, type, plain);
            t2 = new Triple(b, type, typed);

            Console.WriteLine();
            Console.WriteLine("Created two Triples stating a Blank Node has rdf:type of the Literal Nodes created earlier");
            Console.WriteLine("String form of Triple 1 (using Plain Literal) is:");
            Console.WriteLine(t1.ToString());
            Console.WriteLine("String form of Triple 2 (using Typed Literal) is:");
            Console.WriteLine(t2.ToString());
            Console.WriteLine("Hash Code of Triple 1 is " + t1.GetHashCode());
            Console.WriteLine("Hash Code of Triple 2 is " + t2.GetHashCode());
            Console.WriteLine("Hash Codes are Equal? " + t1.GetHashCode().Equals(t2.GetHashCode()));
            Console.WriteLine("Triples are Equal? " + t1.Equals(t2));

            Assert.NotEqual(t1.GetHashCode(), t2.GetHashCode());
            Assert.NotEqual(t1, t2);
        }
コード例 #28
0
        public static bool IsDeprecated(this OntologyResource resource)
        {
            IUriNode deprecated = resource.Graph.CreateUriNode(OWL.deprecated);

            return(resource.GetNodesViaPredicate(deprecated).LiteralNodes().Any(node => node.Value == "true"));
        }
コード例 #29
0
        private void GenerateTemporaryNamespace(RdfXmlWriterContext context, IUriNode u, ref int nextNamespaceID, List<String> tempNamespaceIDs, XmlDocument doc)
        {
            String uri = u.Uri.ToString();
            String nsUri;
            if (uri.Contains("#"))
            {
                //Create a Hash Namespace Uri
                nsUri = uri.Substring(0, uri.LastIndexOf("#") + 1);
            }
            else
            {
                //Create a Slash Namespace Uri
                nsUri = uri.Substring(0, uri.LastIndexOf("/") + 1);
            }

            //Create a Temporary Namespace ID
            while (context.Graph.NamespaceMap.HasNamespace("ns" + nextNamespaceID))
            {
                nextNamespaceID++;
            }
            String prefix = "ns" + nextNamespaceID;
            nextNamespaceID++;
            context.Graph.NamespaceMap.AddNamespace(prefix, new Uri(nsUri));
            tempNamespaceIDs.Add(prefix);

            //Add to XML Document Element
            XmlAttribute ns = doc.CreateAttribute("xmlns:" + prefix, "http://www.w3.org/2000/xmlns/");
            ns.Value = nsUri;
            doc.DocumentElement.Attributes.Append(ns);

            this.RaiseWarning("Created a Temporary Namespace '" + prefix + "' with URI '" + nsUri + "'");
        }
コード例 #30
0
        private String GenerateUriRef(RdfXmlWriterContext context, IUriNode u, UriRefType type, List<String> tempNamespaceIDs, out UriRefType outType)
        {
            String uriref, qname;

            if (context.Graph.NamespaceMap.ReduceToQName(u.Uri.ToString(), out qname))
            {
                //Reduced to QName OK
                uriref = qname;
                outType = UriRefType.QName;
            }
            else
            {
                //Just use the Uri
                uriref = u.Uri.ToString();
                outType = UriRefType.Uri;
            }

            //Convert to a Uri Ref from a QName if required
            if (outType == UriRefType.QName && type == UriRefType.UriRef)
            {
                if (uriref.Contains(':') && !uriref.StartsWith(":"))
                {
                    String prefix = uriref.Substring(0, uriref.IndexOf(':'));
                    if (context.UseDtd && !tempNamespaceIDs.Contains(prefix))
                    {
                        //Must be using a DTD to use references of this form
                        //Can only use entities for non-temporary Namespaces as Temporary Namespaces won't have Entities defined
                        uriref = "&" + uriref.Replace(':', ';');
                    }
                    else
                    {
                        uriref = context.Graph.NamespaceMap.GetNamespaceUri(prefix).ToString() + uriref.Substring(uriref.IndexOf(':') + 1);
                    }
                }
                else
                {
                    if (context.Graph.NamespaceMap.HasNamespace(String.Empty))
                    {
                        uriref = context.Graph.NamespaceMap.GetNamespaceUri(String.Empty).ToString() + uriref.Substring(1);
                    }
                    else
                    {
                        String baseUri = context.Graph.BaseUri.ToString();
                        if (!baseUri.EndsWith("#")) baseUri += "#";
                        uriref = baseUri + uriref;
                    }
                }
                outType = UriRefType.UriRef;
            }

            return uriref;
        }
コード例 #31
0
        /// <summary>
        /// Takes a <see cref="INode">INode</see> and converts it to a <see cref="IValuedNode">IValuedNode</see> if it is not already an instance that implements the interface.
        /// </summary>
        /// <param name="n">Node.</param>
        /// <returns>Valued Node.</returns>
        public static IValuedNode AsValuedNode(this INode n)
        {
            if (n == null)
            {
                return(null);
            }
            if (n is IValuedNode)
            {
                return((IValuedNode)n);
            }

            switch (n.NodeType)
            {
            case NodeType.Blank:
                IBlankNode b = (IBlankNode)n;
                return(new BlankNode(n.Graph, b.InternalID));

            case NodeType.GraphLiteral:
                IGraphLiteralNode glit = (IGraphLiteralNode)n;
                return(new GraphLiteralNode(n.Graph, glit.SubGraph));

            case NodeType.Literal:
                ILiteralNode lit = (ILiteralNode)n;
                // Decide what kind of valued node to produce based on node datatype
                if (lit.DataType != null)
                {
                    String dt = lit.DataType.AbsoluteUri;
                    switch (dt)
                    {
                    case XmlSpecsHelper.XmlSchemaDataTypeBoolean:
                        bool bVal;
                        if (Boolean.TryParse(lit.Value, out bVal))
                        {
                            return(new BooleanNode(n.Graph, bVal));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeByte:
                        // xsd:byte actually maps to SignedByte in .Net
                        sbyte sbVal;
                        if (sbyte.TryParse(lit.Value, out sbVal))
                        {
                            return(new SignedByteNode(n.Graph, sbVal, lit.Value));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeDate:
                        DateTime date;
                        if (DateTime.TryParse(lit.Value, null, DateTimeStyles.AdjustToUniversal, out date))
                        {
                            return(new DateNode(n.Graph, date, lit.Value));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeDateTime:
                        DateTime dateTime;
                        if (DateTime.TryParse(lit.Value, null, DateTimeStyles.AdjustToUniversal, out dateTime))
                        {
                            return(new DateTimeNode(n.Graph, dateTime, lit.Value));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeDayTimeDuration:
                    case XmlSpecsHelper.XmlSchemaDataTypeDuration:
                        TimeSpan timeSpan;
                        try
                        {
                            timeSpan = XmlConvert.ToTimeSpan(lit.Value);
                            return(new TimeSpanNode(n.Graph, timeSpan, lit.Value, lit.DataType));
                        }
                        catch
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeDecimal:
                        Decimal dec;
                        if (Decimal.TryParse(lit.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out dec))
                        {
                            return(new DecimalNode(n.Graph, dec, lit.Value));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeDouble:
                        Double dbl;
                        if (Double.TryParse(lit.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out dbl))
                        {
                            return(new DoubleNode(n.Graph, dbl, lit.Value));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeFloat:
                        Single flt;
                        if (Single.TryParse(lit.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out flt))
                        {
                            return(new FloatNode(n.Graph, flt, lit.Value));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeInt:
                    case XmlSpecsHelper.XmlSchemaDataTypeInteger:
                    case XmlSpecsHelper.XmlSchemaDataTypeLong:
                    case XmlSpecsHelper.XmlSchemaDataTypeShort:
                        long lng;
                        if (Int64.TryParse(lit.Value, out lng))
                        {
                            return(new LongNode(n.Graph, lng, lit.Value, lit.DataType));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeNegativeInteger:
                    case XmlSpecsHelper.XmlSchemaDataTypeNonPositiveInteger:
                        // Must be below zero
                        long neglng;
                        if (Int64.TryParse(lit.Value, out neglng) && neglng < 0)
                        {
                            return(new LongNode(n.Graph, neglng, lit.Value, lit.DataType));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeNonNegativeInteger:
                    case XmlSpecsHelper.XmlSchemaDataTypePositiveInteger:
                        // Must be above zero
                        long poslng;
                        if (Int64.TryParse(lit.Value, out poslng) && poslng >= 0)
                        {
                            return(new LongNode(n.Graph, poslng, lit.Value, lit.DataType));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeUnsignedByte:
                        // xsd:unsignedByte actually maps to Byte in .Net
                        byte byVal;
                        if (byte.TryParse(lit.Value, out byVal))
                        {
                            return(new ByteNode(n.Graph, byVal, lit.Value));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    case XmlSpecsHelper.XmlSchemaDataTypeUnsignedInt:
                    case XmlSpecsHelper.XmlSchemaDataTypeUnsignedLong:
                    case XmlSpecsHelper.XmlSchemaDataTypeUnsignedShort:
                        // Must be unsigned
                        ulong ulng;
                        if (UInt64.TryParse(lit.Value, out ulng))
                        {
                            return(new UnsignedLongNode(n.Graph, ulng, lit.Value, lit.DataType));
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }

                    default:
                        if (SparqlSpecsHelper.IntegerDataTypes.Contains(dt))
                        {
                            long l;
                            if (Int64.TryParse(lit.Value, out l))
                            {
                                return(new LongNode(n.Graph, l, lit.Value, lit.DataType));
                            }
                            else
                            {
                                return(new StringNode(n.Graph, lit.Value, lit.DataType));
                            }
                        }
                        else
                        {
                            return(new StringNode(n.Graph, lit.Value, lit.DataType));
                        }
                    }
                }
                else if (!lit.Language.Equals(String.Empty))
                {
                    return(new StringNode(n.Graph, lit.Value, lit.Language));
                }
                else
                {
                    return(new StringNode(n.Graph, lit.Value));
                }

            case NodeType.Uri:
                IUriNode u = (IUriNode)n;
                return(new UriNode(n.Graph, u.Uri));

            case NodeType.Variable:
                IVariableNode v = (IVariableNode)n;
                return(new VariableNode(n.Graph, v.VariableName));

            default:
                throw new RdfQueryException("Cannot create a valued node for an unknown node type");
            }
        }
コード例 #32
0
 /// <summary>
 /// Formats URIs for CSV output
 /// </summary>
 /// <param name="u">URI</param>
 /// <param name="segment">Triple Segment</param>
 /// <returns></returns>
 protected override string FormatUriNode(IUriNode u, TripleSegment?segment)
 {
     return(this.FormatUri(u.Uri));
 }
コード例 #33
0
ファイル: RDFXMLParser.cs プロジェクト: jmahmud/RDFer
 /// <summary>
 /// Reifies a Triple
 /// </summary>
 /// <param name="context">Parser Context</param>
 /// <param name="uriref">Uri Reference for the Reified Triple</param>
 /// <param name="subj">Subject of the Triple</param>
 /// <param name="pred">Predicate of the Triple</param>
 /// <param name="obj">Object of the Triple</param>
 private void Reify(RdfXmlParserContext context, IUriNode uriref, INode subj, INode pred, INode obj)
 {
     if (!context.Handler.HandleTriple(new Triple(uriref, context.Handler.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfSubject)), subj))) ParserHelper.Stop();
     if (!context.Handler.HandleTriple(new Triple(uriref, context.Handler.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfPredicate)), pred))) ParserHelper.Stop();
     if (!context.Handler.HandleTriple(new Triple(uriref, context.Handler.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfObject)), obj))) ParserHelper.Stop();
     if (!context.Handler.HandleTriple(new Triple(uriref, context.Handler.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfType)), context.Handler.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfStatement))))) ParserHelper.Stop();
 }
コード例 #34
0
ファイル: LeviathanTests.cs プロジェクト: yuryk53/dotnetrdf
        public void SparqlMultisetLeftJoin()
        {
            //Create a load of Nodes to use in the tests
            Graph g = new Graph();

            g.NamespaceMap.AddNamespace(String.Empty, new Uri("http://example.org"));
            IUriNode     s1        = g.CreateUriNode(":s1");
            IUriNode     s2        = g.CreateUriNode(":s2");
            IUriNode     p1        = g.CreateUriNode(":p1");
            IUriNode     p2        = g.CreateUriNode(":p2");
            IUriNode     rdfsLabel = g.CreateUriNode("rdfs:label");
            ILiteralNode o1        = g.CreateLiteralNode("Some Text");
            ILiteralNode o2        = g.CreateLiteralNode("1", new Uri(XmlSpecsHelper.XmlSchemaDataTypeInteger));

            //Create an ID and Null Multiset
            IdentityMultiset id      = new IdentityMultiset();
            NullMultiset     nullset = new NullMultiset();

            //Create and Populate a Multiset
            Multiset m = new Multiset();
            Set      s = new Set();

            s.Add("s", s1);
            s.Add("p", p1);
            s.Add("o", o1);
            m.Add(s);
            s = new Set();
            s.Add("s", s2);
            s.Add("p", p2);
            s.Add("o", o2);
            m.Add(s);

            //Create and Populate another Multiset
            Multiset n = new Multiset();

            s = new Set();
            s.Add("s", s1);
            s.Add("label", o1);
            n.Add(s);

            //Create and Populate another Multiset
            Multiset d = new Multiset();

            s = new Set();
            s.Add("s1", s1);
            s.Add("p1", p1);
            s.Add("o1", o1);
            d.Add(s);
            s = new Set();
            s.Add("s1", s2);
            s.Add("p1", p2);
            s.Add("o1", o2);
            d.Add(s);

            //Show the Sets
            Console.WriteLine("LHS");
            foreach (ISet set in m.Sets)
            {
                Console.WriteLine(set.ToString());
            }
            Console.WriteLine();
            Console.WriteLine("RHS");
            foreach (ISet set in n.Sets)
            {
                Console.WriteLine(set.ToString());
            }
            Console.WriteLine();
            Console.WriteLine("D");
            foreach (ISet set in d.Sets)
            {
                Console.WriteLine(set.ToString());
            }
            Console.WriteLine();

            //Try a Join to Identity
            Console.WriteLine("Join ID-LHS");
            BaseMultiset join = id.Join(m);

            foreach (ISet set in join.Sets)
            {
                Console.WriteLine(set.ToString());
            }
            Console.WriteLine();

            //Try a Join to Identity
            Console.WriteLine("Join LHS-ID");
            join = m.Join(id);
            foreach (ISet set in join.Sets)
            {
                Console.WriteLine(set.ToString());
            }
            Console.WriteLine();

            //Try a Join to Null
            Console.WriteLine("Join NULL-LHS");
            join = nullset.Join(m);
            foreach (ISet set in join.Sets)
            {
                Console.WriteLine(set.ToString());
            }
            Console.WriteLine();

            //Try a Join to Null
            Console.WriteLine("Join LHS-NULL");
            join = m.Join(nullset);
            foreach (ISet set in join.Sets)
            {
                Console.WriteLine(set.ToString());
            }
            Console.WriteLine();

            //Try a LeftJoin
            Console.WriteLine("LeftJoin NULL-LHS");
            BaseMultiset leftjoin = nullset.LeftJoin(m, new ConstantTerm(new BooleanNode(null, true)));

            foreach (ISet set in leftjoin.Sets)
            {
                Console.WriteLine(set.ToString());
            }
            Console.WriteLine();

            //Try a LeftJoin
            Console.WriteLine("LeftJoin LHS-NULL");
            leftjoin = m.LeftJoin(nullset, new ConstantTerm(new BooleanNode(null, true)));
            foreach (ISet set in leftjoin.Sets)
            {
                Console.WriteLine(set.ToString());
            }
            Console.WriteLine();

            //Try a Join
            Console.WriteLine("Join LHS-RHS");
            join = m.Join(n);
            foreach (ISet set in join.Sets)
            {
                Console.WriteLine(set.ToString());
            }
            Console.WriteLine();

            //Try a LeftOuterJoin
            Console.WriteLine("LeftJoin LHS-RHS");
            leftjoin = m.LeftJoin(n, new ConstantTerm(new BooleanNode(null, true)));
            foreach (ISet set in leftjoin.Sets)
            {
                Console.WriteLine(set.ToString());
            }
            Console.WriteLine();

            //Try a Produce
            Console.WriteLine("Product LHS-RHS");
            BaseMultiset product = m.Product(n);

            foreach (ISet set in product.Sets)
            {
                Console.WriteLine(set.ToString());
            }
            Console.WriteLine();

            //Try a Join to Self
            Console.WriteLine("Product LHS-D");
            product = m.Product(d);
            foreach (ISet set in product.Sets)
            {
                Console.WriteLine(set.ToString());
            }
            Console.WriteLine();

            //Try a Union
            Console.WriteLine("Union LHS-RHS");
            BaseMultiset union = m.Union(n);

            foreach (ISet set in union.Sets)
            {
                Console.WriteLine(set.ToString());
            }
            Console.WriteLine();
        }
コード例 #35
0
ファイル: BaseNode.cs プロジェクト: jbunzel/MvcRQ_git
 /// <summary>
 /// Nodes must implement a CompareTo method to allow them to be Sorted
 /// </summary>
 /// <param name="other">Node to compare self to</param>
 /// <returns></returns>
 /// <remarks>
 /// Implementations should use the SPARQL Term Sort Order for ordering nodes (as opposed to value sort order).  Standard implementations of Node type specific comparisons can be found in <see cref="ComparisonHelper">ComparisonHelper</see>
 /// </remarks>
 public abstract int CompareTo(IUriNode other);
コード例 #36
0
ファイル: LeviathanTests.cs プロジェクト: yuryk53/dotnetrdf
        public void SparqlStreamingBgpSelectEvaluation()
        {
            //Get the Data we want to query
            TripleStore store = new TripleStore();
            Graph       g     = new Graph();

            FileLoader.Load(g, "resources\\InferenceTest.ttl");
            store.Add(g);
            //g = new Graph();
            //g.LoadFromFile("noise.ttl");
            //store.Add(g);

            Console.WriteLine(store.Triples.Count() + " Triples in Store");

            //Create the Triple Pattern we want to query with
            IUriNode fordFiesta = g.CreateUriNode(new Uri("http://example.org/vehicles/FordFiesta"));
            IUriNode rdfType    = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfType));
            IUriNode rdfsLabel  = g.CreateUriNode(new Uri(NamespaceMapper.RDFS + "label"));
            IUriNode speed      = g.CreateUriNode(new Uri("http://example.org/vehicles/Speed"));
            IUriNode carClass   = g.CreateUriNode(new Uri("http://example.org/vehicles/Car"));

            TriplePattern allTriples            = new TriplePattern(new VariablePattern("?s"), new VariablePattern("?p"), new VariablePattern("?o"));
            TriplePattern allTriples2           = new TriplePattern(new VariablePattern("?x"), new VariablePattern("?y"), new VariablePattern("?z"));
            TriplePattern tp1                   = new TriplePattern(new VariablePattern("?s"), new NodeMatchPattern(rdfType), new NodeMatchPattern(carClass));
            TriplePattern tp2                   = new TriplePattern(new VariablePattern("?s"), new NodeMatchPattern(speed), new VariablePattern("?speed"));
            TriplePattern tp3                   = new TriplePattern(new VariablePattern("?s"), new NodeMatchPattern(rdfsLabel), new VariablePattern("?label"));
            TriplePattern novars                = new TriplePattern(new NodeMatchPattern(fordFiesta), new NodeMatchPattern(rdfType), new NodeMatchPattern(carClass));
            TriplePattern novars2               = new TriplePattern(new NodeMatchPattern(fordFiesta), new NodeMatchPattern(rdfsLabel), new NodeMatchPattern(carClass));
            FilterPattern blankSubject          = new FilterPattern(new UnaryExpressionFilter(new IsBlankFunction(new VariableTerm("?s"))));
            List <List <ITriplePattern> > tests = new List <List <ITriplePattern> >()
            {
                new List <ITriplePattern>()
                {
                },
                new List <ITriplePattern>()
                {
                    allTriples
                },
                new List <ITriplePattern>()
                {
                    allTriples, allTriples2
                },
                new List <ITriplePattern>()
                {
                    tp1
                },
                new List <ITriplePattern>()
                {
                    tp1, tp2
                },
                new List <ITriplePattern>()
                {
                    tp1, tp3
                },
                new List <ITriplePattern>()
                {
                    novars
                },
                new List <ITriplePattern>()
                {
                    novars, tp1
                },
                new List <ITriplePattern>()
                {
                    novars, tp1, tp2
                },
                new List <ITriplePattern>()
                {
                    novars2
                },
                new List <ITriplePattern>()
                {
                    tp1, blankSubject
                }
            };

            foreach (List <ITriplePattern> tps in tests)
            {
                Console.WriteLine(tps.Count + " Triple Patterns in the Query");
                foreach (ITriplePattern tp in tps)
                {
                    Console.WriteLine(tp.ToString());
                }
                Console.WriteLine();

                ISparqlAlgebra select          = new Bgp(tps);
                ISparqlAlgebra selectOptimised = new LazyBgp(tps, 10);

                //Evaluate with timings
                Stopwatch timer = new Stopwatch();
                TimeSpan  unopt, opt;
                timer.Start();
                BaseMultiset results1 = select.Evaluate(new SparqlEvaluationContext(null, new InMemoryDataset(store)));
                timer.Stop();
                unopt = timer.Elapsed;
                timer.Reset();
                timer.Start();
                BaseMultiset results2 = selectOptimised.Evaluate(new SparqlEvaluationContext(null, new InMemoryDataset(store)));
                timer.Stop();
                opt = timer.Elapsed;

                Console.WriteLine("SELECT = " + results1.GetType().ToString() + " (" + results1.Count + " Results) in " + unopt.ToString());
                Console.WriteLine("SELECT Optimised = " + results2.GetType().ToString() + " (" + results2.Count + " Results) in " + opt.ToString());

                Console.WriteLine();
                Console.WriteLine("Optimised Results");
                foreach (ISet s in results2.Sets)
                {
                    Console.WriteLine(s.ToString());
                }

                Assert.IsTrue(results1.Count >= results2.Count, "Optimised Select should have produced as many/fewer results than Unoptimised Select");

                Console.WriteLine();
            }
        }
コード例 #37
0
 public int CompareTo(IUriNode other)
 {
     return(_source.CompareTo(other));
 }
コード例 #38
0
ファイル: HtmlSchemaWriter.cs プロジェクト: yuryk53/dotnetrdf
        /// <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 (!this.Stylesheet.Equals(String.Empty))
            {
                context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Href, this.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();
#if !NO_WEB
            context.HtmlWriter.WriteLine();
#endif

            //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();
#if !NO_WEB
            context.HtmlWriter.WriteLine();
#endif

            //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();
#if !NO_WEB
                                    context.HtmlWriter.WriteLine();
#endif
                                }
                            }

                            //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, this.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();
#if !NO_WEB
                                context.HtmlWriter.WriteLine();
#endif
                            }

                            //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();

#if !NO_WEB
                                    context.HtmlWriter.WriteLine();
#endif

                                    //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, this.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();
#if !NO_WEB
                                    context.HtmlWriter.WriteLine();
#endif
                                    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();
#if !NO_WEB
                                    context.HtmlWriter.WriteLine();
#endif

                                    //Turtle/N3 Syntax
                                    context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H5);
                                    context.HtmlWriter.WriteEncodedText("Turtle/N3 Syntax");
                                    context.HtmlWriter.RenderEndTag();
#if !NO_WEB
                                    context.HtmlWriter.WriteLine();
#endif
                                    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();
#if !NO_WEB
                                    context.HtmlWriter.WriteLine();
#endif

                                    //SPARQL Syntax
                                    context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.H5);
                                    context.HtmlWriter.WriteEncodedText("SPARQL Syntax");
                                    context.HtmlWriter.RenderEndTag();
#if !NO_WEB
                                    context.HtmlWriter.WriteLine();
#endif
                                    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();
#if !NO_WEB
                                    context.HtmlWriter.WriteLine();
#endif
                                }
                            }
                        }
                    }
                    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();
#if !NO_WEB
            context.HtmlWriter.WriteLine();
#endif

            context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P);
            context.HtmlWriter.WriteEncodedText("This Schema defines the following classes:");
            context.HtmlWriter.RenderEndTag();
#if !NO_WEB
            context.HtmlWriter.WriteLine();
#endif
            context.HtmlWriter.AddStyleAttribute("width", "90%");
            context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, this.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, this.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();
#if !NO_WEB
            context.HtmlWriter.WriteLine();
#endif

            context.HtmlWriter.RenderBeginTag(HtmlTextWriterTag.P);
            context.HtmlWriter.WriteEncodedText("This Schema defines the following properties:");
            context.HtmlWriter.RenderEndTag();
#if !NO_WEB
            context.HtmlWriter.WriteLine();
#endif
            context.HtmlWriter.AddStyleAttribute("width", "90%");
            context.HtmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, this.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, this.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();
#if !NO_WEB
            context.HtmlWriter.WriteLine();
#endif

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

            //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, this.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
                            {
#if !SILVERLIGHT
                                context.HtmlWriter.WriteEncodedText(temp.Segments.Last());
#else
                                context.HtmlWriter.WriteEncodedText(temp.Segments().Last());
#endif
                            }
                        }
                        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();
#if !NO_WEB
                        context.HtmlWriter.WriteLine();
#endif
                        //Output further information about the class
                        IEnumerable <Triple> ts;

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

                        //Output Properties which have this as domain/range
                        ts = context.Graph.GetTriplesWithPredicateObject(rdfsDomain, r["class"]);
                        this.GenerateCaptionedInformation(context, "Properties Include", ts, t => t.Subject);
                        ts = context.Graph.GetTriplesWithPredicateObject(rdfsRange, r["class"]);
                        this.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"]));
                        this.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"]));
                        this.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();
#if !NO_WEB
                        context.HtmlWriter.WriteLine();
#endif
                    }
                }
                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();
#if !NO_WEB
            context.HtmlWriter.WriteLine();
#endif

            //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, this.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
                            {
#if !SILVERLIGHT
                                context.HtmlWriter.WriteEncodedText(temp.Segments.Last());
#else
                                context.HtmlWriter.WriteEncodedText(temp.Segments().Last());
#endif
                            }
                        }
                        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();
#if !NO_WEB
                        context.HtmlWriter.WriteLine();
#endif
                        //Output further information about the property
                        IEnumerable <Triple> ts;

                        //Output any Subproperties
                        ts = context.Graph.GetTriplesWithSubjectPredicate(rdfsSubPropertyOf, r["property"]);
                        this.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"]);
                        this.GenerateCaptionedInformation(context, "Has Domain", context.Graph.ExecuteQuery(getPropertyDomains) as SparqlResultSet, "domain");
                        getPropertyRanges.SetParameter("property", r["property"]);
                        this.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"]));
                        this.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"]));
                        this.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();
#if !NO_WEB
                        context.HtmlWriter.WriteLine();
#endif
                    }
                }
                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
        }
コード例 #39
0
 public override int CompareTo(IUriNode other)
 {
     return Uri.ToString().CompareTo(other.Uri.ToString());
 }
コード例 #40
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", 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);
        }
コード例 #41
0
 /// <summary>
 /// Creates a new Virtual URI Node
 /// </summary>
 /// <param name="g">Graph the Node belongs to</param>
 /// <param name="id">Virtual ID</param>
 /// <param name="provider">Virtual RDF Provider</param>
 /// <param name="value">Materialised Value</param>
 public SimpleVirtualUriNode(IGraph g, int id, IVirtualRdfProvider <int, int> provider, IUriNode value)
     : base(g, id, provider, value)
 {
 }
コード例 #42
0
        /// <summary>
        /// Used to extract the patterns that make up property functions.
        /// </summary>
        /// <param name="patterns">Triple Patterns.</param>
        /// <param name="localFactories">Locally scoped factories.</param>
        /// <returns></returns>
        public static List <IPropertyFunctionPattern> ExtractPatterns(IEnumerable <ITriplePattern> patterns, IEnumerable <IPropertyFunctionFactory> localFactories)
        {
            // Do a first pass which simply looks to find any 'magic' properties
            Dictionary <PatternItem, PropertyFunctionInfo> funcInfo = new Dictionary <PatternItem, PropertyFunctionInfo>();
            List <IMatchTriplePattern> ps = patterns.OfType <IMatchTriplePattern>().ToList();

            if (ps.Count == 0)
            {
                return(new List <IPropertyFunctionPattern>());
            }
            foreach (IMatchTriplePattern tp in ps)
            {
                NodeMatchPattern predItem = tp.Predicate as NodeMatchPattern;
                if (predItem == null)
                {
                    continue;
                }
                IUriNode predNode = predItem.Node as IUriNode;
                if (predNode == null)
                {
                    continue;
                }
                if (PropertyFunctionFactory.IsPropertyFunction(predNode.Uri, localFactories))
                {
                    PropertyFunctionInfo info = new PropertyFunctionInfo(predNode.Uri);
                    info.Patterns.Add(tp);
                    funcInfo.Add(tp.Subject, info);
                }
            }
            // Remove any Patterns we found from the original patterns
            foreach (PropertyFunctionInfo info in funcInfo.Values)
            {
                info.Patterns.ForEach(tp => ps.Remove(tp));
            }

            if (funcInfo.Count == 0)
            {
                return(new List <IPropertyFunctionPattern>());
            }

            // Now for each 'magic' property we found do a further search to see if we are using
            // the collection forms to provide extended arguments
            foreach (PatternItem key in funcInfo.Keys)
            {
                if (key.VariableName != null && key.VariableName.StartsWith("_:"))
                {
                    // If LHS is a blank node may be collection form
                    int count = funcInfo[key].Patterns.Count;
                    ExtractRelatedPatterns(key, key, ps, funcInfo, funcInfo[key].SubjectArgs);
                    if (funcInfo[key].Patterns.Count == count)
                    {
                        // If no further patterns found just single LHS argument
                        funcInfo[key].SubjectArgs.Add(key);
                    }
                }
                else
                {
                    // Otherwise key is the only LHS argument
                    funcInfo[key].SubjectArgs.Add(key);
                }
                PatternItem searchKey = funcInfo[key].Patterns.First().Object;
                if (searchKey.VariableName != null && searchKey.VariableName.StartsWith("_:"))
                {
                    // If RHS is a blank node may be collection form
                    int count = funcInfo[key].Patterns.Count;
                    ExtractRelatedPatterns(key, searchKey, ps, funcInfo, funcInfo[key].ObjectArgs);
                    if (funcInfo[key].Patterns.Count == count)
                    {
                        // If no further patterns found just single RHS argument
                        funcInfo[key].ObjectArgs.Add(searchKey);
                    }
                }
                else
                {
                    // Otherwise single RHS argument
                    funcInfo[key].ObjectArgs.Add(searchKey);
                }
            }

            // Now try to create actual property functions
            List <IPropertyFunctionPattern> propFunctions = new List <IPropertyFunctionPattern>();

            foreach (PatternItem key in funcInfo.Keys)
            {
                IPropertyFunctionPattern propFunc;
                if (PropertyFunctionFactory.TryCreatePropertyFunction(funcInfo[key], localFactories, out propFunc))
                {
                    propFunctions.Add(propFunc);
                }
            }
            return(propFunctions);
        }
コード例 #43
0
        /// <summary>
        /// Copies a Node so it can be used in another Graph since by default Triples cannot contain Nodes from more than one Graph.
        /// </summary>
        /// <param name="original">Node to Copy.</param>
        /// <param name="target">Graph to Copy into.</param>
        /// <returns></returns>
        /// <remarks>
        /// <para>
        /// <strong>Warning:</strong> Copying Blank Nodes may lead to unforseen circumstances since no remapping of IDs between Graphs is done.
        /// </para>
        /// </remarks>
        public static INode CopyNode(INode original, IGraph target)
        {
            // No need to copy if it's already in the relevant Graph
            if (ReferenceEquals(original.Graph, target))
            {
                return(original);
            }

            // if a node can copy itself then let it do it
            var selfcopyable_original = original as Storage.Virtualisation.ICanCopy;

            if (selfcopyable_original != null)
            {
                return(selfcopyable_original.CopyNode(target));
            }

            // if it doesn't, copy it's values:

            if (original.NodeType == NodeType.Uri)
            {
                IUriNode u  = (IUriNode)original;
                IUriNode u2 = new UriNode(target, u.Uri);

                return(u2);
            }
            else if (original.NodeType == NodeType.Literal)
            {
                ILiteralNode l = (ILiteralNode)original;
                ILiteralNode l2;
                if (l.Language.Equals(String.Empty))
                {
                    if (!(l.DataType == null))
                    {
                        l2 = new LiteralNode(target, l.Value, l.DataType);
                    }
                    else
                    {
                        l2 = new LiteralNode(target, l.Value);
                    }
                }
                else
                {
                    l2 = new LiteralNode(target, l.Value, l.Language);
                }

                return(l2);
            }
            else if (original.NodeType == NodeType.Blank)
            {
                IBlankNode b = (IBlankNode)original;
                IBlankNode b2;

                b2 = new BlankNode(target, b.InternalID);
                return(b2);
            }
            else if (original.NodeType == NodeType.Variable)
            {
                IVariableNode v = (IVariableNode)original;
                return(new VariableNode(target, v.VariableName));
            }
            else
            {
                throw new RdfException("Unable to Copy '" + original.GetType().ToString() + "' Nodes between Graphs");
            }
        }
コード例 #44
0
ファイル: BaseNode.cs プロジェクト: jbunzel/MvcRQ_git
 /// <summary>
 /// Nodes must implement an Equals method so we can do type specific equality
 /// </summary>
 /// <param name="other">Node to check for equality</param>
 /// <returns></returns>
 /// <remarks>
 /// Nodes implementations are also required to implement an override of the non-generic Equals method.  Standard implementations of some equality comparisons can be found in <see cref="EqualityHelper">EqualityHelper</see>
 /// </remarks>
 public abstract bool Equals(IUriNode other);
コード例 #45
0
 public MyHandler(IGraph g)
     : base(g)
 {
     _rdfsSubClassOf = g.CreateUriNode(UriFactory.Create("http://www.w3.org/2000/01/rdf-schema#subClassOf"));
     _rdfsLabel      = g.CreateUriNode(UriFactory.Create("http://www.w3.org/2000/01/rdf-schema#label"));
 }
コード例 #46
0
        /// <summary>
        /// Formats a URI Node using QName compression if possible
        /// </summary>
        /// <param name="u">URI</param>
        /// <param name="segment">Triple Segment</param>
        /// <returns></returns>
        protected override string FormatUriNode(IUriNode u, TripleSegment? segment)
        {
            StringBuilder output = new StringBuilder();
            String qname;

            if (this._allowAKeyword && segment == TripleSegment.Predicate && u.Uri.ToString().Equals(RdfSpecsHelper.RdfType))
            {
                output.Append('a');
            }
            else if (this._qnameMapper.ReduceToQName(u.Uri.ToString(), out qname))
            {
                if (this.IsValidQName(qname))
                {
                    output.Append(qname);
                }
                else
                {
                    output.Append('<');
                    output.Append(this.FormatUri(u.Uri));
                    output.Append('>');
                }
            }
            else
            {
                output.Append('<');
                output.Append(this.FormatUri(u.Uri));
                output.Append('>');
            }
            return output.ToString();
        }
コード例 #47
0
        private void GenerateTemporaryNamespace(RdfXmlWriterContext context, IUriNode u, out String tempPrefix, out String tempUri)
        {
            String uri = u.Uri.ToString();
            String nsUri;
            if (uri.Contains("#"))
            {
                //Create a Hash Namespace Uri
                nsUri = uri.Substring(0, uri.LastIndexOf("#") + 1);
            }
            else
            {
                //Create a Slash Namespace Uri
                nsUri = uri.Substring(0, uri.LastIndexOf("/") + 1);
            }

            //Create a Temporary Namespace ID
            //Can't use an ID if already in the Namespace Map either at top level (nesting == 0) or at the current nesting
            while (context.NamespaceMap.HasNamespace("ns" + context.NextNamespaceID) && (context.NamespaceMap.GetNestingLevel("ns" + context.NextNamespaceID) == 0 || context.NamespaceMap.GetNestingLevel("ns" + context.NextNamespaceID) == context.NamespaceMap.NestingLevel))
            {
                context.NextNamespaceID++;
            }
            String prefix = "ns" + context.NextNamespaceID;
            context.NextNamespaceID++;
            context.NamespaceMap.AddNamespace(prefix, new Uri(nsUri));

            tempPrefix = prefix;
            tempUri = nsUri;

            this.RaiseWarning("Created a Temporary Namespace '" + prefix + "' with URI '" + nsUri + "'");
        }
コード例 #48
0
 public override void ApplyToGraph(IGraph graph, IUriNode parent)
 {
     graph.Assert(parent, graph.CreateUriNode(new Uri(CantonConstants.CantonSchema + "origin")), graph.CreateLiteralNode(_origin));
     graph.Assert(parent, graph.CreateUriNode(new Uri(CantonConstants.CantonSchema + "commitId")), graph.CreateLiteralNode("" + _commitId));
 }
コード例 #49
0
        /// <summary>
        /// Populates the settings from an existing serialized configuration
        /// </summary>
        /// <param name="g">Graph</param>
        /// <param name="objNode">Object Node</param>
        public virtual void PopulateFrom(IGraph g, INode objNode)
        {
            foreach (PropertyInfo property in this._properties.Keys)
            {
                ConnectionAttribute attr = this._properties[property];

                if (!String.IsNullOrEmpty(attr.PopulateFrom))
                {
                    INode n = objNode;

                    if (!String.IsNullOrEmpty(attr.PopulateVia))
                    {
                        n = ConfigurationLoader.GetConfigurationNode(g, n, g.CreateUriNode(UriFactory.Create(attr.PopulateVia)));
                        if (n == null)
                        {
                            continue;
                        }
                    }

                    switch (attr.Type)
                    {
                    case ConnectionSettingType.Boolean:
                        bool b = ConfigurationLoader.GetConfigurationBoolean(g, n, g.CreateUriNode(UriFactory.Create(attr.PopulateFrom)), (bool)property.GetValue(this, null));
                        property.SetValue(this, b, null);
                        break;

                    case ConnectionSettingType.File:
                    case ConnectionSettingType.Password:
                    case ConnectionSettingType.String:
                        String s = ConfigurationLoader.GetConfigurationString(g, n, g.CreateUriNode(UriFactory.Create(attr.PopulateFrom)));
                        if (!String.IsNullOrEmpty(s))
                        {
                            property.SetValue(this, s, null);
                        }
                        else
                        {
                            //May be a URI as the object
                            IUriNode u = ConfigurationLoader.GetConfigurationNode(g, n, g.CreateUriNode(UriFactory.Create(attr.PopulateFrom))) as IUriNode;
                            if (u != null)
                            {
                                property.SetValue(this, u.Uri.AbsoluteUri, null);
                            }
                        }
                        break;

                    case ConnectionSettingType.Integer:
                        int i = ConfigurationLoader.GetConfigurationInt32(g, n, g.CreateUriNode(UriFactory.Create(attr.PopulateFrom)), (int)property.GetValue(this, null));
                        property.SetValue(this, i, null);
                        break;

                    case ConnectionSettingType.Enum:
                        String enumStr = ConfigurationLoader.GetConfigurationString(g, n, g.CreateUriNode(UriFactory.Create(attr.PopulateFrom)));
                        if (!String.IsNullOrEmpty(enumStr))
                        {
                            try
                            {
                                Object val = Enum.Parse(property.GetValue(this, null).GetType(), enumStr, false);
                                property.SetValue(this, val, null);
                            }
                            catch
                            {
                                //Ignore errors
                            }
                        }
                        break;
                    }
                }
            }
        }
コード例 #50
0
 /// <summary>
 /// Creates a new SubPropertySelector for the given Graph with the given Target Property
 /// </summary>
 /// <param name="g">Graph selection will occur in</param>
 /// <param name="targetProperty">Property you wish to select upon</param>
 public SubPropertySelector(IGraph g, IUriNode targetProperty)
 {
     this._targetproperty = targetProperty;
     this._subpropof      = g.CreateUriNode(UriFactory.Create(NamespaceMapper.RDFS + "subPropertyOf"));
 }
コード例 #51
0
 /// <summary>
 /// Nodes must implement an Equals method so we can do type specific equality
 /// </summary>
 /// <param name="other">Node to check for equality</param>
 /// <returns></returns>
 /// <remarks>
 /// Nodes implementations are also required to implement an override of the non-generic Equals method.  Standard implementations of some equality comparisons can be found in <see cref="EqualityHelper">EqualityHelper</see>
 /// </remarks>
 public abstract bool Equals(IUriNode other);
コード例 #52
0
 /// <summary>
 /// Creates a new ExactClassSelector for the given Graph with the given Target Class
 /// </summary>
 /// <param name="g"></param>
 /// <param name="targetClass"></param>
 public ExactClassSelector(IGraph g, IUriNode targetClass)
 {
     this._targetclass = targetClass;
     this._type        = g.CreateUriNode(UriFactory.Create(NamespaceMapper.RDF + "type"));
 }
コード例 #53
0
        public void WritingFormattingTriples()
        {
            try
            {
                //Create the Graph and define an additional namespace
                Graph g = new Graph();
                g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org/"));

                //Create URIs used for datatypes
                Uri dtInt        = new Uri(XmlSpecsHelper.XmlSchemaDataTypeInteger);
                Uri dtFloat      = new Uri(XmlSpecsHelper.XmlSchemaDataTypeFloat);
                Uri dtDouble     = new Uri(XmlSpecsHelper.XmlSchemaDataTypeDouble);
                Uri dtDecimal    = new Uri(XmlSpecsHelper.XmlSchemaDataTypeDecimal);
                Uri dtBoolean    = new Uri(XmlSpecsHelper.XmlSchemaDataTypeBoolean);
                Uri dtUnknown    = new Uri("http://example.org/unknownType");
                Uri dtXmlLiteral = new Uri(RdfSpecsHelper.RdfXmlLiteral);

                //Create Nodes used for our test Triples
                IBlankNode   subjBnode     = g.CreateBlankNode();
                IUriNode     subjUri       = g.CreateUriNode(new Uri("http://example.org/subject"));
                IUriNode     subjUri2      = g.CreateUriNode(new Uri("http://example.org/123"));
                IUriNode     predUri       = g.CreateUriNode(new Uri("http://example.org/vocab#predicate"));
                IUriNode     predType      = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfType));
                IBlankNode   objBnode      = g.CreateBlankNode();
                IUriNode     objUri        = g.CreateUriNode(new Uri("http://example.org/object"));
                ILiteralNode objString     = g.CreateLiteralNode("This is a literal");
                ILiteralNode objStringLang = g.CreateLiteralNode("This is a literal with a language specifier", "en");
                ILiteralNode objInt        = g.CreateLiteralNode("123", dtInt);
                ILiteralNode objFloat      = g.CreateLiteralNode("12.3e4", dtFloat);
                ILiteralNode objDouble     = g.CreateLiteralNode("12.3e4", dtDouble);
                ILiteralNode objDecimal    = g.CreateLiteralNode("12.3", dtDecimal);
                ILiteralNode objTrue       = g.CreateLiteralNode("true", dtBoolean);
                ILiteralNode objFalse      = g.CreateLiteralNode("false", dtBoolean);
                ILiteralNode objUnknown    = g.CreateLiteralNode("This is a literal with an unknown type", dtUnknown);
                ILiteralNode objXmlLiteral = g.CreateLiteralNode("<strong>XML Literal</strong>", dtXmlLiteral);

                List <ITripleFormatter> formatters = new List <ITripleFormatter>()
                {
                    new NTriplesFormatter(NTriplesSyntax.Original),
                    new NTriplesFormatter(NTriplesSyntax.Rdf11),
                    new UncompressedTurtleFormatter(),
                    new UncompressedNotation3Formatter(),
                    new TurtleFormatter(g),
                    new TurtleW3CFormatter(g),
                    new Notation3Formatter(g),
                    new CsvFormatter(),
                    new TsvFormatter(),
                    new RdfXmlFormatter()
                };
                List <INode> subjects = new List <INode>()
                {
                    subjBnode,
                    subjUri,
                    subjUri2
                };
                List <INode> predicates = new List <INode>()
                {
                    predUri,
                    predType
                };
                List <INode> objects = new List <INode>()
                {
                    objBnode,
                    objUri,
                    objString,
                    objStringLang,
                    objInt,
                    objFloat,
                    objDouble,
                    objDecimal,
                    objTrue,
                    objFalse,
                    objUnknown,
                    objXmlLiteral
                };
                List <Triple> testTriples = (from s in subjects from p in predicates from o in objects select new Triple(s, p, o)).ToList();

                foreach (Triple t in testTriples)
                {
                    Console.WriteLine("Raw Triple:");
                    Console.WriteLine(t.ToString());
                    Console.WriteLine();
                    foreach (ITripleFormatter f in formatters)
                    {
                        Console.WriteLine(f.GetType().ToString());
                        Console.WriteLine(f.Format(t));
                        Console.WriteLine();
                    }
                    Console.WriteLine();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
コード例 #54
0
ファイル: CsvFormatter.cs プロジェクト: jmahmud/RDFer
 /// <summary>
 /// Formats URIs for CSV output
 /// </summary>
 /// <param name="u">URI</param>
 /// <param name="segment">Triple Segment</param>
 /// <returns></returns>
 protected override string FormatUriNode(IUriNode u, TripleSegment? segment)
 {
     return this.FormatUri(u.Uri);
 }
コード例 #55
0
        /// <summary>
        /// Creates a new Ontology Property for the given resource in the given Graph
        /// </summary>
        /// <param name="resource">Resource</param>
        /// <param name="graph">Graph</param>
        public OntologyProperty(INode resource, IGraph graph)
            : base(resource, graph)
        {
            //Q: Assert that this resource is a property?
            //UriNode rdfType = graph.CreateUriNode(new Uri(OntologyHelper.PropertyType));
            //graph.Assert(new Triple(resource, rdfType, graph.CreateUriNode(new Uri(OntologyHelper.RdfsProperty))));

            this.IntialiseProperty(OntologyHelper.PropertyDomain, false);
            this.IntialiseProperty(OntologyHelper.PropertyRange, false);
            this.IntialiseProperty(OntologyHelper.PropertyEquivalentProperty, false);
            this.IntialiseProperty(OntologyHelper.PropertySubPropertyOf, false);
            this.IntialiseProperty(OntologyHelper.PropertyInverseOf, false);

            //Find derived properties
            IUriNode subPropertyOf = this._graph.CreateUriNode(UriFactory.Create(OntologyHelper.PropertySubPropertyOf));

            this._resourceProperties.Add(PropertyDerivedProperty, new List <INode>());
            this._resourceProperties.Add(PropertyDirectSubProperty, new List <INode>());
            foreach (Triple t in this._graph.GetTriplesWithPredicateObject(subPropertyOf, this._resource))
            {
                if (!this._resourceProperties[PropertyDerivedProperty].Contains(t.Subject))
                {
                    this._resourceProperties[PropertyDerivedProperty].Add(t.Subject);
                }
                if (!this._resourceProperties[PropertyDirectSubProperty].Contains(t.Subject))
                {
                    this._resourceProperties[PropertyDirectSubProperty].Add(t.Subject);
                }
            }
            int c = 0;

            do
            {
                c = this._resourceProperties[PropertyDerivedProperty].Count;
                foreach (INode n in this._resourceProperties[PropertyDerivedProperty].ToList())
                {
                    foreach (Triple t in this._graph.GetTriplesWithPredicateObject(subPropertyOf, n))
                    {
                        if (!this._resourceProperties[PropertyDerivedProperty].Contains(t.Subject))
                        {
                            this._resourceProperties[PropertyDerivedProperty].Add(t.Subject);
                        }
                    }
                }
            } while (c < this._resourceProperties[PropertyDerivedProperty].Count);

            //Find additional super properties
            this._resourceProperties.Add(PropertyDirectSuperProperty, new List <INode>());
            if (this._resourceProperties.ContainsKey(OntologyHelper.PropertySubPropertyOf))
            {
                this._resourceProperties[PropertyDirectSuperProperty].AddRange(this._resourceProperties[OntologyHelper.PropertySubPropertyOf]);

                do
                {
                    c = this._resourceProperties[OntologyHelper.PropertySubPropertyOf].Count;
                    foreach (INode n in this._resourceProperties[OntologyHelper.PropertySubPropertyOf].ToList())
                    {
                        foreach (Triple t in this._graph.GetTriplesWithSubjectPredicate(n, subPropertyOf))
                        {
                            if (!this._resourceProperties[OntologyHelper.PropertySubPropertyOf].Contains(t.Object))
                            {
                                this._resourceProperties[OntologyHelper.PropertySubPropertyOf].Add(t.Object);
                            }
                        }
                    }
                } while (c < this._resourceProperties[OntologyHelper.PropertySubPropertyOf].Count);
            }

            //Find additional inverses
            if (!this._resourceProperties.ContainsKey(OntologyHelper.PropertyInverseOf))
            {
                this._resourceProperties.Add(OntologyHelper.PropertyInverseOf, new List <INode>());
            }
            foreach (Triple t in this._graph.GetTriplesWithPredicateObject(graph.CreateUriNode(UriFactory.Create(OntologyHelper.PropertyInverseOf)), this._resource))
            {
                if (!this._resourceProperties[OntologyHelper.PropertyInverseOf].Contains(t.Subject))
                {
                    this._resourceProperties[OntologyHelper.PropertyInverseOf].Add(t.Subject);
                }
            }
        }
コード例 #56
0
 /// <summary>
 /// Creates a new HasExactPropertySelector which will select Triples with the given Property as the Predicate
 /// </summary>
 /// <param name="targetProperty">The Property Triples to be selected must contain as their Predicate</param>
 public HasExactPropertySelector(IUriNode targetProperty)
 {
     this._targetproperty = targetProperty;
 }
コード例 #57
0
 public override void ApplyToGraph(IGraph graph, IUriNode parent)
 {
     graph.Assert(parent, graph.CreateUriNode(new Uri(CantonConstants.CantonSchema + "origin")), graph.CreateLiteralNode(_origin));
     graph.Assert(parent, graph.CreateUriNode(new Uri(CantonConstants.CantonSchema + "commitId")), graph.CreateLiteralNode("" + _commitId));
 }
コード例 #58
0
        /// <summary>
        /// Generates a SPARQL Service Description Graph for the given Query Handler Configuration or uses the configuration supplied Description Graph
        /// </summary>
        /// <param name="context">HTTP Context</param>
        /// <param name="config">Query Handler Configuration</param>
        /// <param name="descripUri">Base URI of the Description</param>
        /// <returns></returns>
        public static IGraph GetServiceDescription(HttpContext context, BaseQueryHandlerConfiguration config, Uri descripUri)
        {
            //Use user specified Service Description if present
            if (config.ServiceDescription != null)
            {
                return(config.ServiceDescription);
            }

            IGraph g = SparqlServiceDescriber.GetNewGraph();

            //Add the Top Level Node representing the Service
            IUriNode descrip = g.CreateUriNode(descripUri);
            IUriNode rdfType = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfType));
            IUriNode service = g.CreateUriNode("sd:" + ClassService);

            g.Assert(descrip, rdfType, service);

            //Add its sd:url
            IUriNode url = g.CreateUriNode("sd:" + PropertyUrl);

            g.Assert(descrip, url, descrip);

            //Add the sd:supportedLanguage - Requires Query Language to be configurable through the Configuration API
            IUriNode supportedLang = g.CreateUriNode("sd:" + PropertySupportedLanguage);
            IUriNode lang;

            switch (config.Syntax)
            {
            case SparqlQuerySyntax.Extended:
            case SparqlQuerySyntax.Sparql_1_1:
                lang = g.CreateUriNode("sd:" + InstanceSparql11Query);
                break;

            default:
                lang = g.CreateUriNode("sd:" + InstanceSparql10Query);
                break;
            }
            g.Assert(descrip, supportedLang, lang);

            //Add the Result Formats
            IUriNode resultFormat = g.CreateUriNode("sd:" + PropertyResultFormat);

            foreach (MimeTypeDefinition definition in MimeTypesHelper.Definitions)
            {
                if (definition.CanWriteRdf || definition.CanWriteSparqlResults)
                {
                    if (definition.FormatUri != null)
                    {
                        g.Assert(descrip, resultFormat, g.CreateUriNode(new Uri(definition.FormatUri)));
                    }
                }
            }

            //Add Features and Dataset Description
            //First add descriptions for Global Expression Factories
            IUriNode extensionFunction  = g.CreateUriNode("sd:" + PropertyExtensionFunction);
            IUriNode extensionAggregate = g.CreateUriNode("sd:" + PropertyExtensionAggregate);

            foreach (ISparqlCustomExpressionFactory factory in SparqlExpressionFactory.Factories)
            {
                foreach (Uri u in factory.AvailableExtensionFunctions)
                {
                    g.Assert(descrip, extensionFunction, g.CreateUriNode(u));
                }
                foreach (Uri u in factory.AvailableExtensionAggregates)
                {
                    g.Assert(descrip, extensionAggregate, g.CreateUriNode(u));
                }
            }

            //Then get the Configuration Object to add any other Feature Descriptions it wishes to
            config.AddFeatureDescription(g, descrip);

            return(g);
        }
コード例 #59
0
 /// <summary>
 /// Formats a URI Node
 /// </summary>
 /// <param name="u">URI Node</param>
 /// <param name="segment">Triple Segment</param>
 /// <returns></returns>
 protected override string FormatUriNode(IUriNode u, TripleSegment? segment)
 {
     StringBuilder output = new StringBuilder();
     if (this._uriStartChar != null) output.Append(this._uriStartChar);
     if (this._uriEndChar != null)
     {
         output.Append(this.FormatUri(u.Uri));
         output.Append(this._uriEndChar);
     }
     else
     {
         output.Append(this.FormatUri(u.Uri));
     }
     return output.ToString();
 }
コード例 #60
0
        /// <summary>
        /// Generates a SPARQL Service Description Graph for the specified portion of the SPARQL Server Handler Configuration or uses the configuration supplied Description Graph
        /// </summary>
        /// <param name="context">HTTP Context</param>
        /// <param name="config">SPARQL Server Configuration</param>
        /// <param name="descripUri">Base URI of the Description</param>
        /// <param name="type">Portion of the SPARQL Server to describe</param>
        /// <returns></returns>
        public static IGraph GetServiceDescription(HttpContext context, BaseSparqlServerConfiguration config, Uri descripUri, ServiceDescriptionType type)
        {
            //Use user specified Service Description if present
            if (config.ServiceDescription != null)
            {
                return(config.ServiceDescription);
            }

            IGraph   g       = SparqlServiceDescriber.GetNewGraph();
            IUriNode rdfType = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfType));
            IUriNode service = g.CreateUriNode("sd:" + ClassService);

            INode queryNode, updateNode, protocolNode;

            //Query Service Description
            if (config.QueryProcessor != null && (type == ServiceDescriptionType.Query || type == ServiceDescriptionType.All))
            {
                //Add the Top Level Node representing the Query Service
                queryNode = g.CreateUriNode(new Uri(descripUri, "query"));
                g.Assert(queryNode, rdfType, service);

                //Add its sd:url
                IUriNode url = g.CreateUriNode("sd:" + PropertyUrl);
                g.Assert(queryNode, url, queryNode);

                //Add the sd:supportedLanguage
                IUriNode supportedLang = g.CreateUriNode("sd:" + PropertySupportedLanguage);
                IUriNode lang;
                switch (config.QuerySyntax)
                {
                case SparqlQuerySyntax.Extended:
                case SparqlQuerySyntax.Sparql_1_1:
                    lang = g.CreateUriNode("sd:" + InstanceSparql11Query);
                    break;

                default:
                    lang = g.CreateUriNode("sd:" + InstanceSparql10Query);
                    break;
                }
                g.Assert(queryNode, supportedLang, lang);

                //Add the Result Formats
                IUriNode resultFormat = g.CreateUriNode("sd:" + PropertyResultFormat);
                foreach (MimeTypeDefinition definition in MimeTypesHelper.Definitions)
                {
                    if (definition.CanWriteRdf || definition.CanWriteSparqlResults)
                    {
                        if (definition.FormatUri != null)
                        {
                            g.Assert(queryNode, resultFormat, g.CreateUriNode(new Uri(definition.FormatUri)));
                        }
                    }
                }

                //Add Features and Dataset Description
                //First add descriptions for Global Expression Factories
                IUriNode extensionFunction  = g.CreateUriNode("sd:" + PropertyExtensionFunction);
                IUriNode extensionAggregate = g.CreateUriNode("sd:" + PropertyExtensionAggregate);
                foreach (ISparqlCustomExpressionFactory factory in SparqlExpressionFactory.Factories)
                {
                    foreach (Uri u in factory.AvailableExtensionFunctions)
                    {
                        g.Assert(queryNode, extensionFunction, g.CreateUriNode(u));
                    }
                    foreach (Uri u in factory.AvailableExtensionAggregates)
                    {
                        g.Assert(queryNode, extensionAggregate, g.CreateUriNode(u));
                    }
                }
            }
            else
            {
                queryNode = null;
            }

            //Update Service Description
            if (config.UpdateProcessor != null && (type == ServiceDescriptionType.Update || type == ServiceDescriptionType.All))
            {
                //Add the Top Level Node representing the Update Service
                updateNode = g.CreateUriNode(new Uri(descripUri, "update"));
                g.Assert(updateNode, rdfType, service);

                //Add its sd:url
                IUriNode url = g.CreateUriNode("sd:" + PropertyUrl);
                g.Assert(updateNode, url, updateNode);

                //Add the sd:supportedLanguage
                IUriNode supportedLang = g.CreateUriNode("sd:" + PropertySupportedLanguage);
                g.Assert(updateNode, supportedLang, g.CreateUriNode("sd:" + InstanceSparql11Update));

                //Add Features and Dataset Description
                //First add descriptions for Global Expression Factories
                IUriNode extensionFunction  = g.CreateUriNode("sd:" + PropertyExtensionFunction);
                IUriNode extensionAggregate = g.CreateUriNode("sd:" + PropertyExtensionAggregate);
                foreach (ISparqlCustomExpressionFactory factory in SparqlExpressionFactory.Factories)
                {
                    foreach (Uri u in factory.AvailableExtensionFunctions)
                    {
                        g.Assert(updateNode, extensionFunction, g.CreateUriNode(u));
                    }
                    foreach (Uri u in factory.AvailableExtensionAggregates)
                    {
                        g.Assert(updateNode, extensionAggregate, g.CreateUriNode(u));
                    }
                }
            }
            else
            {
                updateNode = null;
            }

            //Graph Store HTTP Protocol Description
            if (config.ProtocolProcessor != null && (type == ServiceDescriptionType.Protocol || type == ServiceDescriptionType.All))
            {
                //Add the Top Level Node representing the Service
                if (descripUri.ToString().EndsWith("/description"))
                {
                    String actualUri = descripUri.ToString();
                    actualUri    = actualUri.Substring(0, actualUri.LastIndexOf("/description") + 1);
                    protocolNode = g.CreateUriNode(new Uri(actualUri));
                }
                else
                {
                    protocolNode = g.CreateUriNode(descripUri);
                }
                g.Assert(protocolNode, rdfType, service);

                //Add its sd:url
                IUriNode url = g.CreateUriNode("sd:" + PropertyUrl);
                g.Assert(protocolNode, url, protocolNode);

                //Add the Input Formats
                IUriNode inputFormat = g.CreateUriNode("sd:" + PropertyInputFormat);
                foreach (MimeTypeDefinition definition in MimeTypesHelper.Definitions)
                {
                    if (definition.CanParseRdf)
                    {
                        if (definition.FormatUri != null)
                        {
                            g.Assert(protocolNode, inputFormat, g.CreateUriNode(new Uri(definition.FormatUri)));
                        }
                    }
                }

                //Add the Result Formats
                IUriNode resultFormat = g.CreateUriNode("sd:" + PropertyResultFormat);
                foreach (MimeTypeDefinition definition in MimeTypesHelper.Definitions)
                {
                    if (definition.CanWriteRdf)
                    {
                        if (definition.FormatUri != null)
                        {
                            g.Assert(protocolNode, resultFormat, g.CreateUriNode(new Uri(definition.FormatUri)));
                        }
                    }
                }
            }
            else
            {
                protocolNode = null;
            }

            //Finally get the Configuration Node to add additional feature and dataset descriptions
            config.AddFeatureDescription(g, queryNode, updateNode, protocolNode);

            return(g);
        }