ジャナ・ビジネス・コンサルティング有限会社トップページへ
/*
 * 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 DeleteDocument
{
    private static string theContainer = "namespaceExampleData.dbxml";

    // Method that deletes all documents from a DB XML container that match a given
    // XQuery.
    private static void doDeleteDocument(XmlManager mgr, XmlContainer container, 
        string query, XmlQueryContext context, XmlTransaction txn)
    {
        System.Console.WriteLine("Deleting documents for expression: '" + query + "'.");
        System.Console.WriteLine("Return to continue: ");
        System.Console.ReadLine();
    
        // Perform our query. We'll delete any document contained in this result set.
        XmlResults results = mgr.Query(txn, query, context, new XmlDocumentConfig());
        System.Console.WriteLine("Found " + results.Size + 
            " matching the expression '" + query + "'.");
    
        // Get an update context.
        using(XmlUpdateContext updateContext = mgr.CreateUpdateContext()) 
        {
            while(results.MoveNext()) 
            {
                XmlDocument document = results.Current.ToDocument();

                string name = document.Name;
                System.Console.WriteLine("Deleting document: " + name + ".");
        
                // Peform the delete
                container.DeleteDocument(txn, document, updateContext);
                System.Console.WriteLine("Deleted document: " + name + ".");
            }
        }
    }

    // Utility method that we use to make sure the documents that we thought 
    // were deleted from the container are in fact deleted. 
    private static void confirmDelete(XmlManager mgr, string query, XmlQueryContext context) 
    {
        System.Console.WriteLine("Confirming the delete.");
        System.Console.WriteLine("The query: '" + query + 
            "' should return result set size 0.");
        XmlResults results = mgr.Query(null, query, context, new XmlDocumentConfig());
        if(results.Size == 0) 
        {
            System.Console.WriteLine("Result set size is 0. Deletion confirmed.");
        } 
        else 
        {
            System.Console.WriteLine("Result set size is " + results.Size +
                ". Deletion failed.");
        }
    }
    
    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");
        
                            // Delete the document that describes Mabolo (a fruit)
                            string query = "collection(\"" + theContainer + "\")/fruits:item[product = 'Mabolo']";

                            // If doDeleteDocument throws an exception then the using block
                            // will call Dispose() on the Transaction, which will cause it
                            // to abort itself.
                            doDeleteDocument(mgr, container, query, context, txn);
                            txn.Commit();

                            confirmDelete(mgr, query, context);
                        }
                    }
                }
            }
        }
        catch(DbXmlException e) 
        {
            System.Console.WriteLine("Error performing document delete 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 deletes an XML document from 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("\tdeleteDocument.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;
    }

}