Exemplo n.º 1
0
 /// <summary>
 /// Creates a new Triple Collection as a wrapper around a SemWeb StatementSink and StatementSource
 /// </summary>
 /// <param name="g">Graph</param>
 /// <param name="sink">Sink</param>
 /// <param name="source">Source</param>
 public SemWebTripleCollection(IGraph g, StatementSink sink, StatementSource source)
 {
     this._g       = g;
     this._sink    = sink;
     this._source  = source;
     this._mapping = new SemWebMapping(this._g);
 }
        public override void Import(StatementSource source)
        {
            bool newDistinct = checkForDuplicates || ((StatementCount == 0) && source.Distinct);

            base.Import(source);             // distinct set to false if !checkForDuplicates
            distinct = newDistinct;
        }
Exemplo n.º 3
0
            public void Import(StatementSource source)
            {
                bool newDistinct = checkForDuplicates || ((StatementCount == 0) && source.Distinct);

                source.Select(this);
                distinct = newDistinct;
            }
Exemplo n.º 4
0
 /// <summary>
 /// Creates a new Triple Collection as a wrapper around a SemWeb StatementSink and StatementSource
 /// </summary>
 /// <param name="g">Graph</param>
 /// <param name="sink">Sink</param>
 /// <param name="source">Source</param>
 public SemWebTripleCollection(IGraph g, StatementSink sink, StatementSource source) 
 {
     this._g = g;
     this._sink = sink;
     this._source = source;
     this._mapping = new SemWebMapping(this._g);
 }
        private IDbCommand PrepareCommand(IDbConnection connection, StatementSource statementSource)
        {
            IDbCommand command = providerFactory.CreateCommand();

            command.Connection  = connection;
            command.CommandText = statementSource.Statement;
            return(command);
        }
Exemplo n.º 6
0
        private void DeleteProduct(Product product)
        {
            StatementSource statementSource = new StatementSource();

            statementSource.Statement =
                "DELETE FROM [Products] " +
                "WHERE [ProductID] = @ProductID";
            statementSource.Parameters = CreateDeleteParam(product);

            ExecuteNonQuery(statementSource);
        }
        public IList <Product> FindProductsWithCategoryId(int categoryId)
        {
            StatementSource statementSource = new StatementSource();

            statementSource.Statement =
                "SELECT * FROM [Products] " +
                "WHERE [Products].CategoryID = @CategoryID";
            statementSource.Parameters = CreateFindProductsWithCategoryIdParam(categoryId);

            return(FindDomainObjectsByCriteria(statementSource).Cast <Product>().ToList());
        }
 private void PrepareCommandParameters(IDbCommand command, StatementSource statementSource)
 {
     foreach (IDbDataParameter dbDataParameter in statementSource.Parameters)
     {
         DbParameter parameter = providerFactory.CreateParameter();
         parameter.ParameterName = dbDataParameter.ParameterName;
         parameter.DbType        = dbDataParameter.DbType;
         parameter.Value         = dbDataParameter.Value;
         command.Parameters.Add(parameter);
     }
 }
        public Product FindProductById(int productId)
        {
            Key             productKey      = new Key(productId);
            StatementSource statementSource = new StatementSource();

            statementSource.Statement =
                "SELECT * FROM [Products] " +
                "WHERE [Products].ProductID = @ProductID";
            statementSource.Parameters = CreateFindProductByIdParam(productId);

            return((Product)FindSingleById(productKey, statementSource));
        }
Exemplo n.º 10
0
        private void UpdateProduct(Product product)
        {
            StatementSource statementSource = new StatementSource();

            statementSource.Statement =
                "UPDATE [Products] " +
                "SET [ProductName] = @ProductName, [SupplierID] = @SupplierID, [CategoryID] = @CategoryID, [QuantityPerUnit] = @QuantityPerUnit, [UnitPrice] = @UnitPrice, [UnitsInStock] = @UnitsInStock, [UnitsOnOrder] = @UnitsOnOrder, [ReorderLevel] = @ReorderLevel, [Discontinued] = @Discontinued " +
                "WHERE [ProductID] = @ProductID";
            statementSource.Parameters = CreateUpdateParam(product);

            ExecuteNonQuery(statementSource);
        }
Exemplo n.º 11
0
        protected virtual SelectableSource GetDataSource(out bool closeAfterQuery)
        {
            closeAfterQuery = false;

            if (System.Web.HttpContext.Current == null)
            {
                throw new InvalidOperationException("This method is not valid outside of an ASP.NET request.");
            }

            string path = System.Web.HttpContext.Current.Request.Path;

            lock (sources) {
                SelectableSource source = (SelectableSource)sources[path];
                if (source != null)
                {
                    return(source);
                }

                System.Collections.Specialized.NameValueCollection config = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationSettings.GetConfig("sparqlSources");
                if (config == null)
                {
                    throw new InvalidOperationException("No sparqlSources config section is set up.");
                }

                string spec = config[path];
                if (spec == null)
                {
                    throw new InvalidOperationException("No data source is set for the path " + path + ".");
                }

                bool reuse = true;
                if (spec.StartsWith("noreuse,"))
                {
                    reuse           = false;
                    closeAfterQuery = true;
                    spec            = spec.Substring("noreuse,".Length);
                }

                StatementSource src = Store.CreateForInput(spec);
                if (!(src is SelectableSource))
                {
                    src = new MemoryStore(src);
                }

                if (reuse)
                {
                    sources[path] = src;
                }

                return((SelectableSource)src);
            }
        }
Exemplo n.º 12
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));
 }
Exemplo n.º 13
0
        protected void ExecuteNonQuery(StatementSource statementSource)
        {
            using (IDbConnection connection = providerFactory.CreateConnection())
            {
                OpenConnection(connection);

                IDbCommand command = PrepareCommand(connection, statementSource);

                PrepareCommandParameters(command, statementSource);

                ExecuteNonQueryCommand(command);
            }
        }
Exemplo n.º 14
0
 public void LoadSchema(StatementSource source)
 {
     if (source is SelectableSource)
     {
         ((SelectableSource)source).Select(
             new SelectFilter(
                 null,
                 new Entity[] { subClassOf, subPropertyOf, domain, range },
                 null, null), Schema);
     }
     else
     {
         source.Select(Schema);
     }
 }
Exemplo n.º 15
0
        /// <summary>
        /// Takes the contents of a SemWeb Statement Source and inputs it into a dotNetRDF Graph
        /// </summary>
        /// <param name="source">Statement Source</param>
        /// <param name="g">Graph</param>
        public static void FromSemWeb(StatementSource source, IGraph g)
        {
            SemWebMapping mapping = new SemWebMapping(g);
            Triple        t;

            MemoryStore mem = new MemoryStore();

            source.Select(mem);

            foreach (Statement stmt in mem)
            {
                t = FromSemWeb(stmt, mapping);
                g.Assert(t);
            }
        }
Exemplo n.º 16
0
        public bool Import(Photo photo, string path, string orig_path)
        {
            XmpFile xmp;

            string source_sidecar = String.Format("{0}{1}{2}.xmp",
                                                  Path.GetDirectoryName(orig_path),
                                                  Path.DirectorySeparatorChar,
                                                  Path.GetFileName(orig_path));

            string dest_sidecar = String.Format("{0}{1}{2}.xmp",
                                                Path.GetDirectoryName(path),
                                                Path.DirectorySeparatorChar,
                                                Path.GetFileName(path));

            if (File.Exists(source_sidecar))
            {
                xmp = new XmpFile(File.OpenRead(source_sidecar));
            }
            else if (File.Exists(dest_sidecar))
            {
                xmp = new XmpFile(File.OpenRead(dest_sidecar));
            }
            else
            {
                xmp = new XmpFile();
            }

            using (ImageFile img = ImageFile.Create(path)) {
                StatementSource source = img as StatementSource;
                if (source != null)
                {
                    try {
                        source.Select(xmp);
                    } catch  {
                    }
                }
            }

            ProcessStore(xmp.Store, photo);
#if enable_debug
            xmp.Save(Console.OpenStandardOutput());
#endif
            return(true);
        }
Exemplo n.º 17
0
        public void Import(StatementSource source)
        {
            if (source == null)
            {
                throw new ArgumentNullException();
            }

            Init();
            connection.BeginTransaction();

            Importer imp = new Importer(this);

            try {
                source.Select(imp);
            } finally {
                imp.RunAddBuffer();
                connection.EndTransaction();
            }
        }
Exemplo n.º 18
0
        private void InsertProduct(Product product)
        {
            StatementSource statementSource = new StatementSource();

            statementSource.Statement =
                "INSERT INTO [Products] " +
                "([ProductName], [SupplierID], [CategoryID], [QuantityPerUnit], [UnitPrice], [UnitsInStock], [UnitsOnOrder], [ReorderLevel], [Discontinued]) " +
                "VALUES (@ProductName, @SupplierID, @CategoryID, @QuantityPerUnit, @UnitPrice, @UnitsInStock, @UnitsOnOrder, @ReorderLevel, @Discontinued)" +
                "SELECT @ProductID = @@IDENTITY";
            statementSource.Parameters = CreateInsertParam(product);

            ExecuteNonQuery(statementSource);

            product.ProductID = (int)statementSource.Parameters.SingleOrDefault(p => p.ParameterName == "@ProductID").Value;

            Key productKey = new Key(product.ProductID);

            product.UniqueKey = productKey;
            IdentityMap <Key, Product> .Instance.PutEntry(productKey, product);
        }
        protected IEnumerable <DomainObject> FindDomainObjectsByCriteria(StatementSource statementSource)
        {
            // You can not search identity map only with where clause.
            // Identity map check will occur in load section.

            // Not found in identity map. Do database query.
            using (IDbConnection connection = providerFactory.CreateConnection())
            {
                OpenConnection(connection);

                IDbCommand command = PrepareCommand(connection, statementSource);

                PrepareCommandParameters(command, statementSource);

                IDataReader reader = ExecuteReader(command);
                while (reader.Read())
                {
                    yield return(MapRecordToDomainObject((IDataRecord)reader));
                }
            }
        }
        //protected IDictionary<string, StatementSource> parameters = new Dictionary<string, StatementSource>();

        protected DomainObject FindSingleById(Key uniqueKey, StatementSource statementSource)
        {
            // Get from identity map.
            DomainObject domainObject = TryGetFromIdentityMap(uniqueKey);

            if (domainObject != null)
            {
                return(domainObject);
            }

            // Not found in identity map. Do database query.
            using (IDbConnection connection = providerFactory.CreateConnection())
            {
                OpenConnection(connection);

                IDbCommand command = PrepareCommand(connection, statementSource);

                PrepareCommandParameters(command, statementSource);

                IDataReader reader = ExecuteQuerySingle(command);

                return(MapRecordToDomainObject((IDataRecord)reader));
            }
        }
Exemplo n.º 21
0
        private bool Update()
        {
            TreeIter  iter;
            ListStore model;
            string    name;
            bool      empty   = true;
            bool      missing = false;

            System.Exception error = null;

            up_to_date = true;

            int i = 0;
            int index_of_expander = 0;

            // Write Exif-Data
            if (exif_info != null)
            {
                foreach (Exif.ExifContent content in exif_info.GetContents())
                {
                    Exif.ExifEntry [] entries = content.GetEntries();

                    i++;

                    if (entries.Length < 1)
                    {
                        continue;
                    }

                    empty = false;

                    name = Exif.ExifUtil.GetIfdNameExtended((Exif.Ifd)i - 1);

                    if (index_of_expander >= exif_vbox.Children.Length)
                    {
                        model = AddExpander(name, index_of_expander);
                    }
                    else
                    {
                        Expander expander = (Expander)exif_vbox.Children[index_of_expander];
                        if (expander.Label == name)
                        {
                            model = (ListStore)((TreeView)expander.Child).Model;
                        }
                        else
                        {
                            model = AddExpander(name, index_of_expander);
                        }
                    }

                    model.GetIterFirst(out iter);

                    foreach (Exif.ExifEntry entry in entries)
                    {
                        string s;

                        if (entry.Title != null)
                        {
                            s = String.Format("{0}\n\t<small>{1}</small>", entry.Title, entry.Value);
                        }
                        else
                        {
                            s = String.Format("Unknown Tag ID={0}\n\t<small>{1}</small>", entry.Tag.ToString(), entry.Value);
                        }

                        if (model.IterIsValid(iter))
                        {
                            model.SetValue(iter, 0, s);
                            model.IterNext(ref iter);
                        }
                        else
                        {
                            model.AppendValues(s);
                        }
                    }

                    // remove rows, that are not used
                    while (model.IterIsValid(iter))
                    {
                        model.Remove(ref iter);
                    }

                    index_of_expander++;
                }
            }


            // Write Extended Metadata
            if (photo != null)
            {
                MetadataStore store = new MetadataStore();
                try {
                    using (ImageFile img = ImageFile.Create(photo.DefaultVersionUri)) {
                        if (img is SemWeb.StatementSource)
                        {
                            StatementSource source = (StatementSource)img;
                            source.Select(store);
                        }
                    }
                } catch (System.IO.FileNotFoundException) {
                    missing = true;
                } catch (System.Exception e) {
                    // Sometimes we don't get the right exception, check for the file
                    if (!System.IO.File.Exists(photo.DefaultVersionUri.LocalPath))
                    {
                        missing = true;
                    }
                    else
                    {
                        // if the file is there but we still got an exception display it.
                        error = e;
                    }
                }

                model = extended_metadata;
                model.GetIterFirst(out iter);

                if (store.StatementCount > 0)
                {
                    empty = false;


                    foreach (Statement stmt in store)
                    {
                        // Skip anonymous subjects because they are
                        // probably part of a collection
                        if (stmt.Subject.Uri == null && store.SelectSubjects(null, stmt.Subject).Length > 0)
                        {
                            continue;
                        }

                        string title;
                        string value;
                        string s;

                        Description.GetDescription(store, stmt, out title, out value);

                        if (value == null)
                        {
                            MemoryStore   substore   = store.Select(new Statement((Entity)stmt.Object, null, null, null)).Load();
                            StringBuilder collection = new StringBuilder();
                            collection.Append(title);
                            WriteCollection(substore, collection);
                            if (model.IterIsValid(iter))
                            {
                                model.SetValue(iter, 0, collection.ToString());
                                model.IterNext(ref iter);
                            }
                            else
                            {
                                model.AppendValues(collection.ToString());
                            }
                        }
                        else
                        {
                            s = String.Format("{0}\n\t<small>{1}</small>", title, value);
                            if (model.IterIsValid(iter))
                            {
                                model.SetValue(iter, 0, s);
                                model.IterNext(ref iter);
                            }
                            else
                            {
                                model.AppendValues(s);
                            }
                        }
                    }
                }
                else
                {
                    // clear Extended Metadata
                    String s = String.Format("<small>{0}</small>", Catalog.GetString("No Extended Metadata Available"));
                    if (model.IterIsValid(iter))
                    {
                        model.SetValue(iter, 0, s);
                        model.IterNext(ref iter);
                    }
                    else
                    {
                        model.AppendValues(s);
                    }
                }

                // remove rows, that are not used
                while (model.IterIsValid(iter))
                {
                    model.Remove(ref iter);
                }
            }

            if (empty)
            {
                string msg;
                if (photo == null)
                {
                    msg = Catalog.GetString("No active photo");
                }
                else if (missing)
                {
                    msg = String.Format(Catalog.GetString("The photo \"{0}\" does not exist"),
                                        photo.DefaultVersionUri);
                }
                else
                {
                    msg = Catalog.GetString("No metadata available");

                    if (error != null)
                    {
                        msg = String.Format("<i>{0}</i>", error);
                    }
                }

                exif_message.Markup = "<span weight=\"bold\">" + msg + "</span>";

                if (display == State.exif)
                {
                    // Child is a Viewport, (AddWithViewport in ctor)
                    ((Viewport)Child).Remove(main_vbox);
                    ((Viewport)Child).Add(exif_message);
                    display = State.message;
                    exif_message.Show();
                }
            }
            else
            {
                // remove Expanders, that are not used
                while (index_of_expander < exif_vbox.Children.Length)
                {
                    exif_vbox.Remove(exif_vbox.Children[index_of_expander]);
                }

                if (display == State.message)
                {
                    // Child is a Viewport, (AddWithViewport in ctor)
                    ((Viewport)Child).Remove(exif_message);
                    ((Viewport)Child).Add(main_vbox);
                    display = State.exif;
                    main_vbox.ShowAll();
                }
            }

            return(false);
        }
Exemplo n.º 22
0
 public MemoryStore(StatementSource source)
     : this()
 {
     Import(source);
 }
Exemplo n.º 23
0
		public override void Import(StatementSource source) {
			bool newDistinct = checkForDuplicates || ((StatementCount==0) && source.Distinct);
			base.Import(source); // distinct set to false if !checkForDuplicates
			distinct = newDistinct;
		}
Exemplo n.º 24
0
 public StoreImpl(StatementSource source) : this()
 {
     Import(source);
 }
Exemplo n.º 25
0
 public void BeginReading(StatementSource source)
 {
     sourceData = source;
     writer = new Thread(WriterRunner);
     writer.Start();
 }
Exemplo n.º 26
0
 public static void Build(StatementSource graph, out bool[,] connectivity, Hashtable indexes)
 {
     connectivity = new bool[indexes.Count, indexes.Count];
     graph.Select(new Sink(connectivity, indexes));
 }
Exemplo n.º 27
0
		public static void Build(StatementSource graph, out bool[,] connectivity, Hashtable indexes) {
			connectivity = new bool[indexes.Count, indexes.Count];
			graph.Select(new Sink(connectivity, indexes));
		}
Exemplo n.º 28
0
 /// <summary>
 /// Creates a new SemWeb Graph which is a dotNetRDF wrapper around a SemWeb StatementSource and StatementSink
 /// </summary>
 /// <param name="sink">Sink</param>
 /// <param name="source">Source</param>
 public SemWebGraph(StatementSink sink, StatementSource source)
 {
     this._triples = new SemWebTripleCollection(this, sink, source);
 }
Exemplo n.º 29
0
		public RDFS(StatementSource schema) : this() {
			LoadSchema(schema);
		}
Exemplo n.º 30
0
        /// <summary>
        /// Takes the contents of a SemWeb Statement Source and inputs it into a dotNetRDF Graph
        /// </summary>
        /// <param name="source">Statement Source</param>
        /// <param name="g">Graph</param>
        public static void FromSemWeb(StatementSource source, IGraph g)
        {
            SemWebMapping mapping = new SemWebMapping(g);
            Triple t;
            
            MemoryStore mem = new MemoryStore();
            source.Select(mem);

            foreach (Statement stmt in mem)
            {
                t = FromSemWeb(stmt, mapping);
                g.Assert(t);
            }
        }
Exemplo n.º 31
0
        public void Import(StatementSource source)
        {
            if (source == null) throw new ArgumentNullException();

            Init();
            connection.BeginTransaction();

            Importer imp = new Importer(this);

            try {
                source.Select(imp);
            } finally {
                imp.RunAddBuffer();
                connection.EndTransaction();
            }
        }
Exemplo n.º 32
0
 public void BeginReading(StatementSource source)
 {
     sourceData = source;
     writer     = new Thread(WriterRunner);
     writer.Start();
 }
Exemplo n.º 33
0
 /// <summary>
 /// Adds the contents of the given Statement Source to the Store
 /// </summary>
 /// <param name="source">Statement Source</param>
 public void Import(StatementSource source)
 {
     source.Select(this);
 }
Exemplo n.º 34
0
		public RDFS(StatementSource schema, SelectableSource data)
		: this(data) {
			LoadSchema(schema);
		}
Exemplo n.º 35
0
        // The next few routines convert a set of axioms from a StatementSource
        // into a data structure of use for the algorithm, with Sequents and things.



        private static Hashtable RulesToCases(StatementSource rules)
        {
            Hashtable   cases       = new Hashtable();
            MemoryStore rules_store = new MemoryStore(rules);

            foreach (Statement p in rules_store)
            {
                if (p.Meta == Statement.DefaultMeta)
                {
                    if (p.Predicate == entLOGIMPLIES && p.Object is Entity)
                    {
                        MemoryStore body = new MemoryStore();
                        MemoryStore head = new MemoryStore();

                        rules_store.Select(new Statement(null, null, null, (Entity)p.Subject), new RemoveMeta(body));
                        rules_store.Select(new Statement(null, null, null, (Entity)p.Object), new RemoveMeta(head));

                        // Any variables in the head not bound in the body represent existentially closed bnodes.
                        // (Euler's OWL test case does this. Wish they had used bnodes instead of vars...)
                        ResSet bodyvars = new ResSet();
                        foreach (Statement b in body)
                        {
                            if (b.Subject is Variable)
                            {
                                bodyvars.Add(b.Subject);
                            }
                            if (b.Predicate is Variable)
                            {
                                bodyvars.Add(b.Predicate);
                            }
                            if (b.Object is Variable)
                            {
                                bodyvars.Add(b.Object);
                            }
                        }
                        foreach (Entity v in head.GetEntities())
                        {
                            if (v is Variable && !bodyvars.Contains(v))
                            {
                                head.Replace(v, new BNode(((Variable)v).LocalName));
                            }
                        }

                        // Replace (...) lists in the body that are tied to the subjects
                        // of user predicates with callArgs objects.
                        Hashtable callArgs = new Hashtable();
                        CollectCallArgs(body, callArgs);

                        // Rules can't have more than one statement in their
                        // consequent.  The best we can do is break up
                        // the consequent into multiple rules.  (Since all head
                        // variables are bound in body, it's equivalent...?)
                        foreach (Statement h in head)
                        {
                            AddSequent(cases, new Sequent(h, body.ToArray(), callArgs));
                        }
                    }
                    else
                    {
                        AddSequent(cases, new Sequent(p, new Statement[0], null));
                    }
                }
            }

            return(cases);
        }
Exemplo n.º 36
0
		/*internal static void Escape(StringBuilder b) {
			b.Replace("\\", "\\\\");
			b.Replace("\"", "\\\"");
			b.Replace("\n", "\\n");
			b.Replace("%", "\\%");
			b.Replace("*", "\\*");
		}*/

		public override void Import(StatementSource source) {
			if (source == null) throw new ArgumentNullException();
			if (isImporting) throw new InvalidOperationException("Store is already importing.");
			
			Init();
			RunAddBuffer();
			
			cachedNextId = -1;
			addStatementBuffer = new StatementList();
			
			BeginTransaction();
			
			try {
				isImporting = true;
				base.Import(source);
			} finally {
				RunAddBuffer();
				EndTransaction();
				
				addStatementBuffer = null;
				isImporting = false;

				entityCache.Clear();
				literalCache.Clear();
			}
		}
Exemplo n.º 37
0
 /// <summary>
 /// Imports the contents of a Source into the underlying Graph
 /// </summary>
 /// <param name="source"></param>
 public void Import(StatementSource source)
 {
     source.Select(this);
 }
Exemplo n.º 38
0
		public MemoryStore(StatementSource source) : this() {
			Import(source);
		}
Exemplo n.º 39
0
 public Euler(StatementSource rules)
 {
     this.rules = RulesToCases(rules);
 }
Exemplo n.º 40
0
        // The next few routines convert a set of axioms from a StatementSource
        // into a data structure of use for the algorithm, with Sequents and things.
        private static Hashtable RulesToCases(StatementSource rules)
        {
            Hashtable cases = new Hashtable();
            MemoryStore rules_store = new MemoryStore(rules);
            foreach (Statement p in rules_store) {
                if (p.Meta == Statement.DefaultMeta) {
                    if (p.Predicate == entLOGIMPLIES && p.Object is Entity) {
                        MemoryStore body = new MemoryStore();
                        MemoryStore head = new MemoryStore();

                        rules_store.Select(new Statement(null, null, null,  (Entity)p.Subject), new RemoveMeta(body));
                        rules_store.Select(new Statement(null, null, null,  (Entity)p.Object), new RemoveMeta(head));

                        // Any variables in the head not bound in the body represent existentially closed bnodes.
                        // (Euler's OWL test case does this. Wish they had used bnodes instead of vars...)
                        ResSet bodyvars = new ResSet();
                        foreach (Statement b in body) {
                            if (b.Subject is Variable) bodyvars.Add(b.Subject);
                            if (b.Predicate is Variable) bodyvars.Add(b.Predicate);
                            if (b.Object is Variable) bodyvars.Add(b.Object);
                        }
                        foreach (Entity v in head.GetEntities()) {
                            if (v is Variable && !bodyvars.Contains(v))
                                head.Replace(v, new BNode(((Variable)v).LocalName));
                        }

                        // Replace (...) lists in the body that are tied to the subjects
                        // of user predicates with callArgs objects.
                        Hashtable callArgs = new Hashtable();
                        CollectCallArgs(body, callArgs);

                        // Rules can't have more than one statement in their
                        // consequent.  The best we can do is break up
                        // the consequent into multiple rules.  (Since all head
                        // variables are bound in body, it's equivalent...?)
                        foreach (Statement h in head)
                            AddSequent(cases, new Sequent(h, body.ToArray(), callArgs));
                    } else {
                        AddSequent(cases, new Sequent(p, new Statement[0], null));
                    }
                }
            }

            return cases;
        }
Exemplo n.º 41
0
    public static void Main(string[] args)
    {
        Opts opts = new Opts();

        opts.ProcessArgs(args);
        if (opts.RemainingArguments.Length != 2 && opts.RemainingArguments.Length != 3)
        {
            opts.DoHelp();
            return;
        }

        string datasource, rootentity, stylesheetfile;

        if (opts.RemainingArguments.Length == 2)
        {
            datasource     = opts.RemainingArguments[0];
            rootentity     = null;
            stylesheetfile = opts.RemainingArguments[1];
        }
        else
        {
            datasource     = opts.RemainingArguments[0];
            rootentity     = opts.RemainingArguments[1];
            stylesheetfile = opts.RemainingArguments[2];
        }

        XsltArgumentList xsltargs = new XsltArgumentList();

        if (opts.param != null)
        {
            foreach (string p in opts.param)
            {
                int eq = p.IndexOf('=');
                if (eq == -1)
                {
                    Console.Error.WriteLine("Param arguments must be name=value.");
                    return;
                }
                string n = p.Substring(0, eq);
                string v = p.Substring(eq + 1);
                xsltargs.AddParam(n, "", v);
            }
        }

        XmlDocument sty = new XmlDocument();

        sty.PreserveWhitespace = true;
        sty.Load(stylesheetfile);

        XslTransform t = new XslTransform();

        t.Load(sty, null, null);

        NamespaceManager nsmgr = new NamespaceManager();

        // Scan xmlsn: attributes in the stylesheet node.
        // For all namespaces of the form assembly://assemblyname/TypeName, load in
        // the methods of that type as extension functions in that namespace.
        // And add xmlns declarations to nsmgr.
        foreach (XmlAttribute a in sty.DocumentElement.Attributes)
        {
            if (!a.Name.StartsWith("xmlns:"))
            {
                continue;
            }

            nsmgr.AddNamespace(a.Value, a.Name.Substring(6));

            System.Uri uri = new System.Uri(a.Value);
            if (uri.Scheme != "assembly")
            {
                continue;
            }
            System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(uri.Host);
            System.Type ty = assembly.GetType(uri.AbsolutePath.Substring(1));
            if (ty == null)
            {
                Console.Error.WriteLine("Type not found: " + uri);
                return;
            }
            object obj = ty.GetConstructor(new Type[0]).Invoke(new Type[0]);
            xsltargs.AddExtensionObject(a.Value, obj);
        }

        StatementSource source = Store.CreateForInput(datasource);
        Store           model;

        if (source is Store)
        {
            model = (Store)source;
        }
        else
        {
            model = new MemoryStore(source);
        }

        XPathNavigator nav;

        if (rootentity != null)
        {
            nav = new XPathSemWebNavigator(rootentity, model, nsmgr);
        }
        else
        {
            nav = new XPathSemWebNavigator(model, nsmgr);
        }

        t.Transform(nav, xsltargs, Console.Out, null);
    }
Exemplo n.º 42
0
		public void Import(StatementSource source) {
			if (source == null) throw new ArgumentNullException();
			if (isImporting) throw new InvalidOperationException("Store is already importing.");
			
			Init();
			RunAddBuffer();
			
			cachedNextId = -1;
			NextId(); // get this before starting transaction because it relies on indexes which may be disabled
			
			addStatementBuffer = new StatementList();
			
			BeginTransaction();
			
			try {
				isImporting = true;
				source.Select(this);
			} finally {
				RunAddBuffer();
				EndTransaction();
				
				addStatementBuffer = null;
				isImporting = false;

				entityCache.Clear();
				literalCache.Clear();
			}
		}
Exemplo n.º 43
0
		public void LoadSchema(StatementSource source) {
			if (source is SelectableSource) {
				((SelectableSource)source).Select(
					new SelectFilter(
					null,
					new Entity[] { subClassOf, subPropertyOf, domain, range },
					null, null), Schema);
			} else {
				source.Select(Schema);
			}
		}
Exemplo n.º 44
0
        public override void Select(StatementSink storage)
        {
            foreach (string infile in files)
            {
                if (!quiet)
                {
                    Console.Error.Write(infile + " ");
                }

                try {
                    DateTime start = DateTime.Now;

                    StatementFilterSink filter = new StatementFilterSink(storage);

                    if (format == null || format != "spec")
                    {
                        string fmt = format;
                        if (fmt == null)
                        {
                            // Use file extension to override default parser type.
                            if (infile.StartsWith("http:"))
                            {
                                fmt = "url";
                            }
                            else if (infile.EndsWith(".nt") || infile.EndsWith(".n3") || infile.EndsWith(".ttl"))
                            {
                                fmt = "n3";
                            }
                            else if (infile.EndsWith(".xml") || infile.EndsWith(".rdf"))
                            {
                                fmt = "xml";
                            }
                            else
                            {
                                Console.Error.WriteLine("Unrecognized file extension in " + infile + ": Trying RDF/XML.");
                                fmt = "xml";
                            }
                        }

                        using (RdfReader parser = RdfReader.Create(fmt, infile)) {
                            if (baseuri != null)
                            {
                                parser.BaseUri = baseuri;
                            }
                            if (meta != null)
                            {
                                parser.Meta = meta;
                            }

                            if (storage is RdfWriter)
                            {
                                ((RdfWriter)storage).Namespaces.AddFrom(parser.Namespaces);
                            }

                            try {
                                parser.Select(filter);
                            } finally {
                                if (parser.Warnings.Count > 0)
                                {
                                    Console.Error.WriteLine("\nThere were warnings parsing this file:");
                                }
                                foreach (string warning in parser.Warnings)
                                {
                                    Console.Error.WriteLine("> " + warning);
                                }
                            }
                        }
                    }
                    else
                    {
                        StatementSource src = Store.Create(infile);
                        src.Select(filter);
                        if (src is IDisposable)
                        {
                            ((IDisposable)src).Dispose();
                        }
                    }

                    totalStatementsRead += filter.StatementCount;

                    TimeSpan time = DateTime.Now - start;

                    if (!quiet)
                    {
                        Console.Error.WriteLine(" {0}m{1}s, {2} statements, {3} st/sec", (int)time.TotalMinutes, (int)time.Seconds, filter.StatementCount, time.TotalSeconds == 0 ? "?" : ((int)(filter.StatementCount / time.TotalSeconds)).ToString());
                    }
                } catch (ParserException e) {
                    Console.Error.WriteLine(" " + e.Message);
                } catch (Exception e) {
                    Console.Error.WriteLine("\n" + e + "\n");
                }
            }
        }
Exemplo n.º 45
0
 /// <summary>
 /// Creates a new SemWeb Graph which is a dotNetRDF wrapper around a SemWeb StatementSource and StatementSink
 /// </summary>
 /// <param name="sink">Sink</param>
 /// <param name="source">Source</param>
 public SemWebGraph(StatementSink sink, StatementSource source)
 {
     this._triples = new SemWebTripleCollection(this, sink, source);
 }
Exemplo n.º 46
0
 public virtual void Write(StatementSource source)
 {
     source.Select(this);
 }
Exemplo n.º 47
0
		public virtual void Write(StatementSource source) {
			source.Select(this);
		}