Ejemplo n.º 1
0
        public void SerializeComplexClass()
        {
            object parliamentaryIncumbency = createClassInstance("ParliamentaryIncumbency");

            parliamentaryIncumbency.GetType().GetProperty("Id").SetValue(parliamentaryIncumbency, new Uri("http://example.org/123"));
            parliamentaryIncumbency.GetType().GetProperty("ParliamentaryIncumbencyStartDate").SetValue(parliamentaryIncumbency, (DateTimeOffset?)DateTimeOffset.UtcNow.Date);
            object member = createClassInstance("Member");

            parliamentaryIncumbency.GetType().GetProperty("ParliamentaryIncumbencyHasMember").SetValue(parliamentaryIncumbency, member);
            object contactPoint1 = createClassInstance("ContactPoint");
            object contactPoint2 = createClassInstance("ContactPoint");
            IEnumerable <object> values = new [] { contactPoint1, contactPoint2 }.Select(c => c);
            MethodInfo           castMethodValues = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(contactPoint1.GetType());
            object castValues = castMethodValues.Invoke(values, new object[] { values });

            parliamentaryIncumbency.GetType().GetProperty("ParliamentaryIncumbencyHasContactPoint").SetValue(parliamentaryIncumbency, castValues);
            member.GetType().GetProperty("Id").SetValue(member, new Uri("http://example.org/member"));
            member.GetType().GetProperty("PersonFamilyName").SetValue(member, "name");
            contactPoint1.GetType().GetProperty("Id").SetValue(contactPoint1, new Uri("http://example.org/contact1"));
            contactPoint1.GetType().GetProperty("FaxNumber").SetValue(contactPoint1, "fax1");
            contactPoint2.GetType().GetProperty("Id").SetValue(contactPoint2, new Uri("http://example.org/contact2"));
            contactPoint2.GetType().GetProperty("FaxNumber").SetValue(contactPoint2, "fax2");

            RdfSerializer serializer = new RdfSerializer();
            Graph         result     = serializer.Serialize(new BaseResource[] { parliamentaryIncumbency as BaseResource }, compilerResults.CompiledAssembly.GetTypes(), SerializerOptions.ExcludeRdfType);

            Assert.AreEqual(result.Triples.Count, 7);
        }
Ejemplo n.º 2
0
        public ActionResult GraphML(int id)
        {
            List <RouteItem> routes = getAllRoutes(id);

            // Using Parliament nuget packages, map user-defined classes into ontology-aligned interfaces which all implement iResource interface
            // This allows us to work with IGraph objects
            IEnumerable <ProcedureRoute> IRoutes = routes.Select(r => r.GiveMeMappedObject());

            RdfSerializer serializer = new RdfSerializer();
            IGraph        graph      = serializer.Serialize(IRoutes, typeof(ProcedureRoute).Assembly.GetTypes());

            SparqlQueryParser parser = new SparqlQueryParser();
            // Nodes
            SparqlQuery     q1    = parser.ParseFromString("PREFIX : <https://id.parliament.uk/schema/> SELECT ?step ?stepName WHERE {?step a :ProcedureStep; :procedureStepName ?stepName. }");
            SparqlResultSet nodes = (SparqlResultSet)graph.ExecuteQuery(q1);

            // Edges
            SparqlQuery     q2    = parser.ParseFromString("PREFIX : <https://id.parliament.uk/schema/> SELECT ?route ?fromStep ?toStep WHERE {?route a :ProcedureRoute; :procedureRouteIsFromProcedureStep ?fromStep; :procedureRouteIsToProcedureStep ?toStep.}");
            SparqlResultSet edges = (SparqlResultSet)graph.ExecuteQuery(q2);

            // Create GraphML
            StringWriter      sw  = new Utf8StringWriter();
            XmlWriterSettings xws = new XmlWriterSettings();

            xws.OmitXmlDeclaration = false;
            xws.Indent             = true;

            using (XmlWriter xw = XmlWriter.Create(sw, xws))
            {
                XNamespace ns  = "http://graphml.graphdrawing.org/xmlns";
                XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
                XNamespace xsiSchemaLocation = "http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd";
                // For yEd, not essential to GraphML. But good for verification
                XNamespace y = "http://www.yworks.com/xml/graphml";

                XDocument doc = new XDocument(
                    new XDeclaration("1.0", "UTF-8", "yes"),
                    new XElement(ns + "graphml",
                                 new XAttribute(XNamespace.Xmlns + "xsi", xsi),
                                 new XAttribute(xsi + "schemaLocation", xsiSchemaLocation),
                                 new XAttribute(XNamespace.Xmlns + "y", y),
                                 new XElement(ns + "key", new XAttribute("for", "node"), new XAttribute("id", "d0"), new XAttribute("yfiles.type", "nodegraphics")),
                                 new XElement(ns + "graph", new XAttribute("id", "G"), new XAttribute("edgedefault", "directed"),
                                              nodes.Select(n => new XElement(ns + "node", new XAttribute("id", n["step"]), new XElement(ns + "data", new XAttribute("name", n["stepName"]), new XAttribute("key", "d0"), new XElement(y + "ShapeNode", new XElement(y + "NodeLabel", new XAttribute("visible", "true"), new XAttribute("autoSizePolicy", "content"), new XText(n["stepName"].ToString())))))),
                                              edges.Select(e => new XElement(ns + "edge", new XAttribute("id", e["route"]), new XAttribute("source", e["fromStep"]), new XAttribute("target", e["toStep"])))
                                              )));
                doc.WriteTo(xw);
            }

            return(Content(sw.ToString(), "application/xml"));
        }
Ejemplo n.º 3
0
        public void SerializeSimpleClass()
        {
            string houseName = "test house";
            object house     = createClassInstance("House");

            house.GetType().GetProperty("Id").SetValue(house, new Uri("http://example.org/123"));
            house.GetType().GetProperty("HouseName").SetValue(house, houseName);

            RdfSerializer serializer = new RdfSerializer();
            Graph         result     = serializer.Serialize(new BaseResource[] { house as BaseResource }, compilerResults.CompiledAssembly.GetTypes(), SerializerOptions.ExcludeRdfType);

            Assert.AreEqual(result.Triples.Count, 1);
            Assert.AreEqual(result.Triples.SingleOrDefault().Object.ToString(), houseName);
        }
Ejemplo n.º 4
0
        private IEnumerable <BaseResource> deserializeTarget(IGraph target)
        {
            IEnumerable <BaseResource> result = null;

            try
            {
                logger.Verbose("Deserialize target");
                RdfSerializer serializer = new RdfSerializer();
                result = serializer.Deserialize(target, modelTypes, new Uri(schemaNamespace));
            }
            catch (Exception e)
            {
                logger.Exception(e);
            }
            return(result);
        }
Ejemplo n.º 5
0
        public static object Execute(ODataQueryOptions options, string sparqlEndpoint, string nameSpace)
        {
            Uri    NamespaceUri = new Uri(nameSpace);
            string queryString  = new SparqlBuilder(options, NamespaceUri).BuildSparql();
            IGraph graph        = null;

            using (var connector = new SparqlConnector(new Uri(sparqlEndpoint)))
            {
                graph = connector.Query(queryString) as IGraph;
            }

            RdfSerializer serializer = new RdfSerializer();
            IEnumerable <BaseResource> ontologyInstances = serializer.Deserialize(graph, typeof(Person).Assembly, NamespaceUri);

            return(ontologyInstances);
        }
Ejemplo n.º 6
0
        private IGraph serializeSource(BaseResource[] source)
        {
            Graph result = null;

            try
            {
                logger.Verbose("Serializing source");
                RdfSerializer serializer = new RdfSerializer();
                result = serializer.Serialize(source, modelTypes, SerializerOptions.ExcludeRdfType);
                result.NamespaceMap.AddNamespace("parl", new Uri(schemaNamespace));
            }
            catch (Exception e)
            {
                logger.Exception(e);
            }
            return(result);
        }
Ejemplo n.º 7
0
        public static object Execute(ODataQueryOptions options, string sparqlEndpoint, string nameSpace)
        {
            Uri    namespaceUri = new Uri(nameSpace);
            string queryString  = new SparqlBuilder(options, namespaceUri).BuildSparql();

            if (options.Count != null && options.Count.Value)
            {
                string selectStr;
                var    entitySeg = options.Context.Path.Segments.Last() as EntitySetSegment;;
                if (entitySeg != null)
                {
                    selectStr = $" SELECT (count(?{entitySeg.EntitySet.Name}) as ?count) ";
                }
                else
                {
                    var seg = options.Context.Path.Segments.Last() as NavigationPropertySegment;
                    selectStr = $" SELECT (count(?{seg.NavigationProperty.Name}) as ?count) ";
                }
                queryString = queryString.Substring(0, queryString.IndexOf("CONSTRUCT")) +
                              selectStr + queryString.Substring(queryString.IndexOf("WHERE"));

                string count = null;
                using (var connector = new SparqlConnector(new Uri(sparqlEndpoint)))
                {
                    var results = connector.Query(queryString) as SparqlResultSet;
                    foreach (var result in results)
                    {
                        count = (result["count"] as LiteralNode).Value;
                    }
                }
                return(count);
            }
            else
            {
                IGraph graph = null;
                using (var connector = new SparqlConnector(new Uri(sparqlEndpoint)))
                {
                    graph = connector.Query(queryString) as IGraph;
                }

                RdfSerializer serializer = new RdfSerializer();
                IEnumerable <BaseResource> ontologyInstances = serializer.Deserialize(graph, typeof(Person).Assembly, namespaceUri);

                return(ontologyInstances);
            }
        }
Ejemplo n.º 8
0
        public void SerializeComplexClassWithTwoOccurancesOfTheSameInstance()
        {
            object procedureRoute = createClassInstance("ProcedureRoute");

            procedureRoute.GetType().GetProperty("Id").SetValue(procedureRoute, new Uri("http://example.org/123"));
            object procedure = createClassInstance("Procedure");

            procedure.GetType().GetProperty("Id").SetValue(procedure, new Uri("http://example.org/procedure"));
            IEnumerable <object> valuesProcedure = new[] { procedure }.Select(c => c);
            MethodInfo           castMethodValuesProcedure = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(procedure.GetType());
            object castValuesProcedure = castMethodValuesProcedure.Invoke(valuesProcedure, new object[] { valuesProcedure });

            procedureRoute.GetType().GetProperty("ProcedureRouteHasProcedure").SetValue(procedureRoute, castValuesProcedure);
            object fromStep = createClassInstance("ProcedureStep");
            object toStep = createClassInstance("ProcedureStep");
            IEnumerable <object> valuesFrom = new[] { fromStep }.Select(c => c);
            MethodInfo           castMethodValuesFrom = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(fromStep.GetType());
            object castValuesFrom = castMethodValuesFrom.Invoke(valuesFrom, new object[] { valuesFrom });
            IEnumerable <object> valuesTo = new[] { toStep }.Select(c => c);
            MethodInfo           castMethodValuesTo = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(toStep.GetType());
            object castValuesTo                     = castMethodValuesTo.Invoke(valuesTo, new object[] { valuesTo });

            procedureRoute.GetType().GetProperty("ProcedureRouteIsFromProcedureStep").SetValue(procedureRoute, castValuesFrom);
            procedureRoute.GetType().GetProperty("ProcedureRouteIsToProcedureStep").SetValue(procedureRoute, castValuesTo);
            fromStep.GetType().GetProperty("Id").SetValue(fromStep, new Uri("http://example.org/step"));
            toStep.GetType().GetProperty("Id").SetValue(toStep, new Uri("http://example.org/step"));
            object precludedProcedureRoute = createClassInstance("PrecludedProcedureRoute");

            precludedProcedureRoute.GetType().GetProperty("Id").SetValue(precludedProcedureRoute, new Uri("http://example.org/123"));
            IEnumerable <object> valuesPrecluded = new[] { precludedProcedureRoute }.Select(c => c);
            MethodInfo           castMethodValuesPrecluded = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(precludedProcedureRoute.GetType());
            object castValuesPrecluded = castMethodValuesPrecluded.Invoke(valuesTo, new object[] { valuesPrecluded });

            fromStep.GetType().GetProperty("ProcedureStepPrecludesPrecludedProcedureRoute").SetValue(fromStep, castValuesPrecluded);
            RdfSerializer serializer = new RdfSerializer();
            Graph         result     = serializer.Serialize(new BaseResource[] { procedureRoute as BaseResource }, compilerResults.CompiledAssembly.GetTypes(), SerializerOptions.ExcludeRdfType);

            Assert.AreEqual(result.Triples.Count, 4);
        }