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

using System;
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)) {
            Console.WriteLine("Updating document for the expression: '" +
                              query + "' ");
            Console.WriteLine("Return to continue: ");
            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();

                Console.WriteLine("About to update the document(s) above.");
                Console.WriteLine("Look for a new element after the target " +
                                  "element, named 'description' ...");
                Console.WriteLine("Return to continue: ");
                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);

                            Console.WriteLine("Performed " + numMod + " modification operations");
                            dumpDocuments(results);
                        }
                    }
                }
            }
        }
    }

    // display documents matching the query
    private static void dumpDocuments(XmlResults results)
    {
        Console.WriteLine("Found " + results.Size + " documents ");

        results.Reset();
        while (results.MoveNext()) {
            using (XmlDocument doc = results.Current.ToDocument()) {
                Console.WriteLine("Document content: ");
                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);

                            Console.WriteLine("If committed, this program will add a new element each time it is run.");
                            Console.WriteLine("Press 'c' to commit this change:");
                            int c = Console.Read();
                            if (c == (int) 'c' || c == (int) 'C') {
                                txn.Commit();
                            } else {
                                txn.Rollback();
                            }
                        }
                    }
                }
            }
        } catch (DbXmlException e) {
            Console.WriteLine("Error performing document modification against " + theContainer);
            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 = Console.Out;
        envconf.ErrorPrefix = "LOG";

        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 (Exception e) {
            env.Close();
            throw e;
        }
    }

    private static void Usage()
    {
        Console.WriteLine("This program modifies documents found in a DBXML container.");
        Console.WriteLine("You should run exampleLoadContainer before running this example.");
        Console.WriteLine("You are only required to pass this command the path location of the");
        Console.WriteLine("database environment that you specified when you loaded the examples data:");
        Console.WriteLine();
        Console.WriteLine("\t-h <dbenv directory>");
        Console.WriteLine("For example:");
        Console.WriteLine("\tmodifyDocument.exe -h examplesEnvironment");

        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) {
                                Console.WriteLine("Invalid option: " + arg);
                                Usage();
                            }
                            envdir = args[i];
                            break;
                        }
                    default:
                        {
                            Console.WriteLine("Unknown option: " + arg);
                            Usage();
                            break;
                        }
                }
            } else {
                Console.WriteLine("Too many arguments: " + arg);
                Usage();
            }
        }
        if (envdir == null) {
            Console.WriteLine("Environment directory not found.");
            Usage();
        }
        return envdir;
    }
}