/********************************************************************************************/ 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 bool ProcessIt(MigrationOptions options, foldertype type) { bool retval = false; switch (type) { case foldertype.Mail: case foldertype.MeetingReq: retval = options.ItemsAndFolders.HasFlag(ItemsAndFoldersOptions.Mail); break; case foldertype.Calendar: retval = options.ItemsAndFolders.HasFlag(ItemsAndFoldersOptions.Calendar); break; case foldertype.Contacts: retval = options.ItemsAndFolders.HasFlag(ItemsAndFoldersOptions.Contacts); break; case foldertype.Task: retval = options.ItemsAndFolders.HasFlag(ItemsAndFoldersOptions.Tasks); break; default: break; } return retval; }
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; } }
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; } }
private bool SkipFolder(MigrationOptions options, List<string> skipList, dynamic folder) { // Note that Rules and OOO do not apply here if ((folder.Id == (int)ZimbraFolders.Calendar && !options.ItemsAndFolders.HasFlag(ItemsAndFoldersOptions.Calendar)) || (folder.Id == (int)ZimbraFolders.Contacts && !options.ItemsAndFolders.HasFlag(ItemsAndFoldersOptions.Contacts)) || (folder.Id == (int)ZimbraFolders.Junk && !options.ItemsAndFolders.HasFlag(ItemsAndFoldersOptions.Junk)) || (folder.Id == (int)ZimbraFolders.Sent && !options.ItemsAndFolders.HasFlag(ItemsAndFoldersOptions.Sent)) || (folder.Id == (int)ZimbraFolders.Tasks && !options.ItemsAndFolders.HasFlag(ItemsAndFoldersOptions.Tasks)) || (folder.Id == (int)ZimbraFolders.Trash && !options.ItemsAndFolders.HasFlag(ItemsAndFoldersOptions.DeletedItems)) || // FBS NOTE THAT THESE ARE EXCHANGE SPECIFIC and need to be removed (folder.ContainerClass == "IPF.Contact" && !options.ItemsAndFolders.HasFlag(ItemsAndFoldersOptions.Contacts)) || (folder.ContainerClass == "IPF.Appointment" && !options.ItemsAndFolders.HasFlag(ItemsAndFoldersOptions.Calendar)) || (folder.ContainerClass == "IPF.Task" && !options.ItemsAndFolders.HasFlag(ItemsAndFoldersOptions.Tasks)) || (folder.ContainerClass == "IPF.Note" && !options.ItemsAndFolders.HasFlag(ItemsAndFoldersOptions.Mail)) || (folder.ContainerClass == "" && // if no container class, assume IPF.Note !options.ItemsAndFolders.HasFlag(ItemsAndFoldersOptions.Mail))) { return true; } for (int i = 0; i < skipList.Count; i++) { if (string.Compare(folder.Name, skipList[i], StringComparison.OrdinalIgnoreCase) == 0) { return true; } } return false; }
private MigrationOptions SetOptions() { MigrationOptions importOpts = new MigrationOptions(); ItemsAndFoldersOptions itemFolderFlags = ItemsAndFoldersOptions.None; OptionsViewModel ovm = ((OptionsViewModel)ViewModelPtrs[(int)ViewType.OPTIONS]); if (ovm.ImportCalendarOptions) itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Calendar; if (ovm.ImportTaskOptions) itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Tasks; if (ovm.ImportContactOptions) itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Contacts; if (ovm.ImportMailOptions) itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Mail; if (ovm.ImportSentOptions) itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Sent; if (ovm.ImportDeletedItemOptions) itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.DeletedItems; if (ovm.ImportJunkOptions) itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Junk; if (ovm.ImportRuleOptions) itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Rules; if (ovm.ImportOOOOptions) itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.OOO; importOpts.DateFilterItem = ovm.DateFilterItem; importOpts.ItemsAndFolders = itemFolderFlags; importOpts.DateFilter = (ovm.IsOnOrAfter) ? ovm.MigrateONRAfter : null; importOpts.MessageSizeFilter = (ovm.IsMaxMessageSize) ? ovm.MaxMessageSize : null; importOpts.SkipFolders = (ovm.IsSkipFolders) ? ovm.FoldersToSkip : null; importOpts.SkipPrevMigrated = ovm.IsSkipPrevMigratedItems; importOpts.MaxErrorCnt = ovm.MaxErrorCount; switch(ovm.LogLevel) { 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; } importOpts.SpecialCharRep = ovm.SpecialCharReplace; importOpts.LangID = ovm.LangID; importOpts.MaxRetries = ovm.MaxRetries; return importOpts; }
public void StartMigration(System.Collections.Generic.List <MVVM.Model.Users> userlist, string Domainname, CssLib.MigrationOptions MailOptions, CountdownEvent countdown, object wrapper, int maxThreads = 2, bool ServerMigrationflag = true, string pstaccountname = "", string pstfile = "") { using (LogBlock logblock = Log.NotTracing() ? null : new LogBlock(GetType() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name)) { int number = 0; if (ServerMigrationflag) { // InitializeBackgoundWorkers(); // Create an array containing maxThreads accounts Account[] AccountArray = new Account[maxThreads]; for (int j = 0; j < maxThreads; j++) { AccountArray[j] = new Account(); AccountArray[j].WorkerSupportsCancellation = true; } // Allocate accounts to threads. Choose the first unused thread. for (int f = 0; f < userlist.Count; f++) { if (userlist[f].IsProvisioned) { Account myAccount = new Account(); string uname = (userlist[f].MappedName != "") ? userlist[f].MappedName : userlist[f].UserName; myAccount.AccountName = uname + "@" + Domainname;// AcctName; myAccount.AccountID = userlist[f].UserName; myAccount.Countdown = countdown; myAccount.NumofErrors = 0; Currentuser = new MVVM.Model.Users(); Currentuser.UserName = userlist[f].UserName; myAccount.Currentuser = Currentuser; myAccount.TestObj = (CssLib.CSMigrationWrapper)wrapper; myAccount.serverMigration = ServerMigrationflag; myAccount.Mailoptions = MailOptions; number = number + 1; myAccount.num = number; myAccount.WorkerSupportsCancellation = true; // choose the first unused thread. bool accountAllocatedToThread = false; while ((!accountAllocatedToThread) && (!_shouldStop)) { for (int threadNum = 0; threadNum < maxThreads; threadNum++) { // This thread is available if (!AccountArray[threadNum].IsBusy) { // System.Console.WriteLine("Starting worker thread: " + threadNum + "account" + myAccount.AccountName); AccountArray[threadNum] = myAccount; AccountArray[threadNum].DoWork += new DoWorkEventHandler(accountToMigrate_DoWork); AccountArray[threadNum].RunWorkerCompleted += new RunWorkerCompletedEventHandler(accountToMigrate_RunWorkerCompleted); //AccountArray[threadNum].ProgressChanged += new ProgressChangedEventHandler(accountToMigrate_ProgressChanged); AccountArray[threadNum].WorkerReportsProgress = true; AccountArray[threadNum].WorkerSupportsCancellation = true; AccountArray[threadNum].RunWorkerAsync(myAccount); accountAllocatedToThread = true; break; } } // If all threads are being used, sleep awhile before checking again if (!accountAllocatedToThread) { Thread.Sleep(500); } } if (_shouldStop) { for (int i = 0; i < maxThreads; i++) { System.Console.WriteLine("cancelling in main callback"); countdown.Signal(); AccountArray[i].CancelAsync(); } } } // if (userlist[f].IsProvisioned) else { string msg = userlist[f].MappedName + " is not provisioned. Exiting migration for '" + userlist[f].UserName + "'\n"; System.Console.WriteLine(msg); countdown.Signal(); } } } else { Account myAccount = new Account(); myAccount.AccountName = pstaccountname;// AcctName; myAccount.AccountID = pstfile; myAccount.Countdown = countdown; Currentuser = new MVVM.Model.Users(); Currentuser.UserName = pstfile; myAccount.Currentuser = Currentuser; myAccount.serverMigration = ServerMigrationflag; myAccount.TestObj = (CssLib.CSMigrationWrapper)wrapper; number = number + 1; myAccount.num = number; myAccount.DoWork += new DoWorkEventHandler(accountToMigrate_DoWork); myAccount.RunWorkerCompleted += new RunWorkerCompletedEventHandler(accountToMigrate_RunWorkerCompleted); //myAccount.ProgressChanged += new ProgressChangedEventHandler(accountToMigrate_ProgressChanged); myAccount.WorkerReportsProgress = true; myAccount.WorkerSupportsCancellation = true; myAccount.Mailoptions = MailOptions; myAccount.RunWorkerAsync(myAccount); } } }
public void test(string accountname, object Test, string accountid, MigrationOptions opts, bool ServerMigration) { MigrationAccount MyAcct = new MigrationAccount(); MyAcct.AccountName = accountname; MyAcct.AccountID = accountid; MyAcct.OnChanged += new MigrationObjectEventHandler(i_OnChanged1); MigrationFolder MyFolder = new MigrationFolder(); MyFolder.OnChanged += new MigrationObjectEventHandler(i_OnChanged12); MyAcct.migrationFolder = MyFolder; /* CSMigrationwrapper test = new CSMigrationwrapper(); * test.StartMigration(MyAcct);*/ CSMigrationWrapper test = (CSMigrationWrapper)Test; // test.StartMigration(MyAcct,opts); test.StartMigration(MyAcct, opts, ServerMigration); }