Exemple #1
0
        /********************************************************************************************/
        static void Main(string[] args)
        {
            if (!mutex.WaitOne(TimeSpan.Zero, true))
            {
            Console.WriteLine("Another instance already running");
            Thread.Sleep(5000);
            return ;
            }
            //save a reference so it does not get GC'd
            consoleHandler = new HandlerRoutine(ConsoleCtrlCheck);
            //set our handler here that will trap exit
            SetConsoleCtrlHandler(consoleHandler, true);
            Migration Test = new Migration();
            CssLib.CSMigrationWrapper TestObj;

            //Account userAccts = new Account();
            while (!keepRunning)
            {

            if (args.Count() > 0)
            {

                if ((args[0].Equals("-Help", StringComparison.CurrentCultureIgnoreCase)) ||(args[0].Equals("-h", StringComparison.CurrentCultureIgnoreCase)))
                {
                    string builder = "Usage of ZimbraMigrationConsole.exe ConfigxmlFile=C:\\MyConfig.xml Users =C:\\users.csv \n";
                    builder += "\n";
                    builder += "ConfigxmlFile= location of the xml file \n";
                    builder += "\n";
                    builder += "Users= location of the csv file \n";
                    builder += "\n";
                    builder += "MaxThreads= Maximum number of threads by default it uses 4.\n";
                    builder += "\n";
                    builder += "MaxErrors= Maximum no of errors allowed for the each migration \n";
                    builder += "\n";
                    builder += "MaxWarn= Maximum no of warnings \n";
                    builder += "\n";
                    builder += " Profile= UserProfile to be migrated for user migration \n";
                    builder += "\n";
                    builder += "DataFile= PST file for the user to be migrated\n";
                    builder += "\n";
                    builder += "SourceHost= The Source server hostname \n";
                    builder += "\n";
                    builder += "SourceAdminID= The Source AdminID \n";
                    builder += "\n";
                    builder += "ZimbraHost= The Zimbra server hostname \n";
                    builder += "\n";
                    builder += "ZimbraPort= The Zimbra port \n";
                    builder += "\n";
                    builder += " ZimbraID= The Zimbra ID. For server migration it’s the admin id and for user migration it’s the userid on Zimbra\n";
                    builder += "\n";
                    builder += " ZimbraPwd= Pwd for Zimbra \n";
                    builder += "\n";
                    builder += "ZimbraDomain= The Zimbra Domain name \n";
                    builder += "\n";
                    builder += "The Migration Item Options can be specified as Mail=True Calendar=True Contacts=True Sent=True DeletedItems=True Junk=True Tasks=True Rules=True OOO=True \n";
                    builder += " By default these options are false. Unless specified in the XML or as arguments \n";
                    builder += "\n";
                    builder += "Verbose= True|False  .This option turns on or off verbose logging \n";
                    builder += "\n";
                    builder += "LogLevel= Debug|Info|Trace  .This option provides various levels of logging \n";
                    builder += "\n";
                    builder += "IsSkipFolders= true|false  .This option provides skipping of folders \n";
                    builder += "\n";
                    builder += "FoldersToSkip= comma separated folder names to be skipped \n";
                    builder += "\n";
                    builder += "IsOnOrAfter= true|false  .This option provides the date filter to migration \n";
                    builder += "\n";
                    builder += "MigrateOnOrAfter= Date in the format YYYY-MM-DD .Items from this date and after get migrated \n";
                    builder += "\n";
                    builder += "IsMaxMessageSize= true|false  .This option provides the maxmessagesize filter to migration \n";
                    builder += "\n";
                    builder += "MaxMessageSize= a numeric value .Items whose size falls into this category after get migrated \n";
                    builder += "\n";
                    builder += "IsSkipPrevMigratedItems= True|false .To skip previously migrated items \n";
                    builder += "\n";
                    builder += "LangID= Language/Locale ID of source account e.g. for Spanish Language/Locale ID is 3082. For more information please refer migration documentation \n";
                    builder += "\n";
                    builder += "For more information see the help file distributed with the exe. \n";

                    System.Console.Write(builder);
                    Log.info(builder);
                    keepRunning = true;
                    Console.ReadKey(true);

                    return;

                }

                try
                {
                CommandLineArgs.I.parseArgs(args, "myStringArg=defaultVal;someLong=12");

                   // CommandLineArgs.I.parseArgs(vargs, "myStringArg=defaultVal;someLong=12");
                    //CommandLineArgs.I.parseArgs(args[0] + args[1] +args[2] +args[3], "myStringArg=defaultVal;someLong=12");

                }
                catch (Exception e)
                {
                    System.Console.WriteLine("Incorrect format of CmdLine arguments" + e.Message);
                    Log.err("Incorrect format of CmdLine arguments" + e.Message);
                    keepRunning = true;
                    if ((CommandLineArgs.I.arg("Silent") != null) &&(CommandLineArgs.I.argAsBool("Silent") == false))
                    { Console.ReadKey(true); }
                    else
                        if((CommandLineArgs.I.arg("Silent") == null))
                            Console.ReadKey(true);

                    return;
                }
                string ConfigXmlFile = CommandLineArgs.I.argAsString("ConfigxmlFile");
                string UserMapFile = CommandLineArgs.I.argAsString("Users");

                string MaxWarns = CommandLineArgs.I.argAsString("MaxWarn");
                string userid = CommandLineArgs.I.argAsString("Profile");
                string Pstfile = CommandLineArgs.I.argAsString("DataFile");
                string ZCSHost = CommandLineArgs.I.argAsString("ZimbraHost");
                string ZCSPort = CommandLineArgs.I.argAsString("ZimbraPort");
                string ZCSID = CommandLineArgs.I.argAsString("ZimbraID");
                string ZCSPwd = CommandLineArgs.I.argAsString("ZimbraPwd");
                string ZCSDomain = CommandLineArgs.I.argAsString("ZimbraDomain");
                string SourceHost = CommandLineArgs.I.argAsString("SourceHost");
                string SourceAdmin = CommandLineArgs.I.argAsString("SourceAdminID");

                //bool Mail = CommandLineArgs.I.argAsBool("Mail");
                bool Mail = false;
                bool Calendar = false;bool Contacts = false;
                bool Sent= false;bool DeletedItems = false;bool Junk = false;bool Tasks=false;bool Rules=false;bool OOO = false;
                 bool UseSSL = false;
                 int MaxErrors =0; int MaxThreads =0;

                string Loglevel = CommandLineArgs.I.argAsString("LogLevel");
                bool Datefilter = false;
                bool SkipFolder = false;
                bool SkipPreviousMigration = false;
                bool IsMaxSize = false;
                string Folderlist = CommandLineArgs.I.argAsString("FoldersToSkip");

                string MigrateDate = CommandLineArgs.I.argAsString("MigrateOnOrAfter");

                string MaxMessageSize = CommandLineArgs.I.argAsString("MaxMessageSize");

                long LangID = 0;

                bool ServerMigration = false;
                XmlConfig myXmlConfig = new XmlConfig();

                bool Silent = false;
                if (CommandLineArgs.I.arg("Silent") != null)
                {
                    Silent = CommandLineArgs.I.argAsBool("Silent");

                }
                else
                    Silent = false;

                if ((ConfigXmlFile != "") && (File.Exists(ConfigXmlFile)))
                {
                    //if ((UserMapFile != "") && (File.Exists(UserMapFile)))
                    if (UserMapFile != "")
                    {
                        if (File.Exists(UserMapFile))
                        {
                            myXmlConfig = new XmlConfig(ConfigXmlFile, UserMapFile);

                            try
                            {
                                myXmlConfig.InitializeConfig();

                                myXmlConfig.GetUserList();
                            }
                            catch (Exception e)
                            {
                                Log.err("Exception in initializeconfig/Getuserlist \n" + e.Message);
                                System.Console.WriteLine("Exception in initializeconfig/Getuserlist \n" + e.Message);
                                //if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true))
                                if (!Silent)
                                { Console.ReadKey(true); }

                                return;

                            }
                        }
                        else
                        {
                            Log.err("UserMap file not present.please check the file name or path");
                            System.Console.WriteLine("UserMap file not present.please check the file name or path");
                           // if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true))

                            if (!Silent)
                            { Console.ReadKey(true); }

                            return;

                        }

                    }
                    else
                    {

                            myXmlConfig = new XmlConfig(ConfigXmlFile, "");

                            try
                            {
                                myXmlConfig.InitializeConfig();
                            }
                            catch (Exception e)
                            {
                                Log.err("Exception in initializeconfig \n" + e.Message);
                                System.Console.WriteLine("Exception in initializeconfig \n" + e.Message);
                                //if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true))
                                if (!Silent)
                                { Console.ReadKey(true); }

                                return;
                            }

                    }
                    if (myXmlConfig.UserList.Count > 0)
                    {

                        ServerMigration = true;
                        if (userid == "")
                            userid = (myXmlConfig.ConfigObj.SourceServer.AdminID != "") ? myXmlConfig.ConfigObj.SourceServer.AdminID : myXmlConfig.ConfigObj.SourceServer.Profile;

                        if (ZCSID == "")
                            ZCSID = myXmlConfig.ConfigObj.ZimbraServer.AdminID;

                        if (ZCSPwd == "")
                            ZCSPwd = myXmlConfig.ConfigObj.ZimbraServer.AdminPwd;

                        if (ZCSID == "")
                        {
                            if ((myXmlConfig.ConfigObj.SourceServer.Profile != ""))
                            {
                               // if (myXmlConfig.ConfigObj.SourceServer.Hostname == "")
                                {
                                    Log.err(" Are you trying Server /User Migration .Check the arguments");
                                    System.Console.WriteLine(" Are you trying Server /User Migration .Check the arguments");
                                    //if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true))
                                    if (!Silent)
                                    { Console.ReadKey(true); }
                                    return;
                                }

                            }
                        }

                    }
                    else
                    {

                        if (userid == "")
                            userid = myXmlConfig.ConfigObj.SourceServer.Profile;

                        if (ZCSID == "")
                            ZCSID = myXmlConfig.ConfigObj.ZimbraServer.UserAccount;

                        if (ZCSPwd == "")
                            ZCSPwd = myXmlConfig.ConfigObj.ZimbraServer.UserPassword;

                        if (Pstfile == "")
                            Pstfile = myXmlConfig.ConfigObj.SourceServer.DataFile;

                    }

                    if ((ZCSHost == "") && (ZCSDomain == ""))
                    {
                        ZCSHost = myXmlConfig.ConfigObj.ZimbraServer.Hostname;
                        ZCSDomain = myXmlConfig.ConfigObj.UserProvision.DestinationDomain;
                    }
                    else
                    {
                        if (ZCSDomain == "")
                        {
                            Log.err("ZimbraHost and ZimbraDomain go together.To override ZimbraHost ,ZimbraDomain has to be overridden as well \n");
                            System.Console.WriteLine("ZimbraHost and ZimbraDomain go together.To override ZimbraHost ,ZimbraDomain has to be overridden as well \n");
                            //if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true))
                            if (!Silent)

                            {
                                System.Console.WriteLine("Press any key to return \n");
                                Console.ReadKey(true);
                            }
                            return;
                        }
                        if (ZCSHost == "")
                        {
                            Log.err("ZimbraHost and ZimbraDomain go together.To override ZimbraDomain ,ZimbraHost has to be overridden as well \n");
                            System.Console.WriteLine("ZimbraHost and ZimbraDomain go together.To override ZimbraDomain ,ZimbraHost has to be overridden as well \n");
                            //if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true))
                            if (!Silent)
                            {
                                System.Console.WriteLine("Press any key to return \n");
                                Console.ReadKey(true);
                            }
                            return;
                        }
                    }

                    if (ZCSPort == "")
                        ZCSPort = myXmlConfig.ConfigObj.ZimbraServer.Port;

                    if (Loglevel == "")
                        Loglevel = myXmlConfig.ConfigObj.GeneralOptions.LogLevel;

                    if (ZCSDomain == "")
                        ZCSDomain = myXmlConfig.ConfigObj.UserProvision.DestinationDomain;

                   /* if (Mail == false)
                        Mail = myXmlConfig.ConfigObj.ImportOptions.Mail;*/

                    if (CommandLineArgs.I.arg("LangID") != null)
                        LangID = CommandLineArgs.I.argAsLong("LangID");
                    else
                        LangID = myXmlConfig.ConfigObj.AdvancedImportOptions.LangID;

                    if (CommandLineArgs.I.arg("MaxThreadCount") != null)
                          MaxThreads = CommandLineArgs.I.argAsInt("MaxThreadCount");
                    else
                        MaxThreads = myXmlConfig.ConfigObj.GeneralOptions.MaxThreadCount;
                    if (MaxThreads == 0)
                        MaxThreads = 4;

                    ;
                    if (CommandLineArgs.I.arg("MaxErrorCount") != null)
                        MaxErrors = CommandLineArgs.I.argAsInt("MaxErrorCount");
                    else
                        MaxErrors = myXmlConfig.ConfigObj.GeneralOptions.MaxErrorCount;

                    if (CommandLineArgs.I.arg("IsSkipPrevMigratedItems") != null)
                    {

                        SkipPreviousMigration = CommandLineArgs.I.argAsBool("IsSkipPrevMigratedItems");
                    }
                    else
                        SkipPreviousMigration = myXmlConfig.ConfigObj.AdvancedImportOptions.IsSkipPrevMigratedItems;

                    if (CommandLineArgs.I.arg("IsMaxMessageSize") != null)
                    {

                        IsMaxSize = CommandLineArgs.I.argAsBool("IsMaxMessageSize");
                    }
                    else
                        IsMaxSize = myXmlConfig.ConfigObj.AdvancedImportOptions.IsMaxMessageSize;

                    if (CommandLineArgs.I.arg("IsSkipFolders") != null)
                    {

                        SkipFolder = CommandLineArgs.I.argAsBool("IsSkipFolders");
                    }
                    else
                        SkipFolder = myXmlConfig.ConfigObj.AdvancedImportOptions.IsSkipFolders;

                    if (CommandLineArgs.I.arg("IsOnOrAfter") != null)
                    {

                        Datefilter = CommandLineArgs.I.argAsBool("IsOnOrAfter");
                    }
                    else
                        Datefilter = myXmlConfig.ConfigObj.AdvancedImportOptions.IsOnOrAfter;

                    if (CommandLineArgs.I.arg("UseSSL") != null)
                    {

                        UseSSL = CommandLineArgs.I.argAsBool("UseSSL");
                    }
                    else
                        UseSSL = myXmlConfig.ConfigObj.ZimbraServer.UseSSL;

                    if (CommandLineArgs.I.arg("Mail") != null)
                    {

                        Mail = CommandLineArgs.I.argAsBool("Mail");
                    }
                    else
                        Mail = myXmlConfig.ConfigObj.ImportOptions.Mail;

                    if (CommandLineArgs.I.arg("Calendar") != null)
                    {

                        Calendar = CommandLineArgs.I.argAsBool("Calendar");
                    }
                    else
                        Calendar = myXmlConfig.ConfigObj.ImportOptions.Calendar;

                    if (CommandLineArgs.I.arg("Contacts") != null)
                    {

                        Contacts = CommandLineArgs.I.argAsBool("Contacts");
                    }
                    else
                        Contacts = myXmlConfig.ConfigObj.ImportOptions.Contacts;

                    if (CommandLineArgs.I.arg("Sent") != null)
                    {

                        Sent = CommandLineArgs.I.argAsBool("Sent");
                    }
                    else
                        Sent = myXmlConfig.ConfigObj.ImportOptions.Sent;

                    if (CommandLineArgs.I.arg("DeletedItems") != null)
                    {

                        DeletedItems = CommandLineArgs.I.argAsBool("DeletedItems");
                    }
                    else
                        DeletedItems = myXmlConfig.ConfigObj.ImportOptions.DeletedItems;

                    if (CommandLineArgs.I.arg("Junk") != null)
                    {

                        Junk = CommandLineArgs.I.argAsBool("Junk");
                    }
                    else
                        Junk = myXmlConfig.ConfigObj.ImportOptions.Junk;

                    if (CommandLineArgs.I.arg("Tasks") != null)
                    {

                        Tasks = CommandLineArgs.I.argAsBool("Tasks");
                    }
                    else
                        Tasks = myXmlConfig.ConfigObj.ImportOptions.Tasks;

                    if (CommandLineArgs.I.arg("Rules") != null)
                    {

                        Rules = CommandLineArgs.I.argAsBool("Rules");
                    }
                    else
                        Rules = myXmlConfig.ConfigObj.ImportOptions.Rules;

                    if (CommandLineArgs.I.arg("OOO") != null)
                    {

                        OOO = CommandLineArgs.I.argAsBool("OOO");
                    }
                    else
                        OOO = myXmlConfig.ConfigObj.ImportOptions.OOO;

                }
                else
                {
                    if (ConfigXmlFile != "")
                    {
                        if (!File.Exists(ConfigXmlFile))
                        {
                            Log.err("XML file not present.please check the file name or path");
                            System.Console.WriteLine("XML file not present.please check the file name or path");
                            //if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true))
                            if (!Silent)
                            { Console.ReadKey(true); }
                            return;
                        }
                    }
                    else
                    {
                        Log.err("Config file or cmdline arguemnts are needed.check the arguments!");
                        System.Console.WriteLine("Config file or cmdline arguemnts are needed.Check the arguments");
                        //if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true))
                        if (!Silent)
                        { Console.ReadKey(true); }
                        return;
                    }

                }

                MigrationOptions importopts = new MigrationOptions();
                ItemsAndFoldersOptions itemFolderFlags = ItemsAndFoldersOptions.None;
                if (Calendar)
                {
                    itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Calendar;
                }
                if (Contacts)
                {
                    itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Contacts;
                }
                if (Mail)
                {
                    itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Mail;
                }
                if (Sent)
                {
                    itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Sent;
                }
                if (DeletedItems)
                {
                    itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.DeletedItems;
                }
                if (Junk)
                {
                    itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Junk;
                }
                if (Tasks)
                {
                    itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Tasks;
                }
                if (Rules)
                {
                    itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Rules;
                }
                if (OOO)
                {
                    itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.OOO;
                }

                bool verbose = false;
                if (CommandLineArgs.I.arg("Verbose") != null)
                {

                    verbose = CommandLineArgs.I.argAsBool("Verbose");
                }
                else
                    verbose = myXmlConfig.ConfigObj.GeneralOptions.Verbose;

                importopts.ItemsAndFolders = itemFolderFlags;

                switch(Loglevel.ToLower())
                {
                case"debug":
                     importopts.VerboseOn = LogLevel.Debug;
                    break;
                case "info":
                    importopts.VerboseOn = LogLevel.Info;
                    break;
                case "trace":
                    importopts.VerboseOn = LogLevel.Trace;
                    break;

                default:
                    importopts.VerboseOn = LogLevel.Info;
                    break;
                }
                if (verbose)
                {

                    if (importopts.VerboseOn < LogLevel.Debug)
                    {
                        importopts.VerboseOn = LogLevel.Debug;
                    }

                }
                else
                {
                   /* if (importopts.VerboseOn > LogLevel.Info)
                    {
                        importopts.VerboseOn = LogLevel.Info;
                    }*/ //will fix this later

                }
                if (MigrateDate == "")
                {
                    MigrateDate = myXmlConfig.ConfigObj.AdvancedImportOptions.MigrateOnOrAfter.ToString();
                }

                if (Datefilter)
                {
                    importopts.DateFilter = MigrateDate;

                }

                if (Folderlist == "")
                {

                    MVVM.ViewModel.OptionsViewModel M = new MVVM.ViewModel.OptionsViewModel();
                    Folderlist = M.ConvertToCSV(myXmlConfig.ConfigObj.AdvancedImportOptions.FoldersToSkip, ",");
                }
                if (SkipFolder)
                {
                    importopts.SkipFolders = Folderlist;

                }

                if (IsMaxSize)
                {
                    if(MaxMessageSize == "")
                        MaxMessageSize = myXmlConfig.ConfigObj.AdvancedImportOptions.MaxMessageSize;

                    importopts.MessageSizeFilter = MaxMessageSize;
                }

                 importopts.SkipPrevMigrated = SkipPreviousMigration;

                 if (SourceHost == "")
                 {
                     SourceHost = myXmlConfig.ConfigObj.SourceServer.Hostname;

                 }
                 if (SourceAdmin == "")
                 {
                     SourceAdmin = myXmlConfig.ConfigObj.SourceServer.AdminID;
                 }

                /* if (MaxErrors == 0)
                 {
                     MaxErrors = myXmlConfig.ConfigObj.GeneralOptions.MaxErrorCount;
                 }*/

                 importopts.LangID = LangID;

                 importopts.MaxErrorCnt =  MaxErrors;

                //importopts.VerboseOn = Verbose;

                try
                {

                    TestObj = new CSMigrationWrapper("MAPI", importopts.VerboseOn);
                }

                catch (Exception e)
                {

                    string error = "Migrationwrapper cannot be initialised ,Migration dll cannot be loaded. ";
                    error += e.Message;
                    System.Console.WriteLine();
                    System.Console.WriteLine(error);
                    Log.err(error);
                   /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red,
                        error);*/
                    System.Console.WriteLine("......... \n");
                    /*ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red,
                            "");*/
                    System.Console.WriteLine("......... \n");
                   // if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true))
                    if (!Silent)
                    Console.ReadKey(true);
                    return;

                }

                System.Console.WriteLine();
                System.Console.WriteLine("Migration Initialization ");
                Log.info("Migration Initialization ");
               /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Green,
                    "  Migration Initialization ");*/
                System.Console.WriteLine("......... \n");
               /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Green,
                        "");*/
                System.Console.WriteLine("......... \n");

                if (userid != "")
                {
                    if (Pstfile == "")
                    {

                        string retval = TestObj.GlobalInit(userid, "", "");

                        if (retval.Length > 0)
                        {
                            System.Console.WriteLine();
                           // System.Console.WriteLine("Error in Migration Initialization ");
                            Log.err("Error in Migration Initialization ");
                            /*ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red,
                                " Error in Migration Initialization ");*/
                            System.Console.WriteLine("......... \n");
                            /*  ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red,
                                      retval);*/
                            System.Console.WriteLine("......... \n");
                            System.Console.WriteLine();

                            return;
                        }
                    }
                }
                else
                {
                    if ((SourceHost != "") && (SourceAdmin != ""))
                    {
                        string retval = TestObj.GlobalInit(SourceHost, SourceAdmin, "");

                        if (retval.Length > 0)
                        {
                            System.Console.WriteLine();
                            System.Console.WriteLine("Error in server Migration Initialization ");
                            Log.err("Error in server Migration Initialization ");
                            /*ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red,
                                " Error in Migration Initialization ");*/
                            System.Console.WriteLine("......... \n");
                            /*  ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red,
                                      retval);*/
                            System.Console.WriteLine("......... \n");
                            System.Console.WriteLine();

                            return;
                        }
                    }

                }

                ZimbraValues.GetZimbraValues().ClientVersion = new MVVM.Model.BuildNum().BUILD_NUM;

                if (ServerMigration)
                {

                    foreach (MVVM.Model.Users user in myXmlConfig.UserList)
                    {

                        Account userAcct = new Account();

                        System.Console.WriteLine();
                        /*ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Green,
                            "Connecting to to Zimbra Server \n   ");*/
                        System.Console.WriteLine("Connecting to to Zimbra Server \n   ");
                        Log.info("Connecting to to Zimbra Server \n   ");
                        System.Console.WriteLine();

                        ZimbraAPI zimbraAPI = new ZimbraAPI(true, importopts.VerboseOn,importopts.SpecialCharRep);
                        /*int stat = zimbraAPI.Logon(
                            myXmlConfig.ConfigObj.zimbraServer.Hostname,
                            myXmlConfig.ConfigObj.zimbraServer.Port,
                            myXmlConfig.ConfigObj.zimbraServer.AdminID,
                            myXmlConfig.ConfigObj.zimbraServer.AdminPwd, true);*/

                        int stat = zimbraAPI.Logon(
                           ZCSHost,
                           ZCSPort,
                          ZCSID,
                          ZCSPwd, UseSSL, true);

                        if (stat != 0)
                        {
                            zimbraAPI.LastError.Count();

                            System.Console.WriteLine();
                           /* string message = "Logon to Zimbra Server for adminAccount " +
                                myXmlConfig.ConfigObj.ZimbraServer.AdminID +"Failed ."+ zimbraAPI.LastError;*/
                            string message = "Logon to Zimbra Server for adminAccount " +
                                myXmlConfig.ConfigObj.ZimbraServer.AdminID + " Failed. " + System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(zimbraAPI.LastError.ToLower());

                            System.Console.WriteLine(message);
                            Log.err(message);
                         /*   ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red,
                                "Logon to to Zimbra Server  for adminAccount failed " +
                                myXmlConfig.ConfigObj.ZimbraServer.AdminID);*/
                            System.Console.WriteLine("......... \n");
                            System.Console.WriteLine();

                            // return;
                        }

                        // userAcct.InitializeMigration(myXmlConfig.ConfigObj.zimbraServer.ZimbraHostname, myXmlConfig.ConfigObj.zimbraServer.Port, myXmlConfig.ConfigObj.zimbraServer.ZimbraAdminID,user.UserName);
                        string acctName;
                        if (user.MappedName == "")
                        {
                             acctName = user.UserName + '@' +
            //                                (myXmlConfig.ConfigObj.UserProvision.DestinationDomain == "" ? ZCSHost : myXmlConfig.ConfigObj.UserProvision.DestinationDomain);
                                  (ZCSDomain == "" ? ZCSHost : ZCSDomain);
                        }
                        else
                        {
                            acctName = user.MappedName + '@' +
                               //(myXmlConfig.ConfigObj.UserProvision.DestinationDomain == "" ? ZCSHost : myXmlConfig.ConfigObj.UserProvision.DestinationDomain);
                               (ZCSDomain == "" ? ZCSHost : ZCSDomain);

                        }

                        if (zimbraAPI.GetAccount(acctName) == 0)
                        {
                            System.Console.WriteLine();
                            System.Console.WriteLine();
                            string mesg = "Migration to Zimbra Started  for UserAccount " +
                                acctName;
                            System.Console.WriteLine(mesg);
                            Log.info(mesg);
                          /*  ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Green,
                                " Migration to Zimbra Started  for UserAccount " +
                                acctName);*/
                            System.Console.WriteLine();
                            System.Console.WriteLine();
                            user.IsProvisioned = true;

                        }
                        else
                        {
                            System.Console.WriteLine();
                            string err = "User is not provisioned on Zimbra Server " +
                                acctName;
                            System.Console.WriteLine(err);
                           /* ProgressUtil.RenderConsoleProgress(30, '\u2591',
                                ConsoleColor.Yellow,
                                " User is not provisioned on Zimbra Server " +
                                acctName);*/
                            Log.info(err);
                            System.Console.WriteLine();
                            System.Console.WriteLine();
                            err = "Provisioning user" + acctName;
                            Log.info(err);
                           /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Green,
                                " Provisioning user" + acctName);*/
                            string historyfile = Path.GetTempPath() + acctName.Substring(0, acctName.IndexOf('@')) + "history.log";
                            if (File.Exists(historyfile))
                            {
                                try
                                {

                                    File.Delete(historyfile);
                                }
                                catch (Exception e)
                                {
                                    string msg = "exception in deleteing the Histroy file " + e.Message;
                                    System.Console.WriteLine(msg);
                                    Log.err(msg);
                                }

                            }
                            System.Console.WriteLine(err);
                            System.Console.WriteLine();
                            System.Console.WriteLine();
                            string Defaultpwd = "";

                            /************************************///if csv file has a pwd use it else looks for the pwd in xml file.
                            if ((user.PWDdefault != ""))
                                Defaultpwd = user.PWDdefault;
                            else
                            {
                                Defaultpwd = myXmlConfig.ConfigObj.UserProvision.DefaultPWD;
                                if (Defaultpwd == null)
                                {
                                    Defaultpwd = "default";
                                }
                            }

                            bool mustChangePW = user.ChangePWD;
                            if (zimbraAPI.CreateAccount(acctName,
                                "",
                                "",
                                "",
                                "",
                                Defaultpwd,
                                mustChangePW,
                                myXmlConfig.ConfigObj.UserProvision.COS) == 0)
                            {
                                System.Console.WriteLine();
                               /* ProgressUtil.RenderConsoleProgress(30, '\u2591',
                                    ConsoleColor.Green,
                                    " Provisioning useraccount success " + acctName);*/
                                err = "Provisioning useraccount success " + acctName;
                                System.Console.WriteLine(err);
                                System.Console.WriteLine();
                                System.Console.WriteLine();
                                Log.info(err);
                                /*ProgressUtil.RenderConsoleProgress(30, '\u2591',
                                    ConsoleColor.Green,
                                    " Migration to Zimbra Started  for UserAccount  " +
                                    user.UserName);*/
                                err = "Migration to Zimbra Started  for UserAccount  " +
                                    user.UserName;

                                System.Console.WriteLine(err);
                                System.Console.WriteLine();
                                System.Console.WriteLine("......... \n");
                                Log.info(err);
                                user.IsProvisioned = true;
                            }
                            else
                            {
                                System.Console.WriteLine();

                               /* ProgressUtil.RenderConsoleProgress(30, '\u2591',
                                    ConsoleColor.Red, " error provisioning user " +
                                    acctName);*/
                                err = "error provisioning user " +
                                    acctName + ". " + System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(zimbraAPI.LastError.ToLower()) + "\n";
                                System.Console.WriteLine(err);
                                Log.err(err);
                               user.IsProvisioned=false;
                            }
                        }

                        string final = user.StatusMessage;
                    }
                    if (myXmlConfig.UserList.Count > 0)
                    {
                        countdownEvent = new CountdownEvent(myXmlConfig.UserList.Count);

                        userAccts.StartMigration(myXmlConfig.UserList, ZCSDomain, importopts, countdownEvent, TestObj, MaxThreads);
                        countdownEvent.Wait();

                        Console.WriteLine("Finished Migration");
                        Log.info("Finished Migration");
                        Console.WriteLine("UNinit Migration");
                        Log.info("UNinit Migration");
                    }

                    string retval = TestObj.GlobalUninit();

                    if (retval.Length > 0)
                    {
                        System.Console.WriteLine();
                        System.Console.WriteLine("Error in Migration UnInitialization ");
                        Log.err("Error in Migration UnInitialization ");
                        /*ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red,
                            " Error in Migration Initialization ");*/
                        System.Console.WriteLine("......... \n");
                        /*  ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red,
                                  retval);*/
                        System.Console.WriteLine("......... \n");
                        System.Console.WriteLine();
                        keepRunning = true;
                        return;
                    }

                    keepRunning = true;

                }
                else
                {

                    if ((userid != "") || (Pstfile != ""))
                    {
                        string accountname = ZCSID;
                        if (!accountname.Contains("@"))
                        {
                            accountname = accountname + "@" + (((ZCSDomain == "") || (ZCSDomain == null)) ? ZCSHost : ZCSDomain);
                        }
                        string accountid = (Pstfile != "") ? Pstfile : userid;

                        ZimbraAPI zimbraAPI = new ZimbraAPI(false, importopts.VerboseOn);

                            System.Console.WriteLine();
                           /* ProgressUtil.RenderConsoleProgress(
                                    30, '\u2591', ConsoleColor.Green,
                                    "Connecting to to Zimbra Server \n   ");*/
                            string err = "Connecting to to Zimbra Server \n   ";
                            System.Console.WriteLine(err);
                            System.Console.WriteLine();

                            Log.info(err);

                            int stat = zimbraAPI.Logon(
                                    ZCSHost,
                                    ZCSPort,
                                    accountname,
                                    ZCSPwd, UseSSL, false);

                            if (stat != 0)
                            {
                                zimbraAPI.LastError.Count();

                                System.Console.WriteLine();
                                /*ProgressUtil.RenderConsoleProgress(
                                        30, '\u2591', ConsoleColor.Red,
                                        "Logon to to Zimbra Server  for userAccount failed " +
                                        ZCSID);*/
                                err = "Logon to Zimbra Server for userAccount " +
                                        ZCSID + " Failed. " + System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(zimbraAPI.LastError.ToLower());
                                System.Console.WriteLine(err);
                                Log.err(err);
                                System.Console.WriteLine("......... \n");
                                System.Console.WriteLine();
                                //Thread.Sleep(2000);
                                if (Pstfile == "")
                                {
                                    string val = TestObj.GlobalUninit();

                                    if (val.Length > 0)
                                    {
                                        System.Console.WriteLine();
                                        System.Console.WriteLine("Error in Migration UnInitialization ");
                                        /*ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red,
                                            " Error in Migration Initialization ");*/
                                        System.Console.WriteLine("......... \n");
                                        /*  ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red,
                                                  retval);*/
                                        System.Console.WriteLine("......... \n");
                                        Log.err("Error in Migration UnInitialization");
                                        System.Console.WriteLine();
                                        keepRunning = true;
                                        return;
                                    }
                                }
                                //if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true))
                                if (!Silent)
                                { Console.ReadKey(true); }

                                keepRunning = true;
                                return;
                            }

                        System.Console.WriteLine();
                       /* ProgressUtil.RenderConsoleProgress(
                                30, '\u2591', ConsoleColor.Green,
                                " Migration to Zimbra Started  for Profile/PST  " +
                                accountid);*/
                        err = "Migration to Zimbra Started  for Profile/PST  " +
                                accountid;
                        System.Console.WriteLine(err);
                        Log.info(err);
                        System.Console.WriteLine();
                        System.Console.WriteLine();

                        //  Test.test(accountname, TestObj, accountid, importopts, false);
                        countdownEvent = new CountdownEvent(1);
                        //Account userAccts = new Account();

                        MVVM.Model.Users User = new MVVM.Model.Users();
                        User.UserName = userid;

                        List<MVVM.Model.Users> users = new List<MVVM.Model.Users>();
                        users.Add(User);
                        userAccts.StartMigration(users, ZCSHost, importopts, countdownEvent, TestObj, MaxThreads, false, accountname, accountid);
                        // Thread.Sleep(129000);

                        countdownEvent.Wait();

                        Log.info("Finished Migration");
                        Console.WriteLine();
                        Console.WriteLine("Finished Migration");
                        Console.WriteLine("UNinit Migration");
                        Log.info("UNinit Migration");

                        if (Pstfile == "")
                        {
                            string retval = TestObj.GlobalUninit();

                            if (retval.Length > 0)
                            {
                                System.Console.WriteLine();
                                System.Console.WriteLine("Error in Migration UnInitialization ");
                                Log.err("Error in Migration UnInitialization ");
                                /*ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red,
                                    " Error in Migration Initialization ");*/
                                System.Console.WriteLine("......... \n");
                                /*  ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red,
                                          retval);*/
                                System.Console.WriteLine("......... \n");
                                System.Console.WriteLine();
                                keepRunning = true;
                                return;
                            }
                        }

                        keepRunning = true;

                    }

                }
            }
            else
            {
                System.Console.WriteLine();
                /*ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red,
                    " Make sure the correct arguments (2) are passed \n");*/
                System.Console.WriteLine("Make sure the correct arguments (2) are passed . type Help for more information\n");
                System.Console.WriteLine();
                Log.err("Make sure the correct arguments (2) are passed . type Help for more information\n");
               // if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true))
                if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == false))
                { Console.ReadKey(true); }
                else
                    if ((CommandLineArgs.I.arg("Silent") == null))
                        Console.ReadKey(true);

                return;

            }
            }

               /// Account userAccts = new Account();
            if (_userRequestExit)
            {
            keepRunning = true;
            //set flag to exit loop.  Other conditions could cause this too, which is why we use a seperate variable
               // Console.WriteLine("Shutting down, user requested exit");

            }
            Log.info("Migration finished");
            System.Console.WriteLine("Press any key to continue \n");
               // if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true))
            if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == false))
            { Console.ReadKey(true); }
            else
            {
            if ((CommandLineArgs.I.arg("Silent") == null))
                Console.ReadKey(true);
            }

            return;
        }
        private void ProcessItems(MigrationAccount Acct, bool isServer, dynamic user, dynamic folder,
        ZimbraAPI api, string path, MigrationOptions options)
        {
            DateTime dt = DateTime.UtcNow;
            dynamic[] itemobjectarray = null ;

            try
            {
            itemobjectarray = user.GetItemsForFolder(folder, dt.ToOADate());
            }
            catch (Exception e)
            {
            Log.err("exception in ProcessItems->user.GetItemsFolder", e.Message);
            }
            if (itemobjectarray != null)
            {
            int iProcessedItems = 0;
            string historyfile = Path.GetTempPath() + Acct.AccountName.Substring(0, Acct.AccountName.IndexOf('@')) + "history.log";
            string historyid = "";

            if (itemobjectarray.GetLength(0) > 0)
            {
                if (Acct.migrationFolder.TotalCountOfItems == itemobjectarray.Count())
                {
                    while (iProcessedItems < Acct.migrationFolder.TotalCountOfItems)
                    {
                        Log.debug("Processing folder", folder.Name, "-- Total items:", folder.ItemCount);
                        foreach (dynamic itemobject in itemobjectarray)
                        {
                            if (options.MaxErrorCnt > 0)
                            {
                                if (Acct.TotalErrors > options.MaxErrorCnt)
                                {
                                    Log.err("Cancelling migration -- error threshold reached");
                                    return;
                                }
                            }

                            Log.trace("CSmigration processitems foldertype from itemobject");
                            foldertype type = (foldertype)itemobject.Type;
                            Log.trace("CSmigration processitems ProcessIt");
                            if (ProcessIt(options, type))
                            {
                                bool bError = false;

                                bool bSkipMessage = false;
                                Dictionary<string, string> dict = new Dictionary<string, string>();
                                string[,] data = null;
                                string itemtype = type.ToString();
                                if (options.IsMaintainenceMode)
                                {
                                    Log.err("Cancelling migration -- Mailbox is in maintainence  mode.Try back later");

                                    return;
                                }

                                try
                                {

                                    string hex = BitConverter.ToString(itemobject.ItemID);
                                    hex = hex.Replace("-", "");
                                    historyid = itemtype + hex;

                                }
                                catch (Exception e)
                                {
                                    Log.err("exception in Bitconverter cconverting itemid to a hexstring", e.Message);

                                }
                                if (options.SkipPrevMigrated)
                                {

                                    Log.trace("CSmigration processitems SkipPrevMigrated is true");
                                    if (historyid != "")
                                    {
                                        Log.trace("CSmigration processitems CheckifAlreadyMigrated");
                                        if (CheckifAlreadyMigrated(historyfile, historyid))
                                        {
                                            bSkipMessage = true;
                                            iProcessedItems++;
                                            continue;
                                        }
                                    }
                                    //uncomment after more testing
                                }
                                try
                                {
                                    Log.trace("CSmigration processitems GetDataForItemID");
                                    data = itemobject.GetDataForItemID(user.GetInternalUser(),
                                                    itemobject.ItemID, itemobject.Type);
                                }
                                catch (Exception e)
                                {
                                    Log.err("exception in ProcessItems->itemobject.GetDataForItemID", e.Message);
                                    iProcessedItems++;
                                    continue;
                                }
                                //check if data is valid
                                if (data == null)
                                {
                                    iProcessedItems++;
                                    continue;
                                }
                                int bound0 = data.GetUpperBound(0);
                                if (bound0 > 0)
                                {
                                    for (int i = 0; i <= bound0; i++)
                                    {
                                        string Key = data[0, i];
                                        string Value = data[1, i];

                                        try
                                        {
                                            dict.Add(Key, Value);
                                            // Console.WriteLine("{0}, {1}", so1, so2);
                                        }
                                        catch (Exception e)
                                        {
                                            string s = string.Format("Exception adding {0}/{1}: {2}", Key, Value, e.Message);
                                            Log.warn(s);
                                            // Console.WriteLine("{0}, {1}", so1, so2);
                                        }
                                    }
                                }

                                api.AccountID = Acct.AccountID;
                                api.AccountName = Acct.AccountName;
                                if (dict.Count > 0)
                                {
                                    int stat = 0;

                                    if ((type == foldertype.Mail) || (type == foldertype.MeetingReq))
                                    {
                                        //Log.debug("Msg Subject: ", dict["Subject"]);
                                        int msf = 0;
                                        if (options.MessageSizeFilter != null)
                                        {
                                            if (options.MessageSizeFilter.Length > 0)
                                            {
                                                msf = Int32.Parse(options.MessageSizeFilter);
                                                msf *= 1000000;
                                                if (dict["wstrmimeBuffer"].Length > msf)    // FBS bug 74000 -- 5/14/12
                                                {
                                                    bSkipMessage = true;
                                                    Log.debug("Skipping", dict["Subject"], "-- message size exceeds size filter value");
                                                }
                                            }
                                        }
                                        if (options.DateFilter != null)
                                        {
                                            try
                                            {
                                                DateTime dtm = DateTime.Parse(dict["Date"]);
                                                DateTime filterDtm = Convert.ToDateTime(options.DateFilter);
                                                if (DateTime.Compare(dtm, filterDtm) < 0)
                                                {
                                                    bSkipMessage = true;
                                                    Log.debug("Skipping", dict["Subject"], "-- message older than date filter value");
                                                }
                                            }
                                            catch (Exception)
                                            {
                                                Log.info(dict["Subject"], ": unable to parse date");
                                            }
                                        }
                                        if (!bSkipMessage)
                                        {
                                            if (dict["tags"].Length > 0)
                                            {
                                                // change the tag names into tag numbers for AddMessage
                                                string tagsNumstrs = DealWithTags(dict["tags"], Acct, api);
                                                bool bRet = dict.Remove("tags");
                                                dict.Add("tags", tagsNumstrs);
                                            }
                                            dict.Add("folderId", folder.FolderPath);
                                            try
                                            {
                                                stat = api.AddMessage(dict);
                                                if (stat != 0)
                                                {
                                                    string errMsg = (api.LastError.IndexOf("upload ID: null") != -1)    // FBS bug 75159 -- 6/7/12
                                                                    ? "Unable to upload file. Please check server message size limits."
                                                                    : api.LastError;
                                                    if (errMsg.Contains("maintenance") || errMsg.Contains("not active"))
                                                    {
                                                        errMsg = errMsg + " Try Back later";
                                                        options.IsMaintainenceMode = true;
                                                    }

                                                    Acct.LastProblemInfo = new ProblemInfo(dict["Subject"], errMsg, ProblemInfo.TYPE_ERR);
                                                    Acct.TotalErrors++;
                                                    bError = true;
                                                }
                                            }
                                            catch (Exception e)
                                            {
                                                Acct.TotalErrors++;
                                                Log.err("Exception caught in ProcessItems->api.AddMessage", e.Message);

                                            }
                                        }
                                    }
                                    else if (type == foldertype.Contacts)
                                    {
                                        //Log.debug("Contact Firstname: ", dict["firstName"]);
                                        if (dict["tags"].Length > 0)
                                        {
                                            // change the tag names into tag numbers for CreateContact
                                            string tagsNumstrs = DealWithTags(dict["tags"], Acct, api);
                                            bool bRet = dict.Remove("tags");
                                            dict.Add("tags", tagsNumstrs);
                                        }
                                        try
                                        {
                                            stat = api.CreateContact(dict, path);

                                            if (stat != 0)
                                            {
                                                string errMsg = api.LastError;
                                                if (errMsg.Contains("maintenance") || errMsg.Contains("not active"))
                                                {
                                                    errMsg = errMsg + " Try Back later";

                                                    options.IsMaintainenceMode = true;
                                                }
                                                Log.err("Error in CreateContact ", errMsg);
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            Acct.TotalErrors++;
                                            Log.err("Exception caught in ProcessItems->api.CreateContact", e.Message);

                                        }
                                    }
                                    else if (type == foldertype.Calendar)
                                    {
                                        //Log.debug("Cal Subject: ", dict["su"]);
                                        if (options.DateFilter != null)
                                        {
                                            try
                                            {
                                                DateTime dtm = DateTime.Parse(dict["sFilterDate"]);
                                                DateTime filterDtm = Convert.ToDateTime(options.DateFilter);
                                                if (DateTime.Compare(dtm, filterDtm) < 0)
                                                {
                                                    bSkipMessage = true;
                                                    Log.debug("Skipping", dict["su"], "-- appointment older than date filter value");
                                                }
                                            }
                                            catch (Exception)
                                            {
                                                Log.info(dict["su"], ": unable to parse date");
                                            }
                                        }
                                        if (!bSkipMessage)
                                        {
                                            try
                                            {
                                                if (dict["tags"].Length > 0)
                                                {
                                                    // change the tag names into tag numbers for AddAppointment
                                                    string tagsNumstrs = DealWithTags(dict["tags"], Acct, api);
                                                    bool bRet = dict.Remove("tags");
                                                    dict.Add("tags", tagsNumstrs);
                                                }
                                                dict.Add("accountNum", Acct.AccountNum.ToString());
                                                stat = api.AddAppointment(dict, path);
                                                if (stat != 0)
                                                {
                                                    string errMsg = api.LastError;
                                                    if (errMsg.Contains("maintenance") || errMsg.Contains("not active"))
                                                    {
                                                        errMsg = errMsg + " Try Back later";

                                                        options.IsMaintainenceMode = true;
                                                    }
                                                    Acct.LastProblemInfo = new ProblemInfo(dict["su"], errMsg,
                                                                                           ProblemInfo.TYPE_ERR);
                                                    Acct.TotalErrors++;
                                                    bError = true;

                                                }

                                            }
                                            catch (Exception e)
                                            {
                                                Acct.LastProblemInfo = new ProblemInfo(dict["su"], e.Message,
                                                                                       ProblemInfo.TYPE_ERR);
                                                Acct.TotalErrors++;
                                                Log.err(dict["su"], "exception caught in ProcessItems->api.AddAppointment", e.Message);

                                            }
                                        }
                                    }
                                    else if (type == foldertype.Task)
                                    {
                                        //Log.debug("Task Subject: ", dict["su"]);
                                        if (options.DateFilter != null)
                                        {
                                            try
                                            {
                                                DateTime dtm = DateTime.Parse(dict["sFilterDate"]);
                                                DateTime filterDtm = Convert.ToDateTime(options.DateFilter);

                                                if (DateTime.Compare(dtm, filterDtm) < 0)
                                                {
                                                    bSkipMessage = true;
                                                    Log.debug("Skipping", dict["su"], "-- task older than date filter value");
                                                }
                                            }
                                            catch (Exception)
                                            {

                                                Log.info(dict["su"], ": unable to parse date");
                                            }
                                        }
                                        if (!bSkipMessage)
                                        {
                                            if (dict["tags"].Length > 0)
                                            {
                                                // change the tag names into tag numbers for AddTask
                                                string tagsNumstrs = DealWithTags(dict["tags"], Acct, api);
                                                bool bRet = dict.Remove("tags");
                                                dict.Add("tags", tagsNumstrs);
                                            }
                                            try
                                            {
                                                stat = api.AddTask(dict, path);

                                                if (stat != 0)
                                                {
                                                    string errMsg = api.LastError;
                                                    if (errMsg.Contains("maintenance") || errMsg.Contains("not active"))
                                                    {
                                                        errMsg = errMsg + " Try Back later";

                                                        options.IsMaintainenceMode = true;
                                                    }

                                                    Log.err("error in AddTask ", errMsg);

                                                }
                                            }
                                            catch (Exception e)
                                            {
                                                Acct.TotalErrors++;
                                                Log.err("exception caught in ProcessItems->api.AddTask", e.Message);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    Acct.LastProblemInfo = new ProblemInfo(Acct.AccountName, "Error on message",
                                                                           ProblemInfo.TYPE_ERR);
                                    Acct.TotalErrors++;
                                    bError = true;
                                }

                                if (!bError)
                                {
                                    // Note the : statement.  It seems weird to set Acct.migrationFolder.CurrentCountOFItems
                                    // to itself, but this is done so the method will be called to increment the progress bar
                                    Acct.migrationFolder.CurrentCountOfItems = bSkipMessage
                                        ? Acct.migrationFolder.CurrentCountOfItems
                                        : Acct.migrationFolder.CurrentCountOfItems + 1;
                                }
                            }
                            if (historyid != "")
                            {
                                try
                                {

                                    File.AppendAllText(historyfile, historyid); //uncomment after more testing
                                    File.AppendAllText(historyfile, "\n");

                                }
                                catch (Exception e)
                                {
                                    Acct.TotalErrors++;
                                    Log.err("CSmigrationwrapper  Exception caught in ProcessItems writing history to the history file", e.Message);
                                }
                            }
                            iProcessedItems++;
                        }
                    }
                }
                else
                {
                    Log.trace(" Itemobjectarray.count is not equal to MigrationFolder.totalcountofitems");
                    while (iProcessedItems < itemobjectarray.Count())
                    {
                        Log.debug("Processing folder", folder.Name, "-- Total items:", folder.ItemCount);
                        foreach (dynamic itemobject in itemobjectarray)
                        {
                            if (options.MaxErrorCnt > 0)
                            {
                                if (Acct.TotalErrors > options.MaxErrorCnt)
                                {
                                    Log.err("Cancelling migration -- error threshold reached");
                                    return;
                                }
                            }
                            foldertype type = (foldertype)itemobject.Type;
                            if (ProcessIt(options, type))
                            {
                                bool bError = false;

                                bool bSkipMessage = false;
                                Dictionary<string, string> dict = new Dictionary<string, string>();
                                string[,] data = null;
                                string itemtype = type.ToString();
                                if (options.IsMaintainenceMode)
                                {
                                    Log.err("Cancelling migration -- Mailbox is in maintainence  mode.Try back later");

                                    return;
                                }

                                try
                                {

                                    string hex = BitConverter.ToString(itemobject.ItemID);
                                    hex = hex.Replace("-", "");
                                    historyid = itemtype + hex;

                                }
                                catch (Exception e)
                                {
                                    Log.err("exception in Bitconverter cconverting itemid to a hexstring", e.Message);

                                }
                                if (options.SkipPrevMigrated)
                                {
                                    if (historyid != "")
                                    {
                                        if (CheckifAlreadyMigrated(historyfile, historyid))
                                        {
                                            bSkipMessage = true;
                                            iProcessedItems++;
                                            continue;
                                        }
                                    }
                                    //uncomment after more testing
                                }
                                try
                                {
                                    data = itemobject.GetDataForItemID(user.GetInternalUser(),
                                                    itemobject.ItemID, itemobject.Type);
                                }
                                catch (Exception e)
                                {
                                    Log.err("exception in ProcessItems->itemobject.GetDataForItemID", e.Message);
                                    iProcessedItems++;
                                    continue;
                                }
                                //check if data is valid
                                if (data == null)
                                {
                                    iProcessedItems++;
                                    continue;
                                }
                                int bound0 = data.GetUpperBound(0);
                                if (bound0 > 0)
                                {
                                    for (int i = 0; i <= bound0; i++)
                                    {
                                        string Key = data[0, i];
                                        string Value = data[1, i];

                                        try
                                        {
                                            dict.Add(Key, Value);
                                            // Console.WriteLine("{0}, {1}", so1, so2);
                                        }
                                        catch (Exception e)
                                        {
                                            string s = string.Format("Exception adding {0}/{1}: {2}", Key, Value, e.Message);
                                            Log.warn(s);
                                            // Console.WriteLine("{0}, {1}", so1, so2);
                                        }
                                    }
                                }

                                api.AccountID = Acct.AccountID;
                                api.AccountName = Acct.AccountName;
                                if (dict.Count > 0)
                                {
                                    int stat = 0;

                                    if ((type == foldertype.Mail) || (type == foldertype.MeetingReq))
                                    {
                                        //Log.debug("Msg Subject: ", dict["Subject"]);
                                        int msf = 0;
                                        if (options.MessageSizeFilter != null)
                                        {
                                            if (options.MessageSizeFilter.Length > 0)
                                            {
                                                msf = Int32.Parse(options.MessageSizeFilter);
                                                msf *= 1000000;
                                                if (dict["wstrmimeBuffer"].Length > msf)    // FBS bug 74000 -- 5/14/12
                                                {
                                                    bSkipMessage = true;
                                                    Log.debug("Skipping", dict["Subject"], "-- message size exceeds size filter value");
                                                }
                                            }
                                        }
                                        if (options.DateFilter != null)
                                        {
                                            try
                                            {
                                                DateTime dtm = DateTime.Parse(dict["Date"]);
                                                DateTime filterDtm = Convert.ToDateTime(options.DateFilter);
                                                if (DateTime.Compare(dtm, filterDtm) < 0)
                                                {
                                                    bSkipMessage = true;
                                                    Log.debug("Skipping", dict["Subject"], "-- message older than date filter value");
                                                }
                                            }
                                            catch (Exception)
                                            {
                                                Log.info(dict["Subject"], ": unable to parse date");
                                            }
                                        }
                                        if (!bSkipMessage)
                                        {
                                            if (dict["tags"].Length > 0)
                                            {
                                                // change the tag names into tag numbers for AddMessage
                                                string tagsNumstrs = DealWithTags(dict["tags"], Acct, api);
                                                bool bRet = dict.Remove("tags");
                                                dict.Add("tags", tagsNumstrs);
                                            }
                                            dict.Add("folderId", folder.FolderPath);
                                            try
                                            {
                                                stat = api.AddMessage(dict);
                                                if (stat != 0)
                                                {
                                                    string errMsg = (api.LastError.IndexOf("upload ID: null") != -1)    // FBS bug 75159 -- 6/7/12
                                                                    ? "Unable to upload file. Please check server message size limits."
                                                                    : api.LastError;
                                                    if (errMsg.Contains("maintenance") || errMsg.Contains("not active"))
                                                    {
                                                        errMsg = errMsg + " Try Back later";
                                                        options.IsMaintainenceMode = true;
                                                    }

                                                    Acct.LastProblemInfo = new ProblemInfo(dict["Subject"], errMsg, ProblemInfo.TYPE_ERR);
                                                    Acct.TotalErrors++;
                                                    bError = true;
                                                }
                                            }
                                            catch (Exception e)
                                            {
                                                Acct.TotalErrors++;
                                                Log.err("Exception caught in ProcessItems->api.AddMessage", e.Message);

                                            }
                                        }
                                    }
                                    else if (type == foldertype.Contacts)
                                    {
                                        //Log.debug("Contact Firstname: ", dict["firstName"]);
                                        if (dict["tags"].Length > 0)
                                        {
                                            // change the tag names into tag numbers for CreateContact
                                            string tagsNumstrs = DealWithTags(dict["tags"], Acct, api);
                                            bool bRet = dict.Remove("tags");
                                            dict.Add("tags", tagsNumstrs);
                                        }
                                        try
                                        {
                                            stat = api.CreateContact(dict, path);

                                            if (stat != 0)
                                            {
                                                string errMsg = api.LastError;
                                                if (errMsg.Contains("maintenance") || errMsg.Contains("not active"))
                                                {
                                                    errMsg = errMsg + " Try Back later";

                                                    options.IsMaintainenceMode = true;
                                                }
                                                Log.err("Error in CreateContact ", errMsg);
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            Acct.TotalErrors++;
                                            Log.err("Exception caught in ProcessItems->api.CreateContact", e.Message);

                                        }
                                    }
                                    else if (type == foldertype.Calendar)
                                    {
                                        //Log.debug("Cal Subject: ", dict["su"]);
                                        if (options.DateFilter != null)
                                        {
                                            try
                                            {
                                                DateTime dtm = DateTime.Parse(dict["sFilterDate"]);
                                                DateTime filterDtm = Convert.ToDateTime(options.DateFilter);
                                                if (DateTime.Compare(dtm, filterDtm) < 0)
                                                {
                                                    bSkipMessage = true;
                                                    Log.debug("Skipping", dict["su"], "-- appointment older than date filter value");
                                                }
                                            }
                                            catch (Exception)
                                            {
                                                Log.info(dict["su"], ": unable to parse date");
                                            }
                                        }
                                        if (!bSkipMessage)
                                        {
                                            try
                                            {
                                                if (dict["tags"].Length > 0)
                                                {
                                                    // change the tag names into tag numbers for AddAppointment
                                                    string tagsNumstrs = DealWithTags(dict["tags"], Acct, api);
                                                    bool bRet = dict.Remove("tags");
                                                    dict.Add("tags", tagsNumstrs);
                                                }
                                                dict.Add("accountNum", Acct.AccountNum.ToString());
                                                stat = api.AddAppointment(dict, path);
                                                if (stat != 0)
                                                {
                                                    string errMsg = api.LastError;
                                                    if (errMsg.Contains("maintenance") || errMsg.Contains("not active"))
                                                    {
                                                        errMsg = errMsg + " Try Back later";

                                                        options.IsMaintainenceMode = true;
                                                    }
                                                    Acct.LastProblemInfo = new ProblemInfo(dict["su"], errMsg,
                                                                                           ProblemInfo.TYPE_ERR);
                                                    Acct.TotalErrors++;
                                                    bError = true;

                                                }

                                            }
                                            catch (Exception e)
                                            {
                                                Acct.LastProblemInfo = new ProblemInfo(dict["su"], e.Message,
                                                                                       ProblemInfo.TYPE_ERR);
                                                Acct.TotalErrors++;
                                                Log.err(dict["su"], "exception caught in ProcessItems->api.AddAppointment", e.Message);

                                            }
                                        }
                                    }
                                    else if (type == foldertype.Task)
                                    {
                                        //Log.debug("Task Subject: ", dict["su"]);
                                        if (options.DateFilter != null)
                                        {
                                            try
                                            {
                                                DateTime dtm = DateTime.Parse(dict["sFilterDate"]);
                                                DateTime filterDtm = Convert.ToDateTime(options.DateFilter);

                                                if (DateTime.Compare(dtm, filterDtm) < 0)
                                                {
                                                    bSkipMessage = true;
                                                    Log.debug("Skipping", dict["su"], "-- task older than date filter value");
                                                }
                                            }
                                            catch (Exception)
                                            {

                                                Log.info(dict["su"], ": unable to parse date");
                                            }
                                        }
                                        if (!bSkipMessage)
                                        {
                                            if (dict["tags"].Length > 0)
                                            {
                                                // change the tag names into tag numbers for AddTask
                                                string tagsNumstrs = DealWithTags(dict["tags"], Acct, api);
                                                bool bRet = dict.Remove("tags");
                                                dict.Add("tags", tagsNumstrs);
                                            }
                                            try
                                            {
                                                stat = api.AddTask(dict, path);

                                                if (stat != 0)
                                                {
                                                    string errMsg = api.LastError;
                                                    if (errMsg.Contains("maintenance") || errMsg.Contains("not active"))
                                                    {
                                                        errMsg = errMsg + " Try Back later";

                                                        options.IsMaintainenceMode = true;
                                                    }

                                                    Log.err("error in AddTask ", errMsg);

                                                }
                                            }
                                            catch (Exception e)
                                            {
                                                Acct.TotalErrors++;
                                                Log.err("exception caught in ProcessItems->api.AddTask", e.Message);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    Acct.LastProblemInfo = new ProblemInfo(Acct.AccountName, "Error on message",
                                                                           ProblemInfo.TYPE_ERR);
                                    Acct.TotalErrors++;
                                    bError = true;
                                }

                                if (!bError)
                                {
                                    // Note the : statement.  It seems weird to set Acct.migrationFolder.CurrentCountOFItems
                                    // to itself, but this is done so the method will be called to increment the progress bar
                                    Acct.migrationFolder.CurrentCountOfItems = bSkipMessage
                                        ? Acct.migrationFolder.CurrentCountOfItems
                                        : Acct.migrationFolder.CurrentCountOfItems + 1;
                                }
                            }
                            if (historyid != "")
                            {
                                try
                                {

                                    File.AppendAllText(historyfile, historyid); //uncomment after more testing
                                    File.AppendAllText(historyfile, "\n");

                                }
                                catch (Exception e)
                                {
                                    Acct.TotalErrors++;
                                    Log.err("CSmigrationwrapper  Exception caught in ProcessItems writing history to the history file", e.Message);
                                }

                            }
                            iProcessedItems++;
                        }
                    }
                }
            }
            }
            else
            {
            Log.err("CSmigrationwrapper --- GetItemsForFolder returned null for itemfolderlist");
            return;
            }
        }
        private void Next()
        {
            if ((this.ZimbraServerHostName.Length == 0) || (this.ZimbraPort.Length == 0))
            {
            MessageBox.Show("Please fill in the host name and port", "Zimbra Migration",
                MessageBoxButton.OK, MessageBoxImage.Error);
            return;
            }
            try
            {
            System.Net.IPAddress address = System.Net.IPAddress.Parse(ZimbraServerHostName);
            MessageBox.Show("Please enter a valid host name rather than an IP address",
                "Zimbra Migration", MessageBoxButton.OK, MessageBoxImage.Error);
            return;
            }
            catch (Exception)
            {}
            ZimbraAPI zimbraAPI = new ZimbraAPI(false);

            int stat = -1;
            try
            {
            stat = zimbraAPI.Logon(this.ZimbraServerHostName, this.ZimbraPort, this.ZimbraUser,
                this.ZimbraUserPasswd, this.ZimbraSSL, false);
            }
            catch (Exception e)
            {
            MessageBox.Show(e.Message, "Logon", MessageBoxButton.OK, MessageBoxImage.Error);
            return;
            }

            if (stat == 0)
            {
            string authToken = ZimbraValues.GetZimbraValues().AuthToken;

            if (authToken.Length > 0)
            {
                zimbraAPI.GetInfo();
                lb.SelectedIndex = 3;
            }
            }
            else
            {
            MessageBox.Show(string.Format("Logon Unsuccessful: {0}", zimbraAPI.LastError),
                "Zimbra Migration", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        public void StartMigration(MigrationAccount Acct, MigrationOptions options, bool isServer = true,
        LogLevel logLevel = LogLevel.Info, bool isPreview = false, bool doRulesAndOOO = true)
        {
            string accountName = "";
            dynamic[] folders = null;
            int idx = Acct.AccountName.IndexOf("@");
            Log.Level level = (Log.Level)logLevel;
            dynamic user = null;
            string value = "";

            options.IsMaintainenceMode = false;

            if (MailClient == "MAPI")
            {
            user = new MapiUser();
            }
            if (!isServer)
            {
            m_umUser = user;
            }
            if (idx == -1)
            {
            Acct.LastProblemInfo = new ProblemInfo(Acct.AccountName, "Illegal account name",
                ProblemInfo.TYPE_ERR);
            Acct.TotalErrors++;
            return;
            }
            else
            {
            accountName = Acct.AccountName.Substring(0, idx);
            }

            Log.init(Path.GetTempPath() + "migration.log", level);  // might have gotten a new level from options
            InitLogFile(accountName, level);
            try
            {
            value = user.Init(isServer ? "host" : "", Acct.AccountID, accountName);
            }
            catch (Exception e)
            {
            string s = string.Format("Initialization Exception. {0}", e.Message);

            Acct.LastProblemInfo = new ProblemInfo(accountName, s, ProblemInfo.TYPE_ERR);
            Acct.TotalErrors++;
            return;
            }
            Log.info("Account name", accountName);
            Log.info("Account Id", Acct.AccountID);
            Log.info("Account Num", Acct.AccountNum.ToString());

            if (value.Length > 0)
            {
            Acct.IsValid = false;
            Log.err("Unable to initialize", accountName, value +"or verify if source mailbox exists.");
            Acct.LastProblemInfo = new ProblemInfo(accountName, value + " Or Verify if source mailbox exists.", ProblemInfo.TYPE_ERR);
            Acct.TotalErrors++;
            //Acct.TotalErrors = Acct.MaxErrorCount;
            return;
            }
            else
            {
            Acct.IsValid = true;
            Log.info(accountName, "initialized");
            }

            // set up check for skipping folders
            List<string> skipList = new List<string>();

            if (options.SkipFolders != null && options.SkipFolders.Length > 0)
            {
            string[] tokens = options.SkipFolders.Split(',');

            for (int i = 0; i < tokens.Length; i++)
            {
                string token = tokens.GetValue(i).ToString();

                skipList.Add(token.Trim());
            }
            }

            Log.debug("Retrieving folders");
            try
            {

            folders = user.GetFolders();
            }
            catch (Exception e)
            {
            Log.err("exception in startmigration->user.GetFolders", e.Message);

            }
            if (folders != null)
            {
            Log.info("CSmigrationwrapper get folders returned folders");
            if (folders.Count() == 0)
            {

                Log.info("No folders for user to migrate");
                return;
            }
            }
            else
            {
            Log.err("CSmigrationwrapper get folders returned null for folders");
            return;
            }
            Acct.migrationFolder.CurrentCountOfItems = folders.Count();
            Log.debug("Retrieved folders.  Count:", Acct.migrationFolder.CurrentCountOfItems.ToString());

            foreach (dynamic folder in folders) {
            if (!SkipFolder(options, skipList, folder))
                Acct.TotalItems += folder.ItemCount;
            }
            Log.info("Acct.TotalItems=", Acct.TotalItems.ToString());
            ZimbraAPI  api = new ZimbraAPI(isServer, logLevel, options.SpecialCharRep);

            api.AccountID = Acct.AccountID;
            api.AccountName = Acct.AccountName;

            api.GetTags();
            foreach (TagInfo taginfo in ZimbraValues.GetZimbraValues().Tags)
            {
            try
            {

                Acct.tagDict.Add(taginfo.TagName, taginfo.TagID);
            }
            catch (Exception e)
            {
                Log.err("Exception in Add tags :",e.Message);
            }
            }

            foreach (dynamic folder in folders)
            {
            string path = "";

            if (options.IsMaintainenceMode)
            {
                Log.err("Cancelling migration -- Mailbox is in maintainence  mode.try back later");
                return;
            }

            if (options.MaxErrorCnt > 0)
            {
                if (Acct.TotalErrors > options.MaxErrorCnt)
                {
                    Log.err("Cancelling migration -- error threshold reached");
                    return;
                }
            }

            if (SkipFolder(options, skipList, folder))
            {
                Log.info("Skipping folder", folder.Name);
                continue;
            }
            Log.info("Processing folder", folder.Name);
            if (folder.Id == 0)
            {
                string ViewType = GetFolderViewType(folder.ContainerClass);
                try
                {

                    int stat = api.CreateFolder(folder.FolderPath, ViewType);
                }
                catch (Exception e)
                {
                    Log.err("Exception in api.CreateFolder in Startmigration ", e.Message);
                }

                path = folder.FolderPath;
            }
            if (folder.ItemCount == 0)
            {
                Log.info("Skipping empty folder", folder.Name);
                continue;
            }
            // Set FolderName at the end, since we trigger results on that, so we need all the values set
            Acct.migrationFolder.TotalCountOfItems = folder.ItemCount;
            Acct.migrationFolder.CurrentCountOfItems = 0;
            Acct.migrationFolder.FolderView = folder.ContainerClass;
            Acct.migrationFolder.FolderName = folder.Name;
            if (folder.Id == (int)ZimbraFolders.Trash)
            {
                path = "/MAPIRoot/Deleted Items";   // FBS EXCHANGE SPECIFIC HACK !!!
            }
            if (!isPreview)
            {
                ProcessItems(Acct, isServer, user, folder, api, path, options);
            }
            }

            // now do Rules
            if ((options.ItemsAndFolders.HasFlag(ItemsAndFoldersOptions.Rules)) && (doRulesAndOOO))
            {
            string[,] data  = null;
            try
            {
                data = user.GetRules();
            }
            catch (Exception e)
            {
                Log.err("Exception in StartMigration->user.Getrules", e.Message);
            }
            if (data != null)
            {
                Acct.TotalItems++;
                Acct.migrationFolder.TotalCountOfItems = 1;
                Acct.migrationFolder.CurrentCountOfItems = 0;
                Acct.migrationFolder.FolderView = "All Rules";
                Acct.migrationFolder.FolderName = "Rules Table";
                api.AccountID = Acct.AccountID;
                api.AccountName = Acct.AccountName;
                if (!isPreview)
                {
                    Dictionary<string, string> dict = new Dictionary<string, string>();
                    int bound0 = data.GetUpperBound(0);
                    if (bound0 > 0)
                    {
                        for (int i = 0; i <= bound0; i++)
                        {
                            string Key = data[0, i];
                            string Value = data[1, i];
                            try
                            {

                                dict.Add(Key, Value);
                            }
                            catch (Exception e)
                            {
                                string s = string.Format("Exception adding {0}/{1}: {2}", Key, Value, e.Message);
                                Log.warn(s);
                                // Console.WriteLine("{0}, {1}", so1, so2);
                            }
                        }
                    }
                        api.AccountID = Acct.AccountID;
                        api.AccountName = Acct.AccountName;
                        try
                        {
                            Log.info("Migrating Rules");
                            int stat = api.AddRules(dict);
                        }
                        catch (Exception e)
                        {
                            Acct.TotalErrors++;
                            Log.err("CSmigrationWrapper: Exception in AddRules ", e.Message);

                        }
                        Acct.migrationFolder.CurrentCountOfItems = 1;
                    }

            }
            else
            {
                Log.info("There are no rules to migrate");
            }
            }

            // now do OOO
            if ((options.ItemsAndFolders.HasFlag(ItemsAndFoldersOptions.OOO)) && (doRulesAndOOO))
            {
            bool isOOO = false;
            string ooo ="";
            try
            {
                ooo = user.GetOOO();
            }
            catch (Exception e)
            {
                Log.err("Exception in StartMigration->user.GetOOO", e.Message);
            }
            if (ooo.Length > 0)
            {
                isOOO = (ooo != "0:");
            }
            if (isOOO)
            {
                Acct.TotalItems++;
                Acct.migrationFolder.TotalCountOfItems = 1;
                Acct.migrationFolder.CurrentCountOfItems = 0;
                Acct.migrationFolder.FolderView = "OOO";
                Acct.migrationFolder.FolderName = "Out of Office";
                api.AccountID = Acct.AccountID;
                api.AccountName = Acct.AccountName;
                if (!isPreview)
                {
                    Log.info("Migrating Out of Office");
                    try
                    {

                        api.AddOOO(ooo, isServer);
                    }
                    catch (Exception e)
                    {
                        Acct.TotalErrors++;
                        Log.err("CSmigrationWrapper: Exception in AddOOO ", e.Message);
                    }
                }
            }
            else
            {
                Log.info("Out of Office state is off, and there is no message");
            }
            }
            try
            {
            user.Uninit();
            }
            catch (Exception e)
            {
            Log.err("Exception in user.Uninit ", e.Message);

            }
            if (!isServer)
            {
            m_umUser = null;
            }
        }
 // if the tag has already been created, just return it; if not, do the req and create it
 private string DealWithTags(string theTags, MigrationAccount acct, ZimbraAPI api)
 {
     string retval = "";
     string[] tokens = theTags.Split(',');
     for (int i = 0; i < tokens.Length; i ++)
     {
     if (i > 0)
     {
         retval += ",";
     }
     string token = tokens.GetValue(i).ToString();
     if (acct.tagDict.ContainsKey(token))
     {
         retval += acct.tagDict[token];
     }
     else
     {
         string tagID = "";  // output from CreateTag
         string color = (acct.tagDict.Count).ToString(); // color starts at 0, will keep bumping up by 1
         int stat = api.CreateTag(token, color, out tagID);  // do request and get the numstr back from response
         acct.tagDict.Add(token, tagID);   // add to existing dict; token is Key, tokenNumstr is Val
         retval += tagID;
     }
     }
     return retval;
 }
        private void Next()
        {
            if ((this.ZimbraServerHostName.Length == 0) || (this.ZimbraPort.Length == 0))
            {
            MessageBox.Show("Please fill in the host name and port", "Zimbra Migration",
                MessageBoxButton.OK, MessageBoxImage.Error);
            return;
            }

            ZimbraAPI zimbraAPI = new ZimbraAPI(true);
            int stat = -1;
            try
            {
            stat = zimbraAPI.Logon(this.ZimbraServerHostName, this.ZimbraPort, this.ZimbraAdmin,
                this.ZimbraAdminPasswd, this.ZimbraSSL, true);
            }
            catch (Exception e)
            {
            MessageBox.Show(e.Message, "Logon", MessageBoxButton.OK, MessageBoxImage.Error);
            return;
            }

            if (stat == 0)
            {
            string authToken = ZimbraValues.GetZimbraValues().AuthToken;

            if (authToken.Length > 0)
            {
                UsersViewModel usersViewModel =
                    ((UsersViewModel)ViewModelPtrs[(int)ViewType.USERS]);
                ScheduleViewModel scheduleViewModel =
                    ((ScheduleViewModel)ViewModelPtrs[(int)ViewType.SCHED]);

                string currentDomain = (usersViewModel.DomainInfoList.Count > 0) ?
                    usersViewModel.DomainInfoList[usersViewModel.CurrentDomainSelection].DomainName : "";

                usersViewModel.DomainInfoList.Clear();
                usersViewModel.DomainList.Clear();
                scheduleViewModel.CosList.Clear();

                zimbraAPI.GetAllDomains();

                foreach (DomainInfo domaininfo in ZimbraValues.GetZimbraValues().ZimbraDomains)
                {
                    string dName = domaininfo.DomainName;
                    usersViewModel.DomainInfoList.Add(new DomainInfo(domaininfo.DomainName, domaininfo.DomainID, domaininfo.zimbraDomainDefaultCOSId));
                    usersViewModel.DomainList.Add(dName);

                    if (dName == currentDomain)
                        usersViewModel.CurrentDomainSelection = usersViewModel.DomainInfoList.Count;
                }

                usersViewModel.DomainsFilledIn = true;

                zimbraAPI.GetAllCos();

                foreach (CosInfo cosinfo in ZimbraValues.GetZimbraValues().COSes)
                {
                    scheduleViewModel.CosList.Add(new CosInfo(cosinfo.CosName, cosinfo.CosID));
                }
                lb.SelectedIndex = 3;
            }
            }
            else
            {
            MessageBox.Show(string.Format("Logon Unsuccessful: {0}", zimbraAPI.LastError),
                "Zimbra Migration", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        public void DoMigrate(bool isPreview)
        {
            bgwlist.Clear();
            if (isServer)
            {
            if (CurrentCOSSelection == -1)
                CurrentCOSSelection = 0;
            UsersViewModel usersViewModel =
                ((UsersViewModel)ViewModelPtrs[(int)ViewType.USERS]);

            if (ZimbraValues.zimbraValues.AuthToken.Length == 0)
            {
                MessageBox.Show("You must log on to the Zimbra server", "Zimbra Migration",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            ConfigViewModelS sourceModel =
                ((ConfigViewModelS)ViewModelPtrs[(int)ViewType.SVRSRC]);

            if (!sourceModel.IsMailServerInitialized)
            {
                MessageBox.Show("You must log on to Exchange", "Zimbra Migration",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            string domainName = usersViewModel.ZimbraDomain;
            string defaultPWD = DefaultPWD;
            string tempMessage = "";
            bool bProvision = false;
            MessageBoxImage mbi = MessageBoxImage.Information;

            for (int i = 0; i < SchedList.Count; i++)
            {
                string userName = (usersViewModel.UsersList[i].MappedName.Length > 0) ?
                    usersViewModel.UsersList[i].MappedName :
                    usersViewModel.UsersList[i].Username;
                string accountName = userName + "@" + domainName;

                if (!SchedList[i].isProvisioned)
                {
                    if (!isPreview)
                    {
                        bProvision = true;
                        if (defaultPWD.Length == 0)
                        {
                            MessageBox.Show("Please provide an initial password",
                                "Zimbra Migration", MessageBoxButton.OK,
                                MessageBoxImage.Exclamation);
                            return;
                        }

                        string cosID = CosList[CurrentCOSSelection].CosID;
                        ZimbraAPI zimbraAPI = new ZimbraAPI(isServer);

                        // FBS bug 71646 -- 3/26/12
                        string displayName = "";
                        string givenName = "";
                        string sn = "";
                        string zfp = "";

                        // FBS bug 73395 -- 4/25/12
                        ObjectPickerInfo opinfo = usersViewModel.GetOPInfo();
                        if (opinfo.DisplayName.Length > 0)
                        {
                            displayName = opinfo.DisplayName;
                        }
                        if (opinfo.GivenName.Length > 0)
                        {
                            givenName = opinfo.GivenName;
                        }
                        if (opinfo.Sn.Length > 0)
                        {
                            sn = opinfo.Sn;
                        }
                        if (opinfo.Zfp.Length > 0)
                        {
                            zfp = opinfo.Zfp;
                        }
                        // end 73395
                        // end 71646

                        string historyfile = Path.GetTempPath() + accountName.Substring(0, accountName.IndexOf('@')) + "history.log";
                        if (File.Exists(historyfile))
                        {
                            try
                            {

                                File.Delete(historyfile);
                            }
                            catch (Exception e)
                            {
                                string msg = "exception in deleteing the Histroy file " + e.Message;
                                System.Console.WriteLine(msg);
                            }

                        }

                        bool mustChangePW = usersViewModel.UsersList[i].MustChangePassword;
                        if (zimbraAPI.CreateAccount(accountName, displayName, givenName, sn, zfp, defaultPWD, mustChangePW, cosID) == 0)
                        {
                            tempMessage += string.Format("{0} Provisioned", userName) + "\n";
                            // MessageBox.Show(string.Format("{0} Provisioned", userName), "Zimbra Migration", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else
                        {
                            // MessageBox.Show(string.Format("Provision unsuccessful for {0}: {1}", userName, zimbraAPI.LastError), "Zimbra Migration", MessageBoxButton.OK, MessageBoxImage.Error);
                            tempMessage += string.Format("Provision unsuccessful for {0}: {1}",
                                userName, zimbraAPI.LastError) + "\n";
                            mbi = MessageBoxImage.Error;
                        }
                    }
                }
            }
            if (bProvision)
            {
                MessageBox.Show(tempMessage, "Zimbra Migration", MessageBoxButton.OK, mbi);
            }
            if (mbi == MessageBoxImage.Error)
            {
                return;
            }
            lb.SelectedIndex = 6;
            }
            else
            {
            lb.SelectedIndex = 4;
            }

            AccountResultsViewModel accountResultsViewModel =
            ((AccountResultsViewModel)ViewModelPtrs[(int)ViewType.RESULTS]);

            accountResultsViewModel.AccountResultsList.Clear();
            if (isServer)
            {
            EnableMigrate = false;
            EnablePreview = false;
            }
            else
            {
            ((OptionsViewModel)ViewModelPtrs[(int)ViewType.OPTIONS]).OEnableNext = false;
            }
            accountResultsViewModel.EnableStop = !EnableMigrate;

            int num = 0;

            foreach (SchedUser su in SchedList)
            {
            accountResultsViewModel.AccountResultsList.Add(new AccountResultsViewModel(this,
                num++, 0, "", "", su.username, 0, "", 0, 0,
                accountResultsViewModel.EnableStop));
            }
            accountResultsViewModel.OpenLogFileEnabled = true;

            // FBS bug 71048 -- 4/16/12 -- use the correct number of threads.
            // If MaxThreadCount not specified, default to 4.  If fewer users than MaxThreadCount, numThreads = numUsers
            OptionsViewModel ovm = ((OptionsViewModel)ViewModelPtrs[(int)ViewType.OPTIONS]);
            int maxThreads = (ovm.MaxThreadCount > 0) ? ovm.MaxThreadCount : 4;
            maxThreads = Math.Min(maxThreads, 8);   // let's make 8 the limit for now
            int numUsers = SchedList.Count;
            int numThreads = Math.Min(numUsers, maxThreads);
            for (int i = 0; i < numUsers; i++)
            {
            Log.info("Schedule bachground workers with numusers :" + numUsers + " and maxthreads are :"+ numThreads);
            if (i < numThreads)
            {
                UserBW bgw = new UserBW(i);
                bgw.DoWork += new System.ComponentModel.DoWorkEventHandler(worker_DoWork);
                bgw.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(
                    worker_ProgressChanged);
                bgw.WorkerReportsProgress = true;
                bgw.WorkerSupportsCancellation = true;
                bgw.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(
                    worker_RunWorkerCompleted);
                bgw.usernum = i;
                bgw.RunWorkerAsync(i);
                bgwlist.Add(bgw);
                Log.info("Background worker started number :",bgw.threadnum);
            }
            else
            {
                Log.info("adding user number to overflow list", i);
                overflowList.Add(i);
            }
            };
        }
        private void Next()
        {
            if (!ValidateUsersList(true))
            return;
            ZimbraAPI zimbraAPI = new ZimbraAPI(isServer);
            if (ZimbraValues.zimbraValues.AuthToken.Length == 0)
            {
            MessageBox.Show("You must log on to the Zimbra server", "Zimbra Migration",
                MessageBoxButton.OK, MessageBoxImage.Error);
            return;
            }
            SaveDomain();

            ScheduleViewModel scheduleViewModel =
            ((ScheduleViewModel)ViewModelPtrs[(int)ViewType.SCHED]);

            scheduleViewModel.EnableProvGB = false;
            for (int i = 0; i < UsersList.Count; i++)
            {
            string userName = (UsersList[i].MappedName.Length > 0) ? UsersList[i].MappedName :
                UsersList[i].Username;
            string acctName = userName + '@' + ZimbraDomain;

            if (zimbraAPI.GetAccount(acctName) == 0)
            {
                UsersList[i].IsProvisioned = true;
                scheduleViewModel.SchedList[i].isProvisioned = true;    // get (SchedList) in schedule view model will set again
            }
            else if (zimbraAPI.LastError.IndexOf("no such account") != -1)
            {
                UsersList[i].IsProvisioned = false;     // get (SchedList) in schedule view model will set again
                scheduleViewModel.SchedList[i].isProvisioned = false;
                if (!scheduleViewModel.EnableProvGB)
                {
                    scheduleViewModel.EnableProvGB = true;
                }
            }
            else
            {
                MessageBox.Show(string.Format("Error accessing account {0}: {1}", acctName,
                    zimbraAPI.LastError), "Zimbra Migration", MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
            }
            lb.SelectedIndex = 5;
        }
        private void Next()
        {
            if (!ValidateUsersList(true))
            return;
            ZimbraAPI zimbraAPI = new ZimbraAPI(isServer);
            if (ZimbraValues.zimbraValues.AuthToken.Length == 0)
            {
            MessageBox.Show("You must log on to the Zimbra server", "Zimbra Migration",
                MessageBoxButton.OK, MessageBoxImage.Error);
            return;
            }
            SaveDomain();

            UsersViewModel usersViewModel =
                    ((UsersViewModel)ViewModelPtrs[(int)ViewType.USERS]);
            ScheduleViewModel scheduleViewModel =
            ((ScheduleViewModel)ViewModelPtrs[(int)ViewType.SCHED]);

            scheduleViewModel.EnableProvGB = false;
            for (int i = 0; i < UsersList.Count; i++)
            {
            string userName = (UsersList[i].MappedName.Length > 0) ? UsersList[i].MappedName :
                UsersList[i].Username;
            string acctName = userName + '@' + ZimbraDomain;

            if (zimbraAPI.GetAccount(acctName) == 0)
            {
                UsersList[i].IsProvisioned = true;
                scheduleViewModel.SchedList[i].isProvisioned = true;    // get (SchedList) in schedule view model will set again
            }
            else if (zimbraAPI.LastError.IndexOf("no such account") != -1)
            {
                UsersList[i].IsProvisioned = false;     // get (SchedList) in schedule view model will set again
                scheduleViewModel.SchedList[i].isProvisioned = false;
                if (!scheduleViewModel.EnableProvGB)
                {
                    scheduleViewModel.EnableProvGB = true;
                }
            }
            else
            {
                MessageBox.Show(string.Format("Error accessing account {0}: {1}", acctName,
                    zimbraAPI.LastError), "Zimbra Migration", MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
            }
            //Logic to get the index of defaulf COS from CosList.
            for (int i = 0; i < scheduleViewModel.CosList.Count; i++)
            {
            if (scheduleViewModel.CosList[i].CosName == "default")
            {
                ZimbraValues.GetZimbraValues().DefaultCosIndex = i;
                break;
            }
            }

            foreach (DomainInfo domaininfo in ZimbraValues.GetZimbraValues().ZimbraDomains)
            {
            if (domaininfo.DomainName == usersViewModel.DomainList[usersViewModel.CurrentDomainSelection])
            {
                if (domaininfo.zimbraDomainDefaultCOSId != "")
                {
                    for (int i = 0; i < scheduleViewModel.CosList.Count; i++)
                    {
                        if (domaininfo.zimbraDomainDefaultCOSId == scheduleViewModel.CosList[i].CosID)
                        {
                            scheduleViewModel.CurrentCOSSelection = i;
                            break;
                        }
                    }
                }
                else
                    scheduleViewModel.CurrentCOSSelection = ZimbraValues.GetZimbraValues().DefaultCosIndex;
            break;
            }
            }
            lb.SelectedIndex = 5;
        }
Exemple #10
0
    private void Next()
    {
        if ((this.ZimbraServerHostName.Length == 0) || (this.ZimbraPort.Length == 0))
        {
            MessageBox.Show("Please fill in the host name and port", "Zimbra Migration",
                MessageBoxButton.OK, MessageBoxImage.Error);
            return;
        }

        ZimbraAPI zimbraAPI = new ZimbraAPI(true);
        int stat = -1;
        try
        {
            stat = zimbraAPI.Logon(this.ZimbraServerHostName, this.ZimbraPort, this.ZimbraAdmin,
                this.ZimbraAdminPasswd, this.ZimbraSSL, true);
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message, "Logon", MessageBoxButton.OK, MessageBoxImage.Error);
            return;
        }

        if (stat == 0)
        {
            string authToken = ZimbraValues.GetZimbraValues().AuthToken;

            if (authToken.Length > 0)
            {
                UsersViewModel usersViewModel =
                    ((UsersViewModel)ViewModelPtrs[(int)ViewType.USERS]);
                ScheduleViewModel scheduleViewModel =
                    ((ScheduleViewModel)ViewModelPtrs[(int)ViewType.SCHED]);
                string currentDomain = (usersViewModel.DomainList.Count > 0) ?
                    usersViewModel.DomainList[usersViewModel.CurrentDomainSelection] : "";

                usersViewModel.DomainList.Clear();
                scheduleViewModel.CosList.Clear();
                zimbraAPI.GetAllDomains();
                for (int i = 0; i < ZimbraValues.GetZimbraValues().Domains.Count; i++)
                {
                    string s = ZimbraValues.GetZimbraValues().Domains[i];

                    usersViewModel.DomainList.Add(s);
                    // if we've loaded a config file where the domain was specified, then set it as selected
                    if (currentDomain != null)
                    {
                        if (currentDomain.Length > 0)
                        {
                            if (s == currentDomain)
                                usersViewModel.CurrentDomainSelection = i;
                            usersViewModel.DomainsFilledIn = true;
                        }
                    }
                }
                zimbraAPI.GetAllCos();
                foreach (CosInfo cosinfo in ZimbraValues.GetZimbraValues().COSes)
                {
                    scheduleViewModel.CosList.Add(new CosInfo(cosinfo.CosName, cosinfo.CosID));
                }
                lb.SelectedIndex = 3;
            }
        }
        else
        {
            MessageBox.Show(string.Format("Logon Unsuccessful: {0}", zimbraAPI.LastError),
                "Zimbra Migration", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }