SearchDocuments.cs sample program

How to search for documents in a document base, using a query coded in XML.

/**
 * Title: SearchDocuments - a sample that searches for documents in a docbase
 *
 * Description:  This sample shows how to use a query to search for documents
 *               in a docbase, and to retrieve the documents.
 *
 * Syntax:       DoSearch       user=<domain\\user>
 *                              password=<password>
 *                              server=<ServerName>
 *                              docbase=<docBaseName>
 *                              queryfile=<queryFile>
 *
 * Copyright:    Copyright (c) 2003, 2010
 * Company:      Ixiasoft Technologies Inc.
 *
 * @version 2.0
 * Modified:     2010-07-13
 */

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

public class SearchDocuments
{

    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
            ("SearchDocuments 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");
    }


        // 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)
            {
               // StringTokenizer tokens = new StringTokenizer(args[i], "=", false);
                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.TextmlServer41.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 documents to
                                        // contain. You can specify: the
                                        // document, its content, indexed
                                        // content, properties, custom
                                        // properties, search result
                                        // information, related errors
                                        // and version number.
                                        // We're asking for them all!
                                        IxiaDocumentServices.Result []
                                            documents =
                                                docServices.GetDocuments
                                                    (subList,
                                        TextmlConstants.TEXTML_DOCUMENT_ALL_FLAGS);

                                        // Process each entry in the sublist.
                                        // Either:
                                        // * Success: print the document name.
                                        // * Failure: print the error message.
                                        for (int i = 0; i < documents.Length;
                                             ++i)
                                        {
                                            if (documents[i].Error != null)
                                                Console.WriteLine
                                                    (documents[i].Error);
                                            else
                                                Console.WriteLine
                                                   (documents[i].Document.Name);
                                        }

                                         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 SearchDocuments.main: " + e.Message);
            Console.WriteLine(e.StackTrace);
            Console.WriteLine();
            Console.WriteLine("Press any key");
            Console.ReadKey();

        }

    }
}