Beispiel #1
0
 /// <summary>
 /// Gets the Value of the function as applied to the given String Literal and Argument
 /// </summary>
 /// <param name="stringLit">Simple/String typed Literal</param>
 /// <param name="arg">Argument</param>
 /// <returns></returns>
 public override IValuedNode ValueInternal(ILiteralNode stringLit, ILiteralNode arg)
 {
     if (stringLit.Value.Equals(string.Empty))
     {
         if (arg.Value.Equals(string.Empty))
         {
             //The Empty String starts with the Empty String
             return new BooleanNode(null, true);
         }
         else
         {
             //Empty String doesn't start with a non-empty string
             return new BooleanNode(null, false);
         }
     }
     else if (arg.Value.Equals(string.Empty))
     {
         //Any non-empty string starts with the empty string
         return new BooleanNode(null, true);
     }
     else
     {
         //Otherwise evalute the StartsWith
         return new BooleanNode(null, stringLit.Value.StartsWith(arg.Value));
     }
 }
        /// <summary>
        /// Gets the Value of the function as applied to the given String Literal
        /// </summary>
        /// <param name="stringLit">Simple/String typed Literal</param>
        /// <returns></returns>
        protected override IValuedNode ValueInternal(ILiteralNode stringLit)
        {
            string temp = stringLit.Value.Trim();
            Regex normalizeSpace = new Regex("\\s{2,}");
            temp = normalizeSpace.Replace(temp, " ");

            return new StringNode(null, temp, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString));
        }
Beispiel #3
0
 /// <summary>
 /// Converts the given String Literal to upper case
 /// </summary>
 /// <param name="stringLit">String Literal</param>
 /// <returns></returns>
 protected override IValuedNode ValueInternal(ILiteralNode stringLit)
 {
     if (stringLit.DataType != null)
     {
         return new StringNode(null, stringLit.Value.ToUpper(), stringLit.DataType);
     }
     else
     {
         return new StringNode(null, stringLit.Value.ToUpper(), stringLit.Language);
     }
 }
Beispiel #4
0
 /// <summary>
 /// Formats Literals for CSV output
 /// </summary>
 /// <param name="l">Literal</param>
 /// <param name="segment">Triple Segment</param>
 /// <returns></returns>
 protected override string FormatLiteralNode(ILiteralNode l, TripleSegment? segment)
 {
     String value = l.Value;
     if (value.Contains('"') || value.Contains(',') || value.Contains('\n') || value.Contains('\r'))
     {
         return '"' + value.Replace("\"", "\"\"") + '"';
     }
     else
     {
         return value;
     }
 }
Beispiel #5
0
 /// <summary>
 /// Gets the Value of the function as applied to the given String Literal and Argument
 /// </summary>
 /// <param name="stringLit">Simple/String typed Literal</param>
 /// <param name="arg">Argument</param>
 /// <returns></returns>
 public override IValuedNode ValueInternal(ILiteralNode stringLit, ILiteralNode arg)
 {
     if (stringLit.Value.Equals(string.Empty))
     {
         //Empty string cannot contain anything
         return new BooleanNode(null, false);
     }
     else if (arg.Value.Equals(string.Empty))
     {
         //Any non-empty string contains the empty string
         return new BooleanNode(null, true);
     }
     else
     {
         //Evalute the Contains
         return new BooleanNode(null, stringLit.Value.Contains(arg.Value));
     }
 }
 /// <summary>
 /// Gets the Value of the function as applied to the given String Literal and Argument.
 /// </summary>
 /// <param name="stringLit">Simple/String typed Literal.</param>
 /// <param name="arg">Argument.</param>
 /// <returns></returns>
 public override IValuedNode ValueInternal(ILiteralNode stringLit, ILiteralNode arg)
 {
     if (stringLit.Value.Equals(string.Empty))
     {
         // Empty string cannot contain anything
         return(new BooleanNode(null, false));
     }
     else if (arg.Value.Equals(string.Empty))
     {
         // Any non-empty string contains the empty string
         return(new BooleanNode(null, true));
     }
     else
     {
         // Evalute the Contains
         return(new BooleanNode(null, stringLit.Value.Contains(arg.Value)));
     }
 }
        public LiteralNodeControl(ILiteralNode n, INodeFormatter formatter)
        {
            InitializeComponent();

            String data = formatter.Format(n);
            if (data.Contains("\"^^"))
            {
                String value = data.Substring(0, data.IndexOf("\"^^") + 3);
                String dt = data.Substring(data.IndexOf("\"^^") + 4);
                this.txtValue.Content = value;
                this.lnkDatatypeUri.Text = dt;
                this._u = n.DataType;
            }
            else
            {
                this.txtValue.Content = data;
            }
        }
Beispiel #8
0
        /// <summary>
        /// Returns an Integer indicating the Ordering of this Node compared to another Node
        /// </summary>
        /// <param name="other">Node to test against</param>
        /// <returns></returns>
        public override int CompareTo(ILiteralNode other)
        {
            if (ReferenceEquals(this, other))
            {
                return(0);
            }

            if (other == null)
            {
                //Variables are considered greater than null
                return(1);
            }
            else
            {
                //Variable Nodes are less than everything else
                return(-1);
            }
        }
Beispiel #9
0
        private static bool IsIllformed(ILiteralNode literal)
        {
            var type    = literal.DataType.AbsoluteUri.Replace(XmlSpecsHelper.NamespaceXmlSchema, string.Empty);
            var schemas = GenerateSchema(type);

            var isIllformed = false;

            void handler(object sender, ValidationEventArgs e)
            {
                isIllformed = true;
            }

            var doc = new XDocument(new XElement(Root, literal.Value));

            doc.Validate(schemas, handler);

            return(isIllformed);
        }
Beispiel #10
0
        public void HelloWorld()
        {
            //Fill in the code shown on this page here to build your hello world application
            Graph g = new Graph();

            IUriNode     dotNetRDF    = g.CreateUriNode(UriFactory.Create("http://www.dotnetrdf.org"));
            IUriNode     says         = g.CreateUriNode(UriFactory.Create("http://example.org/says"));
            ILiteralNode helloWorld   = g.CreateLiteralNode("Hello World");
            ILiteralNode bonjourMonde = g.CreateLiteralNode("Bonjour tout le Monde", "fr");

            g.Assert(new Triple(dotNetRDF, says, helloWorld));
            g.Assert(new Triple(dotNetRDF, says, bonjourMonde));

            Console.WriteLine();
            Console.WriteLine("Raw Output");
            Console.WriteLine();
            foreach (Triple t in g.Triples)
            {
                Console.WriteLine(t.ToString());
            }

            // RDF is written out using one of the Writer types.
            // Use the Save method on the graph to serialise the triples in
            // the specified format to the provided write.
            Console.WriteLine();
            Console.WriteLine("NTriples");
            Console.WriteLine();
            NTriplesWriter ntwriter = new NTriplesWriter();
            var            sw       = new System.IO.StringWriter();

            ntwriter.Save(g, sw);
            Console.WriteLine(sw.ToString());

            Console.WriteLine();
            Console.WriteLine("RDF XML");
            Console.WriteLine();
            RdfXmlWriter rdfxmlwriter = new RdfXmlWriter();

            sw = new System.IO.StringWriter();
            rdfxmlwriter.Save(g, sw);
            Console.WriteLine(sw.ToString());

            // view the Test Results output to see the different serialisations.
        }
Beispiel #11
0
        /// <summary>
        /// Gets the Data Type Uri of the given Node if it has a supported type
        /// </summary>
        /// <param name="n">Node</param>
        /// <returns></returns>
        /// <remarks>
        /// <para>
        /// Only <see cref="ILiteralNode">ILiteralNode</see>'s can have a Data Type
        /// </para>
        /// <para>
        /// The function only returns the Data Type Uri (as a String) if the Data Type of the Literal is one of the supported Data Types
        /// </para>
        /// </remarks>
        public static String GetSupportedDataType(INode n)
        {
            if (n == null)
            {
                throw new RdfException("Data Type cannot be determined for Nulls");
            }

            switch (n.NodeType)
            {
            case NodeType.Blank:
            case NodeType.GraphLiteral:
            case NodeType.Uri:
                throw new RdfException("Data Type cannot be determined for non-Literal Nodes");

            case NodeType.Literal:
                ILiteralNode l = (ILiteralNode)n;
                if (l.DataType == null)
                {
                    if (!l.Language.Equals(String.Empty))
                    {
                        throw new RdfException("Literals with Language Specifiers do not have a Data Type");
                    }
                    else
                    {
                        return(XmlSchemaDataTypeString);
                    }
                }
                else
                {
                    String type = l.DataType.ToString();
                    if (XmlSpecsHelper.IsSupportedType(type))
                    {
                        return(type);
                    }
                    else
                    {
                        return(String.Empty);
                    }
                }

            default:
                throw new RdfException("Data Type cannot be determined for unknown Node types");
            }
        }
Beispiel #12
0
    protected void UnitTestaddRDFTriple()
    {
        var   list = (List <string[]>)Session["PersonalList"];
        Graph g    = (Graph)Session["ggraph"];

        g.NamespaceMap.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/0.1/"));
        g.NamespaceMap.AddNamespace("rdfs", new Uri("http://www.w3.org/2000/01/rdf-schema#"));

        IUriNode personID = g.CreateUriNode(UriFactory.Create("http://unittest.com/"));
        IUriNode Title    = g.CreateUriNode("foaf:title");
        IUriNode Name     = g.CreateUriNode("foaf:name");
        IUriNode Surname  = g.CreateUriNode("foaf:familyName");
        IUriNode Email    = g.CreateUriNode("foaf:mbox");
        IUriNode Phone    = g.CreateUriNode("foaf:phone");
        IUriNode Faculty  = g.CreateUriNode("rdfs:label");
        IUriNode Comments = g.CreateUriNode("rdfs:comment");

        IUriNode rdftype    = g.CreateUriNode("rdf:type");    //FOAFPERSON
        IUriNode foafPerson = g.CreateUriNode("foaf:Person"); //FOAFPERSON

        ILiteralNode NTitle   = g.CreateLiteralNode("title");
        ILiteralNode NName    = g.CreateLiteralNode("name");
        ILiteralNode NSurname = g.CreateLiteralNode("surname");
        IUriNode     NPhone   = g.CreateUriNode(UriFactory.Create("tel:" + "+442380123456"));
        IUriNode     NEmail   = g.CreateUriNode(UriFactory.Create("mailto:" + "*****@*****.**"));

        ILiteralNode NFaculty  = g.CreateLiteralNode("Sfaculty");
        ILiteralNode NComments = g.CreateLiteralNode("Comment");

        g.Assert(personID, Title, NTitle);
        g.Assert(personID, Name, NName);
        g.Assert(personID, Surname, NSurname);
        g.Assert(personID, Email, NEmail);
        g.Assert(personID, Phone, NPhone);
        g.Assert(personID, Faculty, NFaculty);
        g.Assert(personID, Comments, NComments);
        g.Assert(personID, rdftype, foafPerson); //FOAFPERSON

        RdfXmlWriter rdfxmlwriter = new RdfXmlWriter();

        rdfxmlwriter.Save(g, path_user + Session["UserId"].ToString() + ".rdf");

        LoadPersonalData();
    }
Beispiel #13
0
        /// <summary>
        /// Returns the value of the Expression as evaluated for a given Binding as a Literal Node
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        /// <param name="bindingID">Binding ID</param>
        /// <returns></returns>
        public IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID)
        {
            ILiteralNode input  = this.CheckArgument(this._stringExpr, context, bindingID);
            ILiteralNode starts = this.CheckArgument(this._startsExpr, context, bindingID);

            if (!this.IsValidArgumentPair(input, starts))
            {
                throw new RdfQueryException("The Literals provided as arguments to this SPARQL String function are not of valid forms (see SPARQL spec for acceptable combinations)");
            }

            Uri    datatype = (input.DataType != null ? input.DataType : starts.DataType);
            string lang     = (!input.Language.Equals(string.Empty) ? input.Language : starts.Language);

            if (input.Value.Contains(starts.Value))
            {
                int    startIndex  = input.Value.IndexOf(starts.Value) + starts.Value.Length;
                string resultValue = (startIndex >= input.Value.Length ? string.Empty : input.Value.Substring(startIndex));

                if (datatype != null)
                {
                    return(new StringNode(null, resultValue, datatype));
                }
                else if (!lang.Equals(string.Empty))
                {
                    return(new StringNode(null, resultValue, lang));
                }
                else
                {
                    return(new StringNode(null, resultValue));
                }
            }
            else
            {
                if (datatype != null)
                {
                    return(new StringNode(null, string.Empty, datatype));
                }
                else
                {
                    return(new StringNode(null, string.Empty, lang));
                }
            }
        }
Beispiel #14
0
        public void WritingStringIsFullyEscaped()
        {
            String test = "Ends with a \"";

            Console.WriteLine("Original Value - " + test);
            Assert.IsFalse(test.IsFullyEscaped(this._ntripleEscapes, new char[] { '"', '\n', '\r', '\t' }));

            NodeFactory  factory = new NodeFactory();
            ILiteralNode n       = factory.CreateLiteralNode(test);

            NTriplesFormatter formatter = new NTriplesFormatter();
            String            result    = formatter.Format(n);

            Console.WriteLine("Formatted Value - " + result);
            result = result.Substring(1, result.Length - 2);
            Console.WriteLine("Formatted Value with surrounding quotes removed - " + result);

            Assert.IsTrue(result.IsFullyEscaped(this._ntripleEscapes, new char[] { '"', '\n', '\r', '\t' }));
        }
Beispiel #15
0
        /// <summary>
        /// Returns the value of the Expression as evaluated for a given Binding as a Literal Node
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        /// <param name="bindingID">Binding ID</param>
        /// <returns></returns>
        public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID)
        {
            IValuedNode result = this._expr.Evaluate(context, bindingID);
            if (result == null)
            {
                throw new RdfQueryException("Cannot create an IRI from a null");
            }
            else
            {
                switch (result.NodeType)
                {
                    case NodeType.Literal:
                        ILiteralNode lit = (ILiteralNode)result;
                        string baseUri = string.Empty;
                        if (context.Query != null) baseUri = context.Query.BaseUri.ToSafeString();
                        string uri;
                        if (lit.DataType == null)
                        {
                            uri = Tools.ResolveUri(lit.Value, baseUri);
                            return new UriNode(null, UriFactory.Create(uri));
                        }
                        else
                        {
                            string dt = lit.DataType.AbsoluteUri;
                            if (dt.Equals(XmlSpecsHelper.XmlSchemaDataTypeString, StringComparison.Ordinal))
                            {
                                uri = Tools.ResolveUri(lit.Value, baseUri);
                                return new UriNode(null, UriFactory.Create(uri));
                            }
                            else
                            {
                                throw new RdfQueryException("Cannot create an IRI from a non-string typed literal");
                            }
                        }

                    case NodeType.Uri:
                        //Already a URI so nothing to do
                        return result;
                    default:
                        throw new RdfQueryException("Cannot create an IRI from a non-URI/String literal");
                }
            }
        }
Beispiel #16
0
        public LiteralNodeControl(ILiteralNode n, INodeFormatter formatter)
        {
            InitializeComponent();

            String data = formatter.Format(n);

            if (data.Contains("\"^^"))
            {
                String value = data.Substring(0, data.IndexOf("\"^^") + 3);
                String dt    = data.Substring(data.IndexOf("\"^^") + 4);
                this.txtValue.Content    = value;
                this.lnkDatatypeUri.Text = dt;
                this._u = n.DataType;
            }
            else
            {
                this.txtValue.Content = data;
            }
        }
Beispiel #17
0
        private static void PerformanceTestWith2Triples()
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            IGraph g = new Graph();

            IUriNode     dotNetRDF    = g.CreateUriNode(UriFactory.Create("http://www.dotnetrdf.org"));
            IUriNode     says         = g.CreateUriNode(UriFactory.Create("http://example.org/says"));
            ILiteralNode helloWorld   = g.CreateLiteralNode("Hello World");
            ILiteralNode bonjourMonde = g.CreateLiteralNode("Bonjour tout le Monde", "fr");

            g.Assert(new Triple(dotNetRDF, says, helloWorld));
            g.Assert(new Triple(dotNetRDF, says, bonjourMonde));

            sw.Stop();
            Console.WriteLine("Execution time: " + sw.ElapsedMilliseconds + " ms");
        }
Beispiel #18
0
        public static RDFNode ToJenaNode(INode n, JenaMapping mapping)
        {
            switch (n.NodeType)
            {
            case NodeType.Uri:
                return(mapping.Model.createResource(n.ToString()));

            case NodeType.Blank:
                if (mapping.OutputMapping.ContainsKey(n))
                {
                    return(mapping.OutputMapping[n]);
                }
                else
                {
                    AnonId   id    = new AnonId(((IBlankNode)n).InternalID);
                    Resource bnode = mapping.Model.createResource(id);
                    mapping.OutputMapping.Add(n, bnode);
                    if (!mapping.InputMapping.ContainsKey(bnode))
                    {
                        mapping.InputMapping.Add(bnode, n);
                    }
                    return(bnode);
                }

            case NodeType.Literal:
                ILiteralNode lit = (ILiteralNode)n;
                if (lit.DataType != null)
                {
                    return(mapping.Model.createTypedLiteral(lit.Value, TypeMapper.getInstance().getSafeTypeByName(lit.DataType.ToString())));
                }
                else if (!lit.Language.Equals(String.Empty))
                {
                    return(mapping.Model.createLiteral(lit.Value, lit.Language));
                }
                else
                {
                    return(mapping.Model.createLiteral(lit.Value));
                }

            default:
                throw new RdfException("Only URI/Blank/Literal Nodes can be converted to Jena Nodes");
            }
        }
        /// <summary>
        /// Returns an Integer indicating the Ordering of this Node compared to another Node.
        /// </summary>
        /// <param name="other">Node to test against.</param>
        /// <returns></returns>
        public override int CompareTo(ILiteralNode other)
        {
            if (ReferenceEquals(this, other))
            {
                return(0);
            }

            if (other == null)
            {
                // Everything is greater than a null
                // Return a 1 to indicate this
                return(1);
            }
            else
            {
                // URI Nodes are less than Literal Nodes
                return(-1);
            }
        }
Beispiel #20
0
        public IGraph CreateGraph1()
        {
            IGraph g = new Graph();

            g.BaseUri = new Uri("http://example1.org/");

            //Define the Namespaces we want to use
            g.NamespaceMap.AddNamespace("ex", new Uri("http://example1.org"));

            IUriNode     philippe     = g.CreateUriNode("ex:Philippe");
            IUriNode     says         = g.CreateUriNode(UriFactory.Create("http://example.org/says"));
            ILiteralNode helloWorld   = g.CreateLiteralNode("Hello World");
            ILiteralNode bonjourMonde = g.CreateLiteralNode("Bonjour tout le Monde", "fr");

            g.Assert(new Triple(philippe, says, helloWorld));
            g.Assert(new Triple(philippe, says, bonjourMonde));

            return(g);
        }
Beispiel #21
0
        /// <summary>
        /// Gets the numeric value of the function in the given Evaluation Context for the given Binding ID
        /// </summary>
        /// <param name="context">Evaluation Context</param>
        /// <param name="bindingID">Binding ID</param>
        /// <returns></returns>
        public override object NumericValue(SparqlEvaluationContext context, int bindingID)
        {
            INode temp = this._expr.Value(context, bindingID);

            if (temp != null)
            {
                if (temp.NodeType == NodeType.Literal)
                {
                    ILiteralNode lit = (ILiteralNode)temp;
                    if (lit.DataType != null)
                    {
                        if (lit.DataType.ToString().Equals(XmlSpecsHelper.XmlSchemaDataTypeDateTime) || lit.DataType.ToString().Equals(XmlSpecsHelper.XmlSchemaDataTypeDate))
                        {
                            DateTimeOffset dt;
                            if (DateTimeOffset.TryParse(lit.Value, out dt))
                            {
                                return(this.NumericValueInternal(dt));
                            }
                            else
                            {
                                throw new RdfQueryException("Unable to evaluate an XPath Date Time function as the value of the Date Time typed literal couldn't be parsed as a Date Time");
                            }
                        }
                        else
                        {
                            throw new RdfQueryException("Unable to evaluate an XPath Date Time function on a typed literal which is not a Date Time");
                        }
                    }
                    else
                    {
                        throw new RdfQueryException("Unable to evaluate an XPath Date Time function on an untyped literal argument");
                    }
                }
                else
                {
                    throw new RdfQueryException("Unable to evaluate an XPath Date Time function on a non-literal argument");
                }
            }
            else
            {
                throw new RdfQueryException("Unable to evaluate an XPath Date Time function on a null argument");
            }
        }
Beispiel #22
0
        public IGraph CreateGraph2()
        {
            IGraph g = new Graph();

            g.BaseUri = new Uri("http://example1.org/");

            //Define the Namespaces we want to use
            g.NamespaceMap.AddNamespace("ex", new Uri("http://example1.org"));

            IUriNode     marina       = g.CreateUriNode("ex:Marina");
            IUriNode     says         = g.CreateUriNode(UriFactory.Create("http://example.org/says"));
            ILiteralNode helloWorld   = g.CreateLiteralNode("Hello World");
            ILiteralNode bonjourMonde = g.CreateLiteralNode("Привет мир", "ru");

            g.Assert(new Triple(marina, says, helloWorld));
            g.Assert(new Triple(marina, says, bonjourMonde));

            return(g);
        }
        /// <summary>
        /// Gets the Value of the function as applied to the given String Literal and Argument
        /// </summary>
        /// <param name="stringLit">Simple/String typed Literal</param>
        /// <param name="arg">Argument</param>
        /// <returns></returns>
        public override IValuedNode ValueInternal(ILiteralNode stringLit, ILiteralNode arg)
        {
            if (arg == null)
            {
                return(ValueInternal(stringLit));
            }
            else
            {
                string normalized = stringLit.Value;

                switch (arg.Value)
                {
                case XPathFunctionFactory.XPathUnicodeNormalizationFormC:
                    normalized = normalized.Normalize();
                    break;

                case XPathFunctionFactory.XPathUnicodeNormalizationFormD:
                    normalized = normalized.Normalize(NormalizationForm.FormD);
                    break;

                case XPathFunctionFactory.XPathUnicodeNormalizationFormFull:
                    throw new RdfQueryException(".Net does not support Fully Normalized Unicode Form");

                case XPathFunctionFactory.XPathUnicodeNormalizationFormKC:
                    normalized = normalized.Normalize(NormalizationForm.FormKC);
                    break;

                case XPathFunctionFactory.XPathUnicodeNormalizationFormKD:
                    normalized = normalized.Normalize(NormalizationForm.FormKD);
                    break;

                case "":
                    // No Normalization
                    break;

                default:
                    throw new RdfQueryException("'" + arg.Value + "' is not a valid Normalization Form as defined by the XPath specification");
                }

                return(new StringNode(null, normalized, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString)));
            }
        }
Beispiel #24
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");
      }
    }
Beispiel #25
0
        DateTime GetPublishedDate()
        {
            if (_publishedDate == DateTime.MinValue)
            {
                INode subject   = _catalogItem.CreateUriNode(_catalogUri);
                var   pubTriple = _catalogItem.GetTriplesWithSubjectPredicate(subject, _catalogItem.CreateUriNode(Schema.Predicates.Published)).SingleOrDefault();

                if (pubTriple != null)
                {
                    ILiteralNode node = pubTriple.Object as ILiteralNode;

                    if (node != null)
                    {
                        _publishedDate = DateTime.ParseExact(node.Value, "O", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
                    }
                }
            }

            return(_publishedDate);
        }
Beispiel #26
0
        public void NodeCompareToEquivalentLiterals3()
        {
            Graph        g         = new Graph();
            ILiteralNode canonical = (1d).ToLiteral(g);
            ILiteralNode alternate = g.CreateLiteralNode("1.00000", UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeDouble));

            List <INode> ns = new List <INode>()
            {
                canonical,
                alternate
            };

            Assert.NotEqual(canonical, alternate);
            Assert.Equal(0, canonical.CompareTo(alternate));

            this.ShowOrdering(ns);
            this.CheckCombinations(ns);
            this.CheckCombinations <ILiteralNode>(ns.OfType <ILiteralNode>().ToList());
            this.CheckCombinations(ns, new FastNodeComparer());
        }
        public void NodeCompareToEquivalentLiterals2()
        {
            Graph g = new Graph();
            ILiteralNode canonical = (true).ToLiteral(g);
            ILiteralNode alternate = g.CreateLiteralNode("TRUE", UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeBoolean));

            List<INode> ns = new List<INode>()
            {
                canonical,
                alternate                
            };

            Assert.AreNotEqual(canonical, alternate, "Alternate lexical forms should not be equal");
            Assert.AreEqual(0, canonical.CompareTo(alternate), "Comparison should compare alternate lexical forms as equal");

            this.ShowOrdering(ns);
            this.CheckCombinations(ns);
            this.CheckCombinations<ILiteralNode>(ns.OfType<ILiteralNode>().ToList());
            this.CheckCombinations(ns, new FastNodeComparer());
        }
        public virtual void SaveToGraph(VDS.RDF.IGraph target, VDS.RDF.IUriNode provCreatingAction)
        {
            createLocationNode(target);
            //assert that it is a location
            target.Assert(locationNode, UriNodeExt.RdfType(target), target.CreateUriNode(Properties.Settings.Default.Location));
            //assert that it is a tiploc location
            target.Assert(locationNode, UriNodeExt.RdfType(target), target.CreateUriNode(Properties.Settings.Default.TiplocLocation));
            //link to the tiploc code
            ILiteralNode tiplockCodeNode = target.CreateLiteralNode(Tiploc);
            IUriNode     tiplockUriNode  = target.CreateUriNode(Properties.Settings.Default.tiplocCode);

            target.Assert(locationNode, tiplockUriNode, tiplockCodeNode);
            //set the id
            locationNode.IdentifyNode(tiplockCodeNode);
            //lastly, do the prov
            if (provCreatingAction != null)
            {
                locationNode.AssertResponibility(provCreatingAction);
            }
        }
Beispiel #29
0
        public void IndexingNodesInMultiDictionary1()
        {
            Graph        g         = new Graph();
            ILiteralNode canonical = (1).ToLiteral(g);
            ILiteralNode alternate = g.CreateLiteralNode("01", UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeInteger));

            //Use a dud hash function to put everything into a single bucket
            MultiDictionary <INode, int> dictionary = new MultiDictionary <INode, int>(n => 1, false);

            dictionary.Add(canonical, 1);
            Assert.Equal(1, dictionary[canonical]);
            dictionary[alternate] = 2;

            //With everything in a single bucket the keys should be considered
            //equal by the default comparer hence the key count will only be one
            //and retrieving with either 2 gives the value from the second Add()
            Assert.Single(dictionary);
            Assert.Equal(2, dictionary[alternate]);
            Assert.Equal(2, dictionary[canonical]);
        }
Beispiel #30
0
        public void ProcessHeader(System.IO.StreamReader inStream, ref VDS.RDF.IGraph targetGraph, VDS.RDF.IUriNode generationActivity, string fileName)
        {
            string firstLine = inStream.ReadLine();

            if (!firstLine.StartsWith("HD"))//header record type is HD
            {
                throw new ImportFileFormatException(fileName,
                                                    "File must include a header, denoted HD",
                                                    0,
                                                    0
                                                    );
            }
            string   mainframe_id  = firstLine.Substring(2, 20);
            DateTime date_extract  = DateTime.ParseExact(firstLine.Substring(22, 10), dtFormat, ProgramState.Provider);
            string   curr_file_ref = firstLine.Substring(32, 7);
            string   last_file_ref = firstLine.Substring(39, 7);
            // char update_type = firstLine[46];//not going to use this
            DateTime extract_start = DateTime.ParseExact(firstLine.Substring(48, 6), dateFormat, ProgramState.Provider);
            DateTime extract_end   = DateTime.ParseExact(firstLine.Substring(54, 6), dateFormat, ProgramState.Provider);

            //Now put that in the graph
            string   sourceFileUri  = Common.ImportFileUriBaseString + "#" + DateTime.Now.ToString("o") + "SourceFile_" + fileName;
            IUriNode sourceFileNode = targetGraph.CreateUriNode(UriFactory.Create(sourceFileUri));

            targetGraph.Assert(sourceFileNode, UriNodeExt.RdfType(targetGraph), targetGraph.CreateUriNode("prov:Entity"));
            if (generationActivity != null)
            {
                targetGraph.Assert(generationActivity, targetGraph.CreateUriNode(Properties.Settings.Default.provUsed), sourceFileNode);
            }
            ILiteralNode sourceID = targetGraph.CreateLiteralNode(mainframe_id);

            sourceFileNode.IdentifyNode(sourceID);
            //IUriNode idNode = targetGraph.CreateUriNode(Properties.Settings.Default.ID);
            //targetGraph.Assert(sourceFileNode, idNode, sourceID);
            targetGraph.Assert(sourceFileNode, targetGraph.CreateUriNode(UriFactory.Create(Properties.Settings.Default.provGeneratedTime)),
                               targetGraph.CreateLiteralNode(date_extract.ToString(XmlSpecsHelper.XmlSchemaDateTimeFormat), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeDateTime)));
            IUriNode     invalidatedNote = targetGraph.CreateUriNode(Properties.Settings.Default.provInvalidAtTime);
            ILiteralNode timeInvalid     = targetGraph.CreateLiteralNode(extract_end.ToString(XmlSpecsHelper.XmlSchemaDateTimeFormat), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeDateTime));

            targetGraph.Assert(sourceFileNode, invalidatedNote, timeInvalid);
        }
        private ILiteralNode CheckArgument(ISparqlExpression expr, SparqlEvaluationContext context, int bindingID, Func <Uri, bool> argumentTypeValidator)
        {
            INode temp = expr.Evaluate(context, bindingID);

            if (temp != null)
            {
                if (temp.NodeType == NodeType.Literal)
                {
                    ILiteralNode lit = (ILiteralNode)temp;
                    if (lit.DataType != null)
                    {
                        if (argumentTypeValidator(lit.DataType))
                        {
                            // Appropriately typed literals are fine
                            return(lit);
                        }
                        else
                        {
                            throw new RdfQueryException("Unable to evaluate as one of the argument expressions returned a typed literal with an invalid type");
                        }
                    }
                    else if (argumentTypeValidator(UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString)))
                    {
                        // Untyped Literals are treated as Strings and may be returned when the argument allows strings
                        return(lit);
                    }
                    else
                    {
                        throw new RdfQueryException("Unable to evalaute as one of the argument expressions returned an untyped literal");
                    }
                }
                else
                {
                    throw new RdfQueryException("Unable to evaluate as one of the argument expressions returned a non-literal");
                }
            }
            else
            {
                throw new RdfQueryException("Unable to evaluate as one of the argument expressions evaluated to null");
            }
        }
Beispiel #32
0
        public static IGraph CreateGraph()
        {
            IGraph g = new Graph();

            g.BaseUri = new Uri("http://example.org/");

            IUriNode     dotNetRDF    = g.CreateUriNode(UriFactory.Create("http://www.dotnetrdf.org"));
            IUriNode     says         = g.CreateUriNode(UriFactory.Create("http://example.org/says"));
            ILiteralNode helloWorld   = g.CreateLiteralNode("Hello World");
            ILiteralNode bonjourMonde = g.CreateLiteralNode("Bonjour tout le Monde", "fr");

            g.Assert(new Triple(dotNetRDF, says, helloWorld));
            g.Assert(new Triple(dotNetRDF, says, bonjourMonde));

            foreach (Triple t in g.Triples)
            {
                Console.WriteLine(t.ToString());
            }

            return(g);
        }
Beispiel #33
0
        public String SayHello()
        {
            logger.LogFunction("SayHello");
            var   result = "";
            Graph g      = new Graph();

            IUriNode     dotNetRDF    = g.CreateUriNode(UriFactory.Create("http://www.dotnetrdf.org"));
            IUriNode     says         = g.CreateUriNode(UriFactory.Create("http://example.org/says"));
            ILiteralNode helloWorld   = g.CreateLiteralNode("Hello World");
            ILiteralNode bonjourMonde = g.CreateLiteralNode("Bonjour tout le Monde", "fr");

            g.Assert(new Triple(dotNetRDF, says, helloWorld));
            g.Assert(new Triple(dotNetRDF, says, bonjourMonde));

            foreach (Triple t in g.Triples)
            {
                result += t.ToString() + "\n";
            }

            return(result);
        }
Beispiel #34
0
        public ExpansionLinkset(IGraph expansionDescription, INode linksetSubj)
            : base(expansionDescription, linksetSubj)
        {
            this._subject = linksetSubj;

            //Check for aat:ignoreLinkset
            IEnumerable <Triple> ts = expansionDescription.GetTriplesWithSubjectPredicate(linksetSubj, expansionDescription.CreateUriNode("aat:ignoreDataset"));
            Triple t = ts.FirstOrDefault();

            if (t != null)
            {
                if (t.Object.NodeType == NodeType.Literal)
                {
                    ILiteralNode l = (ILiteralNode)t.Object;
                    if (l.DataType != null && l.DataType.ToString().Equals(XmlSpecsHelper.XmlSchemaDataTypeBoolean))
                    {
                        this._ignore = Boolean.Parse(l.Value);
                    }
                }
            }
        }
        DateTime GetPublishedDate()
        {
            if (_publishedDate == DateTime.MinValue)
            {
                INode subject   = _catalogItem.CreateUriNode(_catalogUri);
                var   pubTriple = _catalogItem.GetTriplesWithSubjectPredicate(subject, _catalogItem.CreateUriNode(Schema.Predicates.Published)).SingleOrDefault();

                if (pubTriple != null)
                {
                    ILiteralNode node = pubTriple.Object as ILiteralNode;

                    if (node != null)
                    {
                        _publishedDate = DateTime.Parse(node.Value);
                    }
                }
            }
            _publishedDate = _publishedDate.ToUniversalTime();
            _listed        = (_publishedDate.Year == 1900) ? false : true;
            return(_publishedDate);
        }
Beispiel #36
0
        /// <summary>
        /// Copies a Node using another Node Factory.
        /// </summary>
        /// <param name="original">Node to copy.</param>
        /// <param name="target">Factory 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 Factories is done.
        /// </para>
        /// </remarks>
        public static INode CopyNode(INode original, INodeFactory target)
        {
            if (ReferenceEquals(original.Graph, target))
            {
                return(original);
            }

            switch (original.NodeType)
            {
            case NodeType.Blank:
                return(target.CreateBlankNode(((IBlankNode)original).InternalID));

            case NodeType.GraphLiteral:
                return(target.CreateGraphLiteralNode(((IGraphLiteralNode)original).SubGraph));

            case NodeType.Literal:
                ILiteralNode lit = (ILiteralNode)original;
                if (lit.DataType != null)
                {
                    return(target.CreateLiteralNode(lit.Value, lit.DataType));
                }
                else if (!lit.Language.Equals(String.Empty))
                {
                    return(target.CreateLiteralNode(lit.Value, lit.Language));
                }
                else
                {
                    return(target.CreateLiteralNode(lit.Value));
                }

            case NodeType.Uri:
                return(target.CreateUriNode(((IUriNode)original).Uri));

            case NodeType.Variable:
                return(target.CreateVariableNode(((IVariableNode)original).VariableName));

            default:
                throw new RdfException("Unable to Copy '" + original.GetType().ToString() + "' Nodes between Node Factories");
            }
        }
Beispiel #37
0
 /// <summary>
 /// Gets the Value of the function as applied to the given String Literal and Argument
 /// </summary>
 /// <param name="stringLit">Simple/String typed Literal</param>
 /// <param name="arg">Argument</param>
 /// <returns></returns>
 public override IValuedNode ValueInternal(ILiteralNode stringLit, ILiteralNode arg)
 {
     if (arg.Value.Equals(string.Empty))
     {
         //The substring after the empty string is the input string
         return new StringNode(null, stringLit.Value, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString));
     }
     else
     {
         //Does the String contain the search string?
         if (stringLit.Value.Contains(arg.Value))
         {
             string result = stringLit.Value.Substring(stringLit.Value.IndexOf(arg.Value) + arg.Value.Length);
             return new StringNode(null, result, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString));
         }
         else
         {
             //If it doesn't contain the search string the empty string is returned
             return new StringNode(null, string.Empty, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString));
         }
     }
 }
Beispiel #38
0
        /// <summary>
        /// Determines whether two Literals are equal
        /// </summary>
        /// <param name="a">First Literal</param>
        /// <param name="b">Second Literal</param>
        /// <returns></returns>
        public static bool AreLiteralsEqual(ILiteralNode a, ILiteralNode b)
        {
            if (ReferenceEquals(a, b)) return true;
            if (a == null)
            {
                if (b == null) return true;
                return false;
            }
            else if (b == null)
            {
                return false;
            }

            //Language Tags must be equal (if present)
            //If they don't have language tags then they'll both be set to String.Empty which will give true
            if (a.Language.Equals(b.Language, StringComparison.OrdinalIgnoreCase))
            {
                //Datatypes must be equal (if present)
                //If they don't have Data Types then they'll both be null
                //Otherwise the URIs must be equal
                if (a.DataType == null && b.DataType == null)
                {
                    //Use String equality to get the result
                    return a.Value.Equals(b.Value, StringComparison.Ordinal);
                }
                else if (a.DataType == null)
                {
                    //We have a Null DataType but the other Node doesn't so can't be equal
                    return false;
                }
                else if (b.DataType == null)
                {
                    //The other Node has a Null DataType but we don't so can't be equal
                    return false;
                }
                else if (EqualityHelper.AreUrisEqual(a.DataType, b.DataType))
                {
                    //We have equal DataTypes so use String Equality to evaluate
                    if (Options.LiteralEqualityMode == LiteralEqualityMode.Strict)
                    {
                        //Strict Equality Mode uses Ordinal Lexical Comparison for Equality as per W3C RDF Spec
                        return a.Value.Equals(b.Value, StringComparison.Ordinal);
                    }
                    else
                    {
                        //Loose Equality Mode uses Value Based Comparison for Equality of Typed Nodes
                        return (a.CompareTo(b) == 0);
                    }
                }
                else
                {
                    //Data Types didn't match
                    return false;
                }
            }
            else
            {
                //Language Tags didn't match
                return false;
            }
        }
        static JObject MakeLiteralObject(ILiteralNode node)
        {
            if (node.DataType == null)
            {
                return new JObject { { "@value", node.Value } };
            }
            else
            {
                string dataType = node.DataType.ToString();

                switch (dataType)
                {
                    case "http://www.w3.org/2001/XMLSchema#integer":
                        return new JObject { { "@value", int.Parse(node.Value) } };
                    
                    case "http://www.w3.org/2001/XMLSchema#boolean":
                        return new JObject { { "@value", bool.Parse(node.Value) } };
                    
                    case "http://www.w3.org/2001/XMLSchema#decimal":
                        return new JObject { { "@value", decimal.Parse(node.Value) } };

                    case "http://www.w3.org/2001/XMLSchema#long":
                        return new JObject { { "@value", long.Parse(node.Value) } };

                    case "http://www.w3.org/2001/XMLSchema#short":
                        return new JObject { { "@value", short.Parse(node.Value) } };

                    case "http://www.w3.org/2001/XMLSchema#float":
                        return new JObject { { "@value", float.Parse(node.Value) } };

                    case "http://www.w3.org/2001/XMLSchema#double":
                        return new JObject { { "@value", double.Parse(node.Value) } };

                    default:
                        return new JObject 
                        {
                            { "@value", node.Value },
                            { "@type", dataType }
                        };
                }
            }
        }
Beispiel #40
0
        /// <summary>
        /// Compares two Literal Nodes
        /// </summary>
        /// <param name="a">First Literal Node</param>
        /// <param name="b">Second Literal Node</param>
        /// <returns></returns>
        public static int CompareLiterals(ILiteralNode a, ILiteralNode b)
        {
            if (ReferenceEquals(a, b)) return 0;
            if (a == null)
            {
                if (b == null) return 0;
                return -1;
            }
            else if (b == null)
            {
                return 1;
            }

            //Literal Nodes are ordered based on Type and lexical form
            if (a.DataType == null && b.DataType != null)
            {
                //Untyped Literals are less than Typed Literals
                //Return a -1 to indicate this
                return -1;
            }
            else if (a.DataType != null && b.DataType == null)
            {
                //Typed Literals are greater than Untyped Literals
                //Return a 1 to indicate this
                return 1;
            }
            else if (a.DataType == null && b.DataType == null)
            {
                //If neither are typed use Lexical Ordering on the value
                return a.Value.CompareTo(b.Value);
            }
            else if (EqualityHelper.AreUrisEqual(a.DataType, b.DataType))
            {
                //Are we using a known and orderable DataType?
                String type = a.DataType.ToString();
                if (!XmlSpecsHelper.IsSupportedType(type))
                {
                    //Don't know how to order so use lexical order on the value
                    return a.Value.CompareTo(b.Value);
                }
                else
                {
                    try
                    {
                        switch (type)
                        {
                            case XmlSpecsHelper.XmlSchemaDataTypeBoolean:
                                //Can use Lexical ordering for this
                                return a.Value.ToLower().CompareTo(b.Value.ToLower());

                            case XmlSpecsHelper.XmlSchemaDataTypeByte:
                                //Remember that xsd:byte is actually equivalent to SByte in .Net
                                //Extract the Byte Values and compare
                                sbyte aSByte, bSByte;
                                if (SByte.TryParse(a.Value, out aSByte))
                                {
                                    if (SByte.TryParse(b.Value, out bSByte))
                                    {
                                        return aSByte.CompareTo(bSByte);
                                    }
                                    else
                                    {
                                        return -1;
                                    }
                                }
                                else
                                {
                                    if (SByte.TryParse(b.Value, out bSByte))
                                    {
                                        return 1;
                                    }
                                    else
                                    {
                                        return a.Value.CompareTo(b.Value);
                                    }
                                }

                            case XmlSpecsHelper.XmlSchemaDataTypeUnsignedByte:
                                //Remember that xsd:unsignedByte is equivalent to Byte in .Net
                                //Extract the Byte Values and compare
                                byte aByte, bByte;
                                if (Byte.TryParse(a.Value, out aByte))
                                {
                                    if (Byte.TryParse(b.Value, out bByte))
                                    {
                                        return aByte.CompareTo(bByte);
                                    }
                                    else
                                    {
                                        return -1;
                                    }
                                }
                                else
                                {
                                    if (Byte.TryParse(b.Value, out bByte))
                                    {
                                        return 1;
                                    }
                                    else
                                    {
                                        return a.Value.CompareTo(b.Value);
                                    }
                                }

                            case XmlSpecsHelper.XmlSchemaDataTypeInt:
                            case XmlSpecsHelper.XmlSchemaDataTypeInteger:
                            case XmlSpecsHelper.XmlSchemaDataTypeLong:
                            case XmlSpecsHelper.XmlSchemaDataTypeShort:
                                //Extract the Integer Values and compare
                                long aInt64, bInt64;
                                if (Int64.TryParse(a.Value, out aInt64))
                                {
                                    if (Int64.TryParse(b.Value, out bInt64))
                                    {
                                        return aInt64.CompareTo(bInt64);
                                    }
                                    else
                                    {
                                        return -1;
                                    }
                                }
                                else
                                {
                                    if (Int64.TryParse(b.Value, out bInt64))
                                    {
                                        return 1;
                                    }
                                    else
                                    {
                                        return a.Value.CompareTo(b.Value);
                                    }
                                }

                            case XmlSpecsHelper.XmlSchemaDataTypeNegativeInteger:
                            case XmlSpecsHelper.XmlSchemaDataTypeNonPositiveInteger:
                                //Extract the Integer Values, ensure negative and compare
                                long aNegInt, bNegInt;
                                if (Int64.TryParse(a.Value, out aNegInt))
                                {
                                    if (Int64.TryParse(b.Value, out bNegInt))
                                    {
                                        if (aNegInt >= 0)
                                        {
                                            if (bNegInt >= 0)
                                            {
                                                return a.Value.CompareTo(b.Value);
                                            }
                                            else
                                            {
                                                return 1;
                                            }
                                        }
                                        else if (bNegInt >= 0)
                                        {
                                            return -1;
                                        }
                                        else
                                        {
                                            return aNegInt.CompareTo(bNegInt);
                                        }
                                    }
                                    else if (aNegInt >= 0)
                                    {
                                        return a.Value.CompareTo(b.Value);
                                    }
                                    else
                                    {
                                        return -1;
                                    }
                                }
                                else
                                {
                                    if (Int64.TryParse(b.Value, out bNegInt))
                                    {
                                        if (bNegInt >= 0)
                                        {
                                            return a.Value.CompareTo(b.Value);
                                        }
                                        else
                                        {
                                            return 1;
                                        }
                                    }
                                    else
                                    {
                                        return a.Value.CompareTo(b.Value);
                                    }
                                }

                            case XmlSpecsHelper.XmlSchemaDataTypeUnsignedInt:
                            case XmlSpecsHelper.XmlSchemaDataTypeUnsignedLong:
                            case XmlSpecsHelper.XmlSchemaDataTypeUnsignedShort:
                            case XmlSpecsHelper.XmlSchemaDataTypeNonNegativeInteger:
                            case XmlSpecsHelper.XmlSchemaDataTypePositiveInteger:
                                //Unsigned Integers
                                //Note that for NonNegativeInteger and PositiveInteger we don't need to do the
                                //same checking we have to do for their inverse types since parsing into an 
                                //Unsigned Long ensures that they must be positive
                                ulong aUInt64, bUInt64;
                                if (UInt64.TryParse(a.Value, out aUInt64))
                                {
                                    if (UInt64.TryParse(b.Value, out bUInt64))
                                    {
                                        return aUInt64.CompareTo(bUInt64);
                                    }
                                    else
                                    {
                                        return -1;
                                    }
                                }
                                else
                                {
                                    if (UInt64.TryParse(b.Value, out bUInt64))
                                    {
                                        return 1;
                                    }
                                    else
                                    {
                                        return a.Value.CompareTo(b.Value);
                                    }
                                }

                            case XmlSpecsHelper.XmlSchemaDataTypeDouble:
                                //Extract the Double Values and compare
                                double aDouble, bDouble;
                                if (Double.TryParse(a.Value, out aDouble))
                                {
                                    if (Double.TryParse(b.Value, out bDouble))
                                    {
                                        return aDouble.CompareTo(bDouble);
                                    }
                                    else
                                    {
                                        return -1;
                                    }
                                }
                                else
                                {
                                    if (Double.TryParse(b.Value, out bDouble))
                                    {
                                        return 1;
                                    }
                                    else
                                    {
                                        return a.Value.CompareTo(b.Value);
                                    }
                                }

                            case XmlSpecsHelper.XmlSchemaDataTypeFloat:
                                //Extract the Float Values and compare
                                float aFloat, bFloat;
                                if (Single.TryParse(a.Value, out aFloat))
                                {
                                    if (Single.TryParse(b.Value, out bFloat))
                                    {
                                        return aFloat.CompareTo(bFloat);
                                    }
                                    else
                                    {
                                        return -1;
                                    }
                                }
                                else
                                {
                                    if (Single.TryParse(b.Value, out bFloat))
                                    {
                                        return 1;
                                    }
                                    else
                                    {
                                        return a.Value.CompareTo(b.Value);
                                    }
                                }

                            case XmlSpecsHelper.XmlSchemaDataTypeHexBinary:
                                //Extract the numeric value of the Hex encoded Binary and compare
                                long aHex, bHex;
                                if (Int64.TryParse(a.Value, System.Globalization.NumberStyles.HexNumber, null, out aHex))
                                {
                                    if (Int64.TryParse(b.Value, System.Globalization.NumberStyles.HexNumber, null, out bHex))
                                    {
                                        return aHex.CompareTo(bHex);
                                    }
                                    else
                                    {
                                        return -1;
                                    }
                                }
                                else
                                {
                                    if (Int64.TryParse(b.Value, System.Globalization.NumberStyles.HexNumber, null, out bHex))
                                    {
                                        return 1;
                                    }
                                    else
                                    {
                                        return a.Value.CompareTo(b.Value);
                                    }
                                }

                            case XmlSpecsHelper.XmlSchemaDataTypeBase64Binary:
                                //Extract the numeric value of the Base 64 encoded Binary and compare
                                byte[] aBin, bBin;
                                try
                                {
                                    aBin = Convert.FromBase64String(a.Value);
                                    try
                                    {
                                        bBin = Convert.FromBase64String(b.Value);

                                        if (aBin.Length > bBin.Length)
                                        {
                                            return 1;
                                        }
                                        else if (aBin.Length < bBin.Length)
                                        {
                                            return -1;
                                        }
                                        else
                                        {
                                            for (int i = 0; i < aBin.Length; i++)
                                            {
                                                if (aBin[i] != bBin[i])
                                                {
                                                    return aBin[i].CompareTo(bBin[i]);
                                                }
                                            }
                                            return 0;
                                        }
                                    }
                                    catch
                                    {
                                        return -1;
                                    }
                                }
                                catch
                                {
                                    try
                                    {
                                        bBin = Convert.FromBase64String(b.Value);
                                        return 1;
                                    }
                                    catch
                                    {
                                        return a.Value.CompareTo(b.Value);
                                    }
                                }

                            case XmlSpecsHelper.XmlSchemaDataTypeString:
                                //String Type
                                //Can use Lexical Ordering for this
                                return a.Value.CompareTo(b.Value);

                            case XmlSpecsHelper.XmlSchemaDataTypeAnyUri:
                                //Uri Type
                                //Try and convert to a URI and use lexical ordering
                                Uri aUri, bUri;
                                try
                                {
                                    aUri = new Uri(a.Value);
                                    try
                                    {
                                        bUri = new Uri(b.Value);
                                        return ComparisonHelper.CompareUris(aUri, bUri);
                                    }
                                    catch
                                    {
                                        return -1;
                                    }
                                }
                                catch
                                {
                                    try
                                    {
                                        bUri = new Uri(b.Value);
                                        return 1;
                                    }
                                    catch
                                    {
                                        return a.Value.CompareTo(b.Value);
                                    }
                                }

                            case XmlSpecsHelper.XmlSchemaDataTypeDate:
                            case XmlSpecsHelper.XmlSchemaDataTypeDateTime:
                                //Extract the Date Times and compare
                                DateTimeOffset aDateTimeOffset, bDateTimeOffset;
                                if (DateTimeOffset.TryParse(a.Value, out aDateTimeOffset))
                                {
                                    if (DateTimeOffset.TryParse(b.Value, out bDateTimeOffset))
                                    {
                                        return aDateTimeOffset.CompareTo(bDateTimeOffset);
                                    }
                                    else
                                    {
                                        return -1;
                                    }
                                }
                                else
                                {
                                    if (DateTimeOffset.TryParse(b.Value, out bDateTimeOffset))
                                    {
                                        return 1;
                                    }
                                    else
                                    {
                                        return a.Value.CompareTo(b.Value);
                                    }
                                }

                            default:
                                //Don't know how to order so use lexical order
                                return a.Value.CompareTo(b.Value);
                        }
                    }
                    catch
                    {
                        //There was some error suggesting a non-valid value for a type
                        //e.g. "example"^^xsd:integer
                        //In this case just use Lexical Ordering
                        return a.Value.CompareTo(b.Value);
                    }
                }
            }
            else
            {
                //No way of ordering by value if the Data Types are different
                //Order by Data Type Uri
                //This is required or the Value ordering between types won't occur correctly
                return ComparisonHelper.CompareUris(a.DataType, b.DataType);
            }
        }
        /// <summary>
        /// Formats a Literal Node as a String
        /// </summary>
        /// <param name="l">Literal Node</param>
        /// <param name="segment">Triple Segment</param>
        /// <returns></returns>
        protected override string FormatLiteralNode(ILiteralNode l, TripleSegment? segment)
        {
            StringBuilder output = new StringBuilder();
            String value, qname;
            bool longlit = false, plainlit = false;

            longlit = TurtleSpecsHelper.IsLongLiteral(l.Value);
            plainlit = TurtleSpecsHelper.IsValidPlainLiteral(l.Value, l.DataType);

            if (plainlit)
            {
                if (TurtleSpecsHelper.IsValidDecimal(l.Value) && l.Value.EndsWith("."))
                {
                    //Ensure we strip the trailing dot of any xsd:decimal and add a datatype definition
                    output.Append('"');
                    output.Append(l.Value.Substring(0, l.Value.Length - 1));
                    output.Append("\"^^<");
                    output.Append(this.FormatUri(XmlSpecsHelper.XmlSchemaDataTypeDecimal));
                    output.Append('>');
                }
                else
                {
                    //Otherwise just write out the value
                    output.Append(l.Value);
                }
                //For integers ensure we insert a space after the literal to ensure it can't ever be confused with a decimal
                if (TurtleSpecsHelper.IsValidInteger(l.Value))
                {
                    output.Append(' ');
                }
            }
            else
            {
                output.Append('"');
                if (longlit) output.Append("\"\"");

                value = l.Value;

                bool fullyEscaped = (longlit) ? value.IsFullyEscaped(this._validEscapes, this._longLitMustEscape) : value.IsFullyEscaped(this._validEscapes, this._litMustEscape);

                if (!fullyEscaped)
                {
                    //This first replace escapes all back slashes for good measure
                    value = value.EscapeBackslashes(this._validEscapes);

                    //Then remove null character since it doesn't change the meaning of the Literal
                    value = value.Replace("\0", "");

                    //Don't need all the other escapes for long literals as the characters that would be escaped are permitted in long literals
                    //Need to escape " still
                    value = value.Escape('"');

                    if (!longlit)
                    {
                        //Then if we're not a long literal we'll escape tabs
                        value = value.Replace("\t", "\\t");
                    }
                }
                output.Append(value);
                output.Append('"');
                if (longlit) output.Append("\"\"");

                if (!l.Language.Equals(String.Empty))
                {
                    output.Append('@');
                    output.Append(l.Language.ToLower());
                }
                else if (l.DataType != null)
                {
                    output.Append("^^");
                    if (this._qnameMapper.ReduceToQName(l.DataType.ToString(), out qname))
                    {
                        if (TurtleSpecsHelper.IsValidQName(qname))
                        {
                            output.Append(qname);
                        }
                        else
                        {
                            output.Append('<');
                            output.Append(this.FormatUri(l.DataType));
                            output.Append('>');
                        }
                    }
                    else
                    {
                        output.Append('<');
                        output.Append(this.FormatUri(l.DataType));
                        output.Append('>');
                    }
                }
            }

            return output.ToString();
        }
        /// <summary>
        /// Determines whether the Arguments are valid
        /// </summary>
        /// <param name="stringLit">String Literal</param>
        /// <param name="argLit">Argument Literal</param>
        /// <returns></returns>
        protected bool IsValidArgumentPair(ILiteralNode stringLit, ILiteralNode argLit)
        {
            if (stringLit.DataType != null)
            {
                //If 1st argument has a DataType must be an xsd:string or not valid
                if (!stringLit.DataType.ToString().Equals(XmlSpecsHelper.XmlSchemaDataTypeString)) return false;

                if (argLit.DataType != null)
                {
                    //If 2nd argument also has a DataType must also be an xsd:string or not valid
                    if (!argLit.DataType.ToString().Equals(XmlSpecsHelper.XmlSchemaDataTypeString)) return false;
                    return true;
                }
                else if (argLit.Language.Equals(string.Empty))
                {
                    //If 2nd argument does not have a DataType but 1st does then 2nd argument must have no
                    //Language Tag
                    return true;
                }
                else
                {
                    //2nd argument does not have a DataType but 1st does BUT 2nd has a Language Tag so invalid
                    return false;
                }
            }
            else if (!stringLit.Language.Equals(string.Empty))
            {
                if (argLit.DataType != null)
                {
                    //If 1st argument has a Language Tag and 2nd Argument is typed then must be xsd:string
                    //to be valid
                    return argLit.DataType.ToString().Equals(XmlSpecsHelper.XmlSchemaDataTypeString);
                }
                else if (argLit.Language.Equals(string.Empty) || stringLit.Language.Equals(argLit.Language))
                {
                    //If 1st argument has a Language Tag then 2nd Argument must have same Language Tag
                    //or no Language Tag in order to be valid
                    return true;
                }
                else
                {
                    //Otherwise Invalid
                    return false;
                }
            }
            else
            {
                if (argLit.DataType != null)
                {
                    //If 1st argument is plain literal then 2nd argument must be xsd:string if typed
                    return argLit.DataType.ToString().Equals(XmlSpecsHelper.XmlSchemaDataTypeString);
                }
                else if (argLit.Language.Equals(string.Empty))
                {
                    //If 1st argument is plain literal then 2nd literal cannot have a language tag to be valid
                    return true;
                }
                else
                {
                    //If 1st argument is plain literal and 2nd has language tag then invalid
                    return false;
                }
            }
        }
Beispiel #43
0
        /// <summary>
        /// Formats a Literal Node
        /// </summary>
        /// <param name="l">Literal Node</param>
        /// <param name="segment">Triple Segment</param>
        /// <returns></returns>
        protected override string FormatLiteralNode(ILiteralNode l, TripleSegment? segment)
        {
            StringBuilder output = new StringBuilder();
            String value;

            output.Append('"');
            value = l.Value;

            if (!value.IsFullyEscaped(this._validEscapes, this._litEscapes))
            {
                //This first replace escapes all back slashes for good measure
                value = value.EscapeBackslashes(this._validEscapes);

                //Then these escape characters that can't occur in a NTriples literal
                value = value.Replace("\n", "\\n");
                value = value.Replace("\r", "\\r");
                value = value.Replace("\t", "\\t");
                value = value.Escape('"');

                //Then remove null character since it doesn't change the meaning of the Literal
                value = value.Replace("\0", "");
            }

            foreach (char c in value.ToCharArray())
            {
                output.Append(this.FormatChar(c));
            }
            output.Append('"');

            if (!l.Language.Equals(String.Empty))
            {
                output.Append('@');
                output.Append(l.Language.ToLower());
            }
            else if (l.DataType != null)
            {
                output.Append("^^<");
                foreach (char c in this.FormatUri(l.DataType))
                {
                    output.Append(this.FormatChar(c));
                }
                output.Append('>');
            }

            return output.ToString();
        }
 /// <summary>
 ///   Determines the Length of the given String Literal
 /// </summary>
 /// <param name = "stringLit">String Literal</param>
 /// <returns></returns>
 protected override INode ValueInternal(ILiteralNode stringLit)
 {
     return new LiteralNode(null, stringLit.Value.Length.ToString(),
                            new Uri(XmlSpecsHelper.XmlSchemaDataTypeInteger));
 }
        /// <summary>
        /// Formats a Literal Node
        /// </summary>
        /// <param name="lit">Literal Node</param>
        /// <param name="segment">Triple Segment</param>
        /// <returns></returns>
        protected override string FormatLiteralNode(ILiteralNode lit, TripleSegment? segment)
        {
            StringBuilder output = new StringBuilder();
            if (TurtleSpecsHelper.IsValidPlainLiteral(lit.Value, lit.DataType))
            {
                output.Append(lit.Value);
            }
            else
            {
                String value = lit.Value;

                if (TurtleSpecsHelper.IsLongLiteral(value))
                {
                    value = value.Replace("\n", "\\n");
                    value = value.Replace("\r", "\\r");
                    value = value.Escape('"');
                    value = value.Replace("\t", "\\t");

                    //If there are no wrapper characters then we must escape the deliminator
                    if (value.Contains(this._deliminatorChar))
                    {
                        if (this._literalWrapperChar == null && this._longLiteralWrapperChar == null)
                        {
                            //Replace the deliminator
                            value = value.Replace(new String(new char[] { this._deliminatorChar }), new String(new char[] { this._escapeChar, this._deliminatorChar }));
                        }
                    }

                    //Apply appropriate wrapper characters
                    if (this._longLiteralWrapperChar != null)
                    {
                        output.Append(this._longLiteralWrapperChar + value + this._longLiteralWrapperChar);
                    }
                    else if (this._literalWrapperChar != null)
                    {
                        output.Append(this._literalWrapperChar + value + this._literalWrapperChar);
                    }
                    else
                    {
                        output.Append(value);
                    }
                }
                else
                {
                    //Replace the deliminator
                    value = value.Replace(new String(new char[] { this._deliminatorChar }), new String(new char[] { this._escapeChar, this._deliminatorChar }));

                    //Apply appropriate wrapper characters
                    if (this._literalWrapperChar != null)
                    {
                        output.Append(this._literalWrapperChar + value + this._literalWrapperChar);
                    }
                    else
                    {
                        output.Append(value);
                    }
                }

                if (this._fullLiteralOutput)
                {
                    if (!lit.Language.Equals(String.Empty))
                    {
                        output.Append("@" + lit.Language.ToLower());
                    }
                    else if (lit.DataType != null)
                    {
                        output.Append("^^");
                        if (this._uriStartChar != null) output.Append(this._uriStartChar);
                        if (this._uriEndChar != null)
                        {
                            output.Append(this.FormatUri(lit.DataType));
                            output.Append(this._uriEndChar);
                        }
                        else
                        {
                            output.Append(this.FormatUri(lit.DataType));
                        }
                    }
                }
            }
            return output.ToString();
        }
Beispiel #46
0
 /// <summary>
 /// Converts a Literal Node to a Float
 /// </summary>
 /// <param name="n">Literal Node</param>
 /// <returns></returns>
 public static Single ToFloat(ILiteralNode n)
 {
     if (n.DataType == null) throw new RdfQueryException("Cannot convert an untyped Literal to a Float");
     return Single.Parse(n.Value);
 }
Beispiel #47
0
 /// <summary>
 /// Converts a Literal Node to an Integer
 /// </summary>
 /// <param name="n">Literal Node</param>
 /// <returns></returns>
 public static Int64 ToInteger(ILiteralNode n)
 {
     if (n.DataType == null) throw new RdfQueryException("Cannot convert an untyped Literal to an Integer");
     return Int64.Parse(n.Value);
 }
Beispiel #48
0
 /// <summary>
 /// Converts a Literal Node to a Double
 /// </summary>
 /// <param name="n">Literal Node</param>
 /// <returns></returns>
 public static Double ToDouble(ILiteralNode n)
 {
     if (n.DataType == null) throw new RdfQueryException("Cannot convert an untyped Literal to a Double");
     return Double.Parse(n.Value);
 }
Beispiel #49
0
 /// <summary>
 /// Converts a Literal Node to a Decimal
 /// </summary>
 /// <param name="n">Literal Node</param>
 /// <returns></returns>
 public static Decimal ToDecimal(ILiteralNode n)
 {
     if (n.DataType == null) throw new RdfQueryException("Cannot convert an untyped Literal to a Decimal");
     return Decimal.Parse(n.Value);
 }
Beispiel #50
0
 /// <summary>
 /// Gets the Value of the function as applied to the given String Literal
 /// </summary>
 /// <param name="stringLit">Simple/String typed Literal</param>
 /// <returns></returns>
 protected override IValuedNode ValueInternal(ILiteralNode stringLit)
 {
     return new StringNode(null, stringLit.Value.ToUpper(), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString));
 }
 /// <summary>
 ///   Determines whether the given String Literal starts with the given Argument Literal
 /// </summary>
 /// <param name = "stringLit">String Literal</param>
 /// <param name = "argLit">Argument Literal</param>
 /// <returns></returns>
 protected override bool ValueInternal(ILiteralNode stringLit, ILiteralNode argLit)
 {
     return stringLit.Value.StartsWith(argLit.Value);
 }
 /// <summary>
 ///   Gets the Value of the function as applied to the given String Literal
 /// </summary>
 /// <param name = "stringLit">Simple/String typed Literal</param>
 /// <returns></returns>
 protected override INode ValueInternal(ILiteralNode stringLit)
 {
     return new LiteralNode(null, Uri.EscapeUriString(stringLit.Value));
 }
 /// <summary>
 ///   Gets the Value of the function as applied to the given String Literal and Argument
 /// </summary>
 /// <param name = "stringLit">Simple/String typed Literal</param>
 /// <param name = "arg">Argument</param>
 /// <returns></returns>
 public override INode ValueInternal(ILiteralNode stringLit, ILiteralNode arg)
 {
     if (arg.Value.Equals(String.Empty))
     {
         //The substring before the empty string is the empty string
         return new LiteralNode(null, String.Empty, new Uri(XmlSpecsHelper.XmlSchemaDataTypeString));
     }
     else
     {
         //Does the String contain the search string?
         if (stringLit.Value.Contains(arg.Value))
         {
             String result = stringLit.Value.Substring(0, stringLit.Value.IndexOf(arg.Value));
             return new LiteralNode(null, result, new Uri(XmlSpecsHelper.XmlSchemaDataTypeString));
         }
         else
         {
             //If it doesn't contain the search string the empty string is returned
             return new LiteralNode(null, String.Empty, new Uri(XmlSpecsHelper.XmlSchemaDataTypeString));
         }
     }
 }
 /// <summary>
 ///   Converts the given String Literal to upper case
 /// </summary>
 /// <param name = "stringLit">String Literal</param>
 /// <returns></returns>
 protected override INode ValueInternal(ILiteralNode stringLit)
 {
     return stringLit.DataType != null
                ? new LiteralNode(null, stringLit.Value.ToUpper(), stringLit.DataType)
                : new LiteralNode(null, stringLit.Value.ToUpper(), stringLit.Language);
 }
Beispiel #55
0
 /// <summary>
 /// Converts a Literal Node to a Date Time Offset
 /// </summary>
 /// <param name="n">Literal Node</param>
 /// <returns></returns>
 public static DateTimeOffset ToDateTimeOffset(ILiteralNode n)
 {
     if (n.DataType == null) throw new RdfQueryException("Cannot convert an untyped Literal to a Date Time");
     return DateTimeOffset.Parse(n.Value, null, System.Globalization.DateTimeStyles.AssumeUniversal);
 }
 /// <summary>
 ///   Abstract method that child classes must implement to
 /// </summary>
 /// <param name = "stringLit"></param>
 /// <param name = "argLit"></param>
 /// <returns></returns>
 protected abstract bool ValueInternal(ILiteralNode stringLit, ILiteralNode argLit);
 /// <summary>
 /// Formats a Literal Node using QName compression for the datatype if possible
 /// </summary>
 /// <param name="l">Literal Node</param>
 /// <param name="segment">Triple Segment</param>
 /// <returns></returns>
 protected abstract override string FormatLiteralNode(ILiteralNode l, TripleSegment? segment);
Beispiel #58
0
 /// <summary>
 /// Converts a Literal Node to a Time Span
 /// </summary>
 /// <param name="n">Literal Node</param>
 /// <returns></returns>
 public static TimeSpan ToTimeSpan(ILiteralNode n)
 {
     if (n.DataType == null) throw new RdfQueryException("Cannot convert an untyped Literal to a Time Span");
     return TimeSpan.Parse(n.Value);
 }
Beispiel #59
0
 /// <summary>
 /// Determines whether the String contains the given Argument
 /// </summary>
 /// <param name="stringLit">String Literal</param>
 /// <param name="argLit">Argument Literal</param>
 /// <returns></returns>
 protected override bool ValueInternal(ILiteralNode stringLit, ILiteralNode argLit)
 {
     return stringLit.Value.Contains(argLit.Value);
 }
        /// <summary>
        ///   Determines whether the Arguments are valid
        /// </summary>
        /// <param name = "stringLit">String Literal</param>
        /// <param name = "argLit">Argument Literal</param>
        /// <returns></returns>
        private bool IsValidArgumentPair(ILiteralNode stringLit, ILiteralNode argLit)
        {
            if (stringLit.DataType != null)
            {
                //If 1st argument has a DataType must be an xsd:string or not valid
                if (!stringLit.DataType.ToString().Equals(XmlSpecsHelper.XmlSchemaDataTypeString)) return false;

                if (argLit.DataType != null)
                {
                    //If 2nd argument also has a DataType must also be an xsd:string or not valid
                    if (!argLit.DataType.ToString().Equals(XmlSpecsHelper.XmlSchemaDataTypeString)) return false;
                    return true;
                }
                return argLit.Language.Equals(String.Empty);
            }
            if (!stringLit.Language.Equals(String.Empty))
            {
                if (argLit.DataType != null)
                {
                    //If 1st argument has a Language Tag and 2nd Argument is typed then must be xsd:string
                    //to be valid
                    return argLit.DataType.ToString().Equals(XmlSpecsHelper.XmlSchemaDataTypeString);
                }
                return argLit.Language.Equals(String.Empty) || stringLit.Language.Equals(argLit.Language);
            }
            if (argLit.DataType != null)
            {
                //If 1st argument is plain literal then 2nd argument must be xsd:string if typed
                return argLit.DataType.ToString().Equals(XmlSpecsHelper.XmlSchemaDataTypeString);
            }
            return argLit.Language.Equals(String.Empty);
        }