Exemple #1
0
        public override void onGet(object sender, HttpEventArgs e)
        {
            HttpListenerRequest  request  = e.request;
            HttpListenerResponse response = e.response;

            System.IO.StringWriter stringWriter = new System.IO.StringWriter();
            string valueAsString = "";

            if (request.AcceptTypes.Contains("application/xml"))
            {
                xmlSerializer.Serialize(stringWriter, _value);
                valueAsString        = stringWriter.ToString();
                response.ContentType = "application/xml";
            }
            else if (request.AcceptTypes.Contains("application/json"))
            {
                valueAsString        = JsonConvert.SerializeObject(_value);
                response.ContentType = "application/json";
            }
            else if (request.AcceptTypes.Contains("text/turtle"))
            {
                CompressingTurtleWriter ttlWriter = new CompressingTurtleWriter();
                ttlWriter.Save(RDFGraph, stringWriter);
                valueAsString        = stringWriter.ToString();
                response.ContentType = "text/turtle";
            }
            response.OutputStream.Write(Encoding.UTF8.GetBytes(valueAsString), 0, valueAsString.Length);
            response.Close();
        }
        // Save RDF content to file as turtle
        public static void SaveToFileTurtle(Graph g, String fileName)
        {
            CompressingTurtleWriter turtleWriter = new CompressingTurtleWriter();

            turtleWriter.CompressionLevel = 1;
            turtleWriter.Save(g, fileName);
        }
Exemple #3
0
        public void RunVocab(String[] args)
        {
            if (args.Length < 2)
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: 2 Arguments are required in order to use the -vocab mode");
                return;
            }

            if (File.Exists(args[1]))
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: Cannot output the configuration vocabulary to " + args[1] + " as a file already exists at that location");
                return;
            }

            TurtleParser ttlparser = new TurtleParser();
            StreamReader reader    = new StreamReader(Assembly.GetAssembly(typeof(IGraph)).GetManifestResourceStream("VDS.RDF.Configuration.configuration.ttl"));
            Graph        g         = new Graph();

            ttlparser.Load(g, reader);

            IRdfWriter writer;

            try
            {
                writer = MimeTypesHelper.GetWriterByFileExtension(MimeTypesHelper.GetTrueFileExtension(args[1]));
            }
            catch (RdfWriterSelectionException)
            {
                writer = new CompressingTurtleWriter(WriterCompressionLevel.High);
            }
            writer.Save(g, args[1]);
            Console.WriteLine("rdfWebDeploy: Configuration Vocabulary output to " + args[1]);
        }
Exemple #4
0
        private INode AddConnection(IGraph config, IStorageProvider manager, String persistentFile)
        {
            if (config == null)
            {
                return(null);
            }

            ConfigurationSerializationContext context = new ConfigurationSerializationContext(config);

            if (manager is IConfigurationSerializable)
            {
                INode objNode = context.Graph.CreateUriNode(new Uri("dotnetrdf:storemanager:" + DateTime.Now.ToString("yyyyMMddhhmmss")));
                context.NextSubject = objNode;
                ((IConfigurationSerializable)manager).SerializeConfiguration(context);

                if (persistentFile != null)
                {
                    try
                    {
                        //Persist the graph to disk
                        CompressingTurtleWriter ttlwriter = new CompressingTurtleWriter();
                        ttlwriter.Save(config, persistentFile);
                    }
                    catch
                    {
                        MessageBox.Show("Unable to persist a Connections File to disk", "Internal Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }

                return(objNode);
            }

            return(null);
        }
        public static void SaveToTurtleFile(this IGraph graph, string filepath)
        {
            var writer = new CompressingTurtleWriter {
                CompressionLevel = WriterCompressionLevel.High
            };

            writer.Save(graph, filepath);
        }
Exemple #6
0
            private object SerializeGraph()
            {
                var        writer     = new CompressingTurtleWriter();
                TextWriter textWriter = new StringWriter();

                writer.Save(_graph, textWriter);
                return(textWriter.ToString());
            }
Exemple #7
0
        static void Dump(IGraph graph)
        {
            CompressingTurtleWriter turtleWriter = new CompressingTurtleWriter();

            turtleWriter.DefaultNamespaces.AddNamespace("nuget", new Uri("http://nuget.org/schema#"));
            turtleWriter.PrettyPrintMode  = true;
            turtleWriter.CompressionLevel = 10;
            turtleWriter.Save(graph, Console.Out);
        }
        private string ConvertGraphToString(IGraph graph)
        {
            var turtleWriter = new CompressingTurtleWriter();
            var sw           = new System.IO.StringWriter();

            turtleWriter.Save(graph, sw);
            var data = sw.ToString();

            return(data);
        }
Exemple #9
0
        public void Remove()
        {
            this._g.Retract(this._g.GetTriplesWithSubject(this._objNode));

            if (this._file != null)
            {
                CompressingTurtleWriter ttlwriter = new CompressingTurtleWriter();
                ttlwriter.Save(this._g, this._file);
            }
        }
        private static void SerializeTriples(IGraph graph, Stream target)
        {
            using (var writer = new StreamWriter(target, Encoding.UTF8, 4096, true))
            {
                var serializer = new CompressingTurtleWriter();
                serializer.Save(graph, writer);
            }

            target.Seek(0, SeekOrigin.Begin);
        }
        public static void Dump(IGraph graph, TextWriter writer)
        {
            CompressingTurtleWriter turtleWriter = new CompressingTurtleWriter();

            turtleWriter.DefaultNamespaces.AddNamespace("nuget", new Uri("http://nuget.org/schema#"));
            turtleWriter.DefaultNamespaces.AddNamespace("catalog", new Uri("http://nuget.org/catalog#"));
            turtleWriter.PrettyPrintMode  = true;
            turtleWriter.CompressionLevel = 10;
            turtleWriter.Save(graph, writer);
        }
        static void Main(string[] args)
        {
            string path = @"..\..\..\..\..\src\MakeMetadata\MakeMetadata\nuspec2package.xslt";

            XslCompiledTransform transform = CreateTransform(path);

            string baseAddress = "http://tempuri.org/base/";

            XsltArgumentList arguments = new XsltArgumentList();

            arguments.AddParam("base", "", baseAddress);

            //foreach (KeyValuePair<string, string> arg in transformArgs)
            //{
            //    arguments.AddParam(arg.Key, "", arg.Value);
            //}

            XDocument nuspec = XDocument.Load(new StreamReader(@"c:\data\extended\ledzep.boxset.v1.nuspec"));

            XDocument rdfxml = new XDocument();

            using (XmlWriter writer = rdfxml.CreateWriter())
            {
                transform.Transform(nuspec.CreateReader(), arguments, writer);
            }

            Console.WriteLine(rdfxml);

            Console.WriteLine();

            RdfXmlParser rdfXmlParser = new RdfXmlParser();
            XmlDocument  doc          = new XmlDocument();

            doc.Load(rdfxml.CreateReader());
            IGraph graph = new Graph();

            rdfXmlParser.Load(graph, doc);

            string subject = graph.GetTriplesWithPredicateObject(
                graph.CreateUriNode(new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")),
                graph.CreateUriNode(new Uri("http://nuget.org/schema#Package")))
                             .First()
                             .Subject
                             .ToString();

            CompressingTurtleWriter turtleWriter = new CompressingTurtleWriter();

            turtleWriter.DefaultNamespaces.AddNamespace("nuget", new Uri("http://nuget.org/schema#"));
            turtleWriter.DefaultNamespaces.AddNamespace("package", new Uri(subject + "#"));

            turtleWriter.PrettyPrintMode  = true;
            turtleWriter.CompressionLevel = 10;
            turtleWriter.Save(graph, Console.Out);
        }
Exemple #13
0
        public override void onOptions(object sender, HttpEventArgs e)
        {
            writer.Save(SubscriptionDescription, sw);
            string graphAsString = sw.ToString();

            e.response.StatusCode = 200;
            e.response.OutputStream.Write(Encoding.UTF8.GetBytes(graphAsString), 0, graphAsString.Length);
            e.response.ContentType = "text/turtle";
            e.response.OutputStream.Flush();
            e.response.OutputStream.Close();
        }
Exemple #14
0
        //protected virtual Uri CreateIndexEntry(CatalogItem item, Uri resourceUri, Guid commitId, DateTime commitTimeStamp)
        //{
        //    Uri tmpUri = GetTempUri("catalogindexpage", "ttl");

        //    using (IGraph pageContent = item.CreatePageContent(Context))
        //    {
        //        AddCatalogEntryData(pageContent, item.GetItemType(), resourceUri, commitId, commitTimeStamp);

        //        SaveGraph(pageContent, tmpUri).Wait();
        //    }

        //    return tmpUri;
        //}

        private async Task SaveGraph(IGraph graph, Uri uri)
        {
            StringBuilder sb = new StringBuilder();

            using (var stringWriter = new System.IO.StringWriter(sb))
            {
                CompressingTurtleWriter turtleWriter = new CompressingTurtleWriter();
                turtleWriter.Save(graph, stringWriter);
            }

            StorageContent content = new StringStorageContent(sb.ToString(), "application/json", "no-store");

            await Storage.Save(uri, content);
        }
Exemple #15
0
        protected override void onGet(object sender, HttpEventArgs e)
        {
            HttpListenerRequest  request  = e.request;
            HttpListenerResponse response = e.response;

            System.IO.StringWriter  stringWriter = new System.IO.StringWriter();
            CompressingTurtleWriter ttlWriter    = new CompressingTurtleWriter();

            ttlWriter.Save(RDFGraph, stringWriter);
            string graph = stringWriter.ToString();

            response.OutputStream.Write(Encoding.UTF8.GetBytes(graph), 0, graph.Length);
            response.Close();
        }
        public async Task <Stream> DownloadGraph(Uri graphName)
        {
            Guard.IsValidUri(graphName);

            var result                 = _graphManagementRepo.GetGraph(graphName);
            var stringAsStream         = new MemoryStream();
            var StreamWriter           = new StreamWriter(stringAsStream);
            CompressingTurtleWriter tw = new CompressingTurtleWriter();

            tw.Save(result, StreamWriter, true);
            StreamWriter.Flush();
            stringAsStream.Position = 0;

            return(stringAsStream);
        }
Exemple #17
0
 private void buildResponse(int statusCode, HttpListenerContext context, IGraph responseGraph)
 {
     context.Response.StatusCode = statusCode;
     try
     {
         CompressingTurtleWriter writer         = new CompressingTurtleWriter();
         StreamWriter            responseWriter = new StreamWriter(context.Response.OutputStream);
         writer.Save(responseGraph, responseWriter);
     }
     catch (Exception ex)
     {
         Log.Error(ex, "Could not write to Response output: " + ex.Message);
     }
     finally
     {
         context.Response.OutputStream.Close();
     }
 }
Exemple #18
0
        /// <summary>
        /// https://github.com/dotnetrdf/dotnetrdf/wiki/UserGuide-Hello-World
        /// </summary>
        public void PlayWithHelloWorld()
        {
            IGraph g = CreateGraph();

            // Console.ReadLine();

            NTriplesWriter ntwriter = new NTriplesWriter();

            ntwriter.Save(g, "HelloWorld.nt");

            RdfXmlWriter rdfxmlwriter = new RdfXmlWriter();

            rdfxmlwriter.Save(g, "HelloWorld.rdf");

            CompressingTurtleWriter turtleWriter = new CompressingTurtleWriter();

            turtleWriter.Save(g, "HelloWorld.ttl");
        }
Exemple #19
0
        public void AddRecentConnection(IStorageProvider manager)
        {
            INode objNode = this.AddConnection(this._recentConnections, manager, this._recentConnectionsFile);

            if (objNode != null)
            {
                this.AddConnectionToMenu(manager, this._recentConnections, objNode, this.mnuRecentConnections, this._recentConnectionsFile, false);
            }

            //Check the number of Recent Connections and delete the Oldest if more than 9
            INode        rdfType         = this._recentConnections.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfType));
            INode        storageProvider = this._recentConnections.CreateUriNode(UriFactory.Create(ConfigurationLoader.ClassStorageProvider));
            List <INode> conns           = (from t in
                                            this._recentConnections.GetTriplesWithPredicateObject(rdfType, storageProvider)
                                            select t.Subject).ToList();

            if (conns.Count > MaxRecentConnections)
            {
                conns.Sort();
                conns.Reverse();

                conns.RemoveRange(0, MaxRecentConnections);

                //Remember the ToList() on the retract otherwise we'll hit an error
                foreach (INode obj in conns)
                {
                    this._recentConnections.Retract(this._recentConnections.GetTriplesWithSubject(obj).ToList());
                    this.RemoveFromConnectionsMenu(this.mnuRecentConnections, obj);
                }

                try
                {
                    //Persist the graph to disk
                    CompressingTurtleWriter ttlwriter = new CompressingTurtleWriter();
                    ttlwriter.Save(this._recentConnections, this._recentConnectionsFile);
                }
                catch
                {
                    MessageBox.Show("Unable to persist a Connections File to disk", "Internal Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
Exemple #20
0
        public void AddRecentConnection(IGenericIOManager manager)
        {
            INode objNode = this.AddConnection(this._recentConnections, manager, this._recentConnectionsFile);

            if (objNode != null)
            {
                ToolStripMenuItem item = new ToolStripMenuItem();
                item.Text   = manager.ToString();
                item.Tag    = new QuickConnect(this._recentConnections, objNode);
                item.Click += new EventHandler(QuickConnectClick);
                this.mnuRecentConnections.DropDownItems.Add(item);
            }

            //Check the number of Recent Connections and delete the Oldest if more than 9
            List <INode> conns = this._recentConnections.GetTriplesWithPredicateObject(this._recentConnections.CreateUriNode(new Uri(RdfSpecsHelper.RdfType)), this._recentConnections.CreateUriNode(new Uri(ConfigurationLoader.ConfigurationNamespace + ConfigurationLoader.ClassGenericManager.Substring(ConfigurationLoader.ClassGenericManager.IndexOf(':') + 1)))).Select(t => t.Subject).ToList();

            if (conns.Count > MaxRecentConnections)
            {
                conns.Sort();
                conns.Reverse();

                conns.RemoveRange(0, MaxRecentConnections);

                foreach (INode obj in conns)
                {
                    this._recentConnections.Retract(this._recentConnections.GetTriplesWithSubject(obj));
                    this.RemoveFromConnectionsMenu(this.mnuRecentConnections, obj);
                }

                try
                {
                    //Persist the graph to disk
                    CompressingTurtleWriter ttlwriter = new CompressingTurtleWriter();
                    ttlwriter.Save(this._recentConnections, this._recentConnectionsFile);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unable to persist a Connections File to disk", "Internal Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
Exemple #21
0
        public void ParsingRdfABadSyntax()
        {
            RdfAParser parser = new RdfAParser();
            Graph      g      = new Graph();

            Console.WriteLine("Tests parsing a file which has much invalid RDFa syntax in it, some triples will be produced (6-8) but most of the triples are wrongly encoded and will be ignored");
            g.BaseUri = new Uri("http://www.wurvoc.org/vocabularies/om-1.6/Kelvin_scale");
            FileLoader.Load(g, "resources\\bad_rdfa.html");

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

            Console.WriteLine();
            CompressingTurtleWriter ttlwriter = new CompressingTurtleWriter(WriterCompressionLevel.High);

            ttlwriter.HighSpeedModePermitted = false;
            ttlwriter.Save(g, "test.ttl");
        }
        public override void Complete(IGraph response)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(CallbackUri);

            request.Method      = "POST";
            request.ContentType = "text/turtle";
            CompressingTurtleWriter writer = new CompressingTurtleWriter();
            Stream       requestStream     = request.GetRequestStream();
            StreamWriter requestWriter     = new StreamWriter(requestStream);

            writer.Save(response, requestWriter);
            requestStream.Close();
            try
            {
                request.GetResponse();
            }
            catch (Exception ex)
            {
                Log.Warn(ex, "Could not perform completion request");
            }
        }
        /// <summary>
        /// Saves a Graph to a 4store instance (Warning: Completely replaces any existing Graph with the same URI)
        /// </summary>
        /// <param name="g">Graph to save</param>
        /// <remarks>
        /// <para>
        /// Completely replaces any existing Graph with the same Uri in the store
        /// </para>
        /// <para>
        /// Attempting to save a Graph which doesn't have a Base Uri will result in an error
        /// </para>
        /// </remarks>
        /// <exception cref="RdfStorageException">Thrown if you try and save a Graph without a Base Uri or if there is an error communicating with the 4store instance</exception>
        public void SaveGraph(IGraph g)
        {
            try
            {
                // Set up the Request
                HttpWebRequest request;
                if (g.BaseUri != null)
                {
                    request = (HttpWebRequest)WebRequest.Create(_baseUri + "data/" + Uri.EscapeUriString(g.BaseUri.AbsoluteUri));
                }
                else
                {
                    throw new RdfStorageException("Cannot save a Graph without a Base URI to a 4store Server");
                }
                request.Method      = "PUT";
                request.ContentType = MimeTypesHelper.Turtle[0];
                request             = ApplyRequestOptions(request);

                // Write the Graph as Turtle to the Request Stream
                CompressingTurtleWriter writer = new CompressingTurtleWriter(WriterCompressionLevel.High);
                writer.Save(g, new StreamWriter(request.GetRequestStream()));

                Tools.HttpDebugRequest(request);

                // Make the Request
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Tools.HttpDebugResponse(response);
                    // If we get here then it was OK
                    response.Close();
                }
            }
            catch (WebException webEx)
            {
                throw StorageHelper.HandleHttpError(webEx, "saving a Graph to");
            }
        }
        internal static void WriteGraph(TextWriter writer, IGraph graph, string named, bool plain, bool inHtml)
        {
            string printerName = "plain";

            if (plain)
            {
                DumpTriples(graph, writer, named);
                return;
            }
            else
            {
                IRdfWriter   n3w;
                StringWriter dtt              = new StringWriter();
                string       dttToString      = "error";
                bool         prettyWillWorked = false;

                if (prettyWillWorked)
                {
                    try
                    {
                        n3w = new CompressingTurtleWriter()
                        {
                            DefaultNamespaces = graph.NamespaceMap, PrettyPrintMode = true
                        };
                        n3w.Save(graph, dtt);
                        dttToString      = dtt.ToString();
                        prettyWillWorked = true;
                        printerName      = n3w.GetType().Name;
                    }
                    catch (Exception e)
                    {
                        dttToString      = dtt.ToString();
                        prettyWillWorked = false;
                    }
                }
                if (!prettyWillWorked)
                {
                    n3w = new Notation3Writer()
                    {
                        DefaultNamespaces = graph.NamespaceMap, PrettyPrintMode = true
                    };
                    dtt = new StringWriter();
                    try
                    {
                        lock (graph) n3w.Save(graph, dtt);
                        dttToString = dtt.ToString();
                        printerName = n3w.GetType().Name;
                    }
                    catch (Exception e)
                    {
                        if (inHtml)
                        {
                            writer.WriteLine("<pre><font color='red'>{0} {1} {2}</font></pre>", e.GetType(), e.Message,
                                             e.StackTrace);
                            printerName = "triples";
                            DumpTriples(graph, writer, named);
                        }
                        else
                        {
                            printerName = "plain";
                            DumpTriplesPlain(graph.Triples, writer, "{0}", graph);
                        }
                        return;
                    }
                }
                if (inHtml)
                {
                    writer.WriteLine("<h3>{0} KB {1}</h3>", named, printerName);
                    writer.WriteLine("<pre>");
                }
                dttToString = dttToString.Replace("\r\n", "\n").Replace("\r", "\n");
                foreach (string line in dttToString.Split('\n'))
                {
                    if (String.IsNullOrEmpty(line))
                    {
                        writer.WriteLine();
                        continue;
                    }
                    if (line.StartsWith("@prefix "))
                    {
                        continue;
                    }
                    var hline = line;
                    hline = (" " + hline).Replace(" robokind:", " rk:");
                    hline = hline.Replace("<robokind:", "<rk:");
                    if (inHtml)
                    {
                        hline = hline.Replace("<", "&lt;").Replace(">", "&gt;");
                    }
                    writer.WriteLine(hline);
                }
                if (inHtml)
                {
                    writer.WriteLine("</pre>");
                }
            }
        }
 public void WriteToTurtleFile(string filepath)
 {
     _turtleWriter.Save(_graph, filepath);
 }
Exemple #26
0
 public string GetTTL()
 {
     System.IO.StringWriter sw = new System.IO.StringWriter();
     writer.Save(RDFGraph, sw);
     return(sw.ToString());
 }
Exemple #27
0
        /// <summary>
        /// Saves a Graph to a 4store instance (Warning: Completely replaces any existing Graph with the same URI)
        /// </summary>
        /// <param name="g">Graph to save</param>
        /// <remarks>
        /// <para>
        /// Completely replaces any existing Graph with the same Uri in the store
        /// </para>
        /// <para>
        /// Attempting to save a Graph which doesn't have a Base Uri will result in an error
        /// </para>
        /// </remarks>
        /// <exception cref="RdfStorageException">Thrown if you try and save a Graph without a Base Uri or if there is an error communicating with the 4store instance</exception>
        public void SaveGraph(IGraph g)
        {
            try
            {
#if !NO_RWLOCK
                this._lockManager.EnterWriteLock();
#endif

                //Set up the Request
                HttpWebRequest request;
                if (g.BaseUri != null)
                {
                    request = (HttpWebRequest)WebRequest.Create(this._baseUri + "data/" + Uri.EscapeUriString(g.BaseUri.ToString()));
                }
                else
                {
                    throw new RdfStorageException("Cannot save a Graph without a Base URI to a 4store Server");
                }
                request.Method      = "PUT";
                request.ContentType = MimeTypesHelper.Turtle[0];
                request             = base.GetProxiedRequest(request);

                //Write the Graph as Turtle to the Request Stream
                CompressingTurtleWriter writer = new CompressingTurtleWriter(WriterCompressionLevel.High);
                writer.Save(g, new StreamWriter(request.GetRequestStream()));

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

                //Make the Request
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
#endif
                    //If we get here then it was OK
                    response.Close();
                }
            }
            catch (WebException webEx)
            {
#if DEBUG
                if (Options.HttpDebugging)
                {
                    if (webEx.Response != null)
                    {
                        Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                    }
                }
#endif
                throw new RdfStorageException("A HTTP error occurred while communicating with the 4store Server", webEx);
            }
            finally
            {
#if !NO_RWLOCK
                this._lockManager.ExitWriteLock();
#endif
            }
        }
        public void GraphCreation1()
        {
            //Create a new Empty Graph
            Graph g = new Graph();

            Assert.NotNull(g);

            //Define Namespaces
            g.NamespaceMap.AddNamespace("vds", new Uri("http://www.vdesign-studios.com/dotNetRDF#"));
            g.NamespaceMap.AddNamespace("ecs", new Uri("http://id.ecs.soton.ac.uk/person/"));

            //Check we set the Namespace OK
            Assert.True(g.NamespaceMap.HasNamespace("vds"), "Failed to set a Namespace");

            //Set Base Uri
            g.BaseUri = g.NamespaceMap.GetNamespaceUri("vds");
            Assert.NotNull(g.BaseUri);
            Assert.Equal(g.NamespaceMap.GetNamespaceUri("vds"), g.BaseUri);

            //Create Uri Nodes
            IUriNode rav08r, wh, lac, hcd;

            rav08r = g.CreateUriNode("ecs:11471");
            wh     = g.CreateUriNode("ecs:1650");
            hcd    = g.CreateUriNode("ecs:46");
            lac    = g.CreateUriNode("ecs:60");

            //Create Uri Nodes for some Predicates
            IUriNode supervises, collaborates, advises, has;

            supervises   = g.CreateUriNode("vds:supervises");
            collaborates = g.CreateUriNode("vds:collaborates");
            advises      = g.CreateUriNode("vds:advises");
            has          = g.CreateUriNode("vds:has");

            //Create some Literal Nodes
            ILiteralNode singleLine = g.CreateLiteralNode("Some string");
            ILiteralNode multiLine  = g.CreateLiteralNode("This goes over\n\nseveral\n\nlines");
            ILiteralNode french     = g.CreateLiteralNode("Bonjour", "fr");
            ILiteralNode number     = g.CreateLiteralNode("12", new Uri(g.NamespaceMap.GetNamespaceUri("xsd") + "integer"));

            g.Assert(new Triple(wh, supervises, rav08r));
            g.Assert(new Triple(lac, supervises, rav08r));
            g.Assert(new Triple(hcd, advises, rav08r));
            g.Assert(new Triple(wh, collaborates, lac));
            g.Assert(new Triple(wh, collaborates, hcd));
            g.Assert(new Triple(lac, collaborates, hcd));
            g.Assert(new Triple(rav08r, has, singleLine));
            g.Assert(new Triple(rav08r, has, multiLine));
            g.Assert(new Triple(rav08r, has, french));
            g.Assert(new Triple(rav08r, has, number));

            //Now print all the Statements
            Console.WriteLine("All Statements");
            foreach (Triple t in g.Triples)
            {
                Console.WriteLine(t.ToString());
            }

            //Get statements about Rob Vesse
            Console.WriteLine();
            Console.WriteLine("Statements about Rob Vesse");
            foreach (Triple t in g.GetTriples(rav08r))
            {
                Console.WriteLine(t.ToString());
            }

            //Get Statements about Collaboration
            Console.WriteLine();
            Console.WriteLine("Statements about Collaboration");
            foreach (Triple t in g.GetTriples(collaborates))
            {
                Console.WriteLine(t.ToString());
            }

            //Attempt to output Turtle for this Graph
            try
            {
                Console.WriteLine("Writing Turtle file graph_building_example.ttl");
                var ttlwriter = new CompressingTurtleWriter();
                ttlwriter.Save(g, "graph_building_example.ttl");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
Exemple #29
0
        private void mnuSaveConnection_Click(object sender, EventArgs e)
        {
            if (this.ActiveMdiChild != null)
            {
                if (this.ActiveMdiChild is StoreManagerForm)
                {
                    Object manager;
                    if (this.ActiveMdiChild is StoreManagerForm)
                    {
                        manager = ((StoreManagerForm)this.ActiveMdiChild).Manager;
                    }
                    else
                    {
                        return;
                    }
                    if (manager is IConfigurationSerializable)
                    {
                        this.sfdConnection.Filter = MimeTypesHelper.GetFilenameFilter(true, false, false, false, false, false);
                        if (this.sfdConnection.ShowDialog() == DialogResult.OK)
                        {
                            //Append to existing configuration file or overwrite?
                            ConfigurationSerializationContext context;
                            if (File.Exists(this.sfdConnection.FileName))
                            {
                                DialogResult result = MessageBox.Show("The selected connection file already exists - would you like to append this connection to that file?  Click Yes to append to this file, No to overwrite and Cancel to abort", "Append Connection?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                                switch (result)
                                {
                                case DialogResult.Yes:
                                    Graph g = new Graph();
                                    FileLoader.Load(g, this.sfdConnection.FileName);
                                    context = new ConfigurationSerializationContext(g);
                                    break;

                                case DialogResult.No:
                                    context = new ConfigurationSerializationContext();
                                    break;

                                default:
                                    return;
                                }
                            }
                            else
                            {
                                //Create new configuration file
                                context = new ConfigurationSerializationContext();
                            }

                            //Save the Connection
                            ((IConfigurationSerializable)manager).SerializeConfiguration(context);

                            try
                            {
                                IRdfWriter writer = MimeTypesHelper.GetWriterByFileExtension(MimeTypesHelper.GetTrueFileExtension(this.sfdConnection.FileName));
                                writer.Save(context.Graph, this.sfdConnection.FileName);
                            }
                            catch (RdfWriterSelectionException)
                            {
                                CompressingTurtleWriter ttlwriter = new CompressingTurtleWriter(WriterCompressionLevel.High);
                                ttlwriter.Save(context.Graph, this.sfdConnection.FileName);
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Unable to save the current connection as it does not support this feature", "Save Unavailable", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    this.mnuSaveConnection.Enabled = false;
                }
            }
            else
            {
                this.mnuSaveConnection.Enabled = false;
            }
        }
Exemple #30
0
        /// <summary>
        /// Merges the graphs from IMDb, LastFM and Charts_de into a new database
        /// </summary>
        private static void MergeGraphs()
        {
            Log("Executing MergeGraphs()");
            Log("Connecting to Movie store...");
            var movieStore = new StardogConnector(settings.ServerIp, MoviesDbName, settings.Login, settings.Password);

            movieStore.Timeout = int.MaxValue;

            #region Tunefind
            Log("Connecting to Tunefind store...");
            var tuneFindStore = new StardogConnector(settings.ServerIp, TuneFindDbName, settings.Login, settings.Password);
            var tuneFindGraph = new Graph();
            tuneFindGraph.BaseUri = new Uri("http://imn.htwk-leipzig.de/pbachman/ontologies/tunefind#");
            tuneFindStore.LoadGraph(tuneFindGraph, string.Empty);

            Log("Uploading Graph...");
            movieStore.DeleteGraph("http://imn.htwk-leipzig.de/pbachman/ontologies/tunefind#");
            movieStore.SaveGraph(tuneFindGraph);
            #endregion

            #region IMDB
            Log("Connecting to IMDB store...");
            var imdbStore = new StardogConnector(settings.ServerIp, ImdbDbName, settings.Login, settings.Password);
            var imdbGraph = new Graph();
            imdbGraph.BaseUri = new Uri("http://imn.htwk-leipzig.de/pbachman/ontologies/imdb#");
            imdbStore.LoadGraph(imdbGraph, string.Empty);

            Log("Uploading Graph...");
            movieStore.DeleteGraph("http://imn.htwk-leipzig.de/pbachman/ontologies/imdb#");
            movieStore.SaveGraph(imdbGraph);
            #endregion

            #region LastFM
            Log("Connecting to LastFm store...");
            var lastFmStore = new StardogConnector(settings.ServerIp, LastFmDbName, settings.Login, settings.Password);
            var lastFmGraph = new Graph();
            lastFmGraph.BaseUri = new Uri("http://imn.htwk-leipzig.de/pbachman/ontologies/lastfm#");
            lastFmStore.LoadGraph(lastFmGraph, string.Empty);

            Log("Uploading Graph...");
            movieStore.DeleteGraph("http://imn.htwk-leipzig.de/pbachman/ontologies/lastfm#");
            movieStore.SaveGraph(lastFmGraph);
            #endregion

            #region Charts_de
            Log("Connecting to Chart_De store...");
            var chartsDeStore = new StardogConnector(settings.ServerIp, ChartsDeDbName, settings.Login, settings.Password);
            var chartsDeGraph = new Graph();
            chartsDeGraph.BaseUri = new Uri("http://imn.htwk-leipzig.de/pbachman/ontologies/charts_de#");
            chartsDeStore.LoadGraph(chartsDeGraph, string.Empty);

            Log("Uploading Graph...");
            movieStore.DeleteGraph("http://imn.htwk-leipzig.de/pbachman/ontologies/charts_de#");
            movieStore.SaveGraph(chartsDeGraph);
            #endregion

            Log("Merging Graphs...");
            var movieGraph = SetupMovieGraph();
            movieGraph.Merge(tuneFindGraph);
            movieGraph.Merge(imdbGraph);
            movieGraph.Merge(lastFmGraph);
            movieGraph.Merge(chartsDeGraph);

            Log("Writing Graph...");
            var writer = new CompressingTurtleWriter(TurtleSyntax.W3C);
            writer.Save(movieGraph, @"01_Movies.ttl");
        }