public static void CreatingPlainLiteralWithWrongLanguageTest()
        {
            //Egyszerű literális rossz nyelvi értékkel
            var plainLiteral = new RDFPlainLiteral("C'est la vie!", "WhatThePepperoni");

            Assert.Equal("", plainLiteral.Language);
        }
        public static void CreatingPlainLiteralWithLanguageTest()
        {
            //Egyszerű literális rendes nyelvi értékkel
            var plainLiteral = new RDFPlainLiteral("C'est la vie!", "FR");

            Assert.Equal("C'est la vie!@FR", plainLiteral.ToString());
        }
        public static void CreatingPlainLiteralWithoutLanguageTest()
        {
            //Egyszerű literális nyelv érték hozzáadás nélkül
            var plainLiteral = new RDFPlainLiteral("C'est la vie!");

            Assert.Equal("", plainLiteral.Language);
        }
        public static void CreatingPlainLiteralWithoutValueTest()
        {
            //Egyszerű literális null alapértékkel
            var plainLiteral = new RDFPlainLiteral(null);

            Assert.Equal("", plainLiteral.Value);
        }
        public static void CreatingPlainLiteralWithValidValueTest()
        {
            //Egyszerű literális "normális" alapértékkel
            var plainLiteral = new RDFPlainLiteral("VIK");

            Assert.Equal("VIK", plainLiteral.Value);
        }
        public void AddQuadrupleLiteral(string contextUri, string subjUri, string predUri, string literalValue)
        {
            RDFContext  context = new RDFContext(contextUri);
            RDFResource subj    = new RDFResource(subjUri);
            RDFResource pred    = new RDFResource(predUri);
            RDFLiteral  lit     = new RDFPlainLiteral(literalValue);

            RDFQuadruple quadruple = new RDFQuadruple(context, subj, pred, lit);

            Store.AddQuadruple(quadruple);
        }
Esempio n. 7
0
        /// <summary>
        /// Parses the current quadruple of the data reader
        /// </summary>
        internal static RDFQuadruple ParseQuadruple(IDataReader fetchedQuadruples)
        {
            if (fetchedQuadruples != null)
            {
                RDFContext  qContext   = new RDFContext(fetchedQuadruples["Context"].ToString());
                RDFResource qSubject   = new RDFResource(fetchedQuadruples["Subject"].ToString());
                RDFResource qPredicate = new RDFResource(fetchedQuadruples["Predicate"].ToString());

                //SPO-flavour quadruple
                if (fetchedQuadruples["TripleFlavor"].ToString().Equals("1"))
                {
                    RDFResource qObject = new RDFResource(fetchedQuadruples["Object"].ToString());
                    return(new RDFQuadruple(qContext, qSubject, qPredicate, qObject));
                }

                //SPL-flavour quadruple
                string literal = fetchedQuadruples["Object"].ToString();

                //PlainLiteral
                int lastIndexOfDatatype = literal.LastIndexOf("^^", StringComparison.OrdinalIgnoreCase);
                int lastIndexOfLanguage = literal.LastIndexOf("@", StringComparison.OrdinalIgnoreCase);
                if (!literal.Contains("^^") ||
                    literal.EndsWith("^^") ||
                    RDFModelUtilities.GetUriFromString(literal.Substring(lastIndexOfDatatype + 2)) == null)
                {
                    RDFPlainLiteral pLit = null;
                    if (RDFNTriples.regexLPL.Match(literal).Success)
                    {
                        string pLitValue = literal.Substring(0, lastIndexOfLanguage);
                        string pLitLang  = literal.Substring(lastIndexOfLanguage + 1);
                        pLit = new RDFPlainLiteral(pLitValue, pLitLang);
                    }
                    else
                    {
                        pLit = new RDFPlainLiteral(literal);
                    }
                    return(new RDFQuadruple(qContext, qSubject, qPredicate, pLit));
                }

                //TypedLiteral
                string tLitValue                = literal.Substring(0, lastIndexOfDatatype);
                string tLitDatatype             = literal.Substring(lastIndexOfDatatype + 2);
                RDFModelEnums.RDFDatatypes dt   = RDFModelUtilities.GetDatatypeFromString(tLitDatatype);
                RDFTypedLiteral            tLit = new RDFTypedLiteral(tLitValue, dt);
                return(new RDFQuadruple(qContext, qSubject, qPredicate, tLit));
            }
            throw new RDFStoreException("Cannot parse quadruple because given \"fetchedQuadruples\" parameter is null.");
        }
Esempio n. 8
0
        /// <summary>
        /// Parses the given string to return an instance of pattern member
        /// </summary>
        internal static RDFPatternMember ParseRDFPatternMember(string pMember)
        {
            if (pMember == null)
            {
                throw new RDFQueryException("Cannot parse pattern member because given \"pMember\" parameter is null.");
            }

            #region Uri
            if (Uri.TryCreate(pMember, UriKind.Absolute, out _))
            {
                return(new RDFResource(pMember));
            }
            #endregion

            #region Plain Literal
            int lastIndexOfDatatype = pMember.LastIndexOf("^^", StringComparison.OrdinalIgnoreCase);
            int lastIndexOfLanguage = pMember.LastIndexOf("@", StringComparison.OrdinalIgnoreCase);
            if (!pMember.Contains("^^") ||
                pMember.EndsWith("^^") ||
                RDFModelUtilities.GetUriFromString(pMember.Substring(lastIndexOfDatatype + 2)) == null)
            {
                RDFPlainLiteral pLit = null;
                if (RDFNTriples.regexLPL.Match(pMember).Success)
                {
                    string pLitVal = pMember.Substring(0, lastIndexOfLanguage);
                    string pLitLng = pMember.Substring(lastIndexOfLanguage + 1);
                    pLit = new RDFPlainLiteral(pLitVal, pLitLng);
                }
                else
                {
                    pLit = new RDFPlainLiteral(pMember);
                }
                return(pLit);
            }
            #endregion

            #region Typed Literal
            string tLitValue                = pMember.Substring(0, lastIndexOfDatatype);
            string tLitDatatype             = pMember.Substring(lastIndexOfDatatype + 2);
            RDFModelEnums.RDFDatatypes dt   = RDFModelUtilities.GetDatatypeFromString(tLitDatatype);
            RDFTypedLiteral            tLit = new RDFTypedLiteral(tLitValue, dt);
            return(tLit);

            #endregion
        }
Esempio n. 9
0
        public static RDFGraph WaltDisneyGraphBuild()
        {
            RDFResource donaldduck = new RDFResource("http://www.waltdisney.com/donald_duck");

            RDFPlainLiteral donaldduck_name = new RDFPlainLiteral("Donald Duck");
            //create typed literal
            // "85"^^xsd:integer
            RDFTypedLiteral mickeymouse_age = new RDFTypedLiteral("85", RDFModelEnums.RDFDatatypes.XSD_INTEGER);
            RDFTypedLiteral donaldduck_age  = new RDFTypedLiteral("85", RDFModelEnums.RDFDatatypes.XSD_INTEGER);


            //create triples
            // "Mickey Mouse is 85 years old"
            RDFTriple mickeymouse_is85yr = new RDFTriple(new RDFResource("http://www.waltdisney.com/mickey_mouse"),
                                                         RDFVocabulary.FOAF.AGE,
                                                         mickeymouse_age);

            // "Donald Duck has English-US name "Donald Duck""
            RDFTriple donaldduck_name_enus_triple = new RDFTriple(donaldduck,
                                                                  RDFVocabulary.FOAF.NAME,
                                                                  donaldduck_name);

            // "Donald Duck is 85 years old"
            RDFTriple donaldduck_is85yr = new RDFTriple(donaldduck,
                                                        RDFVocabulary.FOAF.AGE,
                                                        donaldduck_age);



            List <RDFTriple> triples = new List <RDFTriple> {
                mickeymouse_is85yr, donaldduck_name_enus_triple, donaldduck_is85yr
            };

            RDFGraph waltdisney = new RDFGraph(triples);

            waltdisney.SetContext(new Uri("http://waltdisney.com/"));

            return(waltdisney);
        }
Esempio n. 10
0
        /// <summary>
        /// Deserializes the given N-Quads stream to a memory store.
        /// </summary>
        internal static RDFMemoryStore Deserialize(Stream inputStream)
        {
            Int64 nquadIndex = 0;

            try {
                #region deserialize
                using (StreamReader sr = new StreamReader(inputStream)) {
                    RDFMemoryStore result = new RDFMemoryStore();
                    String         nquad  = String.Empty;
                    String[]       tokens = new String[4];
                    RDFResource    S      = null;
                    RDFResource    P      = null;
                    RDFResource    O      = null;
                    RDFLiteral     L      = null;
                    RDFContext     C      = new RDFContext();
                    while ((nquad = sr.ReadLine()) != null)
                    {
                        nquadIndex++;

                        #region sanitize  & tokenize
                        //Cleanup previous data
                        S         = null;
                        tokens[0] = String.Empty;
                        P         = null;
                        tokens[1] = String.Empty;
                        O         = null;
                        L         = null;
                        tokens[2] = String.Empty;
                        C         = new RDFContext();
                        tokens[3] = String.Empty;

                        //Preliminary sanitizations: clean trailing space-like chars
                        nquad = nquad.Trim(new Char[] { ' ', '\t', '\r', '\n' });

                        //Skip empty or comment lines
                        if (nquad == String.Empty || nquad.StartsWith("#"))
                        {
                            continue;
                        }

                        //Tokenizes the sanitized quad
                        tokens = TokenizeNQuad(nquad);
                        #endregion

                        #region subj
                        String subj = tokens[0].TrimStart(new Char[] { '<' })
                                      .TrimEnd(new   Char[] { '>' })
                                      .Replace("_:", "bnode:");
                        S = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(subj));
                        #endregion

                        #region pred
                        String pred = tokens[1].TrimStart(new Char[] { '<' })
                                      .TrimEnd(new   Char[] { '>' });
                        P = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(pred));
                        #endregion

                        #region object
                        if (tokens[2].StartsWith("<") ||
                            tokens[2].StartsWith("bnode:") ||
                            tokens[2].StartsWith("_:"))
                        {
                            String obj = tokens[2].TrimStart(new Char[] { '<' })
                                         .TrimEnd(new Char[] { '>' })
                                         .Replace("_:", "bnode:")
                                         .Trim(new Char[] { ' ', '\n', '\t', '\r' });
                            O = new RDFResource(RDFModelUtilities.ASCII_To_Unicode(obj));
                        }
                        #endregion

                        #region literal
                        else
                        {
                            #region sanitize
                            tokens[2] = RDFNTriples.regexSqt.Replace(tokens[2], String.Empty);
                            tokens[2] = RDFNTriples.regexEqt.Replace(tokens[2], String.Empty);
                            tokens[2] = tokens[2].Replace("\\\"", "\"")
                                        .Replace("\\n", "\n")
                                        .Replace("\\t", "\t")
                                        .Replace("\\r", "\r");
                            tokens[2] = RDFModelUtilities.ASCII_To_Unicode(tokens[2]);
                            #endregion

                            #region plain literal
                            if (!tokens[2].Contains("^^") ||
                                tokens[2].EndsWith("^^") ||
                                tokens[2].Substring(tokens[2].LastIndexOf("^^", StringComparison.Ordinal) + 2, 1) != "<")
                            {
                                if (RDFNTriples.regexLPL.Match(tokens[2]).Success)
                                {
                                    tokens[2] = tokens[2].Replace("\"@", "@");
                                    String pLitValue = tokens[2].Substring(0, tokens[2].LastIndexOf("@", StringComparison.Ordinal));
                                    String pLitLang  = tokens[2].Substring(tokens[2].LastIndexOf("@", StringComparison.Ordinal) + 1);
                                    L = new RDFPlainLiteral(HttpUtility.HtmlDecode(pLitValue), pLitLang);
                                }
                                else
                                {
                                    L = new RDFPlainLiteral(HttpUtility.HtmlDecode(tokens[2]));
                                }
                            }
                            #endregion

                            #region typed literal
                            else
                            {
                                tokens[2] = tokens[2].Replace("\"^^", "^^");
                                String tLitValue    = tokens[2].Substring(0, tokens[2].LastIndexOf("^^", StringComparison.Ordinal));
                                String tLitDatatype = tokens[2].Substring(tokens[2].LastIndexOf("^^", StringComparison.Ordinal) + 2)
                                                      .TrimStart(new Char[] { '<' })
                                                      .TrimEnd(new   Char[] { '>' });
                                RDFModelEnums.RDFDatatype dt = RDFModelUtilities.GetDatatypeFromString(tLitDatatype);
                                L = new RDFTypedLiteral(HttpUtility.HtmlDecode(tLitValue), dt);
                            }
                            #endregion
                        }
                        #endregion

                        #region context
                        if (!String.IsNullOrEmpty(tokens[3]))
                        {
                            String ctx = tokens[3].TrimStart(new Char[] { '<' })
                                         .TrimEnd(new   Char[] { '>' });

                            Uri ctxUri = null;
                            if (Uri.TryCreate(ctx, UriKind.Absolute, out ctxUri))
                            {
                                C = new RDFContext(RDFModelUtilities.ASCII_To_Unicode(ctxUri.ToString()));
                            }
                            else
                            {
                                throw new RDFModelException("found context '" + ctx + "' which is not a well-formed absolute Uri");
                            }
                        }
                        #endregion

                        #region addquadruple
                        if (O != null)
                        {
                            result.AddQuadruple(new RDFQuadruple(C, S, P, O));
                        }
                        else
                        {
                            result.AddQuadruple(new RDFQuadruple(C, S, P, L));
                        }
                        #endregion
                    }
                    return(result);
                }
                #endregion
            }
            catch (Exception ex) {
                throw new RDFModelException("Cannot deserialize N-Quads (line " + nquadIndex + ") because: " + ex.Message, ex);
            }
        }
Esempio n. 11
0
        private void WorkingWithRdfModels()
        {
            // CREATE RESOURCE
            var donaldduck = new RDFResource("http://www.waltdisney.com/donald_duck");

            // CREATE BLANK RESOURCE
            var disney_group = new RDFResource();

            // CREATE PLAIN LITERAL
            // "Donald Duck"
            var donaldduck_name = new RDFPlainLiteral("Donald Duck");
            // CREATE PLAIN LITERAL WITH LANGUAGE TAG
            // "Donald Duck"@en-US
            var donaldduck_name_enusLiteral = new RDFPlainLiteral("Donald Duck", "en-US");
            // CREATE TYPED LITERAL
            // "85"^^xsd:integer
            var mickeymouse_age = new RDFTypedLiteral("85", RDFModelEnums.RDFDatatypes.XSD_INTEGER);


            // CREATE TRIPLES
            // "Mickey Mouse is 85 years old"
            RDFTriple mickeymouse_is85yr
                = new RDFTriple(
                      new RDFResource("http://www.waltdisney.com/mickey_mouse"),
                      new RDFResource("http://xmlns.com/foaf/0.1/age"),
                      new RDFTypedLiteral("85", RDFModelEnums.RDFDatatypes.XSD_INTEGER));

            // "Donald Duck has english (US) name "Donald Duck""
            RDFTriple donaldduck_name_enus = new RDFTriple(
                new RDFResource("http://www.waltdisney.com/donald_duck"),
                new RDFResource("http://xmlns.com/foaf/0.1/name"),
                new RDFPlainLiteral("Donald Duck", "en-US"));


            // CREATE EMPTY GRAPH
            var another_graph     = new RDFGraph();
            var waltdisney_filled = new RDFGraph();

            // CREATE GRAPH FROM A LIST OF TRIPLES
            var triples = new List <RDFTriple> {
                mickeymouse_is85yr, donaldduck_name_enus
            };
            var waltdisney = new RDFGraph(triples);

            // SET CONTEXT OF A GRAPH
            waltdisney.SetContext(new Uri("http://waltdisney.com/"));

            // GET A DATATABLE FROM A GRAPH
            var waltdisney_table = waltdisney.ToDataTable();
            // GET A GRAPH FROM A DATATABLE
            var waltdisney_newgraph = RDFGraph.FromDataTable(waltdisney_table);

            // ITERATE TRIPLES OF A GRAPH WITH FOREACH
            foreach (var t in waltdisney)
            {
                Console.WriteLine("Triple: " + t);
                Console.WriteLine(" Subject: " + t.Subject);
                Console.WriteLine(" Predicate: " + t.Predicate);
                Console.WriteLine(" Object: " + t.Object);
            }

            // ITERATE TRIPLES OF A GRAPH WITH ENUMERATOR
            var triplesEnum = waltdisney.TriplesEnumerator;

            while (triplesEnum.MoveNext())
            {
                Console.WriteLine("Triple: " + triplesEnum.Current);
                Console.WriteLine(" Subject: " + triplesEnum.Current.Subject);
                Console.WriteLine(" Predicate: " + triplesEnum.Current.Predicate);
                Console.WriteLine(" Object: " + triplesEnum.Current.Object);
            }

            // GET COUNT OF TRIPLES CONTAINED IN A GRAPH
            var triplesCount = waltdisney.TriplesCount;

            // MULTIPLE SELECTIONS
            var multiple_selections_graph =
                waltdisney.SelectTriplesBySubject(new RDFResource("http://www.waltdisney.com/donald_duck"))
                .SelectTriplesByPredicate(new RDFResource("http://xmlns.com/foaf/0.1/name"));

            // SET OPERATIONS
            var set_operations_graph = waltdisney.IntersectWith(waltdisney_filled).UnionWith(another_graph);



            /*
             * var ntriplesFormat = RDFModelEnums.RDFFormats.NTriples;
             * // READ N-TRIPLES FILE
             * var graph = RDFGraph.FromFile(ntriplesFormat, "C:\\file.nt");
             * // READ N-TRIPLES STREAM
             * var graph = RDFGraph.FromStream(ntriplesFormat, inStream);
             * // WRITE N-TRIPLES FILE
             * graph.ToFile(ntriplesFormat, "C:\\newfile.nt");
             * // WRITE N-TRIPLES STREAM
             * graph.ToStream(ntriplesFormat, outStream);
             */

            /*
             * var turtleFormat = RDFModelEnums.RDFFormats.Turtle;
             * // READ TURTLE FILE
             * var graph = RDFGraph.FromFile(turtleFormat, "C:\\file.ttl");
             * // READ TURTLE STREAM
             * var graph = RDFGraph.FromStream(turtleFormat, inStream);
             * // WRITE TURTLE FILE
             * graph.ToFile(turtleFormat, "C:\\newfile.ttl");
             * // WRITE TURTLE STREAM
             * graph.ToStream(turtleFormat, outStream);
             */

            /*
             * var xmlFormat = RDFModelEnums.RDFFormats.RdfXml;
             * // READ RDF/XML FILE
             * var graph = RDFGraph.FromFile(xmlFormat, "C:\\file.rdf");
             * // READ RDF/XML STREAM
             * var graph = RDFGraph.FromStream(xmlFormat, inStream);
             * // WRITE RDF/XML FILE
             * graph.ToFile(xmlFormat, "C:\\newfile.rdf");
             * // WRITE RDF/XML STREAM
             * graph.ToStream(xmlFormat, outStream);
             */

            // CREATE NAMESPACE
            var waltdisney_ns = new RDFNamespace("wd", "http://www.waltdisney.com/");

            // USE NAMESPACE IN RESOURCE CREATION
            var duckburg = new RDFResource(waltdisney_ns + "duckburg");
            var mouseton = new RDFResource(waltdisney_ns + "mouseton");


            RDFNamespaceRegister.AddNamespace(waltdisney_ns);

            // Retrieves a namespace by seeking presence of its prefix (null if not found). Supports prefix.cc
            var ns1 = RDFNamespaceRegister.GetByPrefix("dbpedia", false); //local search
            var ns2 = RDFNamespaceRegister.GetByPrefix("dbpedia", true);  //search prefix.cc service if no result

            // GET DEFAULT NAMESPACE
            var nSpace = RDFNamespaceRegister.DefaultNamespace;

            // SET DEFAULT NAMESPACE
            RDFNamespaceRegister.SetDefaultNamespace(waltdisney_ns); //new graphs will default to this context

            // ITERATE NAMESPACES OF REGISTER WITH FOREACH
            foreach (var ns in RDFNamespaceRegister.Instance)
            {
                Console.WriteLine("Prefix: " + ns.NamespacePrefix);
                Console.WriteLine("Namespace: " + ns.NamespaceUri);
            }

            // ITERATE NAMESPACES OF REGISTER WITH ENUMERATOR
            var nspacesEnum = RDFNamespaceRegister.NamespacesEnumerator;

            while (nspacesEnum.MoveNext())
            {
                Console.WriteLine("Prefix: " + nspacesEnum.Current.NamespacePrefix);
                Console.WriteLine("Namespace: " + nspacesEnum.Current.NamespaceUri);
            }


            // CREATE TRIPLES WITH VOCABULARY FACILITIES
            // "Goofy Goof is 82 years old"
            RDFTriple goofygoof_is82yr = new RDFTriple(
                new RDFResource(new Uri("http://www.waltdisney.com/goofy_goof").ToString()),
                RDFVocabulary.FOAF.AGE,
                new RDFPlainLiteral("82")
                );

            // "Donald Duck knows Goofy Goof"
            RDFTriple donaldduck_knows_goofygoof = new RDFTriple(
                new RDFResource(new Uri("http://www.waltdisney.com/donald_duck").ToString()),
                RDFVocabulary.FOAF.KNOWS,
                new RDFResource(new Uri("http://www.waltdisney.com/goofy_goof").ToString())
                );

            // CREATE TYPED LITERALS
            var myAge      = new RDFTypedLiteral("34", RDFModelEnums.RDFDatatypes.XSD_INT);
            var myDate     = new RDFTypedLiteral("2017-01-07", RDFModelEnums.RDFDatatypes.XSD_DATE);
            var myDateTime = new RDFTypedLiteral("2017-01-07T23:11:05", RDFModelEnums.RDFDatatypes.XSD_DATETIME);
            var myXml      = new RDFTypedLiteral("<book>title</book>", RDFModelEnums.RDFDatatypes.RDF_XMLLITERAL);
            var myLiteral  = new RDFTypedLiteral("generic literal", RDFModelEnums.RDFDatatypes.RDFS_LITERAL);

            /*
             * The given list of items may be incomplete.
             * A container is semantically opened to the possibility of having further elements
             *
             * Alt: unordered semantic, duplicates not allowed;
             * Bag: unordered semantic, duplicates allowed;
             * Seq: ordered semantic, duplicates allowed;
             */

            // CREATE CONTAINER AND ADD ITEMS
            RDFContainer beatles_cont = new RDFContainer(RDFModelEnums.RDFContainerTypes.Bag, RDFModelEnums.RDFItemTypes.Resource);

            beatles_cont.AddItem(new RDFResource("http://beatles.com/ringo_starr"));
            beatles_cont.AddItem(new RDFResource("http://beatles.com/john_lennon"));
            beatles_cont.AddItem(new RDFResource("http://beatles.com/paul_mc_cartney"));
            beatles_cont.AddItem(new RDFResource("http://beatles.com/george_harrison"));

            /*
             * The given list of items may not be incomplete.
             * A collection is semantically closed to the possibility of having further elements
             */

            // CREATE COLLECTION AND ADD ITEMS
            RDFCollection beatles_coll = new RDFCollection(RDFModelEnums.RDFItemTypes.Resource);

            beatles_coll.AddItem(new RDFResource("http://beatles.com/ringo_starr"));
            beatles_coll.AddItem(new RDFResource("http://beatles.com/john_lennon"));
            beatles_coll.AddItem(new RDFResource("http://beatles.com/paul_mc_cartney"));
            beatles_coll.AddItem(new RDFResource("http://beatles.com/george_harrison"));


            // ADD CONTAINER/COLLECTION TO GRAPH
            waltdisney.AddContainer(beatles_cont);
            waltdisney.AddCollection(beatles_coll);



            // REIFY TRIPLE AND MERGE IT INTO A GRAPH
            RDFGraph reifGraph = goofygoof_is82yr.ReifyTriple();

            waltdisney = waltdisney.UnionWith(reifGraph);

            // ASSERT SOMETHING ABOUT REIFIED TRIPLE
            waltdisney.AddTriple(new RDFTriple(
                                     new RDFResource("http://www.wikipedia.com/"),
                                     new RDFResource("http://example.org/verb_state"),
                                     goofygoof_is82yr.ReificationSubject
                                     ));


            var existingGraph = new RDFGraph();


            // REIFY CONTAINER
            existingGraph.AddContainer(beatles_cont);

            existingGraph.AddTriple(new RDFTriple(
                                        new RDFResource("http://www.thebeatles.com/"),
                                        RDFVocabulary.FOAF.GROUP,
                                        beatles_cont.ReificationSubject
                                        ));

            // REIFY COLLECTION
            existingGraph.AddCollection(beatles_coll);

            existingGraph.AddTriple(new RDFTriple(
                                        new RDFResource("http://www.thebeatles.com/"),
                                        RDFVocabulary.FOAF.GROUP,
                                        beatles_coll.ReificationSubject
                                        ));

            // WORKING WITH RDF STORES

            // CREATE CONTEXT FROM STRING
            var wdisney_ctx = new RDFContext("http://www.waltdisney.com/");
            // CREATE CONTEXT FROM URI
            var wdisney_ctx_uri = new RDFContext(new Uri("http://www.waltdisney.com/"));
            // CREATE DEFAULT CONTEXT (DEFAULT NAMESPACE)
            var wdisney_ctx_default = new RDFContext();

            // CREATE QUADRUPLES
            // "From Wikipedia.com: Mickey Mouse is 85 years old"
            RDFQuadruple wk_mickeymouse_is85yr = new RDFQuadruple(
                new RDFContext("http://www.wikipedia.com/"),
                new RDFResource("http://www.waltdisney.com/mickey_mouse"),
                RDFVocabulary.FOAF.AGE,
                new RDFTypedLiteral("85", RDFModelEnums.RDFDatatypes.XSD_INTEGER)
                );

            // "From WaltDisney.com: Mickey Mouse is 85 years old"
            RDFQuadruple wd_mickeymouse_is85yr = new RDFQuadruple(
                new RDFContext("http://www.waltdisney.com/"),
                new RDFResource("http://www.waltdisney.com/mickey_mouse"),
                RDFVocabulary.FOAF.AGE,
                new RDFTypedLiteral("85", RDFModelEnums.RDFDatatypes.XSD_INTEGER)
                );

            // "From Wikipedia.com: Donald Duck has english name "Donald Duck""
            RDFQuadruple wk_donald_duck_name_enus = new RDFQuadruple(
                new RDFContext("http://www.wikipedia.com/"),
                new RDFResource("http://www.waltdisney.com/donald_duck"),
                RDFVocabulary.FOAF.NAME,
                new RDFPlainLiteral("Donald Duck", "en")
                );

            // CREATE EMPTY MEMORY STORE
            var wdStore = new RDFMemoryStore();

            // CREATE MEMORY STORE FROM A LIST OF QUADRUPLES
            var quadruples = new List <RDFQuadruple> {
                wk_mickeymouse_is85yr, wk_mickeymouse_is85yr
            };
            var wdStoreFilled = new RDFMemoryStore();

            foreach (var q in quadruples)
            {
                wdStoreFilled.AddQuadruple(q);
            }

            // GET A DATATABLE FROM A MEMORY STORE (any kind of store can be exported to datatable)
            var wdStore_table = wdStoreFilled.ToDataTable();
            // GET A MEMORY STORE FROM A DATATABLE
            var wdStore_new = RDFMemoryStore.FromDataTable(wdStore_table);


            // ITERATE QUADRUPLES OF A MEMORY STORE WITH FOREACH
            foreach (var q in wdStore)
            {
                Console.WriteLine("Quadruple: " + q);
                Console.WriteLine(" Context: " + q.Context);
                Console.WriteLine(" Subject: " + q.Subject);
                Console.WriteLine(" Predicate: " + q.Predicate);
                Console.WriteLine(" Object: " + q.Object);
            }

            // ITERATE QUADRUPLES OF A MEMORY STORE WITH ENUMERATOR
            var quadruplesEnum = wdStore.QuadruplesEnumerator;

            while (quadruplesEnum.MoveNext())
            {
                Console.WriteLine("Quadruple: " + quadruplesEnum.Current);
                Console.WriteLine(" Context: " + quadruplesEnum.Current.Context);
                Console.WriteLine(" Subject: " + quadruplesEnum.Current.Subject);
                Console.WriteLine(" Predicate: " + quadruplesEnum.Current.Predicate);
                Console.WriteLine(" Object: " + quadruplesEnum.Current.Object);
            }

            var nquadsFormat = RDFStoreEnums.RDFFormats.NQuads;

            // READ N-QUADS FILE
            //var myStore = RDFMemoryStore.FromFile(nquadsFormat, "C:\\file.nq");
            // READ N-QUADS STREAM
            //var myStore = RDFMemoryStore.FromStream(nquadsFormat, inStream);
            // WRITE N-QUADS FILE
            wdStoreFilled.ToFile(nquadsFormat, @"C:\TEMP\newfile.nq");
            // WRITE N-QUADS STREAM
            //myStore.ToStream(nquadsFormat, outStream);


            var trixFormat = RDFStoreEnums.RDFFormats.TriX;

            // READ TRIX FILE
            //var memStore = RDFMemoryStore.FromFile(trixFormat, "C:\\file.trix");
            // READ TRIX STREAM
            //var memStore = RDFMemoryStore.FromStream(trixFormat, inStream);
            // WRITE TRIX FILE
            wdStoreFilled.ToFile(trixFormat, @"C:\TEMP\newfile.trix");
            // WRITE TRIX STREAM
            //myStore.ToStream(trixFormat, outStream);


            // CONNECT TO SQLSERVER STORE WITH CONNECTION STRING
            //var sqlServer = new RDFSQLServerStore(sqlServerConnectionString);


            // CREATE EMPTY FEDERATION
            var fed = new RDFFederation();

            /*
             * // CREATE FEDERATION FROM A LIST OF STORES
             * var stores = new List<RDFStore>{ waltDisneyStore, waltDisneyStoreFilled };
             * var fedFilled = new RDFFederation();
             * foreach(var store in stores)
             * {
             *  fedFilled.AddStore(store);
             * }
             */

            // ITERATE STORES OF A FEDERATION
            foreach (var s in fed)
            {
                Console.WriteLine("Store: " + s);
                Console.WriteLine(" Type: " + s.StoreType);
            }
        }
Esempio n. 12
0
        public static void Test()
        {
            RDFFederation federation = new RDFFederation();

            StoreManager manager = new StoreManager();

            federation.AddStore(manager.Store);

            int storeCount = federation.StoresCount;

            // ITERATE STORES OF A FEDERATION
            foreach (RDFStore store in federation)
            {
                Console.WriteLine("Store: " + store);
                Console.WriteLine(" Type: " + store.StoreType);
            }

            /*
             * Create this graph named "http://www.example.org/graph1"
             *
             * <http://www.example.org/index.html> <http://purl.org/dc/elements/1.1/creator> <http://www.example.org/staffid/85740> .
             * <http://www.example.org/index.html> <http://www.example.org/terms/creation-date> "August 16, 1999" .
             * <http://www.example.org/index.html> <http://purl.org/dc/elements/1.1/language> "en" .
             */

            string contextUri = "http://www.example.org/graph1";
            string subjectUri = "http://www.example.org/index.html";

            RDFContext  context = new RDFContext(contextUri);
            RDFResource subj    = new RDFResource(subjectUri);

            RDFResource pred1 = new RDFResource("http://purl.org/dc/elements/1.1/creator");
            RDFResource obj   = new RDFResource("http://www.example.org/staffid/85740");

            RDFQuadruple quadruple1 = new RDFQuadruple(context, subj, pred1, obj);

            manager.Store.AddQuadruple(quadruple1);


            RDFResource pred2 = new RDFResource("http://www.example.org/terms/creation-date");
            RDFLiteral  lit   = new RDFPlainLiteral("August 16, 1999");

            RDFQuadruple quadruple2 = new RDFQuadruple(context, subj, pred2, lit);

            manager.Store.AddQuadruple(quadruple2);

            manager.AddQuadrupleLiteral(contextUri, subjectUri, "http://purl.org/dc/elements/1.1/language", "en");

            // It is recommended that N-Quads files have the extension ".nq" (all lowercase) on all platforms.
            manager.Store.ToFile(RDFStoreEnums.RDFFormats.NQuads, @"C:\TEMP\index.nq");

            manager.Store.ToFile(RDFStoreEnums.RDFFormats.TriX, @"C:\TEMP\index.trix");

            List <RDFGraph> graphs = manager.Store.ExtractGraphs();

            foreach (RDFGraph graph in graphs)
            {
                graph.ToFile(RDFModelEnums.RDFFormats.NTriples, @"C:\TEMP\graph1.nt");
                graph.ToFile(RDFModelEnums.RDFFormats.RdfXml, @"C:\TEMP\graph1.rdf");
                graph.ToFile(RDFModelEnums.RDFFormats.Turtle, @"C:\TEMP\graph1.ttl");
                graph.ToFile(RDFModelEnums.RDFFormats.TriX, @"C:\TEMP\graph1.trix");
            }

            /*
             *
             * // CREATE VARIABLE
             * RDFVariable x = new RDFVariable("x"); // ?X
             * RDFVariable y = new RDFVariable("y"); // ?Y
             * RDFVariable n = new RDFVariable("n"); // ?N (don’t show in SELECT results)
             *
             * // CREATE PATTERNS
             * RDFResource dogOf = new RDFResource(RDFVocabulary.DC.BASE_URI + "dogOf");
             * RDFPattern y_dogOf_x = new RDFPattern(y, dogOf, x); // TRIPLE PATTERN
             * RDFPattern n_y_dogOf_x = new RDFPattern(n, y, dogOf, x); // QUADRUPLE PATTERN
             *
             * // CREATE EMPTY PATTERN GROUP
             * RDFPatternGroup pg1 = new RDFPatternGroup("PG1");
             *
             * // ADD PATTERNS TO PATTERN GROUP
             * pg1.AddPattern(y_dogOf_x);
             *
             * // CREATE PATTERN GROUP FROM A LIST OF PATTERNS
             * List<RDFPattern> patterns = new List<RDFPattern>() { y_dogOf_x };
             * RDFPatternGroup pg2 = new RDFPatternGroup("PG2", patterns);
             *
             * // ADD FILTERS TO PATTERN GROUP
             * pg1.AddFilter(new RDFSameTermFilter(x, donaldduck));
             * pg1.AddFilter(new RDFLangMatchesFilter(n, "it-IT"));
             * pg1.AddFilter(new RDFComparisonFilter(
             * RDFQueryEnums.RDFComparisonFlavors.LessThan, y, new RDFPlainLiteral("25"))); // ?Y < "25"
             *
             * // CREATE SELECT QUERY
             * RDFSelectQuery selectQuery = new RDFSelectQuery();
             *
             *
             * // ADD PATTERN GROUPS TO QUERY
             * selectQuery.AddPatternGroup(pg1);
             *
             * //y_dogOf_x.Optional();
             * //y_dogOf_x.UnionWithNext();
             *
             * // ADD MODIFIERS TO QUERY
             * selectQuery.AddModifier(new RDFDistinctModifier());
             * selectQuery.AddModifier(new RDFOrderByModifier(x, RDFQueryEnums.RDFOrderByFlavors.DESC));
             * selectQuery.AddModifier(new RDFOrderByModifier(n, RDFQueryEnums.RDFOrderByFlavors.ASC));
             * selectQuery.AddModifier(new RDFLimitModifier(100));
             * selectQuery.AddModifier(new RDFOffsetModifier(25));
             */

            /*
             * // APPLY SELECT QUERY TO GRAPH
             * RDFSelectQueryResult selectQueryResult1 = selectQuery.ApplyToGraph(graph);
             * // APPLY SELECT QUERY TO STORE
             * RDFSelectQueryResult selectQueryResult2 = selectQuery.ApplyToStore(store);
             * // APPLY SELECT QUERY TO FEDERATION
             * RDFSelectQueryResult selectQueryResult3 = selectQuery.ApplyToFederation(federation);
             *
             *
             * // CREATE ASK QUERY
             * RDFAskQuery askQuery = new RDFAskQuery();
             *
             * // APPLY ASK QUERY TO GRAPH
             * RDFAskQueryResult askQueryResult1 = askQuery.ApplyToGraph(graph);
             * // APPLY ASK QUERY TO STORE
             * RDFAskQueryResult askQueryResult2 = askQuery.ApplyToStore(store);
             * // APPLY ASK QUERY TO FEDERATION
             * RDFAskQueryResult askQueryResult3 = askQuery.ApplyToFederation(federation);
             *
             *
             * // CREATE CONSTRUCT QUERY
             * RDFConstructQuery constructQuery = new RDFConstructQuery();
             *
             * // APPLY CONSTRUCT QUERY TO GRAPH
             * RDFConstructQueryResult constructResult1 = constructQuery.ApplyToGraph(graph);
             * // APPLY CONSTRUCT QUERY TO STORE
             * RDFConstructQueryResult constructResult2 = constructQuery.ApplyToStore(store);
             * // APPLY CONSTRUCT QUERY TO FEDERATION
             * RDFConstructQueryResult constructResult3 = constructQuery.ApplyToFederation(federation);
             *
             * // CREATE DESCRIBE QUERY
             * RDFDescribeQuery describeQuery = new RDFDescribeQuery();
             *
             * // APPLY DESCRIBE QUERY TO GRAPH
             * RDFDescribeQueryResult describeQueryResult1 = describeQuery.ApplyToGraph(graph);
             * // APPLY DESCRIBE QUERY TO STORE
             * RDFDescribeQueryResult describeQueryResult2 = describeQuery.ApplyToStore(store);
             * // APPLY DESCRIBE QUERY TO FEDERATION
             * RDFDescribeQueryResult describeQueryResult3 = describeQuery.ApplyToFederation(federation);
             */
        }
Esempio n. 13
0
        //source: http://dadev.cloudapp.net/Datos%20Abiertos/PDF/ReferenceGuide.pdf
        static void Main(string[] args)
        {
            //create resource from string
            RDFResource donaldduck = new RDFResource("http://www.waltdisney.com/donald_duck");

            //create resource from uri
            RDFResource goofygoof = new RDFResource(new Uri("http://www.waltdisney.com/goofy_goof").ToString());

            //create plain literal
            // "Donald Duck"
            RDFPlainLiteral donaldduck_name = new RDFPlainLiteral("Donald Duck");
            //create typed literal
            // "85"^^xsd:integer
            RDFTypedLiteral mickeymouse_age = new RDFTypedLiteral("85", RDFModelEnums.RDFDatatypes.XSD_INTEGER);


            //create triples
            // "Mickey Mouse is 85 years old"
            RDFTriple mickeymouse_is85yr = new RDFTriple(new RDFResource("http://www.waltdisney.com/mickey_mouse"),
                                                         new RDFResource("http://xmlns.com/foaf/0.1/age"),
                                                         mickeymouse_age);

            // "Donald Duck has English-US name "Donald Duck""
            RDFTriple donaldduck_name_enus_triple = new RDFTriple(donaldduck,
                                                                  new RDFResource("http://xmlns.com/foaf/0.1/name"),
                                                                  donaldduck_name);

            // "Goofy Goof is 82 years old"
            RDFTriple goofygoof_is82yr = new RDFTriple(goofygoof,
                                                       RDFVocabulary.FOAF.AGE,
                                                       new RDFPlainLiteral("82"));
            // "Donald Duck knows Goofy Goof"
            RDFTriple donaldduck_knows_goofygoof = new RDFTriple(donaldduck,
                                                                 RDFVocabulary.FOAF.KNOWS,
                                                                 goofygoof);

            //create graph from a list of triples
            List <RDFTriple> triples = new List <RDFTriple>
            {
                mickeymouse_is85yr,
                donaldduck_name_enus_triple,
                goofygoof_is82yr,
                donaldduck_knows_goofygoof
            };
            RDFGraph waltdisney = new RDFGraph(triples);

            //set context of a graph
            waltdisney.SetContext(new Uri("http://waltdisney.com/"));

            //iterate triples of a graph
            foreach (RDFTriple t in waltdisney)
            {
                Console.WriteLine($"Triple: {t}\n");
                Console.WriteLine($"Subject: {t.Subject}");
                Console.WriteLine($"Predicate: {t.Predicate}");
                Console.WriteLine($"Object: {t.Object}");
            }

            //compose multiple selections
            RDFGraph triples_by_subject_and_predicate =
                waltdisney.SelectTriplesBySubject(donaldduck)
                .SelectTriplesByPredicate(new RDFResource("http://xmlns.com/foaf/0.1/name"));

            Console.WriteLine("Number of triples where the subject is Donald Duck and the predicate is foaf:name: " + triples_by_subject_and_predicate.TriplesCount);
            Console.WriteLine();

            //create namespace
            RDFNamespace waltdisney_ns = new RDFNamespace("wd", "http://www.waltdisney.com/");

            //set default namespace
            RDFNamespaceRegister.SetDefaultNamespace(waltdisney_ns); //new graphs will default to this context

            //iterate namespaces
            foreach (RDFNamespace ns in RDFNamespaceRegister.Instance)
            {
                Console.WriteLine($"Prefix: {ns.NamespacePrefix}\n");
                Console.WriteLine($"Namespace: {ns.NamespaceUri}\n");
            }
            Console.ReadKey();
        }