ViewVersionList.cs sample program

Lists the current and all previous version numbers of retrieved documents.


/**
 * Title: ViewVersionList.cs   - a sample that displays: a list of documents;
 *                               the current version number of each document;
 *                               and (for each document) a list of the version
 *                               numbers of all previous versions (if any).
 *
 * Description:  This sample shows how to:
 *               * Search for documents in a docbase.
 *               * For each hit (i.e., for each document found):
 *                 - Retrieve the *current* version number.
 *                 - Retrieve a count of previous versions retained
 *                   in the docbase.
 *                 - For each *previous* version of the document:
 *                   * Retrieve the version number.
 *
 * Syntax:       ViewVersionList       user=<domain\\user>
 *                                     password=<password>
 *                                     server=<ServerName>
 *                                     docbase=<docBaseName>
 *                                     queryfile=<queryFile>
 *
 * Copyright:    Copyright (c) 2003, 2011
 * Company:      Ixiasoft Technologies Inc.
 *
 * @version 2.0
 * Modified:     2011-02-01
 */


using Ixiasoft.TextmlServer45;
using System;
using System.Threading;
using System.Text;
using System.Collections;
using System.IO;

public class ViewVersionList
{

    static String TOKEN_USER       = "USER";
    static String TOKEN_PASSWORD   = "PASSWORD";
    static String TOKEN_SERVER     = "SERVER";
    static String TOKEN_DOCBASE    = "DOCBASE";
    static String TOKEN_QUERYFILE  = "QUERYFILE";

    // Valid parameters accepted from command-line
    static String [] validTokens =
        { TOKEN_USER, TOKEN_PASSWORD, TOKEN_SERVER, TOKEN_DOCBASE,
          TOKEN_QUERYFILE };

    // Which parameters must be specified
    static bool[] mandatory   =
        { true      , true          , true        , true         ,
          true            };

    private static void Usage()
    {
        Console.WriteLine
            ("ViewVersionList user=<domain\\user> password=<password> " +
             "server=<serverName> docbase=<docBaseName> " +
             "queryfile=<[path\\]queryFileName>");
        Console.WriteLine
            ("\t<domain\\user>  Name of the user used for security purpose");
        Console.WriteLine
            ("\t<password>      Password of the user");
        Console.WriteLine
            ("\t<ServerName>    Name of TEXTML Server instance");
        Console.WriteLine
            ("\t<DocBaseName>   Document base name");
        Console.WriteLine
            ("\t<[path\\]queryFileName> XML file containing query");

        Console.WriteLine("\nPress any key to exit");
        Console.ReadKey();

    }


    // Extract run-time parameters from command-line
    private static Hashtable Extract(String[] args)
    {
        Hashtable retval = new Hashtable(10);

        for (int i = 0; i < args.Length; ++i)
        {
            String[] tokens = args[i].Split('=');
            String token = null, value = null;

            if (tokens.Length > 1)
                token = tokens[0];
            if (tokens.Length > 1)
                value = tokens[1];

            if (token == null || value == null)
            {
                retval.Clear();
                return retval;
            }

            bool found = false;
            for (int j = 0; j < validTokens.Length && !found; ++j)
            {
                if (validTokens[j].CompareTo(token.ToUpperInvariant()) == 0 &&
                    !retval.ContainsKey(validTokens[j]))
                {
                    retval.Add(validTokens[j], value);
                    found = true;
                }
            }

            if (!found)
            {
                retval.Clear();
                return retval;
            }
        }

        for (int i = 0; i < validTokens.Length; ++i)
        {
            if (mandatory[i] && !retval.ContainsKey(validTokens[i]))
            {
                retval.Clear();
                return retval;
            }
        }

        return retval;
    }


    // Read the query file, and return its contents as a String object
    private static String ReadQuery(String fileName)
    {
        FileStream stream = new FileStream(fileName,FileMode.Open);
        StreamReader reader = new StreamReader(stream, Encoding.Unicode);

        StringBuilder buff = new StringBuilder((int)stream.Length);

        try
        {
            while ( !reader.EndOfStream )
                buff.Append((char)reader.Read());
        }
        finally
        {
            reader.Close();
        }

        return buff.ToString();
    }



    static void Main(string[] args)
    {
        String user = "";

        // Parse the command line
        Hashtable map = Extract(args);

        // Validate the command-line parameters
        if (map.Count == 0)
        {
            Usage();
            return;
        }

        if (map.ContainsKey(TOKEN_USER))
            user = (String)map[TOKEN_USER];

        if (user.IndexOf("\\") == -1)
        {
            Usage();
            return;
        }
        Hashtable parms = new Hashtable(1);

        try
        {
            // Get the ClientServices object
            IxiaClientServices cs =
                Ixiasoft.TextmlServer45.ClientServicesFactory.getInstance();

            // extract <domain> (or machine-name) from <user>
            String domain = user.Substring(0, user.IndexOf("\\"));
            String userName = user.Substring(user.IndexOf("\\") + 1);

            // Prepare to login to the TEXTML Server instance
            cs.Login(domain, userName, (String)map[TOKEN_PASSWORD]);

            // Read the query from the query file
            String query = ReadQuery((String)map[TOKEN_QUERYFILE]);

            try
            {
                // Get the ServerServices  for the server specified by the user
                IxiaServerServices ss =
                    cs.ConnectServer((String) map[TOKEN_SERVER]);
                try
                {
                    // Get the DocbaseServices for the specified docbase
                    // on that server
                    IxiaDocBaseServices docbase =
                        ss.ConnectDocBase((String) map[TOKEN_DOCBASE]);
                    try
                    {
                        // Then, the SearchServices for that docbase
                        IxiaSearchServices search = docbase.SearchServices;

                        IxiaQueryAnalyzer qa = search.GetQueryAnalyzer();
                        try
                        {
                            Console.WriteLine("Executing query:");
                            Console.WriteLine(query);
                            System.Console.WriteLine();

                            // Search the specified docbase with the
                            // specified query. Store the results in
                            // a ResultSpace, which is a container for
                            // the data returned by a SearchServices search.
                            IxiaResultSpace result =
                                search.SearchDocuments(query);

                            // If you got this far, then your query did
                            // not throw an exception.
                            try
                            {
                                // How many hits did the query produce?
                                int count = result.Count;

                                Console.WriteLine
                                    ("Query found " + count + " documents");
                                System.Console.WriteLine();

                                if (count > 100)
                                    count = 100;

                                if (count != 0)
                                {
                                    Console.WriteLine("First " + count +
                                                      " Document names:");

                                    // Store the ResultSpace of the search
                                    // as a SubList, an implementation
                                    // of the Java List interface.
                                    IxiaSubList subList =
                                        new IxiaSubList(result);

                                    // Mark a range of items that
                                    // includes all items.
                                    // Each item is data about one document.
                                    subList.MarkRange (0, count-1);

                                    // Get a DocumentServices object for
                                    // the docbase that we just searched
                                    IxiaDocumentServices docServices =
                                        docbase.DocumentServices;

                                    try
                                    {
                                        // Retrieve <documents> (an array of
                                        // Result objects), one element for
                                        // each document in the <subList>.

                                        // Use the second parameter to specify
                                        // what you want the <Result> object to
                                        // contain. We're asking for a list of
                                        // the version numbers of any previous
                                        // version of the document
IxiaDocumentServices.Result [] documents = docServices.GetDocuments
                               (subList,
                                TextmlConstants.TEXTML_DOCUMENT_VERSIONS_LIST);

                                        // Process each entry in the sublist.
                                        // Either:
                                        // * Success: print the version info.
                                        // * Failure: print the error message.
                                        for (int i = 0; i < documents.Length;
                                             ++i)
                                        {
                                            if (documents[i].Error != null)
                                            {
                                                Console.WriteLine
                                                    (documents[i].Error);
                                            }
                                            else
// Display the name and version number of this document, followed by the
// version number of each previous version that is still stored in the docbase.
{
    Console.Write
       (String.Format("\nDocument: {0}" +
                      "\n  Current version number: {1}" +
                      "\n  Number of previous versions retained: {2}",
                      documents[i].Document.Name,
                      documents[i].Document.Version,
                      documents[i].Document.PreviousVersionList.Count));

    // If there are any previous versions of the document, display their
    // version numbers as a list.
    if (documents[i].Document.PreviousVersionList.Count > 0)
    {
        Console.WriteLine("\n  Version numbers (of the previous versions):");

        for (int j = 0;
             j < documents[i].Document.PreviousVersionList.Count; ++j)
        {
            Console.Write
                (String.Format("  {0} ",
                 documents[i].Document.PreviousVersionList[j]));
        }
    }
    Console.WriteLine("");
}  // End of else block
                                        } // end of for loop

                                         System.Console.WriteLine();

                                      }
                                      finally
                                      {
                                         docServices.Release();  // Free memory
                                      }
                                }
                                else    // result.Count() returned zero
                                    Console.WriteLine
                                        ("No documents in query");
                             }
                             finally
                             {
                                result.Release();
                             }
                         }
                         finally
                         {
                             search.Release();
                         }
                    }
                    finally
                    {
                        docbase.Release();
                    }
                }
                finally
                {
                    ss.Release();
                }
            }
            finally
            {
                // Don't forget to logout
                cs.Logout();
                Console.WriteLine();
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();

            }
        }
        catch (Exception e)
        {
            Console.WriteLine("**Exception ViewVersionList.main: " + e.Message);
            Console.WriteLine(e.StackTrace);
            Console.WriteLine();
            Console.WriteLine("Press any key");
            Console.ReadKey();

        }

    }
}