public ProblemInfo(MigrationAccount Acct, string objectName, string theMsg, int msgType, ref bool bError) { bool bErrNotWarn = (msgType == ProblemInfo.TYPE_ERR); this.ObjectName = objectName; this.Msg = theMsg; this.MsgType = msgType; FormattedMsg = "[" + DateTime.Now.ToString("MM-dd HH:mm:ss.fff") + "] "; FormattedMsg += bErrNotWarn ? "Error" : "Warning"; FormattedMsg += (" in [" + Acct.CurrFolder.FolderName + "\\"); FormattedMsg += objectName + "]"; FormattedMsg += ": "; FormattedMsg += Msg; if (bErrNotWarn) { Log.err(FormattedMsg); bError = true; } else { Log.warn(FormattedMsg); } }
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; } }
// 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; }
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; } }
// Background thread stuff private void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { eventArglist.Add(e); int num = (int)e.Argument; Log.info(" In Do work for threads for user number", num); MigrationAccount MyAcct = new MigrationAccount(); UsersViewModel usersViewModel = ((UsersViewModel)ViewModelPtrs[(int)ViewType.USERS]); AccountResultsViewModel accountResultsViewModel = ((AccountResultsViewModel)ViewModelPtrs[(int)ViewType.RESULTS]); // main one string accountname = accountResultsViewModel.AccountResultsList[num].AccountName; string accountid = ""; if (isServer) { accountname = accountname + "@" + usersViewModel.ZimbraDomain; accountid = usersViewModel.UsersList[num].Username; int idx = accountid.IndexOf("@"); if (idx != -1) // domain would be Exchange domain, not Zimbra domain accountid = accountid.Substring(0, idx); } else { ConfigViewModelU sourceModel = ((ConfigViewModelU)ViewModelPtrs[(int)ViewType.USRSRC]); ConfigViewModelUDest destModel = ((ConfigViewModelUDest)ViewModelPtrs[(int)ViewType.USRDEST]); accountname = ZimbraValues.GetZimbraValues().AccountName;//accountname + "@" + destModel.ZimbraServerHostName; accountid = (sourceModel.IspST) ? sourceModel.PSTFile : sourceModel.ProfileList[sourceModel.CurrentProfileSelection]; } MyAcct.AccountName = accountname; MyAcct.AccountID = accountid; MyAcct.AccountNum = num; MyAcct.OnChanged += new MigrationObjectEventHandler(Acct_OnAcctChanged); MigrationFolder MyFolder = new MigrationFolder(); MyFolder.AccountNum = num; MyFolder.OnChanged += new MigrationObjectEventHandler(Folder_OnChanged); MyAcct.migrationFolder = MyFolder; CSMigrationWrapper mw = ((IntroViewModel)ViewModelPtrs[(int)ViewType.INTRO]).mw; MigrationOptions importOpts = SetOptions(); bool isVerbose = ((OptionsViewModel)ViewModelPtrs[(int)ViewType.OPTIONS]).LoggingVerbose; bool doRulesAndOOO = ((OptionsViewModel)ViewModelPtrs[(int)ViewType.OPTIONS]).OEnableRulesAndOOO; if (isVerbose) { if (importOpts.VerboseOn < LogLevel.Debug) { importOpts.VerboseOn = LogLevel.Debug; } } Log.info(" start migration for account ", MyAcct.AccountNum); //mw.StartMigration(MyAcct, importOpts, isServer, (isVerbose ? (LogLevel.Debug):(LogLevel.Info)), m_isPreview); mw.StartMigration(MyAcct, importOpts, isServer, importOpts.VerboseOn, m_isPreview, doRulesAndOOO); // special case to format last user progress message int count = accountResultsViewModel.AccountResultsList[num].UserResultsList.Count; if (count > 0) { if (!m_isPreview) { string lastmsg = accountResultsViewModel.AccountResultsList[num].UserResultsList[count - 1].UserProgressMsg; int len = lastmsg.Length; bool isOOOorRules = ((MyFolder.FolderView == "OOO") || (MyFolder.FolderView == "All Rules")); accountResultsViewModel.AccountResultsList[num].UserResultsList[count - 1].UserProgressMsg = FormatTheLastMsg(MyFolder, isOOOorRules); accountResultsViewModel.AccountResultsList[num].PBValue = 100; // to make sure if (accountResultsViewModel.AccountResultsList[num].CurrentItemNum != accountResultsViewModel.AccountResultsList[num].TotalItemsToMigrate) { FormatGlobalMsg(accountResultsViewModel.AccountResultsList[num]); } } else { // For preview, take the "foldername (n items)" message we constructed, extract the n, and make "Total n" string msg = ""; string lastmsg = accountResultsViewModel.AccountResultsList[num].PBMsgValue; int idxParen = lastmsg.IndexOf("("); int idxItems = lastmsg.IndexOf("items"); if ((idxParen != -1) && (idxItems != -1)) { int numLen = idxItems - idxParen - 2; // for the paren and the space string numStr = lastmsg.Substring(idxParen + 1, numLen); msg = "Total: " + numStr; accountResultsViewModel.AccountResultsList[num].UserResultsList[count - 1].UserProgressMsg = (msg.Length > 0) ? msg : ""; } } } ///// if (!m_isPreview) { int tnum = GetThreadNum(MyAcct.AccountNum); //Log.info(" in worker_RunWorkerCompleted for ThreadNum : " + tnum); if ((!(MyAcct.IsValid)) && (MyAcct.TotalErrors > 0)) { Log.info(" in DOWORK -- Migration failed for usernum: " + MyAcct.AccountNum + " and threadnum" + tnum); accountResultsViewModel.AccountResultsList[num].PBMsgValue = "Migration Failed - Invalid account"; accountResultsViewModel.AccountResultsList[num].AcctProgressMsg = "Failed"; } else { if ((!(MyAcct.IsCompletedMigration)) && (MyAcct.TotalErrors > 0)) { Log.info(" in DOWORK -- Migration Incomplete for usernum: " + MyAcct.AccountNum + " and threadnum" + tnum); accountResultsViewModel.AccountResultsList[num].PBMsgValue = "Migration Incomplete - Please Re-Run Migration"; accountResultsViewModel.AccountResultsList[num].AcctProgressMsg = "Incomplete"; } else { Log.info(" in DOWORK -- Migration completed for usernum: " + MyAcct.AccountNum + " and threadnum" + tnum); accountResultsViewModel.AccountResultsList[num].PBMsgValue = "Migration complete"; accountResultsViewModel.AccountResultsList[num].AcctProgressMsg = "Complete"; } } } else { string msg = "Total items: {0}"; accountResultsViewModel.AccountResultsList[num].PBMsgValue = String.Format(msg, accountResultsViewModel.AccountResultsList[num].TotalItemsToMigrate); } if (importOpts.IsMaintainenceMode) { accountResultsViewModel.AccountResultsList[num].PBMsgValue = "Migration Incomplete"; accountResultsViewModel.AccountResultsList[num].AcctProgressMsg = "InComplete"; } }
public void Acct_OnChanged(object sender, CssLib.MigrationObjectEventArgs e) // See similar code in ScheduleViewModel......can we dedupe? { // while (!_shouldStop) { //string msg = ""; CssLib.MigrationAccount a = (CssLib.MigrationAccount)sender; if (e.PropertyName == "NumAccountItemsToMigrate") { /*System.Console.WriteLine(); * ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Yellow, "TotalItems to Migrate For UserAccount " + a.AccountID.ToString() + " is " + e.NewValue.ToString()); * System.Console.WriteLine();*/ // a.TotalItems = Convert.ToInt32(e.NewValue); Currentuser.StatusMessage = "Total Items to Migrate For UserAccount " + a.AccountID + " is " + e.NewValue.ToString(); /*System.Console.WriteLine(); * System.Console.WriteLine();*/ } else if (e.PropertyName == "NumAccountErrs") { this.NumofErrors = (int)a.NumAccountErrs + 1; // this happens first System.Console.WriteLine(); if (a.MaxErrorCount > 0) { if (this.NumofErrors >= a.MaxErrorCount) { System.Console.WriteLine(); if (a.LastProblemInfo != null) { System.Console.WriteLine(); string mesg = a.LastProblemInfo.Msg; System.Console.WriteLine(mesg); System.Console.WriteLine(); } System.Console.WriteLine(); Currentuser.StatusMessage = "Total Errors For UserAccount " + a.AccountID.ToString() + " are " + this.NumofErrors.ToString(); System.Console.WriteLine(Currentuser.StatusMessage); string Messg = "Migration For UserAccount Cancelled because MaxErrorCount has been reached"; // ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red, "Migration For UserAccount Cancelled"); System.Console.WriteLine(Messg); System.Console.WriteLine(); System.Console.WriteLine(); //this.countdown.Signal(); //this.RequestCancel(); // this.RequestStop(); //Countdown.Signal(); CancelAsync(); //Thread.CurrentThread.Abort(); } } if (a.LastProblemInfo != null) { System.Console.WriteLine(); string mesg = a.LastProblemInfo.Msg; System.Console.WriteLine(mesg); System.Console.WriteLine(); } /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Yellow, "TotalErrors For UserAccount " + a.AccountID.ToString() + Numoferrors.ToString());*/ //donot use progressutil we want to have consistent logging. /*Currentuser.StatusMessage = "Total Errors For UserAccount " + a.AccountID.ToString() + "are" + NumofErrors.ToString(); * System.Console.WriteLine(Currentuser.StatusMessage); * System.Console.WriteLine(); * System.Console.WriteLine();*/ } else if (e.PropertyName == "NumAccountWarns") { NumofWarns = (int)a.NumAccountWarns + 1; System.Console.WriteLine(); /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Yellow, "TotalWarnings For UserAccount " + a.AccountID.ToString() + NumofWarns.ToString());*/ //donot use progressutil we want to have consistent logging. Currentuser.StatusMessage = "Total Warnings For UserAccount " + a.AccountID.ToString() + NumofWarns.ToString(); System.Console.WriteLine(Currentuser.StatusMessage); System.Console.WriteLine(); } else { /* System.Console.WriteLine(); * ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Yellow, "TotalItems to Migrate For UserAccount " + a.AccountName.ToString() + " is " + e.NewValue.ToString()); * System.Console.WriteLine();/* * msg = "Begin {0} Migration"; * string msgF = String.Format(msg, a.AccountName); * System.Console.WriteLine(msgF);*/ } } }
private void accountToMigrate_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { Account accnt = e.Argument as Account; // ------------------------------------------------ // Create a thread-specific log for this thread // ------------------------------------------------ string AccountName = accnt.AccountName; int i = AccountName.IndexOf("@"); if (i != -1) { AccountName = AccountName.Substring(0, i); } // Similar code in ScheduleViewModel.cs::worker_DoWork // Log suffix [src accnt] to [targ accnt] string sSrc = Path.GetFileNameWithoutExtension(accnt.AccountID); Log.StartNewLogfileForThisThread("[" + sSrc + "] to [" + AccountName + "]"); // If you change this, also change OpenLogFile() using (LogBlock logblock = Log.NotTracing() ? null : new LogBlock(GetType() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name)) // LogBlock not available here...it is now logging moved to ZimbraAPI { // Get argument from DoWorkEventArgs argument. Can use any type here with cast // int myProcessArguments = (int)e.Argument; // "ProcessFile" is the name of my method that does the main work. Replace with your own method! // Can return reulsts from this method, i.e. a status (OK, FAIL etc) //e.Result = ProcessFile(myProcessArgument); BackgroundWorker worker = sender as BackgroundWorker; // Assign the result of the computation // to the Result property of the DoWorkEventArgs // object. This is will be available to the // RunWorkerCompleted eventhandler. // e.Result = Accounworker, e); //int num = 0; //while (!_shouldStop) { accnt.WorkerSupportsCancellation = true; CssLib.MigrationAccount MyAcct = new CssLib.MigrationAccount(); MyAcct.AccountName = accnt.AccountName; MyAcct.AccountID = accnt.AccountID; MyAcct.MaxErrorCount = accnt.Mailoptions.MaxErrorCnt; MyAcct.AccountNum = accnt.num; MyAcct.OnChanged += new CssLib.MigrationObjectEventHandler(Acct_OnChanged); CssLib.MigrationFolder MyFolder = new CssLib.MigrationFolder(); //MyFolder.AccountNum = argumentTest.num; int idx = MyAcct.AccountName.IndexOf("@"); if (idx != -1) { MyFolder.AccountID = MyAcct.AccountName.Substring(0, idx); } // MyFolder.AccountID = argumentTest.AccountID; MyFolder.OnChanged += new CssLib.MigrationObjectEventHandler(Folder_OnChanged); MyAcct.CurrFolder = MyFolder; CssLib.CSMigrationWrapper mw = accnt.TestObj; if (accnt.CancellationPending) { e.Cancel = true; } else { // TestObj.Migrate(MigrateOptions); mw.StartMigration(MyAcct, accnt.Mailoptions, accnt.serverMigration); if (accnt.Mailoptions.IsMaintainenceMode) { System.Console.WriteLine("Mailbox is in Maintainence mode. Try again Later"); } accnt.NumofErrors = MyAcct.NumAccountErrs; //Last item migration string sAcccountID = "[" + MyFolder.AccountID.ToString() + "]"; string msg2 = sAcccountID.PadRight(25, ' ') + MyFolder.FolderName.PadRight(25, ' ') + "{0,5:#} of {1,5:#} migrated successfully"; string msgF = String.Format(msg2, MyFolder.NumFolderItemsMigrated, MyFolder.NumFolderItemsToMigrate); System.Console.WriteLine(msgF); } } if (_shouldStop) { worker.CancelAsync(); accnt.CancelAsync(); accnt.countdown.Signal(); e.Cancel = true; } if (_shouldCancel) { //worker.CancelAsync(); // argumentTest.CancelAsync(); // argumentTest.NumofErrors = NumofErrors; accnt.CancelAsync(); } } }
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); }