ジャナ・ビジネス・コンサルティング有限会社トップページへ
/*
 * 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 ModifyDocument
{

    private static string theContainer = "namespaceExampleData.dbxml";

    // Method to add a "description" element after the query's target nodes
    private static void doModify(XmlManager mgr, XmlContainer container, XmlQueryContext context,
        string query, XmlTransaction txn) 
    {

        using(XmlQueryExpression expression = mgr.Prepare(txn, query, context)) 
        {
       
            System.Console.WriteLine("Updating document for the expression: '" + 
                query + "' ");
            System.Console.WriteLine("Return to continue: ");
            System.Console.ReadLine();
        
            // Print the document(s) to be updated -- those that describe 
            // Zapote Blanco (a fruit). The document strings are only being 
            // printed to show before/after results.
            // Most modification programs would not perform the additional queries.
            using(XmlResults results = expression.Execute(txn, context, new XmlDocumentConfig())) 
            {
                dumpDocuments(results);
      
                results.Reset();

                System.Console.WriteLine("About to update the document(s) above.");
                System.Console.WriteLine("Look for a new element after the target " +
                    "element, named 'description' ...");
                System.Console.WriteLine("Return to continue: ");
                System.Console.ReadLine();
       
                // The modification is a new element in the target node, called 
                // "descripton, which goes immediately after the <product> element.
                // if this program is run more than once, and committed, additional
                // identical elements are added.  It is easy to modify this program
                // to change the modification.
                using(XmlModify modify = mgr.CreateModify()) 
                {
                    using(XmlQueryExpression subexpr = mgr.Prepare(txn, ".", context)) 
                    {
                        modify.AddInsertAfterStep(subexpr, XmlModifyXmlObject.Element, "description", "very nice");

                        using(XmlUpdateContext uc = mgr.CreateUpdateContext()) 
                        {
                            long numMod = modify.Execute(txn, results, context, uc);
        
                            System.Console.WriteLine("Performed " + numMod + " modification operations");
                            dumpDocuments(results);
                        }
                    }
                }
            }
        }
    }

    // display documents matching the query
    private static void dumpDocuments(XmlResults results) 
    {
        System.Console.WriteLine("Found " + results.Size + " documents ");
        
        results.Reset();
        while(results.MoveNext()) 
        {
            using(XmlDocument doc = results.Current.ToDocument()) 
            {
                System.Console.WriteLine("Document content: ");
                System.Console.WriteLine(doc.StringContent);
            }
        }
    }
    
    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)) 
                {

                    // Start a transaction
                    using(XmlTransaction txn = mgr.CreateTransaction()) 
                    {

                        // 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");
        
                            // Modify the document that describes "Zapote Blanco" (a fruit)
                            string query = "collection(\"" + theContainer + "\")/fruits:item/product[. = 'Zapote Blanco']";

                            doModify(mgr, container, context, query, txn);

                            System.Console.WriteLine("If committed, this program will add a new element each time it is run.");
                            System.Console.WriteLine("Press 'c' to commit this change:");
                            int c = System.Console.Read();
                            if (c == (int)'c' || c == (int)'C')
                                txn.Commit();
                            else
                                txn.Rollback();
                        }

                    }

                }
            }
        }
        catch(DbXmlException e) 
        {
            System.Console.WriteLine("Error performing document modification 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 modifies documents found in a DBXML container.");
        System.Console.WriteLine("You should run exampleLoadContainer before running this example.");
        System.Console.WriteLine("You are only required to pass this command the path location of the");
        System.Console.WriteLine("database 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("\tmodifyDocument.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;
    }

}