ジャナ・ビジネス・コンサルティング有限会社トップページへ
/*
 * Berkeley DB XML .NET API
 * 
 * Copyright (C) 2007 Jana Business Consulting Ltd. All rights reserved.
 * 
 * For more information, see http://www.janabiz.com.
 * 
 */

using JanaBiz.Db;
using JanaBiz.DbXml;
using JanaBiz.DbXml.Exceptions;

public class QueryWithContext
{
    private static string theContainer = "namespaceExampleData.dbxml";

    // Performs a query against a document using an QueryContext.
    private static void doContextQuery(XmlManager mgr, string query, 
        XmlQueryContext context)
    {
        // Perform a single query against the referenced container using
        // the referenced context.
        System.Console.WriteLine("Exercising query: '" + query + "'.");
        System.Console.WriteLine("Return to continue: ");
        System.Console.ReadLine();
    
        // Perform the query
        XmlResults results = mgr.Query(null, query, context, new XmlDocumentConfig());
        // Iterate over the results
        while(results.MoveNext())
        {
            System.Console.WriteLine(results.Current);
        }
        System.Console.WriteLine(results.Size + " results returned for query '" 
            + query + "'.");
    }

    public static void Main(string[] args) 
    {

        string envdir = parseArguments(args);
                
        DbEnvironment dbEnv = null;
        XmlManager mgr = null;
        XmlContainer container = null;

        try 
        {
            // Open an environment 
            dbEnv = CreateDbEnvironment(envdir);
            
            // Open a manager
            using(mgr = CreateManager(dbEnv)) 
            {

                // Open a transactional container
                XmlContainerConfig containerconfig = new XmlContainerConfig();
                containerconfig.Transactional = true;
                using(container = mgr.OpenContainer(null, theContainer,
                          containerconfig))
                {

                    // Create a context and declare the namespaces
                    using(XmlQueryContext context = mgr.CreateQueryContext()) 
                    {
                        context.SetNamespace("fruits", "http://groceryItem.dbxml/fruits");
                        context.SetNamespace("vegetables", "http://groceryItem.dbxml/vegetables");
                        context.SetNamespace("desserts", "http://groceryItem.dbxml/desserts");

                        // Set a variable
                        context.SetVariableValue("aDessert",
                            new XmlValue("Blueberry Boy Bait"));

                        // Perform the queries

                        // Find all the Vendor documents in the database. Vendor documents do
                        // not use namespaces, so this query returns documents.
                        doContextQuery(mgr, "collection(\"" + theContainer +
                            "\")/vendor", context);

                        // Find the product document for "Lemon Grass". 
                        // This query returns no documents
                        // because a namespace prefix is not identified for the 'item' node.
                        doContextQuery(mgr, "collection(\"" + theContainer +
                            "\")/item/product[.=\"Lemon Grass\"]", context);

                        // Find the product document for "Lemon Grass" using the namespace 
                        // prefix 'fruits'. This query successfully returns a document.
                        doContextQuery(mgr, "collection(\"" + theContainer +
                            "\")/fruits:item/product[.=\"Lemon Grass\"]", context);

                        // Find all the vegetables
                        doContextQuery(mgr, "collection(\"" + theContainer +
                            "\")/vegetables:item", context);

                        // Find the dessert called Blueberry Boy Bait.
                        // Note the use of a variable.
                        doContextQuery(mgr, "collection(\"" + theContainer +
                            "\")/desserts:item/product[.=$aDessert]", context);
                    }
                }
            }
        }
        catch(DbXmlException e) 
        {
            System.Console.WriteLine("Error performing query against " + theContainer);
            System.Console.WriteLine(e.ToString());
        }
        finally
        {
            if(container != null)
            {
                container.Close();
            }
            if(mgr != null)
            {
                mgr.Close();
            }
            if(dbEnv != null)
            {
                dbEnv.Close();
            }
        }
    }
    
    public static DbEnvironment CreateDbEnvironment(string envdir) 
    {
        DbEnvironmentConfig envconf = new DbEnvironmentConfig();
        envconf.CacheSize = 50 * 1024;
        envconf.AllowCreate = true;    
        envconf.InitializeCache = true;
        envconf.Transactional = true;
        envconf.InitializeLocking = true;
        envconf.InitializeLogging = true;
        envconf.RunRecovery = true;
        envconf.ErrorWriter = System.Console.Out;
        envconf.ErrorPrefix = "PREFIX"; 

        DbEnvironment env = new DbEnvironment(envdir, envconf);
        
        return env;
    }

    public static XmlManager CreateManager(DbEnvironment env) 
    {
        XmlManagerConfig mgrconfig = new XmlManagerConfig();
        mgrconfig.AdoptEnvironment = true;
        try 
        {
            return new XmlManager(env, mgrconfig);
        }
        catch(System.Exception e) 
        {
            env.Close();
            throw e;
        }
    }

    private static void Usage() 
    {
        System.Console.WriteLine("This program illustrates how to query for documents that require namespace");
        System.Console.WriteLine("usage in the query. You should run exampleLoadContainer before running this example.");
        System.Console.WriteLine("You are only required to pass this command the path location of the database");
        System.Console.WriteLine("environment that you specified when you loaded the examples data:");
        System.Console.WriteLine();        
        System.Console.WriteLine("\t-h <dbenv directory>");
        System.Console.WriteLine("For example:");
        System.Console.WriteLine("\tqueryWithContext.exe -h examplesEnvironment");

        System.Environment.Exit(-1);
    }

    private static string parseArguments(string[] args) 
    {
        string envdir = null;
        for(int i = 0; i < args.Length; ++i) 
        {
            string arg = args[i];
            if((arg.StartsWith("-")
#if WIN32
                || arg.StartsWith("/")
#endif
                ) && arg.Length > 1) 
            {
                switch(arg[1]) 
                {
                    case 'h': 
                    {
                        ++i;
                        if(i >= args.Length) 
                        {
                            System.Console.WriteLine("Invalid option: " + arg);
                            Usage();
                        }
                        envdir = args[i];
                        break;
                    }
                    default: 
                    {
                        System.Console.WriteLine("Unknown option: " + arg);
                        Usage();
                        break;
                    }
                }
            }
            else 
            {
                System.Console.WriteLine("Too many arguments: " + arg);
                Usage();
            }
        }
        if(envdir == null) 
        {
            System.Console.WriteLine("Environment directory not found.");
            Usage();
        }
        return envdir;
    }

}