Esempio n. 1
0
        public static Store resolveURI(Uri uri)
        {
            Store store = new SemWeb.MemoryStore();

            store.Import(SemWeb.RdfReader.LoadFromUri(uri));
            return(store);
        }
Esempio n. 2
0
 public Store ImportXmlFiles(IEnumerable fileNames)
 {
     var store = new MemoryStore();
     foreach (string fName in fileNames)
         store.Import(new RdfXmlReader(fName));
     return store;
 }
Esempio n. 3
0
    static void RunManifestFile(string manifestfile)
    {
        // Load the manifest file
        manifestfile = Path.GetDirectoryName(manifestfile) + "/"; // for good measure
        MemoryStore manifest = new MemoryStore();
        using (RdfReader m = new N3Reader(manifestfile + "/manifest.ttl")) {
            m.BaseUri = manifestfile;
            manifest.Import(m);
        }

        // Declare some resources

        Entity rdf_first = "http://www.w3.org/1999/02/22-rdf-syntax-ns#first";
        Entity rdf_rest = "http://www.w3.org/1999/02/22-rdf-syntax-ns#rest";
        Entity rdf_nil = "http://www.w3.org/1999/02/22-rdf-syntax-ns#nil";

        Entity mf_entries = "http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#entries";

        // Get the start of the entries list.
        Entity entries_root = (Entity)manifest.SelectObjects(manifestfile, mf_entries)[0];

        // Loop through the tests.
        while (true) {
            Entity test = (Entity)manifest.SelectObjects(entries_root, rdf_first)[0];
            RunTest(test, manifest);

            entries_root = (Entity)manifest.SelectObjects(entries_root, rdf_rest)[0];
            if (entries_root == rdf_nil)
                break;
        }
    }
        public void InteropSemWebReadVia()
        {
            MemoryStore mem = new MemoryStore();
            mem.Import(new N3Reader("InferenceTest.ttl"));

            Console.WriteLine("SemWeb got the following Statements:");
            foreach (Statement stmt in mem)
            {
                Console.WriteLine(stmt.ToString());
            }
            Console.WriteLine();

            Graph g = new Graph();
            SemWebConverter.FromSemWeb(mem, g);

            Console.WriteLine("dotNetRDF got the following Triples via Conversion:");
            foreach (Triple t in g.Triples)
            {
                Console.WriteLine(t.ToString());
            }
            Console.WriteLine();

            Graph h = new Graph();
            FileLoader.Load(h, "InferenceTest.ttl");

            Console.WriteLine("dotNetRDF got the following Triples directly from the File:");
            foreach (Triple t in g.Triples)
            {
                Console.WriteLine(t.ToString());
            }
            Console.WriteLine();

            Assert.AreEqual(g, h, "Graphs should have ben equal");
        }
Esempio n. 5
0
        public void Run(IComponentsConfig config, string targetFile)
        {
            var rdfStore = new MemoryStore();

            rdfStore.Add(new Statement(NS.CSO.classEntity, NS.Rdfs.subClassOf, NS.Rdfs.ClassEntity));
            rdfStore.Add(new Statement(NS.CSO.interfaceEntity, NS.Rdfs.subClassOf, NS.Rdfs.ClassEntity));

            var assemblyExtractor = new AssemblyMetadata();
            assemblyExtractor.Extract( System.Web.HttpRuntime.BinDirectory, rdfStore);

            var configExtractor = new WinterMetadata();
            var baseUri = String.IsNullOrEmpty(BaseUri) ?
                "file:///"+System.Web.HttpRuntime.AppDomainAppPath.Replace('\\','/')+"#" :
                BaseUri;
            configExtractor.BaseNs = baseUri;
            configExtractor.Extract(config, rdfStore);

            using (RdfXmlWriter wr = new RdfXmlWriter(targetFile)) {
                wr.BaseUri = NS.NrMeta;
                wr.Namespaces.AddNamespace(NS.DotNet.Type, "type");
                wr.Namespaces.AddNamespace(NS.DotNet.Property, "prop");
                wr.Namespaces.AddNamespace(NS.NrMetaTerms, "nr");
                wr.Write(rdfStore);
            }
        }
Esempio n. 6
0
		public static StatementSource CreateForInput(string spec) {
			if (spec.StartsWith("rdfs+")) {
				StatementSource s = CreateForInput(spec.Substring(5));
				if (!(s is SelectableSource)) s = new MemoryStore(s);
				return new SemWeb.Inference.RDFS(s, (SelectableSource)s);
			}
			return (StatementSource)Create(spec, false);
		}		
 protected static MemoryStore CreateMemoryStore()
 {
     string mp3s = Settings.Default.testStoreLocation;
     string musicOntology = Settings.Default.testStoreLocation;
     MemoryStore store = new MemoryStore();
     //			store.AddReasoner(new Euler(new N3Reader(MusicConstants.OntologyURL)));
     store.Import(new N3Reader(musicOntology));
     store.Import(new N3Reader(mp3s));
     return store;
 }
Esempio n. 8
0
 public static string GetLabel(Entity entity, MemoryStore rdfStore)
 {
     string label = new ArrayList<string>(entity.Uri.Split('/', '#')).Last;
     Resource[] labels = rdfStore.SelectObjects(entity, P_LABEL);
     if (labels.Length > 0)
     {
         label = ((Literal)labels[0]).Value; // *** always take the first available label
         label = label.Replace('/', '-');
     }
     return label;
 }
Esempio n. 9
0
    public static void Main()
    {
        MemoryStore store = new MemoryStore();

        store.Import(new RdfXmlReader(Console.In));

        // The 'using' is important because it is necessary
        // to Close or Dispose the writer once writing is
        // complete so that the final statement is closed
        // with a period.
        using (RdfWriter writer = new N3Writer(Console.Out))
            writer.Write(store);
    }
 public static void Add(string s, string p, string o, MemoryStore ms)
 {
     if (!string.IsNullOrEmpty(s) && !string.IsNullOrEmpty(p) && !string.IsNullOrEmpty(o))
     {
         ms.Add(new Statement(new Entity(s), new Entity(p), new Literal(o), Statement.DefaultMeta));
         #region Tracing
     #line hidden
         if (Logger.IsDebugEnabled)
         {
             Logger.Debug("Added <{0}> <{1}> <{2}>.", s,p,o);
         }
     #line default
         #endregion
     }
 }
Esempio n. 11
0
    public static void Main(string[] args)
    {
        if (args.Length < 2) {
            Console.WriteLine("Usage: euler.exe axioms.n3 axioms... {questions.n3 | -sparql query.sparql}");
            return;
        }

        // Load Axioms

        bool sparql = false;

        MemoryStore axioms = new MemoryStore();
        for (int i = 0; i < args.Length-1; i++) {
            if (i > 0 && i == args.Length-2 && args[i] == "-sparql") {
                sparql = true;
                break;
            }

            N3Reader axiomsreader = new N3Reader(args[i]);
            axiomsreader.BaseUri = "http://www.example.org/arbitrary/base#";
            axioms.Import(axiomsreader);
        }

        Euler engine = new Euler(axioms);

        // Load question
        if (!sparql) {
            MemoryStore question = new MemoryStore();
            question.Import(new N3Reader(args[args.Length-1]));

            Proof[] proofs = engine.Prove(null, question.ToArray());

            foreach (Proof p in proofs) {
                Console.WriteLine(p.ToString());
            }
        } else {
            using (StreamReader fs = new StreamReader(args[args.Length-1])) {
                string q = fs.ReadToEnd();

                Store store = new Store();
                store.AddReasoner(engine);

                SparqlEngine s = new SparqlEngine(q);
                s.Run(store, Console.Out);
            }
        }
    }
 public void AddNewRDFData(string rdfData, bool removeExistingDataForSubjects)
 {
     MemoryStore store = new MemoryStore();
     RdfXmlReader reader = new RdfXmlReader(new System.IO.StringReader(rdfData));
     store.Import(reader);
     // its possible that we want to update info about some existing concept
     // if removeExistingDataForSubjects is true we first remove existing information before we start adding statements
     if (removeExistingDataForSubjects)
     {
         foreach (Entity subject in store.SelectSubjects(null, null))
             _conceptsStore.Remove(new Statement(subject, null, null));
     }
     foreach (Statement s in store.Select(new Statement(null, null, null)))
         AddNewStatement(s);
     foreach (Entity subject in store.SelectSubjects(null, null))
         UpdateSuggestionsForUri(subject.Uri);
 }
        public void InteropSemWebWriteVia()
        {
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");

            MemoryStore mem = new MemoryStore();
            SemWebConverter.ToSemWeb(g, mem);

            RdfWriter writer = new RdfXmlWriter("semweb.rdf");
            writer.Write(mem);
            writer.Close();

            //Read the output graph back in to check for equality
            Graph h = new Graph();
            FileLoader.Load(h, "semweb.rdf");

            Assert.AreEqual(g, h, "Graphs should have been equal");
        }
Esempio n. 14
0
    public static void Main()
    {
        // Create the instance data

        MemoryStore dataModel = new MemoryStore();

        BNode me = new BNode("me");
        BNode you = new BNode("you");

        Entity rdfType = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
        Entity rdfsLabel= "http://www.w3.org/2000/01/rdf-schema#label";
        Entity foafPerson = "http://xmlns.com/foaf/0.1/Person";
        Entity foafAgent = "http://xmlns.com/foaf/0.1/Agent";
        Entity foafName = "http://xmlns.com/foaf/0.1/name";

        dataModel.Add(new Statement(me, rdfType, foafPerson));
        dataModel.Add(new Statement(you, rdfType, foafPerson));
        dataModel.Add(new Statement(me, foafName, (Literal)"John Doe"));
        dataModel.Add(new Statement(you, foafName, (Literal)"Sam Smith"));

        // Create the RDFS engine and apply it to the data model.

        RDFS engine = new RDFS();
        engine.LoadSchema(RdfReader.LoadFromUri(new Uri("http://xmlns.com/foaf/0.1/index.rdf")));

        dataModel.AddReasoner(engine);

        // Query the data model

        // Ask for who are typed as Agents.  Note that the people are
        // typed as foaf:Person, and the schema asserts that foaf:Person
        // is a subclass of foaf:Agent.
        Console.WriteLine("Who are Agents?");
        foreach (Entity r in dataModel.SelectSubjects(rdfType, foafAgent))
            Console.WriteLine("\t" + r);

        // Ask for the rdfs:labels of everyone.  Note that the data model
        // has foaf:names for the people, and the schema asserts that
        // foaf:name is a subproperty of rdfs:label.
        Console.WriteLine("People's labels:");
        foreach (Statement s in dataModel.Select(new Statement(null, rdfsLabel, null)))
            Console.WriteLine("\t" + s);
    }
Esempio n. 15
0
    public static void Main()
    {
        MemoryStore store = new MemoryStore();

        Entity computer = new Entity("http://example.org/computer");
        Entity says = "http://example.org/says";
        Entity wants = "http://example.org/wants";
        Entity desire = new BNode();
        Entity description = new Entity("http://example.org/description");

        store.Add(new Statement(computer, says, (Literal)"Hello world!"));
        store.Add(new Statement(computer, wants, desire));
        store.Add(new Statement(desire, description, (Literal)"to be human"));
        store.Add(new Statement(desire, RDF+"type", (Entity)"http://example.org/Desire"));

        using (RdfWriter writer = new RdfXmlWriter(Console.Out)) {
            writer.Namespaces.AddNamespace("http://example.org/", "ex");
            writer.Write(store);
        }
    }
Esempio n. 16
0
        public virtual void Replace(Entity find, Entity replacement)
        {
            MemoryStore deletions = new MemoryStore();
            MemoryStore additions = new MemoryStore();

            Select(new Statement(find, null, null, null), deletions);
            Select(new Statement(null, find, null, null), deletions);
            Select(new Statement(null, null, find, null), deletions);
            Select(new Statement(null, null, null, find), deletions);

            foreach (Statement s in deletions)
            {
                Remove(s);
                additions.Add(s.Replace(find, replacement));
            }

            foreach (Statement s in additions)
            {
                Add(s);
            }
        }
        public void InteropSemWebGraphConversion()
        {
            Graph g = new Graph();
            FileLoader.Load(g, "Turtle.ttl");

            MemoryStore mem = new MemoryStore();
            SemWebConverter.ToSemWeb(g, mem);

            Graph h = new Graph();
            SemWebConverter.FromSemWeb(mem, h);

            Assert.AreEqual(g, h, "1 - Graphs should have been equal");

            MemoryStore mem2 = new MemoryStore();
            SemWebConverter.ToSemWeb(h, mem2);

            Graph i = new Graph();
            SemWebConverter.FromSemWeb(mem2, i);

            Assert.AreEqual(h, i, "2 - Graphs should have been equal");
        }
Esempio n. 18
0
    public static void Main()
    {
        MemoryStore store = new MemoryStore();

        Entity container = new Entity("http://www.example.org/#container");

        store.Add(new Statement(container, RDF+"type", (Entity)(RDF+"Bag")));
        store.Add(new Statement(container, RDF+"_3", (Literal)"Three"));
        store.Add(new Statement(container, RDF+"_2", (Literal)"Two"));
        store.Add(new Statement(container, RDF+"_1", (Literal)"One"));

        // use the rdfs:member property to match for any rdf:_### predicates.
        Entity rdfs_member = (Entity)(RDFS+"member");

        using (RdfWriter writer = new N3Writer(Console.Out)) {
            writer.Namespaces.AddNamespace(RDF, "rdf");
            store.Select(new Statement(container, rdfs_member, null), writer);
        }

        foreach (Resource r in store.SelectObjects(container, rdfs_member))
            Console.WriteLine(r);
    }
        private static void AddPropertyToStore(OwlInstanceSupertype track, PropertyInfo pi, MemoryStore ms)
        {
            if (track == null)
                throw new ArgumentNullException("track");
            if (pi == null)
                throw new ArgumentNullException("pi");
            if (ms == null)
                throw new ArgumentNullException("ms");

            if (pi.GetValue(track, null) != null)
            {
                Add(track.InstanceUri, pi.GetOwlResourceUri(), pi.GetValue(track, null).ToString(), ms);
                #region Tracing
            #line hidden
                if (Logger.IsDebugEnabled)
                {
                    Logger.Debug("Added property {0} to store.", pi.Name);
                }
            #line default
                #endregion
            }
        }
Esempio n. 20
0
        static void Main(string[] args)
        {
            var rdfStore = new MemoryStore();

            //rdfStore.Add(new Statement(NS.CSO.classEntity, NS.Rdfs.subClassOf, NS.Rdfs.ClassEntity));
            //rdfStore.Add(new Statement(NS.CSO.interfaceEntity, NS.Rdfs.subClassOf, NS.Rdfs.ClassEntity));

            var rdfsReasoner = new RDFS();
            rdfsReasoner.LoadSchema(rdfStore);
            rdfStore.AddReasoner(rdfsReasoner);

            /*using (var wr = new RdfXmlWriter(Console.Out)) {
                wr.BaseUri = NS.NrMeta;
                wr.Write(rdfStore);
            }*/

            /*var r = rdfStore.Contains(new Statement(
                (Entity)(NS.NrDotNetType + "NReco.Operations.ChainOperationCall"),
                (Entity)NS.Rdfs.subClassOfEntity,
                (Entity)(NS.NrDotNetType + "NReco.Operations.OperationCall") )); //
            Console.WriteLine(r.ToString());*/
            /*foreach (Statement s in rdfStore.Select(new Statement(
                    (Entity)(NS.NrDotNetProp+"ContextFilter"),
                    (Entity)NS.Rdfs.domainEntity,
                    null))) { //Entity)(NS.NrDotNetType + "NReco.IProvider`2")
                Console.WriteLine(s.Object.Uri.ToString());
            }*/
            /*Query query = new GraphMatch(new N3Reader(new StringReader(rdfQuery)));
            QueryResultSink sink = new SparqlXmlQuerySink(Console.Out);
            query.Run(rdfStore, sink); */

            using (RdfXmlWriter wr = new RdfXmlWriter(@"c:\temp\_1.rdf")) {
                //wr.BaseUri = NS.NrMeta;
                //wr.Namespaces.AddNamespace(NS.DotNet.Type, "t");
                //wr.Namespaces.AddNamespace(NS.DotNet.Property, "p");
                wr.Write(rdfStore);
            }
            Console.ReadKey();
        }
Esempio n. 21
0
    public static void Main(string[] argv)
    {
        if (argv.Length < 3) {
            Console.WriteLine("Usage: query.exe format queryfile datafile");
            return;
        }

        string format = argv[0];
        string queryfile = argv[1];
        string datafile = argv[2];

        Query query;

        if (format == "rsquary") {
            // Create a simple-entailment "RSquary" query
            // from the N3 file.
            query = new GraphMatch(new N3Reader(queryfile));
        } else {
            // Create a SPARQL query by reading the file's
            // contents.
            query = new SparqlEngine(new StreamReader(queryfile));
        }

        // Load the data file from disk
        MemoryStore data = new MemoryStore();
        data.Import(new N3Reader(datafile));

        // First, print results in SPARQL XML Results format...

        // Create a result sink where results are written to.
        QueryResultSink sink = new SparqlXmlQuerySink(Console.Out);

        // Run the query.
        query.Run(data, sink);

        // Second, print the results via our own custom QueryResultSink...
        query.Run(data, new PrintQuerySink());
    }
Esempio n. 22
0
 public ArtifactStore(string storeLocation)
 {
     string ontology = "";
     string data = "";
     store = new MemoryStore();
     ontology = Read(Constants.OntologyUri);
     store.AddReasoner(new Euler(new N3Reader(new StringReader(ontology))));
     if (File.Exists(storeLocation))
     {
         switch (GetStoreFormat(storeLocation))
         {
             case StoreFormat.N3:
                 data = File.ReadAllText(storeLocation);
                 N3Reader reader = new N3Reader(new StringReader(data));
                 store.Import(reader);
                 break;
             case StoreFormat.RDF:
                 data = File.ReadAllText(storeLocation);
                 store.Import(new RdfXmlReader(new StringReader(data)));
                 break;
         }
     }
 }
Esempio n. 23
0
    public static void Main(string[] args)
    {
        if (args.Length != 2) {
            Console.WriteLine("runtests.exe basepath manifestfile");
            return;
        }

        basepath = args[0];
        string manifestfile = Path.Combine(basepath, args[1]);

        RdfReader reader = new RdfXmlReader(manifestfile);
        if (!manifestfile.EndsWith(".rdf"))
            reader = new N3Reader(manifestfile);
        reader.BaseUri = "http://www.example.org/";

        MemoryStore testlist = new MemoryStore(reader);

        // RDF/XML TESTS

        foreach (Entity test in testlist.GetEntitiesOfType("http://www.w3.org/2000/10/rdf-tests/rdfcore/testSchema#PositiveParserTest"))
            RunTest(testlist, test, true, 0);
        foreach (Entity test in testlist.GetEntitiesOfType("http://www.w3.org/2000/10/rdf-tests/rdfcore/testSchema#NegativeParserTest"))
            RunTest(testlist, test, false, 0);

        // N3 TESTS

        foreach (Entity test in testlist.GetEntitiesOfType("http://www.w3.org/2004/11/n3test#PositiveParserTest"))
            RunTest(testlist, test, true, 1);
        foreach (Entity test in testlist.GetEntitiesOfType("http://www.w3.org/2004/11/n3test#NegativeParserTest"))
            RunTest(testlist, test, false, 1);

        Console.WriteLine("Total Tests:\t{0}", total);
        Console.WriteLine("Total Failures:\t{0} ({1}%)", badfail+badpass, (int)(100*(float)(badpass+badfail)/total));
        Console.WriteLine("Positive Fails:\t{0}", badfail);
        Console.WriteLine("Negative Fails:\t{0}", badpass);
        Console.WriteLine("Test Errors:\t{0}", error);
    }
Esempio n. 24
0
    public static void Main()
    {
        Store store = new MemoryStore();
        store.Import(RdfReader.LoadFromUri(new Uri(example_foaf_file)));

        // Dump out the data, for fun
        using (RdfWriter writer = new RdfXmlWriter(Console.Out)) {
            writer.Write(store);
        }

        Console.WriteLine("These are the people in the file:");
        foreach (Statement s in store.Select(new Statement(null, rdftype, foafPerson))) {
            foreach (Resource r in store.SelectObjects(s.Subject, foafname))
                Console.WriteLine(r);
        }
        Console.WriteLine();

        Console.WriteLine("And here's RDF/XML just for some of the file:");
        using (RdfWriter w = new RdfXmlWriter(Console.Out)) {
            store.Select(new Statement(null, foafname, null), w);
            store.Select(new Statement(null, foafknows, null), w);
        }
        Console.WriteLine();
    }
Esempio n. 25
0
    public static void Main()
    {
        // Create the instance data

        MemoryStore dataModel = new MemoryStore();

        BNode paris = new BNode("paris");
        BNode orleans = new BNode("orleans");
        BNode chartres = new BNode("chartres");
        BNode amiens = new BNode("amiens");
        BNode blois = new BNode("blois");
        BNode bourges = new BNode("bourges");
        BNode tours = new BNode("tours");
        BNode lemans = new BNode("lemans");
        BNode angers = new BNode("angers");
        BNode nantes = new BNode("nantes");

        Entity oneway = new Entity("http://www.agfa.com/w3c/euler/graph.axiom#oneway");
        Entity path = new Entity("http://www.agfa.com/w3c/euler/graph.axiom#path");

        dataModel.Add(new Statement(paris, oneway, orleans));
        dataModel.Add(new Statement(paris, oneway, chartres));
        dataModel.Add(new Statement(paris, oneway, amiens));
        dataModel.Add(new Statement(orleans, oneway, blois));
        dataModel.Add(new Statement(orleans, oneway, bourges));
        dataModel.Add(new Statement(blois, oneway, tours));
        dataModel.Add(new Statement(chartres, oneway, lemans));
        dataModel.Add(new Statement(lemans, oneway, angers));
        dataModel.Add(new Statement(lemans, oneway, tours));
        dataModel.Add(new Statement(angers, oneway, nantes));

        // Create the inference rules by reading them from a N3 string.

        string rules =
            "@prefix : <http://www.agfa.com/w3c/euler/graph.axiom#>.\n" +
            "\n" +
            "{ ?a :oneway ?b } => { ?a :path ?b } .\n" +
            "{ ?a :path ?b . ?b :path ?c . } => { ?a :path ?c } .\n";

        // Create our question in the form of a statement to test.

        Statement question = new Statement(paris, path, nantes);

        // Create the Euler engine

        Euler engine = new Euler(new N3Reader(new StringReader(rules)));

        // First Method of Inference:
        // Ask the engine whether there is a path from paris to nantes.
        // The Prove method will return a list of proofs, or an empty
        // array if it could not find a proof.

        foreach (Proof p in engine.Prove(dataModel, new Statement[] { question })) {
            Console.WriteLine(p.ToString());
        }

        // Second Method of Inference:
        // Apply the engine to the data model and then use the data
        // model's Contains method to see if the statement is "in"
        // the model + reasoning.

        dataModel.AddReasoner(engine);

        Console.WriteLine("Euler Says the Question is: " + dataModel.Contains(question));
    }
Esempio n. 26
0
		public static void GetDescription (MemoryStore store, Statement stmt, out string label, out string value)
		{
			string predicate = stmt.Predicate.Uri;

			Description d = (Description) table [predicate];

			label = System.IO.Path.GetFileName (predicate);
			value = null;

			if (stmt.Object is SemWeb.Literal)
			        value = ((SemWeb.Literal)(stmt.Object)).Value;

			if (d != null) {
				label = d.title;
				if (d.formater != null && stmt.Object is Literal)
					value = d.formater.GetValue (store, (SemWeb.Literal)stmt.Object);

			} else {
				Statement sstmt = new Statement (stmt.Predicate,
								 (Entity)MetadataStore.Namespaces.Resolve ("rdfs:label"),
								 null);
				
				foreach (Statement tstmt in MetadataStore.Descriptions.Select (sstmt))
					if (tstmt.Object is SemWeb.Literal)
						label = ((SemWeb.Literal)(tstmt.Object)).Value;
			}
			return;
		}
    protected void RadioButtonList2_SelectedIndexChanged(object sender, EventArgs e)
    {
        WizardStepType t = new WizardStepType();
        string result = string.Empty;
        //if (Convert.ToInt32(Session["item"]) <((DataTable)Session["array"]).Rows.Count)
        //{
        //    Question.Text = "Do you have " +((DataTable)Session["array"]).Rows[Convert.ToInt32(Session["item"])][1].ToString()+"?";
        //    Session["item"] = Convert.ToInt32(Session["item"])+1;
        //    RadioButtonList2.Items.Clear();
        //    RadioButtonList2.Items.Add(new ListItem("Yes"));
        //    RadioButtonList2.Items.Add(new ListItem("No"));
        //}
        if (Session["array"] != null)
        {
            if (RadioButtonList2.SelectedItem.Text == "Yes")
            {
                ((ArrayList)Session["a"]).Add("'" + ((ArrayList)Session["arraylist"])[Convert.ToInt32(Session["item"])].ToString() + "'");
                string expr = string.Empty;
                foreach (string items in ((ArrayList)Session["a"]))
                {
                    expr = expr + items + ",";

                }
                //if(expr!=string.Empty)
                // expr="Symptoms in ("+expr.Remove(expr.Length - 1)+") and";

                expr = "Symptoms in( '" + ((ArrayList)Session["arraylist"])[Convert.ToInt32(Session["item"])].ToString() + "') and";
                DataView dv;
                if (GridView1.Rows.Count > 0)
                {
                    string expr1 = string.Empty;

                    foreach (GridViewRow r in GridView1.Rows)
                    {
                        expr1 = expr1 + "'" + r.Cells[0].Text + "',";

                    }
                    expr1 = expr + " Disease in (" + expr1.Remove(expr1.Length - 1) + ")";
                    dv = new DataView(((DataTable)Session["array"]), expr1, "", DataViewRowState.CurrentRows);
                }
                else
                {
                    expr = expr.Remove(expr.Length - 3);
                    dv = new DataView(((DataTable)Session["array"]), expr, "", DataViewRowState.CurrentRows);
                }

                DataTable dt2 = dv.ToTable();

                // foreach (DataRowView drv in dv)

                //{

                //    value = (int)drv["column1"];

                //   }

                //  DataRow[] foundrows = ((DataTable)Session["array"]).Select("Symptoms like '" + ((DataTable)Session["array"]).Rows[Convert.ToInt32(Session["item"])][1].ToString() + "'");

                if (dt2.Rows.Count > 0)
                {
                    GridView1.DataSource = dt2;
                    GridView1.DataBind();
                    //   GridView1.Columns[1].Visible = false;
                    if (GridView1.Rows.Count == 1)
                    {
                        t = myWizard.WizardSteps[2].StepType;
                        if (t == WizardStepType.Complete)
                        {
                            lblName.Text = GridView1.Rows[0].Cells[0].Text;

                            Query query;
                            string queryfile = @"C:\Query.txt";
                            string datafile = @"C:\KLM11.n3";
                            string str = "PREFIX table:<http://www.owl-ontologies.com/Ontology1183162121.owl#> \n " +
                            "SELECT distinct ?med  \n " +
                            "FROM <C:/KLM11.N3> \n " +
                            " where \n" +
                           "{\n" +
                           " ?Disease table:disease ?name.\n" +
                            " ?Disease table:symptoms ?symp.\n" +
                            " ?Disease table:classification ?class.\n" +
                          " ?class table:class-name \"" + RadioButtonList1.SelectedItem.Text + "\". \n" +
                          "?name table:disease-name ?nam.\n" +
                          " Filter regex(?nam, \"" + GridView1.Rows[0].Cells[0].Text + "\",\"i\"). \n " +
                          "?name table:medication ?med.\n }";

                            TextWriter stringWriter = new StringWriter();
                            stringWriter.Write(str);

                            query = new SparqlEngine(str);
                            MemoryStore data = new MemoryStore();
                            data.Import(new N3Reader(datafile));

                            PrintQuerySink psink = new PrintQuerySink();
                            query.Run(data, psink);
                            foreach (string s in psink.al)
                                result = result + s + ",";
                            if (result != string.Empty)
                                result = result.Remove(result.Length - 1);

                            //ListBox1.DataSource = psink.al;
                            //ListBox1.DataBind();

                        }

                    }
                    // GridView1.Columns[1].Visible = false;
                }

            }

            if (t != WizardStepType.Complete)
            {

                if (Convert.ToInt32(Session["item"]) < ((ArrayList)Session["arraylist"]).Count - 1)
                {

                    Session["item"] = Convert.ToInt32(Session["item"]) + 1;
                    RadioButtonList2.Items[0].Selected = false;
                    RadioButtonList2.Items[1].Selected = false;
                    Question.Text = "Do you have " + ((ArrayList)Session["arraylist"])[Convert.ToInt32(Session["item"])].ToString() + "?";

                }
            }
            else
            {

                Response.Redirect("~/Patient/DiagResult.aspx?dis='" + GridView1.Rows[0].Cells[0].Text + "' &med='" + result + "'");

            }
        }
    }
    protected void myWizard_NextButtonClick(object sender, System.Web.UI.WebControls.WizardNavigationEventArgs e)
    {
        Query query;
        string queryfile = @"C:\Query.txt";
        string datafile = @"C:\KLM11.n3";
        string str = "PREFIX table:<http://www.owl-ontologies.com/Ontology1183162121.owl#> \n " +
        "SELECT distinct ?name ?symp   \n " +
        "FROM <C:/KLM11.owl> \n " +
        " where \n" +
           "{\n" +
           " ?Disease table:disease ?name.\n" +
        " ?Disease table:symptoms ?symp.\n" +
        " ?Disease table:classification ?class.\n" +
          " ?class table:class-name \"" + RadioButtonList1.SelectedItem.Text + "\" }\n";

        TextWriter stringWriter = new StringWriter();
        stringWriter.Write(str);

        query = new SparqlEngine(str);
        MemoryStore data = new MemoryStore();
        data.Import(new N3Reader(datafile));

        // First, print results in SPARQL XML Results format...

        // Create a result sink where results are written to.
        XmlTextWriter writer = new XmlTextWriter("C:\\temp\\xmltest3.xml", null);

        QueryResultSink sink = new SparqlXmlQuerySink(writer);

        // Run the query.
        query.Run(data, sink);

        writer.Close();
        TextWriter stringWriter1 = new StringWriter();

        dt.Columns.Add("Disease");
        dt.Columns.Add("Symptoms");
        query.Run(data, stringWriter1);
        //Response.Write(stringWriter1.ToString());

        FileStream fs = new FileStream("C:\\temp\\xmltest3.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        xmldoc = new XmlDocument();
        xmldoc.Load(fs);
        XmlNodeList xmlnode = xmldoc.GetElementsByTagName("binding");
        Console.WriteLine("Here is the list of catalogs\n\n");

        for (int i = 0; i < xmlnode.Count; i++)
        {

            XmlAttributeCollection xmlattrc = xmlnode[i].Attributes;

            //XML Attribute Name and Value returned
            //Example: <Book id = "001">

            //First Child of the XML file - Catalog.xml - returned
            //Example: <Author>Mark</Author>

            dt.Rows.Add(xmlnode[i].NextSibling.InnerText.Replace("http://www.owl-ontologies.com/Ontology1183162121.owl#", ""), xmlnode[i].InnerText.Replace("http://www.owl-ontologies.com/Ontology1183162121.owl#", ""));
            i = i + 1;

        }

        fs.Close();

        str = string.Empty;
        str = "PREFIX table:<http://www.owl-ontologies.com/Ontology1183162121.owl#> \n " +
          "SELECT distinct  ?symp   \n " +
          "FROM <C:/KLM11.owl> \n " +
          " where \n" +
         "{\n" +
         " ?Disease table:disease ?name.\n" +
          " ?Disease table:symptoms ?symp.\n" +
          " ?Disease table:classification ?class.\n" +
        " ?class table:class-name \"" + RadioButtonList1.SelectedItem.Text + "\" }\n";

        // Response.Write("Catalog Finished");
        query = new SparqlEngine(str);
        data = new MemoryStore();
        data.Import(new N3Reader(datafile));
        PrintQuerySink psink = new PrintQuerySink();
        query.Run(data, psink);

        Question.Text = "Do you have " + psink.al[0].ToString() + "?";
        a = new ArrayList();
        Session["array"] = dt;
        processQuestions();
        Session["item"] = 0;
        Session["a"] = a;
        Session["arraylist"] = psink.al;
        GridView1.DataSource = null;

        //foreach (string s in psink.array)
        //{
        //    CheckBoxList1.Items.Add(new ListItem(s));
        //}
        //CheckBoxList1.
    }
 private static void CreateMemoryStore()
 {
     string serialisedLocation = Settings.Default.testStoreLocation;
     store = new MemoryStore();
     //			store.AddReasoner(new Euler(new N3Reader(MusicConstants.OntologyURL)));
     store.Import(new N3Reader(serialisedLocation));
 }
 public void MyTearDown()
 {
     if (store != null)
         store = null;
 }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Query query;
        XmlDocument xmldoc;
        DataTable dt = new DataTable();
        PrintQuerySink psink = new PrintQuerySink();

        dt.Columns.Add("Name");
        dt.Columns.Add("Disease");
        dt.Columns.Add("Symptom");
        dt.Columns.Add("Medication");

        DirectoryInfo dir = new DirectoryInfo(@"C:\PatientOWLFiles");
        FileInfo[] n3files = dir.GetFiles("*.n3");

        foreach (FileInfo f in n3files)
        {

            string datafile = f.FullName;
            string str = string.Empty;

            if (DropDownList1.SelectedIndex == 0)
            {
                str = "PREFIX table:<http://www.owl-ontologies.com/Ontology1183162121.owl#> \n " +
               "SELECT distinct ?dis ?symp ?medi  \n " +
               "from <" + f.FullName + ">\n " +
               " where \n" +
              "{\n" +
              " ?Disease table:disease ?dis.\n" +
              " ?dis table:symptoms ?sym. \n" +
              " ?dis table:medication ?med. \n" +
              "?dis table:disease-name ?dise.\n" +
               "?sym table:symp-name ?symp.\n" +
               "?med table:med-name ?medi.\n";
                str = str + "Filter regex(?dise, \"" + TextBox1.Text + "\" ,\"i\").\n";

            }
            else if (DropDownList1.SelectedIndex == 1)
            {
                str = "PREFIX table:<http://www.owl-ontologies.com/Ontology1183162121.owl#> \n " +
               "SELECT distinct ?dis ?symp  ?medi \n " +
               "from <" + f.FullName + ">\n " +
               " where \n" +
              "{\n" +
              " ?Disease table:disease ?dis.\n" +
              " ?dis table:symptoms ?sym. \n" +
              " ?dis table:medication ?med. \n" +
              "?dis table:disease-name ?dise.\n" +
               "?sym table:symp-name ?symp.\n" +
               "?med table:med-name ?medi.\n";
                str = str + "Filter regex(?symp, \"" + TextBox1.Text + "\" ,\"i\").\n";

            }
            else if (DropDownList1.SelectedIndex == 2)
            {
                str = "PREFIX table:<http://www.owl-ontologies.com/Ontology1183162121.owl#> \n " +
               "SELECT distinct ?dis ?symp ?medi  \n " +
               "from <" + f.FullName + ">\n " +
               " where \n" +
              "{\n" +
              " ?Disease table:disease ?dis.\n" +
              " ?dis table:symptoms ?sym. \n" +
              " ?dis table:medication ?med. \n" +
              "?dis table:disease-name ?dise.\n" +
               "?sym table:symp-name ?symp.\n" +
               "?med table:med-name ?medi.\n";
                str = str + "Filter regex(?medi, \"" + TextBox1.Text + "\" ,\"i\").\n";

            }

            str = str + "  }\n";

            TextWriter stringWriter = new StringWriter();
            stringWriter.Write(str);

            query = new SparqlEngine(str);
            MemoryStore data = new MemoryStore();
            data.Import(new N3Reader(datafile));

            // First, print results in SPARQL XML Results format...

            // Create a result sink where results are written to.
            XmlTextWriter writer = new XmlTextWriter("C:\\temp\\xmltest3.xml", null);

            QueryResultSink sink = new SparqlXmlQuerySink(writer);

            // Run the query.
            query.Run(data, sink);

            writer.Close();
            TextWriter stringWriter1 = new StringWriter();

            query.Run(data, stringWriter1);

            psink._pName = f.Name.Replace(".n3", "");
            query.Run(data, psink);
            //Response.Write(stringWriter1.ToString());

            //    FileStream fs = new FileStream("C:\\temp\\xmltest3.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            //    xmldoc = new XmlDocument();
            //    xmldoc.Load(fs);
            //    XmlNodeList xmlnode = xmldoc.GetElementsByTagName("binding");

            //    for (int i = 0; i < xmlnode.Count; i++)
            //    {

            //        XmlAttributeCollection xmlattrc = xmlnode[i].Attributes;

            //        //XML Attribute Name and Value returned
            //        //Example: <Book id = "001">

            //        //First Child of the XML file - Catalog.xml - returned
            //        //Example: <Author>Mark</Author>
            //        i = i + 1;
            //        dt.Rows.Add(f.Name.Replace(".n3",""),xmlnode[i].NextSibling.InnerText.Replace("http://www.owl-ontologies.com/Ontology1183162121.owl#", ""), xmlnode[i-1].InnerText.Replace("http://www.owl-ontologies.com/Ontology1183162121.owl#", ""),xmlnode[i].InnerText.Replace("http://www.owl-ontologies.com/Ontology1183162121.owl#", ""));

            //    }

            //    fs.Close();
        }

        if (psink.list.Count > 0)
        {
            GridView1.DataSource = null;
            Result r = new Result();
            r.R = psink.list;
            GridView1.DataSource = psink.list;

            GridView1.DataBind();
            GridView1.Visible = true;
            lblMessage.Visible = false;
        }
        else
        {
            lblMessage.Text = "No records found";
            lblMessage.Visible = true;
            dt = new DataTable();
        }
    }
    protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Query query;
        XmlDocument xmldoc;
        DataTable dt = new DataTable();
        PrintQuerySink psink = new PrintQuerySink();

        string datafile = ListBox1.SelectedValue.ToString();
        string str = string.Empty;
        dt.Columns.Add("Name");
        dt.Columns.Add("Disease");
        dt.Columns.Add("Symptom");
        dt.Columns.Add("Medication");

        str = "PREFIX table:<http://www.owl-ontologies.com/Ontology1183162121.owl#> \n " +
        "SELECT distinct ?dis ?symp ?medi  \n " +
        "from <" + ListBox1.SelectedValue.ToString() + ">\n " +
        " where \n" +
           "{\n" +
           " ?Disease table:disease ?dis.\n" +
           " ?dis table:symptoms ?sym. \n" +
           " ?dis table:medication ?med. \n" +
           "?dis table:disease-name ?dise.\n" +
        "?sym table:symp-name ?symp.\n" +
        "?med table:med-name ?medi.\n }";
        query = new SparqlEngine(str);
        MemoryStore data = new MemoryStore();
        data.Import(new N3Reader(datafile));
        psink._pName = ListBox1.SelectedValue.ToString().Replace(".n3", "").Replace(@"C:\PatientOWLFiles\", "");
        query.Run(data, psink);

        if (psink.list.Count > 0)
        {
            GridView1.DataSource = null;
            Result r = new Result();
            r.R = psink.list;
            GridView1.DataSource = psink.list;
            GridView1.Visible = true;
            GridView1.DataBind();
            lblMessage.Visible = false;
        }
        else
        {
            lblMessage.Text = "No records found";
            GridView1.Visible = false;
            lblMessage.Visible = true;
            dt = new DataTable();
        }
    }
Esempio n. 33
0
        private static object Create(string spec, bool output)
        {
            string[] multispecs = spec.Split('\n', '|');
            if (multispecs.Length > 1)
            {
                SemWeb.Stores.MultiStore multistore = new SemWeb.Stores.MultiStore();
                foreach (string mspec in multispecs)
                {
                    object mstore = Create(mspec.Trim(), output);
                    if (mstore is SelectableSource)
                    {
                        multistore.Add((SelectableSource)mstore);
                    }
                    else if (mstore is StatementSource)
                    {
                        MemoryStore m = new MemoryStore((StatementSource)mstore);
                        multistore.Add(m);
                    }
                }
                return(multistore);
            }

            string type = spec;

            int c = spec.IndexOf(':');

            if (c != -1)
            {
                type = spec.Substring(0, c);
                spec = spec.Substring(c + 1);
            }
            else
            {
                spec = "";
            }

            Type ttype;

            switch (type)
            {
            case "mem":
                return(new MemoryStore());

            case "xml":
                if (spec == "")
                {
                    throw new ArgumentException("Use: xml:filename");
                }
                if (output)
                {
                    return(new RdfXmlWriter(spec));
                }
                else
                {
                    return(new RdfXmlReader(spec));
                }

            case "n3":
            case "ntriples":
            case "nt":
            case "turtle":
                if (spec == "")
                {
                    throw new ArgumentException("Use: format:filename");
                }
                if (output)
                {
                    N3Writer ret = new N3Writer(spec);                             // turtle is default format
                    switch (type)
                    {
                    case "nt":
                    case "ntriples":
                        ret.Format = N3Writer.Formats.NTriples;
                        break;
                    }
                    return(ret);
                }
                else
                {
                    return(new N3Reader(spec));
                }

            /*case "file":
             *      if (spec == "") throw new ArgumentException("Use: format:filename");
             *      if (output) throw new ArgumentException("The FileStore does not support writing.");
             *      return new SemWeb.Stores.FileStore(spec);*/
            case "sqlite":
            case "mysql":
            case "postgresql":
                if (spec == "")
                {
                    throw new ArgumentException("Use: sqlite|mysql|postgresql:table:connection-string");
                }

                c = spec.IndexOf(':');
                if (c == -1)
                {
                    throw new ArgumentException("Invalid format for SQL spec parameter (table:constring).");
                }
                string table = spec.Substring(0, c);
                spec = spec.Substring(c + 1);

                string classtype = null;
                if (type == "sqlite")
                {
                    classtype = "SemWeb.Stores.SqliteStore, SemWeb.SqliteStore";
                    spec      = spec.Replace(";", ",");
                }
                else if (type == "mysql")
                {
                    classtype = "SemWeb.Stores.MySQLStore, SemWeb.MySQLStore";
                }
                else if (type == "postgresql")
                {
                    classtype = "SemWeb.Stores.PostgreSQLStore, SemWeb.PostgreSQLStore";
                }
                ttype = Type.GetType(classtype);
                if (ttype == null)
                {
                    throw new NotSupportedException("The storage type in <" + classtype + "> could not be found.");
                }
                return(Activator.CreateInstance(ttype, new object[] { spec, table }));

            /*case "bdb":
             *      return new SemWeb.Stores.BDBStore(spec);*/
            case "sparql-http":
                return(new SemWeb.Remote.SparqlHttpSource(spec));

            case "class":
                ttype = Type.GetType(spec);
                if (ttype == null)
                {
                    throw new NotSupportedException("The class <" + spec + "> could not be found.");
                }
                return(Activator.CreateInstance(ttype));

            default:
                throw new ArgumentException("Unknown parser type: " + type);
            }
        }