public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) { return(true); } System.Windows.Shell.TaskbarItemProgressState state = (System.Windows.Shell.TaskbarItemProgressState)value; if (state == System.Windows.Shell.TaskbarItemProgressState.Indeterminate) { return(true); } return(false); }
public static bool CheckBranchCondition(EngineState s, BranchCondition c, out string logMessage) { { bool match = false; switch (c.Type) { case BranchConditionType.Equal: case BranchConditionType.Smaller: case BranchConditionType.Bigger: case BranchConditionType.SmallerEqual: case BranchConditionType.BiggerEqual: case BranchConditionType.EqualX: { string compArg1 = StringEscaper.Preprocess(s, c.Arg1); string compArg2 = StringEscaper.Preprocess(s, c.Arg2); bool ignoreCase = true; if (c.Type == BranchConditionType.EqualX) { ignoreCase = false; } NumberHelper.CompareStringNumberResult comp = NumberHelper.CompareStringNumber(compArg1, compArg2, ignoreCase); switch (comp) { case NumberHelper.CompareStringNumberResult.Equal: // For String and Number { if (c.Type == BranchConditionType.Equal && !c.NotFlag || c.Type == BranchConditionType.SmallerEqual && !c.NotFlag || c.Type == BranchConditionType.BiggerEqual && !c.NotFlag || c.Type == BranchConditionType.Smaller && c.NotFlag || c.Type == BranchConditionType.Bigger && c.NotFlag || c.Type == BranchConditionType.EqualX && !c.NotFlag) { match = true; } logMessage = $"[{compArg1}] is equal to [{compArg2}]"; } break; case NumberHelper.CompareStringNumberResult.Smaller: // For Number { if (c.Type == BranchConditionType.Smaller && !c.NotFlag || c.Type == BranchConditionType.SmallerEqual && !c.NotFlag || c.Type == BranchConditionType.Bigger && c.NotFlag || c.Type == BranchConditionType.BiggerEqual && c.NotFlag || c.Type == BranchConditionType.Equal && c.NotFlag || c.Type == BranchConditionType.EqualX && c.NotFlag) { match = true; } logMessage = $"[{compArg1}] is smaller than [{compArg2}]"; } break; case NumberHelper.CompareStringNumberResult.Bigger: // For Number { if (c.Type == BranchConditionType.Bigger && !c.NotFlag || c.Type == BranchConditionType.BiggerEqual && !c.NotFlag || c.Type == BranchConditionType.Smaller && c.NotFlag || c.Type == BranchConditionType.SmallerEqual && c.NotFlag || c.Type == BranchConditionType.Equal && c.NotFlag || c.Type == BranchConditionType.EqualX && c.NotFlag) { match = true; } logMessage = $"[{compArg1}] is bigger than [{compArg2}]"; } break; case NumberHelper.CompareStringNumberResult.NotEqual: // For String { if (c.Type == BranchConditionType.Equal && c.NotFlag || c.Type == BranchConditionType.EqualX && c.NotFlag) { match = true; } logMessage = $"[{compArg1}] is not equal to [{compArg2}]"; } break; default: throw new InternalException($"Cannot compare [{compArg1}] and [{compArg2}]"); } } break; case BranchConditionType.ExistFile: { string filePath = StringEscaper.Preprocess(s, c.Arg1); // Check filePath contains wildcard bool containsWildcard = true; if (Path.GetFileName(filePath).IndexOfAny(new char[] { '*', '?' }) == -1) // No wildcard { containsWildcard = false; } // Check if file exists if (filePath.Trim().Equals(string.Empty, StringComparison.Ordinal)) { match = false; } else if (containsWildcard) { if (Directory.Exists(FileHelper.GetDirNameEx(filePath)) == false) { match = false; } else { string[] list = Directory.GetFiles(FileHelper.GetDirNameEx(filePath), Path.GetFileName(filePath)); if (0 < list.Length) { match = true; } else { match = false; } } } else { match = File.Exists(filePath); } if (match) { logMessage = $"File [{filePath}] exists"; } else { logMessage = $"File [{filePath}] does not exist"; } if (c.NotFlag) { match = !match; } } break; case BranchConditionType.ExistDir: { string dirPath = StringEscaper.Preprocess(s, c.Arg1); // Check filePath contains wildcard bool containsWildcard = true; if (Path.GetFileName(dirPath).IndexOfAny(new char[] { '*', '?' }) == -1) // No wildcard { containsWildcard = false; } // Check if directory exists if (dirPath.Trim().Equals(string.Empty, StringComparison.Ordinal)) { match = false; } else if (containsWildcard) { if (Directory.Exists(FileHelper.GetDirNameEx(dirPath)) == false) { match = false; } else { string[] list = Directory.GetDirectories(FileHelper.GetDirNameEx(dirPath), Path.GetFileName(dirPath)); if (0 < list.Length) { match = true; } else { match = false; } } } else { match = Directory.Exists(dirPath); } if (match) { logMessage = $"Directory [{dirPath}] exists"; } else { logMessage = $"Directory [{dirPath}] does not exist"; } if (c.NotFlag) { match = !match; } } break; case BranchConditionType.ExistSection: { string iniFile = StringEscaper.Preprocess(s, c.Arg1); string section = StringEscaper.Preprocess(s, c.Arg2); match = Ini.CheckSectionExist(iniFile, section); if (match) { logMessage = $"Section [{section}] exists in INI file [{iniFile}]"; } else { logMessage = $"Section [{section}] does not exist in INI file [{iniFile}]"; } if (c.NotFlag) { match = !match; } } break; case BranchConditionType.ExistRegSection: case BranchConditionType.ExistRegSubKey: { string rootKey = StringEscaper.Preprocess(s, c.Arg1); string subKey = StringEscaper.Preprocess(s, c.Arg2); RegistryKey regRoot = RegistryHelper.ParseStringToRegKey(rootKey); if (regRoot == null) { throw new InvalidRegKeyException($"Invalid registry root key [{rootKey}]"); } using (RegistryKey regSubKey = regRoot.OpenSubKey(subKey)) { match = (regSubKey != null); if (match) { logMessage = $"Registry SubKey [{rootKey}\\{subKey}] exists"; } else { logMessage = $"Registry SubKey [{rootKey}\\{subKey}] does not exist"; } } if (c.NotFlag) { match = !match; } } break; case BranchConditionType.ExistRegKey: case BranchConditionType.ExistRegValue: { string rootKey = StringEscaper.Preprocess(s, c.Arg1); string subKey = StringEscaper.Preprocess(s, c.Arg2); string valueName = StringEscaper.Preprocess(s, c.Arg3); match = true; RegistryKey regRoot = RegistryHelper.ParseStringToRegKey(rootKey); if (regRoot == null) { throw new InvalidRegKeyException($"Invalid registry root key [{rootKey}]"); } using (RegistryKey regSubKey = regRoot.OpenSubKey(subKey)) { if (regSubKey == null) { match = false; } else { object value = regSubKey.GetValue(valueName); if (value == null) { match = false; } } if (match) { logMessage = $"Registry Value [{rootKey}\\{subKey}\\{valueName}] exists"; } else { logMessage = $"Registry Value [{rootKey}\\{subKey}\\{valueName}] does not exist"; } } if (c.NotFlag) { match = !match; } } break; case BranchConditionType.ExistRegMulti: { string rootKey = StringEscaper.Preprocess(s, c.Arg1); string subKey = StringEscaper.Preprocess(s, c.Arg2); string valueName = StringEscaper.Preprocess(s, c.Arg3); string subStr = StringEscaper.Preprocess(s, c.Arg4); match = false; RegistryKey regRoot = RegistryHelper.ParseStringToRegKey(rootKey); if (regRoot == null) { throw new InvalidRegKeyException($"Invalid registry root key [{rootKey}]"); } using (RegistryKey regSubKey = regRoot.OpenSubKey(subKey)) { if (regSubKey == null) { logMessage = $"Registry SubKey [{rootKey}\\{subKey}] does not exist"; } else { object valueData = regSubKey.GetValue(valueName, null); if (valueData == null) { logMessage = $"Registry Value [{rootKey}\\{subKey}\\{valueName}] does not exist"; } else { RegistryValueKind kind = regSubKey.GetValueKind(valueName); if (kind != RegistryValueKind.MultiString) { logMessage = $"Registry Value [{rootKey}\\{subKey}\\{valueName}] is not REG_MULTI_SZ"; } else { string[] strs = (string[])valueData; if (strs.Contains(subStr, StringComparer.OrdinalIgnoreCase)) { match = true; logMessage = $"Registry Value [{rootKey}\\{subKey}\\{valueName}] contains substring [{subStr}]"; } else { logMessage = $"Registry Value [{rootKey}\\{subKey}\\{valueName}] does not contain substring [{subStr}]"; } } } } } if (c.NotFlag) { match = !match; } } break; case BranchConditionType.ExistVar: { Variables.VarKeyType type = Variables.DetermineType(c.Arg1); if (type == Variables.VarKeyType.Variable) { match = s.Variables.ContainsKey(Variables.TrimPercentMark(c.Arg1)); if (match) { logMessage = $"Variable [{c.Arg1}] exists"; } else { logMessage = $"Variable [{c.Arg1}] does not exist"; } } else { match = false; logMessage = $"[{c.Arg1}] is not a variable"; } if (c.NotFlag) { match = !match; } } break; case BranchConditionType.ExistMacro: { string macroName = StringEscaper.Preprocess(s, c.Arg1); match = s.Macro.MacroDict.ContainsKey(macroName) || s.Macro.LocalDict.ContainsKey(macroName); if (match) { logMessage = $"Macro [{macroName}] exists"; } else { logMessage = $"Macro [{macroName}] does not exist"; } if (c.NotFlag) { match = !match; } } break; case BranchConditionType.WimExistIndex: { string wimFile = StringEscaper.Preprocess(s, c.Arg1); string imageIndexStr = StringEscaper.Preprocess(s, c.Arg2); if (!NumberHelper.ParseInt32(imageIndexStr, out int imageIndex)) { logMessage = $"Index [{imageIndexStr}] is not a positive integer"; } else if (imageIndex < 1) { logMessage = $"Index [{imageIndexStr}] is not a positive integer"; } else { if (File.Exists(wimFile)) { try { using (Wim wim = Wim.OpenWim(wimFile, OpenFlags.DEFAULT)) { WimInfo wi = wim.GetWimInfo(); if (imageIndex <= wi.ImageCount) { match = true; logMessage = $"ImageIndex [{imageIndex}] exists in [{wimFile}]"; } else { logMessage = $"ImageIndex [{imageIndex}] does not exist in [{wimFile}]"; } } } catch (WimLibException e) { logMessage = $"Error [{e.ErrorCode}] occured while handling [{wimFile}]"; } } else { logMessage = $"Wim [{wimFile}] does not exist"; } } if (c.NotFlag) { match = !match; } } break; case BranchConditionType.WimExistFile: { string wimFile = StringEscaper.Preprocess(s, c.Arg1); string imageIndexStr = StringEscaper.Preprocess(s, c.Arg2); string filePath = StringEscaper.Preprocess(s, c.Arg3); if (!NumberHelper.ParseInt32(imageIndexStr, out int imageIndex)) { logMessage = $"Index [{imageIndexStr}] is not a positive integer"; } else if (imageIndex < 1) { logMessage = $"Index [{imageIndexStr}] is not a positive integer"; } else { if (File.Exists(wimFile)) { try { using (Wim wim = Wim.OpenWim(wimFile, OpenFlags.DEFAULT)) { bool isFile = false; CallbackStatus WimExistFileCallback(DirEntry dentry, object userData) { if ((dentry.Attributes & FileAttribute.DIRECTORY) == 0) { isFile = true; } return(CallbackStatus.CONTINUE); } try { wim.IterateDirTree(imageIndex, filePath, IterateFlags.DEFAULT, WimExistFileCallback, null); if (isFile) { match = true; logMessage = $"File [{filePath}] exists in [{wimFile}]"; } else { logMessage = $"File [{filePath}] does not exist in [{wimFile}]"; } } catch (WimLibException e) { switch (e.ErrorCode) { case ErrorCode.INVALID_IMAGE: logMessage = $"File [{filePath}] does not have image index [{imageIndex}]"; break; case ErrorCode.PATH_DOES_NOT_EXIST: logMessage = $"File [{filePath}] does not exist in [{wimFile}]"; break; default: logMessage = $"Error [{e.ErrorCode}] occured while handling [{wimFile}]"; break; } } } } catch (WimLibException e) { logMessage = $"Error [{e.ErrorCode}] occured while handling [{wimFile}]"; } } else { logMessage = $"Wim [{wimFile}] does not exist"; } } if (c.NotFlag) { match = !match; } } break; case BranchConditionType.WimExistDir: { string wimFile = StringEscaper.Preprocess(s, c.Arg1); string imageIndexStr = StringEscaper.Preprocess(s, c.Arg2); string dirPath = StringEscaper.Preprocess(s, c.Arg3); if (!NumberHelper.ParseInt32(imageIndexStr, out int imageIndex)) { logMessage = $"Index [{imageIndexStr}] is not a positive integer"; } else if (imageIndex < 1) { logMessage = $"Index [{imageIndexStr}] is not a positive integer"; } else { if (File.Exists(wimFile)) { try { using (Wim wim = Wim.OpenWim(wimFile, OpenFlags.DEFAULT)) { bool isDir = false; CallbackStatus WimExistFileCallback(DirEntry dentry, object userData) { if ((dentry.Attributes & FileAttribute.DIRECTORY) != 0) { isDir = true; } return(CallbackStatus.CONTINUE); } try { wim.IterateDirTree(imageIndex, dirPath, IterateFlags.DEFAULT, WimExistFileCallback, null); if (isDir) { match = true; logMessage = $"Dir [{dirPath}] exists in [{wimFile}]"; } else { logMessage = $"Dir [{dirPath}] does not exist in [{wimFile}]"; } } catch (WimLibException e) { switch (e.ErrorCode) { case ErrorCode.INVALID_IMAGE: logMessage = $"Dir [{dirPath}] does not have image index [{imageIndex}]"; break; case ErrorCode.PATH_DOES_NOT_EXIST: logMessage = $"Dir [{dirPath}] does not exist in [{wimFile}]"; break; default: logMessage = $"Error [{e.ErrorCode}] occured while handling [{wimFile}]"; break; } } } } catch (WimLibException e) { logMessage = $"Error [{e.ErrorCode}] occured while handling [{wimFile}]"; } } else { logMessage = $"Wim [{wimFile}] does not exist"; } } if (c.NotFlag) { match = !match; } } break; case BranchConditionType.Ping: { string host = StringEscaper.Preprocess(s, c.Arg1); Ping pinger = new Ping(); try { try { PingReply reply = pinger.Send(host); if (reply.Status == IPStatus.Success) { match = true; } else { match = false; } } catch { match = false; } if (match) { logMessage = $"[{host}] responded to Ping"; } else { logMessage = $"[{host}] did not respond to Ping"; } } catch (PingException e) { match = false; logMessage = $"Error while pinging [{host}] : [{e.Message}]"; } if (c.NotFlag) { match = !match; } } break; case BranchConditionType.Online: { // Note that system connected only to local network also returns true match = NetworkInterface.GetIsNetworkAvailable(); if (match) { logMessage = "System is online"; } else { logMessage = "System is offline"; } if (c.NotFlag) { match = !match; } } break; case BranchConditionType.Question: // can have 1 or 3 argument { string question = StringEscaper.Preprocess(s, c.Arg1); bool autoTimeout = false; if (c.Arg2 != null && c.Arg3 != null) { autoTimeout = true; } int timeout = 0; bool defaultChoice = false; if (autoTimeout) { string timeoutStr = StringEscaper.Preprocess(s, c.Arg2); if (NumberHelper.ParseInt32(timeoutStr, out timeout) == false) { autoTimeout = false; } if (timeout <= 0) { autoTimeout = false; } string defaultChoiceStr = StringEscaper.Preprocess(s, c.Arg3); if (defaultChoiceStr.Equals("True", StringComparison.OrdinalIgnoreCase)) { defaultChoice = true; } else if (defaultChoiceStr.Equals("False", StringComparison.OrdinalIgnoreCase)) { defaultChoice = false; } } System.Windows.Shell.TaskbarItemProgressState oldTaskbarItemProgressState = s.MainViewModel.TaskbarProgressState; // Save our progress state s.MainViewModel.TaskbarProgressState = System.Windows.Shell.TaskbarItemProgressState.Paused; if (autoTimeout) { MessageBoxResult result = MessageBoxResult.None; Application.Current.Dispatcher.Invoke(() => { result = CustomMessageBox.Show(question, "Confirm", MessageBoxButton.YesNo, MessageBoxImage.Question, timeout); }); if (result == MessageBoxResult.None) { match = defaultChoice; if (defaultChoice) { logMessage = "[Yes] was automatically chosen"; } else { logMessage = "[No] was automatically chosen"; } } else if (result == MessageBoxResult.Yes) { match = true; logMessage = "[Yes] was chosen"; } else if (result == MessageBoxResult.No) { match = false; logMessage = "[No] was chosen"; } else { throw new InternalException("Internal Error at Check() of If,Question"); } } else { MessageBoxResult result = MessageBox.Show(question, "Confirm", MessageBoxButton.YesNo, MessageBoxImage.Question); if (result == MessageBoxResult.Yes) { match = true; logMessage = "[Yes] was chosen"; } else if (result == MessageBoxResult.No) { match = false; logMessage = "[No] was chosen"; } else { throw new InternalException("Internal Error at Check() of If,Question"); } } if (c.NotFlag) { match = !match; } s.MainViewModel.TaskbarProgressState = oldTaskbarItemProgressState; } break; default: throw new InternalException($"Internal BranchCondition check error"); } return(match); } }
private void UpdateTaskbarErrorState(double progressValue, System.Windows.Shell.TaskbarItemProgressState progressState, string description) { UpdateTaskbarErrorState(progressValue, progressState); taskbarInfo.Description = description; }
private void UpdateTaskbarErrorState(double progressValue, System.Windows.Shell.TaskbarItemProgressState progressState) { taskbarInfo.ProgressValue = progressValue; taskbarInfo.ProgressState = progressState; }
public void CreateCaseSyncFileStart(Epi.ImportExport.Filters.RowFilters filters, Epi.RecordProcessingScope recordProcessingScope) { if (IsWaitingOnOtherClients) { return; } if (String.IsNullOrEmpty(SyncFilePath.Trim())) { throw new InvalidOperationException(); } var stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); bool includeCases = IncludeCasesAndContacts || IncludeCasesOnly; bool includeCaseExposures = true; bool includeContacts = IncludeCasesAndContacts; bool deIdentifyData = DeIdentifyData; #region Remove extraneous data int rows = 0; OverallSyncStatus = "Deleting extraneous page table rows..."; IDbDriver db = _project.CollectedData.GetDatabase(); foreach (View form in _project.Views) { foreach (Page page in form.Pages) { Query deleteQuery = db.CreateQuery("DELETE FROM " + form.Name + " WHERE GlobalRecordId NOT IN (SELECT GlobalRecordId FROM " + page.TableName + ")"); rows = db.ExecuteNonQuery(deleteQuery); if (rows > 0) { // report ?? } Query pageDeleteQuery = db.CreateQuery("DELETE FROM " + page.TableName + " WHERE GlobalRecordId NOT IN (SELECT GlobalRecordId FROM " + form.Name + ")"); rows = db.ExecuteNonQuery(deleteQuery); if (rows > 0) { // report ?? } } } Query linksDeleteQuery = db.CreateQuery("DELETE FROM metaLinks WHERE ToViewId = @ToViewId AND ToRecordGuid NOT IN (SELECT GlobalRecordId FROM " + ContactForm.TableName + ")"); linksDeleteQuery.Parameters.Add(new QueryParameter("@ToViewId", DbType.Int32, ContactFormId)); rows = db.ExecuteNonQuery(linksDeleteQuery); if (db.TableExists("metaHistory")) { Query historyDeleteQuery = db.CreateQuery("DELETE FROM metaHistory WHERE ContactGUID NOT IN (SELECT GlobalRecordId FROM " + ContactForm.TableName + ")"); rows = db.ExecuteNonQuery(historyDeleteQuery); } #endregion // Remove extraneous data RecordsExported = String.Empty; IsDataSyncing = true; IsShowingExportProgress = true; var doc = new XmlDocument { XmlResolver = null }; SendMessageForAwaitAll(); Task.Factory.StartNew( () => { doc = CreateCaseSyncFile(includeCases, includeCaseExposures, includeContacts, filters, deIdentifyData, recordProcessingScope); }, System.Threading.CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).ContinueWith( delegate { try { if (!String.IsNullOrEmpty(doc.InnerText)) { string compressedText = Epi.ImportExport.ImportExportHelper.Zip(doc.OuterXml); compressedText = "[[EPIINFO7_VHF_CASE_SYNC_FILE__0937]]" + compressedText; Epi.Configuration.EncryptStringToFile(compressedText, SyncFilePath, "vQ@6L'<J3?)~5=vQnwh(2ic;>.<=dknF&/TZ4Uu!$78", "", "", 1000); } } catch (Exception) { // do nothing... if the XML is invalid, we should have already alerted the user in a different method } finally { SendMessageForUnAwaitAll(); } TaskbarProgressState = System.Windows.Shell.TaskbarItemProgressState.None; TaskbarProgressValue = 0; ProgressValue = 0; IsDataSyncing = false; stopwatch.Stop(); SyncStatus = String.Empty; OverallSyncStatus = "Finished exporting data to sync file. Elapsed time: " + stopwatch.Elapsed.TotalMinutes.ToString("F1") + " minutes."; }, TaskScheduler.FromCurrentSynchronizationContext()); }
private XmlDocument CreateCaseSyncFile(bool includeCases, bool includeCaseExposures, bool includeContacts, Epi.ImportExport.Filters.RowFilters filters, bool deIdentifyData, Epi.RecordProcessingScope recordProcessingScope) { TaskbarProgressValue = 0; TaskbarProgressState = System.Windows.Shell.TaskbarItemProgressState.Normal; ProgressValue = 0; _increment = 0.25; if (includeCaseExposures && includeContacts) { _increment = 0.25; } else if (includeCaseExposures && !includeContacts) { _increment = 0.34; } else if (!includeCaseExposures && !includeContacts) { _increment = 0.5; } IDbDriver database = _project.CollectedData.GetDatabase(); //#region Repair page tables //RemoveExtraneousPageTableRecordsCommand.Execute(null); //#endregion // Repair page tables #region Case and Lab Data //var packager = new ContactTracing.ExportView.XmlSqlDataPackager(CaseForm, "sync") //new Epi.ImportExport.ProjectPackagers.XmlDataPackager(CaseForm, "sync") var packager = new Epi.ImportExport.ProjectPackagers.XmlDataPackager(CaseForm, "sync") { RecordProcessingScope = recordProcessingScope }; packager.StatusChanged += unpackager_StatusChanged; packager.UpdateProgress += unpackager_UpdateProgress; if (filters == null) { filters = new Epi.ImportExport.Filters.RowFilters(database, Epi.ImportExport.Filters.ConditionJoinTypes.And); } if (includeCases == false) { // filter out all cases var tfc = new Epi.ImportExport.TextRowFilterCondition("[EpiCaseDef] = @EpiCaseDef", "EpiCaseDef", "@EpiCaseDef", "1000") { Description = "EpiCaseDef is equal to 1000" }; filters.Add(tfc); } DateTime dateValue = DateTime.MinValue; DateTime today = DateTime.Now; TimeSpan ts = new TimeSpan(int.Parse(Days), 0, 0, 0); DateTime nDaysAgo = today - ts; dateValue = nDaysAgo; var daysAgoFilter = new Epi.ImportExport.DateRowFilterCondition("LastSaveTime >= @LastSaveTime", "LastSaveTime", "@LastSaveTime", dateValue); filters.Add(daysAgoFilter); packager.Filters = new Dictionary <string, Epi.ImportExport.Filters.RowFilters> { { "CaseInformationForm", filters } }; if (deIdentifyData) { if (!IsCountryUS) { packager.FieldsToNull.Add(CaseForm.Name, new List <string> { "Surname", "OtherNames", "PhoneNumber", "PhoneOwner", "HeadHouse", "ContactName1", "ContactName2", "ContactName3", "FuneralName1", "FuneralName2", "HospitalBeforeIllPatient", "TradHealerName", "InterviewerName", "InterviewerPhone", "InterviwerEmail", "ProxyName" }); packager.FieldsToNull.Add(LabForm.Name, new List <string> { "SurnameLab", "OtherNameLab" }); } else { packager.FieldsToNull.Add(CaseForm.Name, new List <string> { "Surname", "OtherNames", "PhoneNumber", "PhoneOwner", "HeadHouse", "ContactName1", "ContactName2", "ContactName3", "FuneralName1", "FuneralName2", "HospitalBeforeIllPatient", "TradHealerName", "InterviewerName", "InterviewerPhone", "InterviwerEmail", "ProxyName", "DOB", "Email", "AddressRes", "AddressOnset", "ProxyPhone", "ProxyEmail" }); packager.FieldsToNull.Add(LabForm.Name, new List <string> { "SurnameLab", "OtherNameLab", "PersonLabSubmit", "PhoneLabSubmit", "EmailLabSubmit" }); } } packager.IncludeNullFieldData = false; var doc = new XmlDocument { XmlResolver = null }; bool failed = false; try { OverallSyncStatus = "Packaging case records..."; doc = packager.PackageForm(); TaskbarProgressValue = TaskbarProgressValue + _increment; OverallSyncStatus = "Finished packaging case records"; if (packager.ExportInfo.RecordsPackaged.ContainsKey(LabForm)) { RecordsExported = "Exported: " + RecordsExported + packager.ExportInfo.RecordsPackaged[CaseForm].ToString() + " cases, " + packager.ExportInfo.RecordsPackaged[LabForm].ToString() + " lab results"; } else { RecordsExported = "Exported: " + RecordsExported + packager.ExportInfo.TotalRecordsPackaged.ToString() + " cases"; } } catch (Exception ex) { if (SyncProblemsDetected != null) { SyncProblemsDetected(ex, new EventArgs()); } failed = true; } finally { packager.StatusChanged -= unpackager_StatusChanged; packager.UpdateProgress -= unpackager_UpdateProgress; } if (failed) { return(doc); } #endregion // Case and Lab Data #region Contact Data if (includeContacts) { OverallSyncStatus = "Packaging contact records..."; //packager = new ContactTracing.ExportView.XmlSqlDataPackager(ContactForm, "sync") //new Epi.ImportExport.ProjectPackagers.XmlSqlDataPackager(ContactForm, "sync"); packager = new Epi.ImportExport.ProjectPackagers.XmlDataPackager(ContactForm, "sync") { RecordProcessingScope = recordProcessingScope }; packager.StatusChanged += unpackager_StatusChanged; packager.UpdateProgress += unpackager_UpdateProgress; packager.RecordProcessingScope = recordProcessingScope; filters = new Epi.ImportExport.Filters.RowFilters(database, Epi.ImportExport.Filters.ConditionJoinTypes.And); daysAgoFilter = new Epi.ImportExport.DateRowFilterCondition("LastSaveTime >= @LastSaveTime", "LastSaveTime", "@LastSaveTime", dateValue); filters.Add(daysAgoFilter); packager.Filters = new Dictionary <string, Epi.ImportExport.Filters.RowFilters> { { ContactForm.Name, filters } }; if (deIdentifyData) { if (!IsCountryUS) { packager.FieldsToNull.Add(ContactForm.Name, new List <string> { "ContactSurname", "ContactOtherNames", "ContactHeadHouse", "ContactPhone", "LC1" }); } else { packager.FieldsToNull.Add(ContactForm.Name, new List <string> { "ContactSurname", "ContactOtherNames", "ContactHeadHouse", "ContactPhone", "LC1", "ContactDOB", "ContactAddress", "ContactEmail" }); } } try { XmlDocument contactDoc = packager.PackageForm(); RecordsExported = RecordsExported + ", " + packager.ExportInfo.TotalRecordsPackaged.ToString() + " contacts"; XmlNodeList xnList = contactDoc.SelectNodes("/DataPackage/Form"); if (IsCountryUS) { foreach (XmlNode node in contactDoc.GetElementsByTagName("FieldInfo")) { if (node.Attributes[0].Value == "AdminOverride") { node.ParentNode.RemoveChild(node); break; } } } if (xnList.Count == 1) { XmlNode nodeToCopy = doc.ImportNode(contactDoc.SelectSingleNode("/DataPackage/Form"), true); // note: target XmlNode parentNode = doc.SelectSingleNode("/DataPackage"); parentNode.AppendChild(nodeToCopy); //doc.Save(@"C:\Temp\ContactTest.xml"); } } catch (Exception ex) { //if (SyncProblemsDetected != null) //{ // SyncProblemsDetected(ex, new EventArgs()); //} // TODO: Re-work this } finally { packager.StatusChanged -= unpackager_StatusChanged; packager.UpdateProgress -= unpackager_UpdateProgress; } } TaskbarProgressValue = TaskbarProgressValue + _increment; OverallSyncStatus = "Finished packaging contact records"; #endregion // Contact Data #region Link Data if (includeCaseExposures || includeContacts) { OverallSyncStatus = "Packaging relationship records..."; #region metaLinks table XmlElement links = doc.CreateElement("Links"); Query selectQuery = database.CreateQuery("SELECT * FROM [metaLinks] ORDER BY [LastContactDate] DESC"); DataTable linksTable = database.Select(selectQuery); foreach (DataRow row in linksTable.Rows) { XmlElement link = doc.CreateElement("Link"); var toViewId = (int)row["ToViewId"]; var fromViewId = (int)row["FromViewId"]; if (includeCaseExposures && toViewId == CaseFormId && fromViewId == CaseFormId) { // we have a case-to-case link, add it foreach (DataColumn dc in linksTable.Columns) { XmlElement element = doc.CreateElement(dc.ColumnName); if (row[dc] != DBNull.Value) { if (row[dc] is DateTime || dc.ColumnName.Equals("LastContactDate", StringComparison.OrdinalIgnoreCase)) { var dt = (DateTime)row[dc]; element.InnerText = dt.Ticks.ToString(); } else { element.InnerText = row[dc].ToString(); } } else { element.InnerText = String.Empty; } //if (!String.IsNullOrEmpty(element.InnerText) || !element.Name.StartsWith("Day", StringComparison.OrdinalIgnoreCase)) //{ link.AppendChild(element); //} } } if (includeContacts && toViewId == ContactFormId && fromViewId == CaseFormId) { // we have a case-to-contact link, add it foreach (DataColumn dc in linksTable.Columns) { XmlElement element = doc.CreateElement(dc.ColumnName); if (row[dc] != DBNull.Value) { if (row[dc] is DateTime || dc.ColumnName.Equals("LastContactDate", StringComparison.OrdinalIgnoreCase)) { var dt = (DateTime)row[dc]; element.InnerText = dt.Ticks.ToString(); } else { element.InnerText = row[dc].ToString(); } } else { element.InnerText = String.Empty; } //if (!String.IsNullOrEmpty(element.InnerText) || !element.Name.StartsWith("Day", StringComparison.OrdinalIgnoreCase)) //{ link.AppendChild(element); //} } } links.AppendChild(link); } doc.ChildNodes[0].AppendChild(links); #endregion // metaLinks table TaskbarProgressValue = TaskbarProgressValue + _increment; RecordsExported = RecordsExported + ", " + linksTable.Rows.Count.ToString() + " relationships"; if (includeContacts) { if (database.TableExists("metaHistory")) { OverallSyncStatus = "Packaging daily follow-up records..."; #region metaHistory table XmlElement followUps = doc.CreateElement("ContactFollowUps"); selectQuery = database.CreateQuery("SELECT * FROM [metaHistory] ORDER BY [ContactGUID] DESC, [FollowUpDate] DESC"); DataTable followUpsTable = database.Select(selectQuery); foreach (DataRow row in followUpsTable.Rows) { XmlElement followUp = doc.CreateElement("ContactFollowUp"); XmlElement guid = doc.CreateElement("ContactGUID"); guid.InnerText = row["ContactGUID"].ToString(); followUp.AppendChild(guid); CultureInfo format = CultureInfo.InvariantCulture; XmlElement fuDate = doc.CreateElement("FollowUpDate"); fuDate.InnerText = Convert.ToDateTime(row["FollowUpDate"]).ToString(format.DateTimeFormat.ShortDatePattern); followUp.AppendChild(fuDate); XmlElement statusOnDate = doc.CreateElement("StatusOnDate"); statusOnDate.InnerText = row["StatusOnDate"].ToString(); followUp.AppendChild(statusOnDate); XmlElement note = doc.CreateElement("Note"); note.InnerText = row["Note"].ToString(); followUp.AppendChild(note); if (row.Table.Columns.Contains("Temp1")) { XmlElement temp1 = doc.CreateElement("Temp1"); if (row["Temp1"] != DBNull.Value) { temp1.InnerText = Convert.ToDouble(row["Temp1"]).ToString(System.Globalization.CultureInfo.InvariantCulture); } followUp.AppendChild(temp1); XmlElement temp2 = doc.CreateElement("Temp2"); if (row["Temp2"] != DBNull.Value) { temp2.InnerText = Convert.ToDouble(row["Temp2"]).ToString(System.Globalization.CultureInfo.InvariantCulture); } followUp.AppendChild(temp2); } followUps.AppendChild(followUp); } #endregion // metaHistory table doc.ChildNodes[0].AppendChild(followUps); TaskbarProgressValue = TaskbarProgressValue + _increment; RecordsExported = RecordsExported + ", " + followUpsTable.Rows.Count.ToString() + " follow-ups"; } } } #endregion // Link Data return(doc); }
public static List <LogInfo> UserInput(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_UserInput)); CodeInfo_UserInput info = cmd.Info as CodeInfo_UserInput; UserInputType type = info.Type; switch (type) { case UserInputType.DirPath: case UserInputType.FilePath: { Debug.Assert(info.SubInfo.GetType() == typeof(UserInputInfo_DirFile)); UserInputInfo_DirFile subInfo = info.SubInfo as UserInputInfo_DirFile; System.Windows.Shell.TaskbarItemProgressState oldTaskbarItemProgressState = s.MainViewModel.TaskbarProgressState; // Save our progress state s.MainViewModel.TaskbarProgressState = System.Windows.Shell.TaskbarItemProgressState.Paused; string initPath = StringEscaper.Preprocess(s, subInfo.InitPath); string selectedPath = initPath; if (type == UserInputType.FilePath) { string filter = "All Files|*.*"; string initFile = Path.GetFileName(initPath); if (initFile.StartsWith("*.", StringComparison.Ordinal) || initFile.Equals("*", StringComparison.Ordinal)) { // If wildcard exists, apply to filter. string ext = Path.GetExtension(initFile); if (1 < ext.Length && ext.StartsWith(".", StringComparison.Ordinal)) { ext = ext.Substring(1); } filter = $"{ext} Files|{initFile}"; } Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog() { Filter = filter, InitialDirectory = Path.GetDirectoryName(initPath), }; if (dialog.ShowDialog() == true) { selectedPath = dialog.FileName; logs.Add(new LogInfo(LogState.Success, $"File path [{selectedPath}] was chosen by user")); } else { logs.Add(new LogInfo(LogState.Error, "File path was not chosen by user")); return(logs); } } else { VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog() { SelectedPath = initPath, }; bool failure = false; Application.Current.Dispatcher.Invoke(() => { MainWindow w = Application.Current.MainWindow as MainWindow; if (dialog.ShowDialog(w) == true) { selectedPath = dialog.SelectedPath; logs.Add(new LogInfo(LogState.Success, $"Directory path [{selectedPath}] was chosen by user")); } else { logs.Add(new LogInfo(LogState.Error, "Directory path was not chosen by user")); failure = true; } }); if (failure) { return(logs); } } s.MainViewModel.TaskbarProgressState = oldTaskbarItemProgressState; List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, selectedPath); logs.AddRange(varLogs); } break; default: // Error throw new InvalidCodeCommandException($"Wrong UserInputType [{type}]"); } return(logs); }
public static List <LogInfo> Message(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_Message)); CodeInfo_Message info = cmd.Info as CodeInfo_Message; string message = StringEscaper.Preprocess(s, info.Message); MessageBoxImage image; switch (info.Action) { case CodeMessageAction.None: case CodeMessageAction.Information: image = MessageBoxImage.Information; break; case CodeMessageAction.Confirmation: image = MessageBoxImage.Question; break; case CodeMessageAction.Error: image = MessageBoxImage.Error; break; case CodeMessageAction.Warning: image = MessageBoxImage.Warning; break; default: // Internal Logic Error Debug.Assert(false); image = MessageBoxImage.Information; break; } System.Windows.Shell.TaskbarItemProgressState oldTaskbarItemProgressState = s.MainViewModel.TaskbarProgressState; // Save our progress state s.MainViewModel.TaskbarProgressState = System.Windows.Shell.TaskbarItemProgressState.Paused; if (info.Timeout == null) { MessageBox.Show(message, cmd.Addr.Script.Title, MessageBoxButton.OK, image); } else { string timeoutStr = StringEscaper.Preprocess(s, info.Timeout); if (NumberHelper.ParseInt32(timeoutStr, out int timeout) == false) { throw new ExecuteException($"[{timeoutStr}] is not a valid positive integer"); } if (timeout <= 0) { throw new ExecuteException($"Timeout must be a positive integer [{timeoutStr}]"); } Application.Current?.Dispatcher.Invoke(() => { CustomMessageBox.Show(message, cmd.Addr.Script.Title, MessageBoxButton.OK, image, timeout); }); } s.MainViewModel.TaskbarProgressState = oldTaskbarItemProgressState; string[] slices = message.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); string firstLine = message; if (0 < slices.Length) { firstLine = slices[0]; } logs.Add(new LogInfo(LogState.Success, $"MessageBox [{firstLine}]", cmd)); return(logs); }