/// <summary> /// Handles the Click event of the btnDeleteBatch control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void btnDeleteBatch_Click(object sender, RoutedEventArgs e) { if (MessageBox.Show("Are you sure you want to delete this batch and all of its transactions?", "Confirm", MessageBoxButton.OKCancel) == MessageBoxResult.OK) { try { if (this.SelectedFinancialBatch != null) { RockConfig config = RockConfig.Load(); RockRestClient client = new RockRestClient(config.RockBaseUrl); client.Login(config.Username, config.Password); var transactions = grdBatchItems.DataContext as BindingList <FinancialTransaction>; if (transactions != null) { foreach (var transaction in transactions) { client.Delete(string.Format("api/FinancialTransactions/{0}", transaction.Id)); } } client.Delete(string.Format("api/FinancialBatches/{0}", this.SelectedFinancialBatch.Id)); } } catch (Exception ex) { ShowException(ex); } LoadFinancialBatchesGrid(); } }
/// <summary> /// Loads the combo boxes. /// </summary> public void LoadLookups() { RockConfig rockConfig = RockConfig.Load(); RockRestClient client = new RockRestClient(rockConfig.RockBaseUrl); client.Login(rockConfig.Username, rockConfig.Password); List <Campus> campusList = client.GetData <List <Campus> >("api/Campuses"); cbCampus.SelectedValuePath = "Id"; cbCampus.DisplayMemberPath = "Name"; cbCampus.Items.Clear(); cbCampus.Items.Add(new Campus { Id = 0, Name = string.Empty }); foreach (var campus in campusList.OrderBy(a => a.Name)) { cbCampus.Items.Add(campus); } cbCampus.SelectedIndex = 0; var currencyTypeDefinedType = client.GetDataByGuid <DefinedType>("api/DefinedTypes", Rock.Client.SystemGuid.DefinedType.FINANCIAL_CURRENCY_TYPE.AsGuid()); this.CurrencyValueList = client.GetData <List <DefinedValue> >("api/DefinedValues", "DefinedTypeId eq " + currencyTypeDefinedType.Id.ToString()); //// load all the Transaction Source values and fetch the attributes so that we can filter the selectable ones (core.ShowInCheckScanner=true) //// when populating the dropdown on the scanning prompt page. //// don't filter them here because we might be viewing transactions that have an unselectable Transaction Source Type var sourceTypeDefinedType = client.GetDataByGuid <DefinedType>("api/DefinedTypes", Rock.Client.SystemGuid.DefinedType.FINANCIAL_SOURCE_TYPE.AsGuid()); var sourceTypeUri = string.Format("api/DefinedValues?$filter=DefinedTypeId eq {0}&loadAttributes=simple", sourceTypeDefinedType.Id.ToString()); this.SourceTypeValueList = client.GetData <List <DefinedValue> >(sourceTypeUri); }
/// <summary> /// Handles the Click event of the btnDeleteTransaction control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void btnDeleteTransaction_Click(object sender, RoutedEventArgs e) { int transactionId = (int)(sender as Button).CommandParameter; if (MessageBox.Show("Are you sure you want to delete this transaction?", "Confirm", MessageBoxButton.OKCancel) == MessageBoxResult.OK) { try { FinancialTransaction financialTransaction = grdBatchItems.SelectedValue as FinancialTransaction; if (financialTransaction != null) { RockConfig config = RockConfig.Load(); RockRestClient client = new RockRestClient(config.RockBaseUrl); client.Login(config.Username, config.Password); client.Delete(string.Format("api/FinancialTransactions/{0}", transactionId)); UpdateBatchUI(this.SelectedFinancialBatch); } } catch (Exception ex) { ShowException(ex); } } }
/// <summary> /// Determines whether [is duplicate scan] [the specified scanned document]. /// </summary> /// <param name="scannedDoc">The scanned document.</param> /// <returns></returns> public static bool IsDuplicateScan(ScannedDocInfo scannedDoc) { if (!scannedDoc.IsCheck) { return(false); } if (scannedDoc.BadMicr) { return(false); } var uploadClient = EnsureUploadScanRestClient(); if (uploadClient == null) { var rockConfig = RockConfig.Load(); uploadClient = new RockRestClient(rockConfig.RockBaseUrl); uploadClient.Login(rockConfig.Username, rockConfig.Password); } var alreadyScanned = uploadClient.PostDataWithResult <string, bool>("api/FinancialTransactions/AlreadyScanned", scannedDoc.ScannedCheckMicrData); return(alreadyScanned); }
/// <summary> /// Handles the ListChanged event of the bindingList control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="ListChangedEventArgs"/> instance containing the event data.</param> protected void bindingList_ListChanged(object sender, ListChangedEventArgs e) { var transactions = grdBatchItems.DataContext as BindingList <FinancialTransaction>; if (transactions != null) { RockConfig rockConfig = RockConfig.Load(); var client = new RockRestClient(rockConfig.RockBaseUrl); client.Login(rockConfig.Username, rockConfig.Password); foreach (var transaction in transactions.Where(a => a.FinancialPaymentDetail == null)) { if (transaction.FinancialPaymentDetailId.HasValue) { transaction.FinancialPaymentDetail = transaction.FinancialPaymentDetail ?? client.GetData <FinancialPaymentDetail>(string.Format("api/FinancialPaymentDetails/{0}", transaction.FinancialPaymentDetailId ?? 0)); if (transaction.FinancialPaymentDetail != null) { transaction.FinancialPaymentDetail.CurrencyTypeValue = this.CurrencyValueList.FirstOrDefault(a => a.Id == transaction.FinancialPaymentDetail.CurrencyTypeValueId); } } } } DisplayTransactionCount(); }
/// <summary> /// Initializes a new instance of the <see cref="SelectPledgeAccountsPage"/> class. /// </summary> public SelectPledgeAccountsPage() { InitializeComponent(); RockConfig rockConfig = RockConfig.Load(); _rockRestClient = new RockRestClient(rockConfig.RockBaseUrl); _rockRestClient.Login(rockConfig.Username, rockConfig.Password); _financialAccountList = _rockRestClient.GetData <List <Rock.Client.FinancialAccount> >("api/FinancialAccounts"); cbIncludeChildAccounts.IsChecked = ReportOptions.Current.PledgesIncludeChildAccounts; cbIncludeNonCashGifts.IsChecked = ReportOptions.Current.PledgesIncludeNonCashGifts; if (ReportOptions.Current.PledgesAccountIds == null) { // default to No Accounts for Pledges ReportOptions.Current.PledgesAccountIds = new List <int>(); } foreach (var account in _financialAccountList.OrderBy(a => a.Order).ThenBy(a => a.PublicName)) { lstPledgeAccounts.Items.Add(new CheckBox { Tag = account.Id, Content = account.PublicName, IsChecked = ReportOptions.Current.PledgesAccountIds.Contains(account.Id) }); } // default to the currently configured CashAccountsId (if configured), or default to all _selectedAccountIds = ReportOptions.Current.PledgesAccountIds ?? _financialAccountList.Select(a => a.Id).ToList(); cbShowInactive.IsChecked = rockConfig.ShowInactiveAccounts; ApplyFilter(); }
/// <summary> /// Initializes a new instance of the <see cref="SelectPersonsPage"/> class. /// </summary> public SelectPersonsPage() { InitializeComponent(); RockConfig rockConfig = RockConfig.Load(); _rockRestClient = new RockRestClient(rockConfig.RockBaseUrl); _rockRestClient.Login(rockConfig.Username, rockConfig.Password); }
/// <summary> /// Initializes a new instance of the <see cref="SelectPersonsPage"/> class. /// </summary> public SelectPersonsPage() { InitializeComponent(); RockConfig rockConfig = RockConfig.Load(); _rockRestClient = new RockRestClient( rockConfig.RockBaseUrl ); _rockRestClient.Login( rockConfig.Username, rockConfig.Password ); }
/// <summary> /// Initializes a new instance of the <see cref="SelectPersonsPage"/> class. /// </summary> public SelectPersonsPage() { InitializeComponent(); RockConfig rockConfig = RockConfig.Load(); _rockRestClient = new RockRestClient(rockConfig.RockBaseUrl); _rockRestClient.Login(rockConfig.Username, rockConfig.Password); var dataViews = _rockRestClient.GetData <List <Rock.Client.DataView> >("api/DataViews", "EntityType/Name eq 'Rock.Model.Person'").OrderBy(a => a.Name); ddlDataView.DisplayMemberPath = "Name"; ddlDataView.ItemsSource = dataViews; }
/// <summary> /// Initializes a new instance of the <see cref="SelectPersonsPage"/> class. /// </summary> public SelectPersonsPage() { InitializeComponent(); RockConfig rockConfig = RockConfig.Load(); _rockRestClient = new RockRestClient( rockConfig.RockBaseUrl ); _rockRestClient.Login( rockConfig.Username, rockConfig.Password ); var dataViews = _rockRestClient.GetData<List<Rock.Client.DataView>>( "api/DataViews", "EntityType/Name eq 'Rock.Model.Person'" ).OrderBy( a => a.Name ); ddlDataView.DisplayMemberPath = "Name"; ddlDataView.ItemsSource = dataViews; }
/// <summary> /// Silently tries to log the exception to the server's exception log service /// </summary> /// <param name="ex">The ex.</param> public static void LogException(Exception ex) { try { RockConfig config = RockConfig.Load(); RockRestClient client = new RockRestClient(config.RockBaseUrl); client.Login(config.Username, config.Password); client.PostData <Exception>("api/ExceptionLogs/LogException", ex); } catch { // intentionally ignore if we can't log the exception to the server } }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void btnSave_Click(object sender, RoutedEventArgs e) { RockConfig rockConfig = RockConfig.Load(); try { txtRockUrl.Text = txtRockUrl.Text.Trim(); Uri rockUrl = new Uri(txtRockUrl.Text); var validSchemes = new string[] { Uri.UriSchemeHttp, Uri.UriSchemeHttps }; if (!validSchemes.Contains(rockUrl.Scheme)) { txtRockUrl.Text = "http://" + rockUrl.AbsoluteUri; } RockRestClient client = new RockRestClient(txtRockUrl.Text); client.Login(rockConfig.Username, rockConfig.Password); } catch (WebException wex) { HttpWebResponse response = wex.Response as HttpWebResponse; if (response != null) { if (response.StatusCode == HttpStatusCode.Unauthorized) { // valid URL but invalid login, so navigate back to the LoginPage rockConfig.RockBaseUrl = txtRockUrl.Text; rockConfig.Save(); LoginPage loginPage = new LoginPage(true); this.NavigationService.Navigate(loginPage); return; } } lblAlert.Content = wex.Message; lblAlert.Visibility = Visibility.Visible; return; } catch (Exception ex) { lblAlert.Content = ex.Message; lblAlert.Visibility = Visibility.Visible; return; } rockConfig.RockBaseUrl = txtRockUrl.Text; rockConfig.LogoFile = txtLogoFile.Text; rockConfig.Save(); this.NavigationService.GoBack(); }
/// <summary> /// Silently tries to log the exception to the server's exception log service /// </summary> /// <param name="ex">The ex.</param> public static void LogException( Exception ex) { try { RockConfig config = RockConfig.Load(); RockRestClient client = new RockRestClient( config.RockBaseUrl ); client.Login( config.Username, config.Password ); client.PostData<Exception>( "api/ExceptionLogs/LogException", ex ); } catch { // intentionally ignore if we can't log the exception to the server } }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void btnSave_Click( object sender, RoutedEventArgs e ) { RockConfig rockConfig = RockConfig.Load(); try { txtRockUrl.Text = txtRockUrl.Text.Trim(); Uri rockUrl = new Uri( txtRockUrl.Text ); var validSchemes = new string[] { Uri.UriSchemeHttp, Uri.UriSchemeHttps }; if ( !validSchemes.Contains( rockUrl.Scheme ) ) { txtRockUrl.Text = "http://" + rockUrl.AbsoluteUri; } RockRestClient client = new RockRestClient( txtRockUrl.Text ); client.Login( rockConfig.Username, rockConfig.Password ); } catch ( WebException wex ) { HttpWebResponse response = wex.Response as HttpWebResponse; if ( response != null ) { if ( response.StatusCode == HttpStatusCode.Unauthorized ) { // valid URL but invalid login, so navigate back to the LoginPage rockConfig.RockBaseUrl = txtRockUrl.Text; rockConfig.Save(); LoginPage loginPage = new LoginPage( true ); this.NavigationService.Navigate( loginPage ); return; } } lblAlert.Content = wex.Message; lblAlert.Visibility = Visibility.Visible; return; } catch ( Exception ex ) { lblAlert.Content = ex.Message; lblAlert.Visibility = Visibility.Visible; return; } rockConfig.RockBaseUrl = txtRockUrl.Text; rockConfig.LogoFile = txtLogoFile.Text; rockConfig.Save(); this.NavigationService.GoBack(); }
/// <summary> /// Initializes a new instance of the <see cref="SelectAccountsPage"/> class. /// </summary> public SelectAccountsPage() { InitializeComponent(); RockConfig rockConfig = RockConfig.Load(); _rockRestClient = new RockRestClient( rockConfig.RockBaseUrl ); _rockRestClient.Login( rockConfig.Username, rockConfig.Password ); var accounts = _rockRestClient.GetData<List<Rock.Model.FinancialAccount>>( "api/FinancialAccounts", "IsActive eq true and IsTaxDeductible eq true" ); lstAccounts.ItemsSource = accounts.Select( a => new NameIdIsChecked { Id = a.Id, Name = a.Name, IsChecked = true } ); lblWarning.Visibility = Visibility.Hidden; }
/// <summary> /// Initializes a new instance of the <see cref="SelectAccountsPage"/> class. /// </summary> public SelectAccountsPage() { InitializeComponent(); RockConfig rockConfig = RockConfig.Load(); _rockRestClient = new RockRestClient( rockConfig.RockBaseUrl ); _rockRestClient.Login( rockConfig.Username, rockConfig.Password ); var accounts = _rockRestClient.GetData<List<Rock.Client.FinancialAccount>>( "api/FinancialAccounts" ); lstAccounts.ItemsSource = accounts.OrderBy( a => a.Order ).ThenBy( a => a.Name ).Select( a => new NameIdIsChecked { Id = a.Id, Name = a.Name, IsChecked = true } ); lblWarning.Visibility = Visibility.Hidden; }
/// <summary> /// Initializes the RestClient for Uploads and loads any data that is needed for the scan session (if it isn't already initialized) /// </summary> /// <returns></returns> public static RockRestClient EnsureUploadScanRestClient() { if (UploadScannedItemClient == null) { RockConfig rockConfig = RockConfig.Load(); UploadScannedItemClient = new RockRestClient(rockConfig.RockBaseUrl); UploadScannedItemClient.Login(rockConfig.Username, rockConfig.Password); } if (binaryFileTypeContribution == null || transactionTypeValueContribution == null) { binaryFileTypeContribution = UploadScannedItemClient.GetDataByGuid <BinaryFileType>("api/BinaryFileTypes", new Guid(Rock.Client.SystemGuid.BinaryFiletype.CONTRIBUTION_IMAGE)); transactionTypeValueContribution = UploadScannedItemClient.GetDataByGuid <DefinedValue>("api/DefinedValues", new Guid(Rock.Client.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION)); } return(UploadScannedItemClient); }
/// <summary> /// Handles the RunWorkerCompleted event of the bw control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RunWorkerCompletedEventArgs"/> instance containing the event data.</param> protected void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Error != null) { RockConfig rockConfig = RockConfig.Load(); _rockRestClient = new RockRestClient(rockConfig.RockBaseUrl); _rockRestClient.Login(rockConfig.Username, rockConfig.Password); throw e.Error; } if (!e.Cancelled) { grdPersons.DataContext = e.Result as List <object>; } }
/// <summary> /// Initializes a new instance of the <see cref="SelectAccountsPage"/> class. /// </summary> public SelectAccountsPage() { InitializeComponent(); RockConfig rockConfig = RockConfig.Load(); _rockRestClient = new RockRestClient(rockConfig.RockBaseUrl); _rockRestClient.Login(rockConfig.Username, rockConfig.Password); var accounts = _rockRestClient.GetData <List <Rock.Client.FinancialAccount> >("api/FinancialAccounts"); lstAccounts.ItemsSource = accounts.OrderBy(a => a.Order).ThenBy(a => a.Name).Select(a => new NameIdIsChecked { Id = a.Id, Name = a.PublicName, IsChecked = true }); lblWarning.Visibility = Visibility.Hidden; }
/// <summary> /// Initializes a new instance of the <see cref="SelectAdvancedFeaturesPage"/> class. /// </summary> public SelectAdvancedFeaturesPage() { InitializeComponent(); cbHideRefundedTransactions.IsChecked = ReportOptions.Current.HideRefundedTransactions; cbHideCorrectedTransactions.IsChecked = ReportOptions.Current.HideCorrectedTransactions; var orderByItems = Enum.GetValues(typeof(Rock.StatementGenerator.OrderBy)).OfType <Rock.StatementGenerator.OrderBy>().Select(a => a.ConvertToString(true)).ToList(); ddlOrderBy.ItemsSource = orderByItems; ddlOrderBy.SelectedValue = ReportOptions.Current.OrderBy.ConvertToString(true); RockConfig rockConfig = RockConfig.Load(); _rockRestClient = new RockRestClient(rockConfig.RockBaseUrl); _rockRestClient.Login(rockConfig.Username, rockConfig.Password); var transactionTypeDefinedType = _rockRestClient.GetDataByGuid <Rock.Client.DefinedType>("api/DefinedTypes", Rock.Client.SystemGuid.DefinedType.FINANCIAL_TRANSACTION_TYPE.AsGuid()); _transactionTypes = _rockRestClient.GetData <List <Rock.Client.DefinedValue> >($"api/DefinedValues?$filter=DefinedTypeId eq {transactionTypeDefinedType.Id}"); lstTransactionTypes.Items.Clear(); var defaultTransactionTypeGuids = new Guid[] { Rock.Client.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION.AsGuid() }; foreach (var transactionType in _transactionTypes) { var transactionTypeCheckbox = new CheckBox { Tag = transactionType.Id, Content = transactionType.Value }; if (ReportOptions.Current.TransactionTypeIds != null) { transactionTypeCheckbox.IsChecked = ReportOptions.Current.TransactionTypeIds.Contains(transactionType.Id); } else { transactionTypeCheckbox.IsChecked = defaultTransactionTypeGuids.Contains(transactionType.Guid); } lstTransactionTypes.Items.Add(transactionTypeCheckbox); } lblTransactionTypesWarning.Visibility = Visibility.Hidden; }
/// <summary> /// Handles the RunWorkerCompleted event of the bw control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RunWorkerCompletedEventArgs"/> instance containing the event data.</param> protected void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Error != null) { RockConfig rockConfig = RockConfig.Load(); _rockRestClient = new RockRestClient(rockConfig.RockBaseUrl); _rockRestClient.Login(rockConfig.Username, rockConfig.Password); throw e.Error; } if (!e.Cancelled) { grdPersons.DataContext = e.Result as List <object>; } activeSearchBackgroundWorkers = new ConcurrentBag <BackgroundWorker>(activeSearchBackgroundWorkers.Where(a => a != sender as BackgroundWorker)); }
/// <summary> /// Updates the batch UI. /// </summary> /// <param name="selectedBatch">The selected batch.</param> private void UpdateBatchUI(FinancialBatch selectedBatch) { if (selectedBatch == null) { HideBatch(); return; } else { ShowBatch(false); } RockConfig rockConfig = RockConfig.Load(); RockRestClient client = new RockRestClient(rockConfig.RockBaseUrl); client.Login(rockConfig.Username, rockConfig.Password); SelectedFinancialBatchId = selectedBatch.Id; lblBatchNameReadOnly.Content = selectedBatch.Name; lblBatchCampusReadOnly.Content = selectedBatch.CampusId.HasValue ? client.GetData <Campus>(string.Format("api/Campus/{0}", selectedBatch.CampusId)).Name : None.Text; lblBatchDateReadOnly.Content = selectedBatch.BatchStartDateTime.Value.ToString("d"); lblBatchCreatedByReadOnly.Content = client.GetData <Person>(string.Format("api/People/{0}", selectedBatch.CreatedByPersonId)).FullName; lblBatchControlAmountReadOnly.Content = selectedBatch.ControlAmount.ToString("F"); txtBatchName.Text = selectedBatch.Name; if (selectedBatch.CampusId.HasValue) { cbCampus.SelectedValue = selectedBatch.CampusId; } else { cbCampus.SelectedValue = 0; } dpBatchDate.SelectedDate = selectedBatch.BatchStartDateTime; lblCreatedBy.Content = lblBatchCreatedByReadOnly.Content as string; txtControlAmount.Text = selectedBatch.ControlAmount.ToString("F"); List <FinancialTransaction> transactions = client.GetData <List <FinancialTransaction> >("api/FinancialTransactions/", string.Format("BatchId eq {0}", selectedBatch.Id)); grdBatchItems.DataContext = transactions.OrderByDescending(a => a.TransactionDateTime); }
/// <summary> /// Handles the Loaded event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void Page_Loaded(object sender, RoutedEventArgs e) { var images = FinancialTransactionImages.OrderBy(a => a.Order).ToList(); RockConfig config = RockConfig.Load(); RockRestClient client = new RockRestClient(config.RockBaseUrl); client.Login(config.Username, config.Password); if (images.Count > 0) { var imageUrl = string.Format("{0}GetImage.ashx?Id={1}", config.RockBaseUrl.EnsureTrailingForwardslash(), images[0].BinaryFileId); var imageBytes = client.DownloadData(imageUrl); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = new MemoryStream(imageBytes); bitmapImage.EndInit(); imgFront.Source = bitmapImage; } else { imgFront.Source = null; } if (images.Count > 1) { var imageUrl = string.Format("{0}GetImage.ashx?Id={1}", config.RockBaseUrl.EnsureTrailingForwardslash(), images[1].BinaryFileId); var imageBytes = client.DownloadData(imageUrl); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = new MemoryStream(imageBytes); bitmapImage.EndInit(); imgBack.Source = bitmapImage; } else { imgBack.Source = null; } }
/// <summary> /// Loads the financial batches grid. /// </summary> public void LoadFinancialBatchesGrid() { RockConfig config = RockConfig.Load(); RockRestClient client = new RockRestClient(config.RockBaseUrl); client.Login(config.Username, config.Password); List <FinancialBatch> pendingBatches = client.GetDataByEnum <List <FinancialBatch> >("api/FinancialBatches", "Status", BatchStatus.Pending); // Order by Batch Id starting with most recent grdBatches.DataContext = pendingBatches.OrderByDescending(a => a.Id); if (pendingBatches.Count > 0) { if (SelectedFinancialBatch != null) { // try to set the selected batch in the grid to our current batch (if it still exists in the database) grdBatches.SelectedValue = pendingBatches.FirstOrDefault(a => a.Id.Equals(SelectedFinancialBatch.Id)); } // if there still isn't a selected batch, set it to the first one if (grdBatches.SelectedValue == null) { grdBatches.SelectedIndex = 0; } } else { SelectedFinancialBatch = null; } bool startWithNewBatch = !pendingBatches.Any(); if (startWithNewBatch) { // don't let them start without having at least one batch, so just show the list with the Add button HideBatch(); } else { gBatchDetailList.Visibility = Visibility.Visible; } }
/// <summary> /// Loads the combo boxes. /// </summary> private void LoadComboBoxes() { RockConfig rockConfig = RockConfig.Load(); RockRestClient client = new RockRestClient(rockConfig.RockBaseUrl); client.Login(rockConfig.Username, rockConfig.Password); List <Campus> campusList = client.GetData <List <Campus> >("api/Campus"); cbCampus.SelectedValuePath = "Id"; cbCampus.DisplayMemberPath = "Name"; cbCampus.Items.Clear(); cbCampus.Items.Add(new Campus { Id = None.Id, Name = None.Text }); foreach (var campus in campusList.OrderBy(a => a.Name)) { cbCampus.Items.Add(campus); } cbCampus.SelectedIndex = 0; }
/// <summary> /// Handles the Loaded event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void Page_Loaded( object sender, RoutedEventArgs e ) { var images = FinancialTransactionImages.OrderBy( a => a.Order ).ToList(); RockConfig config = RockConfig.Load(); RockRestClient client = new RockRestClient( config.RockBaseUrl ); client.Login( config.Username, config.Password ); if ( images.Count > 0 ) { var imageUrl = string.Format( "{0}GetImage.ashx?Id={1}", config.RockBaseUrl.EnsureTrailingForwardslash(), images[0].BinaryFileId ); var imageBytes = client.DownloadData( imageUrl ); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = new MemoryStream( imageBytes ); bitmapImage.EndInit(); imgFront.Source = bitmapImage; } else { imgFront.Source = null; } if ( images.Count > 1 ) { var imageUrl = string.Format( "{0}GetImage.ashx?Id={1}", config.RockBaseUrl.EnsureTrailingForwardslash(), images[1].BinaryFileId ); var imageBytes = client.DownloadData( imageUrl ); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = new MemoryStream( imageBytes ); bitmapImage.EndInit(); imgBack.Source = bitmapImage; } else { imgBack.Source = null; } }
/// <summary> /// Shows the transaction grid item detail. /// </summary> private void ShowTransactionGridItemDetail() { try { FinancialTransaction financialTransaction = grdBatchItems.SelectedValue as FinancialTransaction; if (financialTransaction != null) { RockConfig config = RockConfig.Load(); RockRestClient client = new RockRestClient(config.RockBaseUrl); client.Login(config.Username, config.Password); financialTransaction.Images = client.GetData <List <FinancialTransactionImage> >("api/FinancialTransactionImages", string.Format("TransactionId eq {0}", financialTransaction.Id)); BatchItemDetailPage.batchPage = this; BatchItemDetailPage.FinancialTransaction = financialTransaction; this.NavigationService.Navigate(BatchItemDetailPage); } } catch (Exception ex) { ShowException(ex); } }
/// <summary> /// Loads the financial batches grid. /// </summary> private void LoadFinancialBatchesGrid() { RockConfig config = RockConfig.Load(); RockRestClient client = new RockRestClient(config.RockBaseUrl); client.Login(config.Username, config.Password); List <FinancialBatch> pendingBatches = client.GetDataByEnum <List <FinancialBatch> >("api/FinancialBatches", "Status", BatchStatus.Pending); grdBatches.DataContext = pendingBatches.OrderByDescending(a => a.BatchStartDateTime).ThenBy(a => a.Name); if (pendingBatches.Count > 0) { if (SelectedFinancialBatchId > 0) { grdBatches.SelectedValue = pendingBatches.FirstOrDefault(a => a.Id.Equals(SelectedFinancialBatchId)); } else { grdBatches.SelectedIndex = 0; } } UpdateBatchUI(grdBatches.SelectedValue as FinancialBatch); }
/// <summary> /// Handles the RowEdit event of the grdBatchItems control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="MouseButtonEventArgs"/> instance containing the event data.</param> protected void grdBatchItems_RowEdit(object sender, MouseButtonEventArgs e) { try { FinancialTransaction financialTransaction = grdBatchItems.SelectedValue as FinancialTransaction; if (financialTransaction != null) { RockConfig config = RockConfig.Load(); RockRestClient client = new RockRestClient(config.RockBaseUrl); client.Login(config.Username, config.Password); financialTransaction.Images = client.GetData <List <FinancialTransactionImage> >("api/FinancialTransactionImages", string.Format("TransactionId eq {0}", financialTransaction.Id)); foreach (var image in financialTransaction.Images) { image.BinaryFile = client.GetData <BinaryFile>(string.Format("api/BinaryFiles/{0}", image.BinaryFileId)); try { image.BinaryFile.Data = client.GetData <BinaryFileData>(string.Format("api/BinaryFileDatas/{0}", image.BinaryFileId)); } catch (Exception ex) { throw new Exception("Error getting check image data: " + ex.Message); } } BatchItemDetailPage.TransactionImageTypeValueFront = client.GetDataByGuid <DefinedValue>("api/DefinedValues", new Guid(Rock.SystemGuid.DefinedValue.TRANSACTION_IMAGE_TYPE_CHECK_FRONT)); BatchItemDetailPage.TransactionImageTypeValueBack = client.GetDataByGuid <DefinedValue>("api/DefinedValues", new Guid(Rock.SystemGuid.DefinedValue.TRANSACTION_IMAGE_TYPE_CHECK_BACK)); BatchItemDetailPage.FinancialTransaction = financialTransaction; this.NavigationService.Navigate(BatchItemDetailPage); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation); } }
/// <summary> /// Shows the transaction grid item detail. /// </summary> private void ShowTransactionGridItemDetail() { try { FinancialTransaction financialTransaction = grdBatchItems.SelectedValue as FinancialTransaction; if ( financialTransaction != null ) { RockConfig config = RockConfig.Load(); RockRestClient client = new RockRestClient( config.RockBaseUrl ); client.Login( config.Username, config.Password ); financialTransaction.Images = client.GetData<List<FinancialTransactionImage>>( "api/FinancialTransactionImages", string.Format( "TransactionId eq {0}", financialTransaction.Id ) ); BatchItemDetailPage.batchPage = this; BatchItemDetailPage.FinancialTransaction = financialTransaction; this.NavigationService.Navigate( BatchItemDetailPage ); } } catch ( Exception ex ) { ShowException( ex ); } }
/// <summary> /// Updates the batch UI. /// </summary> /// <param name="selectedBatch">The selected batch.</param> private void UpdateBatchUI(FinancialBatch selectedBatch) { if (selectedBatch == null) { grdBatchItems.DataContext = null; DisplayTransactionCount(); HideBatch(); return; } else { ShowBatch(false); } RockConfig rockConfig = RockConfig.Load(); RockRestClient client = new RockRestClient(rockConfig.RockBaseUrl); client.Login(rockConfig.Username, rockConfig.Password); SelectedFinancialBatch = selectedBatch; lblBatchNameReadOnly.Content = selectedBatch.Name; lblBatchIdReadOnly.Content = string.Format("Batch Id: {0}", selectedBatch.Id); lblBatchCampusReadOnly.Content = selectedBatch.CampusId.HasValue ? client.GetData <Campus>(string.Format("api/Campuses/{0}", selectedBatch.CampusId ?? 0)).Name : string.Empty; lblBatchDateReadOnly.Content = selectedBatch.BatchStartDateTime.Value.ToString("d"); var createdByPerson = client.GetData <Person>(string.Format("api/People/GetByPersonAliasId/{0}", selectedBatch.CreatedByPersonAliasId ?? 0)); if (createdByPerson != null) { lblBatchCreatedByReadOnly.Content = string.Format("{0} {1}", createdByPerson.NickName, createdByPerson.LastName); } else { lblBatchCreatedByReadOnly.Content = string.Empty; } lblBatchControlAmountReadOnly.Content = selectedBatch.ControlAmount.ToString("F"); txtBatchName.Text = selectedBatch.Name; if (selectedBatch.CampusId.HasValue) { cbCampus.SelectedValue = selectedBatch.CampusId; } else { cbCampus.SelectedValue = 0; } dpBatchDate.SelectedDate = selectedBatch.BatchStartDateTime; lblCreatedBy.Content = lblBatchCreatedByReadOnly.Content as string; txtControlAmount.Text = selectedBatch.ControlAmount.ToString("F"); txtNote.Text = selectedBatch.Note; // start a background thread to download transactions since this could take a little while and we want a Wait cursor BackgroundWorker bw = new BackgroundWorker(); Rock.Wpf.WpfHelper.FadeOut(lblCount, 0); lblCount.Content = "Loading..."; Rock.Wpf.WpfHelper.FadeIn(lblCount, 300); List <FinancialTransaction> transactions = null; grdBatchItems.DataContext = null; bw.DoWork += delegate(object s, DoWorkEventArgs ee) { ee.Result = null; transactions = client.GetData <List <FinancialTransaction> >("api/FinancialTransactions/", string.Format("BatchId eq {0}", selectedBatch.Id)); }; bw.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs ee) { this.Cursor = null; foreach (var transaction in transactions) { if (transaction.FinancialPaymentDetailId.HasValue) { transaction.FinancialPaymentDetail = transaction.FinancialPaymentDetail ?? client.GetData <FinancialPaymentDetail>(string.Format("api/FinancialPaymentDetails/{0}", transaction.FinancialPaymentDetailId ?? 0)); if (transaction.FinancialPaymentDetail != null) { transaction.FinancialPaymentDetail.CurrencyTypeValue = this.CurrencyValueList.FirstOrDefault(a => a.Id == transaction.FinancialPaymentDetail.CurrencyTypeValueId); } } } // sort starting with most recent first var bindingList = new BindingList <FinancialTransaction>(transactions.OrderByDescending(a => a.CreatedDateTime).ToList()); bindingList.RaiseListChangedEvents = true; bindingList.ListChanged += bindingList_ListChanged; grdBatchItems.DataContext = bindingList; DisplayTransactionCount(); }; this.Cursor = Cursors.Wait; bw.RunWorkerAsync(); }
/// <summary> /// Handles the Click event of the btnLogin control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void btnLogin_Click(object sender, RoutedEventArgs e) { lblLoginWarning.Visibility = Visibility.Hidden; txtUsername.Text = txtUsername.Text.Trim(); txtRockUrl.Text = txtRockUrl.Text.Trim(); RockRestClient rockRestClient = new RockRestClient(txtRockUrl.Text); string userName = txtUsername.Text; string password = txtPassword.Password; // start a background thread to Login since this could take a little while and we want a Wait cursor BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += delegate(object s, DoWorkEventArgs ee) { ee.Result = null; rockRestClient.Login(userName, password); }; // when the Background Worker is done with the Login, run this bw.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs ee) { this.Cursor = null; btnLogin.IsEnabled = true; try { if (ee.Error != null) { throw ee.Error; } Person person = rockRestClient.GetData <Person>(string.Format("api/People/GetByUserName/{0}", userName)); person.Aliases = rockRestClient.GetData <List <PersonAlias> >("api/PersonAlias/", "PersonId eq " + person.Id); RockConfig rockConfig = RockConfig.Load(); rockConfig.RockBaseUrl = txtRockUrl.Text; rockConfig.Username = txtUsername.Text; rockConfig.Password = txtPassword.Password; rockConfig.Save(); BatchPage batchPage = new BatchPage(person); if (this.NavigationService.CanGoBack) { // if we got here from some other Page, go back this.NavigationService.GoBack(); } else { this.NavigationService.Navigate(batchPage); } } catch (WebException wex) { // show WebException on the form, but any others should end up in the ExceptionDialog HttpWebResponse response = wex.Response as HttpWebResponse; if (response != null) { if (response.StatusCode.Equals(HttpStatusCode.Unauthorized)) { lblLoginWarning.Content = "Invalid Login"; lblLoginWarning.Visibility = Visibility.Visible; return; } } string message = wex.Message; if (wex.InnerException != null) { message += "\n" + wex.InnerException.Message; } lblRockUrl.Visibility = Visibility.Visible; txtRockUrl.Visibility = Visibility.Visible; lblLoginWarning.Content = message; lblLoginWarning.Visibility = Visibility.Visible; return; } }; // set the cursor to Wait, disable the login button, and start the login background process this.Cursor = Cursors.Wait; btnLogin.IsEnabled = false; bw.RunWorkerAsync(); }
/// <summary> /// Creates the document. /// </summary> /// <param name="financialTransactionQry">The financial transaction qry.</param> /// <returns></returns> public Document RunReport() { UpdateProgress( "Connecting..." ); // Login and setup options for REST calls RockConfig rockConfig = RockConfig.Load(); _rockRestClient = new RockRestClient( rockConfig.RockBaseUrl ); _rockRestClient.Login( rockConfig.Username, rockConfig.Password ); // shouldn't happen, but just in case the StartDate isn't set, set it to the first day of the current year DateTime firstDayOfYear = new DateTime( DateTime.Now.Year, 1, 1 ); // note: if a specific person is specified, get them even if they don't have an address. _contributionStatementOptionsREST = new Rock.Net.RestParameters.ContributionStatementOptions { StartDate = Options.StartDate ?? firstDayOfYear, EndDate = Options.EndDate, AccountIds = Options.AccountIds, IncludeIndividualsWithNoAddress = Options.PersonId.HasValue || Options.IncludeIndividualsWithNoAddress, PersonId = Options.PersonId, OrderByPostalCode = true }; var organizationAddressAttribute = _rockRestClient.GetData<List<Rock.Client.Attribute>>( "api/attributes", "Key eq 'OrganizationAddress'" ).FirstOrDefault(); if ( organizationAddressAttribute != null ) { var organizationAddressAttributeValue = _rockRestClient.GetData<List<Rock.Client.AttributeValue>>( "api/AttributeValues", string.Format( "AttributeId eq {0}", organizationAddressAttribute.Id ) ).FirstOrDefault(); Guid locationGuid = Guid.Empty; if ( Guid.TryParse( organizationAddressAttributeValue.Value, out locationGuid ) ) { _organizationAddressLocation = _rockRestClient.GetData<List<Rock.Client.Location>>( "api/locations", string.Format( "Guid eq guid'{0}'", locationGuid ) ).FirstOrDefault(); } } // If we don't have a _organizationAddressLocation, just create an empty location _organizationAddressLocation = _organizationAddressLocation ?? new Rock.Client.Location(); // setup report layout and events DocumentLayout report = new DocumentLayout( this.Options.LayoutFile ); //// if there is an imgLogo and the path is "logo.jpg", use the logo specified in rockconfig. //// We have to read the layout as Xml first to figure out what the Path of the imgLogo XmlDocument layoutXmlDoc = new XmlDocument(); layoutXmlDoc.Load( this.Options.LayoutFile ); var imageNodes = layoutXmlDoc.GetElementsByTagName( "image" ); foreach ( var imageNode in imageNodes.OfType<XmlNode>() ) { string imagePath = imageNode.Attributes["path"].Value; string imageId = imageNode.Attributes["id"].Value; if ( imageId.Equals( "imgLogo" ) && imagePath.Equals( RockConfig.DefaultLogoFile, StringComparison.OrdinalIgnoreCase ) ) { Image imgLogo = report.GetReportElementById( "imgLogo" ) as Image; if ( imgLogo != null ) { try { if ( !rockConfig.LogoFile.Equals( RockConfig.DefaultLogoFile, StringComparison.OrdinalIgnoreCase ) ) { imgLogo.ImageData = ceTe.DynamicPDF.Imaging.ImageData.GetImage( rockConfig.LogoFile ); } } catch ( Exception ex ) { throw new Exception( "Error loading Logo Image: " + rockConfig.LogoFile + "\n\n" + ex.Message ); } } } } Query query = report.GetQueryById( "OuterQuery" ); if ( query == null ) { throw new MissingReportElementException( "Report requires a QueryElement named 'OuterQuery'" ); } query.OpeningRecordSet += mainQuery_OpeningRecordSet; Query orgInfoQuery = report.GetQueryById( "OrgInfoQuery" ); if ( orgInfoQuery == null ) { throw new MissingReportElementException( "Report requires a QueryElement named 'OrgInfoQuery'" ); } orgInfoQuery.OpeningRecordSet += orgInfoQuery_OpeningRecordSet; _accountSummaryQuery = report.GetQueryById( "AccountSummaryQuery" ); if ( _accountSummaryQuery == null ) { // not required. Just don't do anything if it isn't there } else { _accountSummaryQuery.OpeningRecordSet += delegate( object s, OpeningRecordSetEventArgs ee ) { // create a recordset for the _accountSummaryQuery which is the GroupBy summary of AccountName, Amount /* The structure of _transactionsDataTable is DateTime TransactionDateTime string CurrencyTypeValueName string Summary (main transaction summary) DataTable Details { int AccountId string AccountName string Summary (detail summary) decimal Amount } */ var detailsData = new DataTable(); detailsData.Columns.Add( "AccountId", typeof( int ) ); detailsData.Columns.Add( "AccountName" ); detailsData.Columns.Add( "Amount", typeof( decimal ) ); foreach ( var details in _transactionsDataTable.AsEnumerable().Select( a => ( a["Details"] as DataTable ) ) ) { foreach ( var row in details.AsEnumerable() ) { detailsData.Rows.Add( row["AccountId"], row["AccountName"], row["Amount"] ); } } var summaryTable = detailsData.AsEnumerable().GroupBy( g => g["AccountId"] ).Select( a => new { AccountName = a.Max( x => x["AccountName"].ToString() ), Amount = a.Sum( x => decimal.Parse( x["Amount"].ToString() ) ) } ).OrderBy( o => o.AccountName ); ee.RecordSet = new EnumerableRecordSet( summaryTable ); }; } UpdateProgress( "Getting Data..." ); // get outer query data from Rock database via REST now vs in mainQuery_OpeningRecordSet to make sure we have data DataSet personGroupAddressDataSet = _rockRestClient.PostDataWithResult<Rock.Net.RestParameters.ContributionStatementOptions, DataSet>( "api/FinancialTransactions/GetContributionPersonGroupAddress", _contributionStatementOptionsREST ); _personGroupAddressDataTable = personGroupAddressDataSet.Tables[0]; RecordCount = _personGroupAddressDataTable.Rows.Count; if ( RecordCount > 0 ) { Document doc = report.Run(); return doc; } else { return null; } }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void btnSave_Click(object sender, RoutedEventArgs e) { _rockConfig.CaptureAmountOnScan = chkCaptureAmountOnScan.IsChecked == true; _rockConfig.RequireControlAmount = chkRequireControlAmount.IsChecked == true; _rockConfig.RequireControlItemCount = chkRequireControlItemCount.IsChecked == true; AddAccountsForAmountsToSave(); if (_rockConfig.CaptureAmountOnScan && _rockConfig.SelectedAccountForAmountsIds.Count() == 0) { MessageBox.Show("Please select at least one account", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning); return; } try { txtRockUrl.Text = txtRockUrl.Text.Trim(); Uri rockUrl = new Uri(txtRockUrl.Text); var validSchemes = new string[] { Uri.UriSchemeHttp, Uri.UriSchemeHttps }; if (!validSchemes.Contains(rockUrl.Scheme)) { txtRockUrl.Text = "http://" + rockUrl.AbsoluteUri; } RockRestClient client = new RockRestClient(txtRockUrl.Text); client.Login(_rockConfig.Username, _rockConfig.Password); BatchPage.LoggedInPerson = client.GetData <Person>(string.Format("api/People/GetByUserName/{0}", _rockConfig.Username)); } catch (WebException wex) { HttpWebResponse response = wex.Response as HttpWebResponse; if (response != null) { if (response.StatusCode == HttpStatusCode.Unauthorized) { // valid URL but invalid login, so navigate back to the LoginPage _rockConfig.RockBaseUrl = txtRockUrl.Text; _rockConfig.Save(); LoginPage loginPage = new LoginPage(true); this.NavigationService.Navigate(loginPage); return; } } lblAlert.Content = wex.Message; lblAlert.Visibility = Visibility.Visible; return; } catch (Exception ex) { App.LogException(ex); lblAlert.Content = ex.Message; lblAlert.Visibility = Visibility.Visible; return; } _rockConfig.RockBaseUrl = txtRockUrl.Text; switch (cboScannerInterfaceType.SelectedItem as string) { case "MagTek COM": _rockConfig.ScannerInterfaceType = RockConfig.InterfaceType.MICRImageRS232; break; case "MagTek Image Safe": _rockConfig.ScannerInterfaceType = RockConfig.InterfaceType.MagTekImageSafe; break; default: _rockConfig.ScannerInterfaceType = RockConfig.InterfaceType.RangerApi; break; } string imageOption = cboImageOption.SelectedValue as string; _rockConfig.Sensitivity = txtSensitivity.Text.Trim().AsInteger().ToString(); _rockConfig.Plurality = txtPlurality.Text.Trim().AsInteger().ToString(); switch (imageOption) { case "Grayscale": _rockConfig.ImageColorType = RangerImageColorTypes.ImageColorTypeGrayscale; break; case "Color": _rockConfig.ImageColorType = RangerImageColorTypes.ImageColorTypeColor; break; default: _rockConfig.ImageColorType = RangerImageColorTypes.ImageColorTypeBitonal; break; } string comPortName = cboMagTekCommPort.SelectedItem as string; if (!string.IsNullOrWhiteSpace(comPortName)) { _rockConfig.MICRImageComPort = short.Parse(comPortName.Replace("COM", string.Empty)); } var campusFilter = cboCampusFilter.SelectedItem as Campus; _rockConfig.CampusIdFilter = campusFilter?.Id; _rockConfig.Save(); BatchPage.LoadLookups(); // shutdown the scanner so that options will be reloaded when the batch page loads if (BatchPage.rangerScanner != null) { BatchPage.rangerScanner.ShutDown(); } BatchPage.UnbindAllEvents(); BatchPage.BindDeviceToPage(); BatchPage.ConnectToScanner(); BatchPage.LoadFinancialBatchesGrid(); BatchPage.UpdateBatchUI(BatchPage.SelectedFinancialBatch); this.NavigationService.Navigate(BatchPage); }
/// <summary> /// Determines whether [is duplicate scan] [the specified scanned document]. /// </summary> /// <param name="scannedDoc">The scanned document.</param> /// <returns></returns> private bool IsDuplicateScan( ScannedDocInfo scannedDoc ) { if ( !scannedDoc.IsCheck ) { return false; } if ( scannedDoc.BadMicr ) { return false; } var uploadClient = EnsureUploadScanRestClient(); if ( uploadClient == null ) { var rockConfig = RockConfig.Load(); uploadClient = new RockRestClient( rockConfig.RockBaseUrl ); uploadClient.Login( rockConfig.Username, rockConfig.Password ); } var alreadyScanned = uploadClient.PostDataWithResult<string, bool>( "api/FinancialTransactions/AlreadyScanned", scannedDoc.ScannedCheckMicrData ); return alreadyScanned; }
/// <summary> /// Updates the batch UI. /// </summary> /// <param name="selectedBatch">The selected batch.</param> private void UpdateBatchUI( FinancialBatch selectedBatch ) { if ( selectedBatch == null ) { HideBatch(); return; } else { ShowBatch( false ); } RockConfig rockConfig = RockConfig.Load(); RockRestClient client = new RockRestClient( rockConfig.RockBaseUrl ); client.Login( rockConfig.Username, rockConfig.Password ); SelectedFinancialBatch = selectedBatch; lblBatchNameReadOnly.Content = selectedBatch.Name; lblBatchCampusReadOnly.Content = selectedBatch.CampusId.HasValue ? client.GetData<Campus>( string.Format( "api/Campus/{0}", selectedBatch.CampusId ) ).Name : None.Text; lblBatchDateReadOnly.Content = selectedBatch.BatchStartDateTime.Value.ToString( "d" ); lblBatchCreatedByReadOnly.Content = client.GetData<Person>( string.Format( "api/People/GetByPersonAliasId/{0}", selectedBatch.CreatedByPersonAliasId ) ).FullName; lblBatchControlAmountReadOnly.Content = selectedBatch.ControlAmount.ToString( "F" ); txtBatchName.Text = selectedBatch.Name; if ( selectedBatch.CampusId.HasValue ) { cbCampus.SelectedValue = selectedBatch.CampusId; } else { cbCampus.SelectedValue = 0; } dpBatchDate.SelectedDate = selectedBatch.BatchStartDateTime; lblCreatedBy.Content = lblBatchCreatedByReadOnly.Content as string; txtControlAmount.Text = selectedBatch.ControlAmount.ToString( "F" ); List<FinancialTransaction> transactions = client.GetData<List<FinancialTransaction>>( "api/FinancialTransactions/", string.Format( "BatchId eq {0}", selectedBatch.Id ) ); foreach ( var transaction in transactions ) { transaction.CurrencyTypeValue = this.CurrencyValueList.FirstOrDefault( a => a.Id == transaction.CurrencyTypeValueId ); } // include CheckNumber for checks that we scanned in this session var scannedCheckList = ScannedDocList.Where( a => a.IsCheck ).ToList(); var gridList = transactions.OrderByDescending( a => a.CreatedDateTime ).Select( a => new { FinancialTransaction = a, CheckNumber = a.CurrencyTypeValue.Guid == Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CHECK.AsGuid() ? scannedCheckList.FirstOrDefault( s => s.TransactionId == a.Id ) != null ? scannedCheckList.FirstOrDefault( s => s.TransactionId == a.Id ).CheckNumber : "****" : "-" } ); grdBatchItems.DataContext = gridList; }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void btnSave_Click( object sender, RoutedEventArgs e ) { RockConfig rockConfig = RockConfig.Load(); try { txtRockUrl.Text = txtRockUrl.Text.Trim(); Uri rockUrl = new Uri( txtRockUrl.Text ); var validSchemes = new string[] { Uri.UriSchemeHttp, Uri.UriSchemeHttps }; if ( !validSchemes.Contains( rockUrl.Scheme ) ) { txtRockUrl.Text = "http://" + rockUrl.AbsoluteUri; } RockRestClient client = new RockRestClient( txtRockUrl.Text ); client.Login( rockConfig.Username, rockConfig.Password ); BatchPage.LoggedInPerson = client.GetData<Person>( string.Format( "api/People/GetByUserName/{0}", rockConfig.Username ) ); } catch ( WebException wex ) { HttpWebResponse response = wex.Response as HttpWebResponse; if ( response != null ) { if ( response.StatusCode == HttpStatusCode.Unauthorized ) { // valid URL but invalid login, so navigate back to the LoginPage rockConfig.RockBaseUrl = txtRockUrl.Text; rockConfig.Save(); LoginPage loginPage = new LoginPage( true ); this.NavigationService.Navigate( loginPage ); return; } } lblAlert.Content = wex.Message; lblAlert.Visibility = Visibility.Visible; return; } catch ( Exception ex ) { App.LogException( ex ); lblAlert.Content = ex.Message; lblAlert.Visibility = Visibility.Visible; return; } rockConfig.RockBaseUrl = txtRockUrl.Text; if ( cboScannerInterfaceType.SelectedItem.Equals( "MagTek" ) ) { rockConfig.ScannerInterfaceType = RockConfig.InterfaceType.MICRImageRS232; } else { rockConfig.ScannerInterfaceType = RockConfig.InterfaceType.RangerApi; } string imageOption = cboImageOption.SelectedValue as string; rockConfig.Sensitivity = txtSensitivity.Text.Trim().AsInteger().ToString(); rockConfig.Plurality = txtPlurality.Text.Trim().AsInteger().ToString(); switch ( imageOption ) { case "Grayscale": rockConfig.ImageColorType = RangerImageColorTypes.ImageColorTypeGrayscale; break; case "Color": rockConfig.ImageColorType = RangerImageColorTypes.ImageColorTypeColor; break; default: rockConfig.ImageColorType = RangerImageColorTypes.ImageColorTypeBitonal; break; } string comPortName = cboMagTekCommPort.SelectedItem as string; if ( !string.IsNullOrWhiteSpace( comPortName ) ) { rockConfig.MICRImageComPort = short.Parse( comPortName.Replace( "COM", string.Empty ) ); } rockConfig.Save(); // shutdown the scanner so that options will be reloaded when the batch page loads if ( BatchPage.rangerScanner != null ) { BatchPage.rangerScanner.ShutDown(); } BatchPage.ConnectToScanner(); this.NavigationService.GoBack(); }
/// <summary> /// Handles the RunWorkerCompleted event of the bw control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RunWorkerCompletedEventArgs"/> instance containing the event data.</param> protected void bw_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e ) { if ( e.Error != null ) { RockConfig rockConfig = RockConfig.Load(); _rockRestClient = new RockRestClient( rockConfig.RockBaseUrl ); _rockRestClient.Login( rockConfig.Username, rockConfig.Password ); throw e.Error; } if ( !e.Cancelled ) { grdPersons.DataContext = e.Result as List<object>; } }
/// <summary> /// Handles the RowEdit event of the grdBatchItems control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="MouseButtonEventArgs"/> instance containing the event data.</param> protected void grdBatchItems_RowEdit( object sender, MouseButtonEventArgs e ) { try { FinancialTransaction financialTransaction = grdBatchItems.SelectedValue as FinancialTransaction; if ( financialTransaction != null ) { RockConfig config = RockConfig.Load(); RockRestClient client = new RockRestClient( config.RockBaseUrl ); client.Login( config.Username, config.Password ); financialTransaction.Images = client.GetData<List<FinancialTransactionImage>>( "api/FinancialTransactionImages", string.Format( "TransactionId eq {0}", financialTransaction.Id ) ); foreach ( var image in financialTransaction.Images ) { image.BinaryFile = client.GetData<BinaryFile>( string.Format( "api/BinaryFiles/{0}", image.BinaryFileId ) ); try { image.BinaryFile.Data = client.GetData<BinaryFileData>( string.Format( "api/BinaryFileDatas/{0}", image.BinaryFileId ) ); if (image.BinaryFile.Data == null || image.BinaryFile.Data.Content == null) { throw new Exception( "Image Content is empty" ); } } catch (Exception ex) { throw new Exception( "Error getting check image data: " + ex.Message ); } } BatchItemDetailPage.TransactionImageTypeValueFront = client.GetDataByGuid<DefinedValue>( "api/DefinedValues", new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_IMAGE_TYPE_CHECK_FRONT ) ); BatchItemDetailPage.TransactionImageTypeValueBack = client.GetDataByGuid<DefinedValue>( "api/DefinedValues", new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_IMAGE_TYPE_CHECK_BACK ) ); BatchItemDetailPage.FinancialTransaction = financialTransaction; this.NavigationService.Navigate( BatchItemDetailPage ); } } catch ( Exception ex ) { MessageBox.Show( ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation ); } }
/// <summary> /// Loads the combo boxes. /// </summary> private void LoadComboBoxes() { RockConfig rockConfig = RockConfig.Load(); RockRestClient client = new RockRestClient( rockConfig.RockBaseUrl ); client.Login( rockConfig.Username, rockConfig.Password ); List<Campus> campusList = client.GetData<List<Campus>>( "api/Campus" ); cbCampus.SelectedValuePath = "Id"; cbCampus.DisplayMemberPath = "Name"; cbCampus.Items.Clear(); cbCampus.Items.Add( new Campus { Id = None.Id, Name = None.Text } ); foreach ( var campus in campusList.OrderBy( a => a.Name ) ) { cbCampus.Items.Add( campus ); } cbCampus.SelectedIndex = 0; var currencyTypeDefinedType = client.GetDataByGuid<DefinedType>( "api/DefinedTypes", Rock.SystemGuid.DefinedType.FINANCIAL_CURRENCY_TYPE.AsGuid() ); this.CurrencyValueList = client.GetData<List<DefinedValue>>( "api/DefinedValues", "DefinedTypeId eq " + currencyTypeDefinedType.Id.ToString() ); var sourceTypeDefinedType = client.GetDataByGuid<DefinedType>( "api/DefinedTypes", Rock.SystemGuid.DefinedType.FINANCIAL_SOURCE_TYPE.AsGuid() ); this.SourceTypeValueList = client.GetData<List<DefinedValue>>( "api/DefinedValues", "DefinedTypeId eq " + sourceTypeDefinedType.Id.ToString() ); }
/// <summary> /// Loads the financial batches grid. /// </summary> private void LoadFinancialBatchesGrid() { RockConfig config = RockConfig.Load(); RockRestClient client = new RockRestClient( config.RockBaseUrl ); client.Login( config.Username, config.Password ); List<FinancialBatch> pendingBatches = client.GetDataByEnum<List<FinancialBatch>>( "api/FinancialBatches", "Status", BatchStatus.Pending ); grdBatches.DataContext = pendingBatches.OrderByDescending( a => a.BatchStartDateTime ).ThenBy( a => a.Name ); if ( pendingBatches.Count > 0 ) { if ( SelectedFinancialBatch != null ) { // try to set the selected batch in the grid to our current batch (if it still exists in the database) grdBatches.SelectedValue = pendingBatches.FirstOrDefault( a => a.Id.Equals( SelectedFinancialBatch.Id ) ); } // if there still isn't a selected batch, set it to the first one if ( grdBatches.SelectedValue == null ) { grdBatches.SelectedIndex = 0; } } bool startWithNewBatch = !pendingBatches.Any(); if ( startWithNewBatch ) { // don't let them start without having at least one batch, so just show the list with the Add button HideBatch(); } else { gBatchDetailList.Visibility = Visibility.Visible; UpdateBatchUI( grdBatches.SelectedValue as FinancialBatch ); } }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void btnSave_Click( object sender, RoutedEventArgs e ) { RockConfig rockConfig = RockConfig.Load(); try { txtRockUrl.Text = txtRockUrl.Text.Trim(); RockRestClient client = new RockRestClient( txtRockUrl.Text ); client.Login( rockConfig.Username, rockConfig.Password ); BatchPage.LoggedInPerson = client.GetData<Person>( string.Format( "api/People/GetByUserName/{0}", rockConfig.Username ) ); } catch ( WebException wex ) { HttpWebResponse response = wex.Response as HttpWebResponse; if ( response != null ) { if ( response.StatusCode == HttpStatusCode.Unauthorized ) { // valid URL but invalid login, so navigate back to the LoginPage rockConfig.RockBaseUrl = txtRockUrl.Text; rockConfig.Save(); LoginPage loginPage = new LoginPage( true ); this.NavigationService.Navigate( loginPage ); return; } } lblAlert.Content = wex.Message; lblAlert.Visibility = Visibility.Visible; return; } catch ( Exception ex ) { lblAlert.Content = ex.Message; lblAlert.Visibility = Visibility.Visible; return; } rockConfig.RockBaseUrl = txtRockUrl.Text; if ( cboScannerInterfaceType.SelectedItem.Equals( "MagTek" ) ) { rockConfig.ScannerInterfaceType = RockConfig.InterfaceType.MICRImageRS232; } else { rockConfig.ScannerInterfaceType = RockConfig.InterfaceType.RangerApi; } string imageOption = cboImageOption.SelectedValue as string; switch ( imageOption ) { case "Grayscale": rockConfig.ImageColorType = ImageColorType.ImageColorTypeGrayscale; break; case "Color": rockConfig.ImageColorType = ImageColorType.ImageColorTypeColor; break; default: rockConfig.ImageColorType = ImageColorType.ImageColorTypeBitonal; break; } string comPortName = cboMagTekCommPort.SelectedItem as string; if ( !string.IsNullOrWhiteSpace( comPortName ) ) { rockConfig.MICRImageComPort = short.Parse( comPortName.Replace( "COM", string.Empty ) ); } rockConfig.Save(); this.NavigationService.GoBack(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void btnSave_Click(object sender, RoutedEventArgs e) { RockConfig rockConfig = RockConfig.Load(); try { txtRockUrl.Text = txtRockUrl.Text.Trim(); RockRestClient client = new RockRestClient(txtRockUrl.Text); client.Login(rockConfig.Username, rockConfig.Password); BatchPage.LoggedInPerson = client.GetData <Person>(string.Format("api/People/GetByUserName/{0}", rockConfig.Username)); } catch (WebException wex) { HttpWebResponse response = wex.Response as HttpWebResponse; if (response != null) { if (response.StatusCode == HttpStatusCode.Unauthorized) { // valid URL but invalid login, so navigate back to the LoginPage rockConfig.RockBaseUrl = txtRockUrl.Text; rockConfig.Save(); LoginPage loginPage = new LoginPage(true); this.NavigationService.Navigate(loginPage); return; } } lblAlert.Content = wex.Message; lblAlert.Visibility = Visibility.Visible; return; } catch (Exception ex) { lblAlert.Content = ex.Message; lblAlert.Visibility = Visibility.Visible; return; } rockConfig.RockBaseUrl = txtRockUrl.Text; if (cboScannerInterfaceType.SelectedItem.Equals("MagTek")) { rockConfig.ScannerInterfaceType = RockConfig.InterfaceType.MICRImageRS232; } else { rockConfig.ScannerInterfaceType = RockConfig.InterfaceType.RangerApi; } string imageOption = cboImageOption.SelectedValue as string; switch (imageOption) { case "Grayscale": rockConfig.ImageColorType = ImageColorType.ImageColorTypeGrayscale; break; case "Color": rockConfig.ImageColorType = ImageColorType.ImageColorTypeColor; break; default: rockConfig.ImageColorType = ImageColorType.ImageColorTypeBitonal; break; } string comPortName = cboMagTekCommPort.SelectedItem as string; if (!string.IsNullOrWhiteSpace(comPortName)) { rockConfig.MICRImageComPort = short.Parse(comPortName.Replace("COM", string.Empty)); } rockConfig.Save(); this.NavigationService.GoBack(); }
/// <summary> /// Handles the DoWork event of the bwUploadScannedChecks control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="DoWorkEventArgs"/> instance containing the event data.</param> private void bwUploadScannedChecks_DoWork( object sender, DoWorkEventArgs e ) { BackgroundWorker bw = sender as BackgroundWorker; RockConfig rockConfig = RockConfig.Load(); RockRestClient client = new RockRestClient( rockConfig.RockBaseUrl ); client.Login( rockConfig.Username, rockConfig.Password ); AssemblyName assemblyName = Assembly.GetExecutingAssembly().GetName(); string appInfo = string.Format( "{0}, version: {1}", assemblyName.Name, assemblyName.Version ); BinaryFileType binaryFileTypeContribution = client.GetDataByGuid<BinaryFileType>( "api/BinaryFileTypes", new Guid( Rock.SystemGuid.BinaryFiletype.CONTRIBUTION_IMAGE ) ); DefinedValue transactionTypeValueContribution = client.GetDataByGuid<DefinedValue>( "api/DefinedValues", new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION ) ); int totalCount = ScannedDocList.Where( a => !a.Uploaded ).Count(); int position = 1; foreach ( ScannedDocInfo scannedDocInfo in ScannedDocList.Where( a => !a.Uploaded ) ) { // upload image of front of doc string frontImageFileName = string.Format( "image1_{0}.png", RockDateTime.Now.ToString( "o" ).RemoveSpecialCharacters() ); int frontImageBinaryFileId = client.UploadBinaryFile( frontImageFileName, Rock.SystemGuid.BinaryFiletype.CONTRIBUTION_IMAGE.AsGuid(), scannedDocInfo.FrontImagePngBytes, false ); // upload image of back of doc (if it exists) int? backImageBinaryFileId = null; if ( scannedDocInfo.BackImageData != null ) { // upload image of back of doc string backImageFileName = string.Format( "image2_{0}.png", RockDateTime.Now.ToString( "o" ).RemoveSpecialCharacters() ); backImageBinaryFileId = client.UploadBinaryFile( backImageFileName, Rock.SystemGuid.BinaryFiletype.CONTRIBUTION_IMAGE.AsGuid(), scannedDocInfo.BackImagePngBytes, false ); } int percentComplete = position++ * 100 / totalCount; bw.ReportProgress( percentComplete ); FinancialTransaction financialTransactionScanned = new FinancialTransaction(); Guid transactionGuid = Guid.NewGuid(); financialTransactionScanned.BatchId = SelectedFinancialBatch.Id; financialTransactionScanned.TransactionCode = string.Empty; financialTransactionScanned.Summary = "Scanned from Check Scanner Utility"; financialTransactionScanned.Guid = transactionGuid; financialTransactionScanned.TransactionDateTime = SelectedFinancialBatch.BatchStartDateTime; financialTransactionScanned.CurrencyTypeValueId = scannedDocInfo.CurrencyTypeValue.Id; financialTransactionScanned.SourceTypeValueId = scannedDocInfo.SourceTypeValue.Id; financialTransactionScanned.TransactionTypeValueId = transactionTypeValueContribution.Id; if ( scannedDocInfo.IsCheck ) { FinancialTransactionScannedCheck financialTransactionScannedCheck = new FinancialTransactionScannedCheck(); // Rock server will encrypt CheckMicrPlainText to this since we can't have the DataEncryptionKey in a RestClient financialTransactionScannedCheck.FinancialTransaction = financialTransactionScanned; financialTransactionScannedCheck.ScannedCheckMicr = scannedDocInfo.ScannedCheckMicr; client.PostData<FinancialTransactionScannedCheck>( "api/FinancialTransactions/PostScanned", financialTransactionScannedCheck ); } else { client.PostData<FinancialTransaction>( "api/FinancialTransactions", financialTransactionScanned as FinancialTransaction ); } // get the FinancialTransaction back from server so that we can get it's Id int transactionId = client.GetIdFromGuid( "api/FinancialTransactions/", transactionGuid ); // upload FinancialTransactionImage records for front/back FinancialTransactionImage financialTransactionImageFront = new FinancialTransactionImage(); financialTransactionImageFront.BinaryFileId = frontImageBinaryFileId; financialTransactionImageFront.TransactionId = transactionId; financialTransactionImageFront.Order = 0; client.PostData<FinancialTransactionImage>( "api/FinancialTransactionImages", financialTransactionImageFront ); if ( backImageBinaryFileId.HasValue ) { FinancialTransactionImage financialTransactionImageBack = new FinancialTransactionImage(); financialTransactionImageBack.BinaryFileId = backImageBinaryFileId.Value; financialTransactionImageBack.TransactionId = transactionId; financialTransactionImageBack.Order = 1; client.PostData<FinancialTransactionImage>( "api/FinancialTransactionImages", financialTransactionImageBack ); } scannedDocInfo.Uploaded = true; scannedDocInfo.TransactionId = transactionId; } ScanningPage.ClearScannedDocHistory(); }
/// <summary> /// Handles the RowEdit event of the grdBatchItems control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="MouseButtonEventArgs"/> instance containing the event data.</param> protected void grdBatchItems_RowEdit( object sender, MouseButtonEventArgs e ) { try { FinancialTransaction financialTransaction = grdBatchItems.SelectedValue.GetPropertyValue( "FinancialTransaction" ) as FinancialTransaction; if ( financialTransaction != null ) { RockConfig config = RockConfig.Load(); RockRestClient client = new RockRestClient( config.RockBaseUrl ); client.Login( config.Username, config.Password ); financialTransaction.Images = client.GetData<List<FinancialTransactionImage>>( "api/FinancialTransactionImages", string.Format( "TransactionId eq {0}", financialTransaction.Id ) ); BatchItemDetailPage.FinancialTransactionImages = financialTransaction.Images; this.NavigationService.Navigate( BatchItemDetailPage ); } } catch ( Exception ex ) { MessageBox.Show( ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation ); } }
/// <summary> /// Creates the document. /// </summary> /// <param name="financialTransactionQry">The financial transaction qry.</param> /// <returns></returns> public int RunReport() { UpdateProgress("Connecting..."); // Login and setup options for REST calls RockConfig rockConfig = RockConfig.Load(); _rockRestClient = new RockRestClient(rockConfig.RockBaseUrl); _rockRestClient.Login(rockConfig.Username, rockConfig.Password); // shouldn't happen, but just in case the StartDate isn't set, set it to the first day of the current year DateTime firstDayOfYear = new DateTime(DateTime.Now.Year, 1, 1); // note: if a specific person is specified, get them even if they don't have an address. _contributionStatementOptionsREST = new { StartDate = Options.StartDate ?? firstDayOfYear, EndDate = Options.EndDate, AccountIds = Options.AccountIds, IncludeIndividualsWithNoAddress = Options.PersonId.HasValue || Options.IncludeIndividualsWithNoAddress, DataViewId = Options.DataViewId, PersonId = Options.PersonId, OrderByPostalCode = true }; var organizationAddressAttribute = _rockRestClient.GetData <List <Rock.Client.Attribute> >("api/attributes", "Key eq 'OrganizationAddress'").FirstOrDefault(); if (organizationAddressAttribute != null) { var organizationAddressAttributeValue = _rockRestClient.GetData <List <Rock.Client.AttributeValue> >("api/AttributeValues", string.Format("AttributeId eq {0}", organizationAddressAttribute.Id)).FirstOrDefault(); Guid locationGuid = Guid.Empty; if (Guid.TryParse(organizationAddressAttributeValue.Value, out locationGuid)) { _organizationAddressLocation = _rockRestClient.GetData <List <Rock.Client.Location> >("api/locations", string.Format("Guid eq guid'{0}'", locationGuid)).FirstOrDefault(); } } // If we don't have a _organizationAddressLocation, just create an empty location _organizationAddressLocation = _organizationAddressLocation ?? new Rock.Client.Location(); UpdateProgress("Getting Data..."); // get outer query data from Rock database via REST now vs in mainQuery_OpeningRecordSet to make sure we have data DataSet personGroupAddressDataSet = _rockRestClient.PostDataWithResult <object, DataSet>("api/FinancialTransactions/GetContributionPersonGroupAddress", _contributionStatementOptionsREST); var allStatements = personGroupAddressDataSet.Tables[0]; RecordCount = allStatements.Rows.Count; if (RecordCount > 0) { int chapterSize = RecordCount; bool useChapters = this.Options.ChapterSize.HasValue; if (this.Options.ChapterSize.HasValue) { chapterSize = this.Options.ChapterSize.Value; } else { this.Options.ChapterSize = RecordCount; } int currentRecordIndex = 0; int chapterIndex = 1; while (currentRecordIndex < RecordCount) { // if its the last run adjust the chapter size so we don't go over if ((currentRecordIndex + chapterSize) > RecordCount) { chapterSize = RecordCount - currentRecordIndex; } _personGroupAddressDataTable = (DataTable)allStatements.AsEnumerable().Skip(currentRecordIndex).Take(chapterSize).CopyToDataTable <DataRow>(); var report = GetReportLayout(rockConfig); Document doc = report.Run(); var filePath = string.Empty; if (useChapters) { filePath = string.Format(@"{0}\{1}-chapter{2}.pdf", this.Options.SaveDirectory, this.Options.BaseFileName, chapterIndex); } else { filePath = string.Format(@"{0}\{1}.pdf", this.Options.SaveDirectory, this.Options.BaseFileName); } File.WriteAllBytes(filePath, doc.Draw()); currentRecordIndex = currentRecordIndex + this.Options.ChapterSize.Value; chapterIndex++; } } return(RecordCount); }
/// <summary> /// Handles the Click event of the btnScan control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void btnScan_Click( object sender, RoutedEventArgs e ) { // set the checkforDuplicateClient to null to ensure we have a fresh connection (just in case they changed the url, or if the connection died for some other reason) checkforDuplicateClient = null; this.NavigationService.Navigate( this.ScanningPromptPage ); }
/// <summary> /// Determines whether [is duplicate scan] [the specified scanned document]. /// </summary> /// <param name="scannedDoc">The scanned document.</param> /// <returns></returns> private bool IsDuplicateScan( ScannedDocInfo scannedDoc ) { if ( !scannedDoc.IsCheck ) { return false; } if ( checkforDuplicateClient == null ) { var rockConfig = RockConfig.Load(); checkforDuplicateClient = new RockRestClient( rockConfig.RockBaseUrl ); checkforDuplicateClient.Login( rockConfig.Username, rockConfig.Password ); } // first check if we have already scanned this doc during this session (we might not have uploaded it yet) var alreadyScanned = ScannedDocList.Any( a => a.IsCheck && a.ScannedCheckMicr == scannedDoc.ScannedCheckMicr ); // if we didn't already scan it in this session, check the server if ( !alreadyScanned ) { alreadyScanned = checkforDuplicateClient.PostDataWithResult<string, bool>( "api/FinancialTransactions/AlreadyScanned", scannedDoc.ScannedCheckMicr ); } return alreadyScanned; }
/// <summary> /// Handles the Click event of the btnLogin control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void btnLogin_Click( object sender, RoutedEventArgs e ) { txtUsername.Text = txtUsername.Text.Trim(); txtRockUrl.Text = txtRockUrl.Text.Trim(); Uri rockUrl = new Uri( txtRockUrl.Text ); var validSchemes = new string[] { Uri.UriSchemeHttp, Uri.UriSchemeHttps }; if ( !validSchemes.Contains(rockUrl.Scheme) ) { txtRockUrl.Text = "http://" + rockUrl.AbsoluteUri; } RockRestClient rockRestClient = new RockRestClient( txtRockUrl.Text ); string userName = txtUsername.Text; string password = txtPassword.Password; // start a background thread to Login since this could take a little while and we want a Wait cursor BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += delegate( object s, DoWorkEventArgs ee ) { ee.Result = null; rockRestClient.Login( userName, password ); }; // when the Background Worker is done with the Login, run this bw.RunWorkerCompleted += delegate( object s, RunWorkerCompletedEventArgs ee ) { this.Cursor = null; btnLogin.IsEnabled = true; try { if ( ee.Error != null ) { throw ee.Error; } Rock.Client.Person person = rockRestClient.GetData<Rock.Client.Person>( string.Format( "api/People/GetByUserName/{0}", userName ) ); RockConfig rockConfig = RockConfig.Load(); rockConfig.RockBaseUrl = txtRockUrl.Text; rockConfig.Username = txtUsername.Text; rockConfig.Password = txtPassword.Password; rockConfig.Save(); if ( this.NavigationService.CanGoBack ) { // if we got here from some other Page, go back this.NavigationService.GoBack(); } else { StartPage startPage = new StartPage(); this.NavigationService.Navigate( startPage ); } } catch ( WebException wex ) { // show WebException on the form, but any others should end up in the ExceptionDialog HttpWebResponse response = wex.Response as HttpWebResponse; if ( response != null ) { if ( response.StatusCode.Equals( HttpStatusCode.Unauthorized ) ) { lblLoginWarning.Content = "Invalid Login"; lblLoginWarning.Visibility = Visibility.Visible; return; } } string message = wex.Message; if ( wex.InnerException != null ) { message += "\n" + wex.InnerException.Message; } lblRockUrl.Visibility = Visibility.Visible; txtRockUrl.Visibility = Visibility.Visible; lblLoginWarning.Content = message; lblLoginWarning.Visibility = Visibility.Visible; return; } }; // set the cursor to Wait, disable the login button, and start the login background process this.Cursor = Cursors.Wait; btnLogin.IsEnabled = false; bw.RunWorkerAsync(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void btnSave_Click(object sender, RoutedEventArgs e) { RockConfig rockConfig = RockConfig.Load(); try { txtRockUrl.Text = txtRockUrl.Text.Trim(); Uri rockUrl = new Uri(txtRockUrl.Text); var validSchemes = new string[] { Uri.UriSchemeHttp, Uri.UriSchemeHttps }; if (!validSchemes.Contains(rockUrl.Scheme)) { txtRockUrl.Text = "http://" + rockUrl.AbsoluteUri; } RockRestClient client = new RockRestClient(txtRockUrl.Text); client.Login(rockConfig.Username, rockConfig.Password); BatchPage.LoggedInPerson = client.GetData <Person>(string.Format("api/People/GetByUserName/{0}", rockConfig.Username)); BatchPage.LoggedInPerson.Aliases = client.GetData <List <PersonAlias> >("api/PersonAlias/", "PersonId eq " + BatchPage.LoggedInPerson.Id); } catch (WebException wex) { HttpWebResponse response = wex.Response as HttpWebResponse; if (response != null) { if (response.StatusCode == HttpStatusCode.Unauthorized) { // valid URL but invalid login, so navigate back to the LoginPage rockConfig.RockBaseUrl = txtRockUrl.Text; rockConfig.Save(); LoginPage loginPage = new LoginPage(true); this.NavigationService.Navigate(loginPage); return; } } lblAlert.Content = wex.Message; lblAlert.Visibility = Visibility.Visible; return; } catch (Exception ex) { lblAlert.Content = ex.Message; lblAlert.Visibility = Visibility.Visible; return; } rockConfig.RockBaseUrl = txtRockUrl.Text; if (cboScannerInterfaceType.SelectedItem.Equals("MagTek")) { rockConfig.ScannerInterfaceType = RockConfig.InterfaceType.MICRImageRS232; } else { rockConfig.ScannerInterfaceType = RockConfig.InterfaceType.RangerApi; } string imageOption = cboImageOption.SelectedValue as string; switch (imageOption) { case "Grayscale": rockConfig.ImageColorType = ImageColorType.ImageColorTypeGrayscale; break; case "Color": rockConfig.ImageColorType = ImageColorType.ImageColorTypeColor; break; default: rockConfig.ImageColorType = ImageColorType.ImageColorTypeBitonal; break; } string comPortName = cboMagTekCommPort.SelectedItem as string; if (!string.IsNullOrWhiteSpace(comPortName)) { rockConfig.MICRImageComPort = short.Parse(comPortName.Replace("COM", string.Empty)); } rockConfig.SourceTypeValueGuid = (cboTransactionSourceType.SelectedItem as DefinedValue).Guid.ToString(); rockConfig.Save(); // shutdown the scanner so that options will be reloaded when the batch page loads if (BatchPage.rangerScanner != null) { BatchPage.rangerScanner.ShutDown(); } this.NavigationService.GoBack(); }
/// <summary> /// Initializes the RestClient for Uploads and loads any data that is needed for the scan session (if it isn't already initialized) /// </summary> /// <returns></returns> private RockRestClient EnsureUploadScanRestClient() { if ( _uploadScannedItemClient == null ) { RockConfig rockConfig = RockConfig.Load(); _uploadScannedItemClient = new RockRestClient( rockConfig.RockBaseUrl ); _uploadScannedItemClient.Login( rockConfig.Username, rockConfig.Password ); } if ( binaryFileTypeContribution == null || transactionTypeValueContribution == null ) { binaryFileTypeContribution = _uploadScannedItemClient.GetDataByGuid<BinaryFileType>( "api/BinaryFileTypes", new Guid( Rock.Client.SystemGuid.BinaryFiletype.CONTRIBUTION_IMAGE ) ); transactionTypeValueContribution = _uploadScannedItemClient.GetDataByGuid<DefinedValue>( "api/DefinedValues", new Guid( Rock.Client.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION ) ); } return _uploadScannedItemClient; }
/// <summary> /// Handles the DoWork event of the bwUploadScannedChecks control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="DoWorkEventArgs"/> instance containing the event data.</param> private void bwUploadScannedChecks_DoWork( object sender, DoWorkEventArgs e ) { BackgroundWorker bw = sender as BackgroundWorker; RockConfig rockConfig = RockConfig.Load(); RockRestClient client = new RockRestClient( rockConfig.RockBaseUrl ); client.Login( rockConfig.Username, rockConfig.Password ); AssemblyName assemblyName = Assembly.GetExecutingAssembly().GetName(); string appInfo = string.Format( "{0}, version: {1}", assemblyName.FullName, assemblyName.Version ); BinaryFileType binaryFileTypeContribution = client.GetDataByGuid<BinaryFileType>( "api/BinaryFileTypes", new Guid( Rock.SystemGuid.BinaryFiletype.CONTRIBUTION_IMAGE ) ); DefinedValue currencyTypeValueCheck = client.GetDataByGuid<DefinedValue>( "api/DefinedValues", new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CHECK ) ); DefinedValue transactionTypeValueContribution = client.GetDataByGuid<DefinedValue>( "api/DefinedValues", new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION ) ); DefinedValue transactionImageTypeValueFront = client.GetDataByGuid<DefinedValue>( "api/DefinedValues", new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_IMAGE_TYPE_CHECK_FRONT ) ); DefinedValue transactionImageTypeValueBack = client.GetDataByGuid<DefinedValue>( "api/DefinedValues", new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_IMAGE_TYPE_CHECK_BACK ) ); int totalCount = ScannedCheckList.Where( a => !a.Uploaded ).Count(); int position = 1; foreach ( ScannedCheckInfo scannedCheckInfo in ScannedCheckList.Where( a => !a.Uploaded ) ) { // upload image of front of check BinaryFile binaryFileFront = new BinaryFile(); binaryFileFront.Guid = Guid.NewGuid(); binaryFileFront.FileName = string.Format( "{0}_{1}_{2}_front.png", scannedCheckInfo.RoutingNumber, scannedCheckInfo.MaskedAccountNumber, scannedCheckInfo.CheckNumber ); binaryFileFront.BinaryFileTypeId = binaryFileTypeContribution.Id; binaryFileFront.IsSystem = false; binaryFileFront.MimeType = "image/png"; client.PostData<BinaryFile>( "api/BinaryFiles/", binaryFileFront ); // upload image data content of front of check binaryFileFront.Data = new BinaryFileData(); binaryFileFront.Data.Content = scannedCheckInfo.FrontImagePngBytes; binaryFileFront.Data.Id = client.GetDataByGuid<BinaryFile>( "api/BinaryFiles/", binaryFileFront.Guid ).Id; client.PostData<BinaryFileData>( "api/BinaryFileDatas/", binaryFileFront.Data ); // upload image of back of check (if it exists) BinaryFile binaryFileBack = null; if ( scannedCheckInfo.BackImageData != null ) { binaryFileBack = new BinaryFile(); binaryFileBack.Guid = Guid.NewGuid(); binaryFileBack.FileName = string.Format( "{0}_{1}_{2}_back.png", scannedCheckInfo.RoutingNumber, scannedCheckInfo.MaskedAccountNumber, scannedCheckInfo.CheckNumber ); // upload image of back of check binaryFileBack.BinaryFileTypeId = binaryFileTypeContribution.Id; binaryFileBack.IsSystem = false; binaryFileBack.MimeType = "image/png"; client.PostData<BinaryFile>( "api/BinaryFiles/", binaryFileBack ); // upload image data content of back of check binaryFileBack.Data = new BinaryFileData(); binaryFileBack.Data.Content = scannedCheckInfo.BackImagePngBytes; binaryFileBack.Data.Id = client.GetDataByGuid<BinaryFile>( "api/BinaryFiles/", binaryFileBack.Guid ).Id; client.PostData<BinaryFileData>( "api/BinaryFileDatas/", binaryFileBack.Data ); } int percentComplete = position++ * 100 / totalCount; bw.ReportProgress( percentComplete ); FinancialTransactionScannedCheck financialTransactionScannedCheck = new FinancialTransactionScannedCheck(); financialTransactionScannedCheck.BatchId = SelectedFinancialBatch.Id; financialTransactionScannedCheck.TransactionCode = string.Empty; financialTransactionScannedCheck.Summary = string.Format( "Scanned Check from {0}", appInfo ); financialTransactionScannedCheck.Guid = Guid.NewGuid(); financialTransactionScannedCheck.TransactionDateTime = SelectedFinancialBatch.BatchStartDateTime; financialTransactionScannedCheck.CurrencyTypeValueId = currencyTypeValueCheck.Id; financialTransactionScannedCheck.CreditCardTypeValueId = null; financialTransactionScannedCheck.SourceTypeValueId = null; financialTransactionScannedCheck.AuthorizedPersonId = null; financialTransactionScannedCheck.TransactionTypeValueId = transactionTypeValueContribution.Id; // Rock server will encrypt CheckMicrPlainText to this since we can't have the DataEncryptionKey in a RestClient financialTransactionScannedCheck.CheckMicrEncrypted = null; financialTransactionScannedCheck.ScannedCheckMicr = string.Format( "{0}_{1}_{2}", scannedCheckInfo.RoutingNumber, scannedCheckInfo.AccountNumber, scannedCheckInfo.CheckNumber ); client.PostData<FinancialTransactionScannedCheck>( "api/FinancialTransactions/PostScanned", financialTransactionScannedCheck ); // get the FinancialTransaction back from server so that we can get it's Id financialTransactionScannedCheck.Id = client.GetDataByGuid<FinancialTransaction>( "api/FinancialTransactions", financialTransactionScannedCheck.Guid ).Id; // get the BinaryFiles back so that we can get their Ids binaryFileFront.Id = client.GetDataByGuid<BinaryFile>( "api/BinaryFiles", binaryFileFront.Guid ).Id; // upload FinancialTransactionImage records for front/back FinancialTransactionImage financialTransactionImageFront = new FinancialTransactionImage(); financialTransactionImageFront.BinaryFileId = binaryFileFront.Id; financialTransactionImageFront.TransactionId = financialTransactionScannedCheck.Id; financialTransactionImageFront.TransactionImageTypeValueId = transactionImageTypeValueFront.Id; client.PostData<FinancialTransactionImage>( "api/FinancialTransactionImages", financialTransactionImageFront ); if ( binaryFileBack != null ) { // get the BinaryFiles back so that we can get their Ids binaryFileBack.Id = client.GetDataByGuid<BinaryFile>( "api/BinaryFiles", binaryFileBack.Guid ).Id; FinancialTransactionImage financialTransactionImageBack = new FinancialTransactionImage(); financialTransactionImageBack.BinaryFileId = binaryFileBack.Id; financialTransactionImageBack.TransactionId = financialTransactionScannedCheck.Id; financialTransactionImageBack.TransactionImageTypeValueId = transactionImageTypeValueBack.Id; client.PostData<FinancialTransactionImage>( "api/FinancialTransactionImages", financialTransactionImageBack ); } scannedCheckInfo.Uploaded = true; } }
/// <summary> /// Handles the Loaded event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void Page_Loaded( object sender, RoutedEventArgs e ) { // set the uploadScannedItemClient to null and reconnect to ensure we have a fresh connection (just in case they changed the url, or if the connection died for some other reason) _uploadScannedItemClient = null; EnsureUploadScanRestClient(); ShowStartupPage(); _itemsUploaded = 0; _itemsSkipped = 0; _itemsScanned = 0; _firstNoItemsWarning = true; ShowUploadStats(); StartScanning(); lblScanItemCountInfo.Visibility = Visibility.Collapsed; }
/// <summary> /// Loads the combo boxes. /// </summary> private void LoadComboBoxes() { RockConfig rockConfig = RockConfig.Load(); RockRestClient client = new RockRestClient( rockConfig.RockBaseUrl ); client.Login( rockConfig.Username, rockConfig.Password ); List<Campus> campusList = client.GetData<List<Campus>>( "api/Campus" ); cbCampus.SelectedValuePath = "Id"; cbCampus.DisplayMemberPath = "Name"; cbCampus.Items.Clear(); cbCampus.Items.Add( new Campus { Id = None.Id, Name = None.Text } ); foreach ( var campus in campusList.OrderBy( a => a.Name ) ) { cbCampus.Items.Add( campus ); } cbCampus.SelectedIndex = 0; }
/// <summary> /// Creates the document. /// </summary> /// <param name="financialTransactionQry">The financial transaction qry.</param> /// <returns></returns> public Document RunReport() { UpdateProgress("Connecting..."); // Login and setup options for REST calls RockConfig rockConfig = RockConfig.Load(); _rockRestClient = new RockRestClient(rockConfig.RockBaseUrl); _rockRestClient.Login(rockConfig.Username, rockConfig.Password); // shouldn't happen, but just in case the StartDate isn't set, set it to the first day of the current year DateTime firstDayOfYear = new DateTime(DateTime.Now.Year, 1, 1); // note: if a specific person is specified, get them even if they don't have an address. _contributionStatementOptionsREST = new { StartDate = Options.StartDate ?? firstDayOfYear, EndDate = Options.EndDate, AccountIds = Options.AccountIds, IncludeIndividualsWithNoAddress = Options.PersonId.HasValue || Options.IncludeIndividualsWithNoAddress, DataViewId = Options.DataViewId, PersonId = Options.PersonId, OrderByPostalCode = true }; var organizationAddressAttribute = _rockRestClient.GetData <List <Rock.Client.Attribute> >("api/attributes", "Key eq 'OrganizationAddress'").FirstOrDefault(); if (organizationAddressAttribute != null) { var organizationAddressAttributeValue = _rockRestClient.GetData <List <Rock.Client.AttributeValue> >("api/AttributeValues", string.Format("AttributeId eq {0}", organizationAddressAttribute.Id)).FirstOrDefault(); Guid locationGuid = Guid.Empty; if (Guid.TryParse(organizationAddressAttributeValue.Value, out locationGuid)) { _organizationAddressLocation = _rockRestClient.GetData <List <Rock.Client.Location> >("api/locations", string.Format("Guid eq guid'{0}'", locationGuid)).FirstOrDefault(); } } // If we don't have a _organizationAddressLocation, just create an empty location _organizationAddressLocation = _organizationAddressLocation ?? new Rock.Client.Location(); // setup report layout and events DocumentLayout report = new DocumentLayout(this.Options.LayoutFile); //// if there is an imgLogo and the path is "logo.jpg", use the logo specified in rockconfig. //// We have to read the layout as Xml first to figure out what the Path of the imgLogo XmlDocument layoutXmlDoc = new XmlDocument(); layoutXmlDoc.Load(this.Options.LayoutFile); var imageNodes = layoutXmlDoc.GetElementsByTagName("image"); foreach (var imageNode in imageNodes.OfType <XmlNode>()) { string imagePath = imageNode.Attributes["path"].Value; string imageId = imageNode.Attributes["id"].Value; if (imageId.Equals("imgLogo") && imagePath.Equals(RockConfig.DefaultLogoFile, StringComparison.OrdinalIgnoreCase)) { Image imgLogo = report.GetReportElementById("imgLogo") as Image; if (imgLogo != null) { try { if (!rockConfig.LogoFile.Equals(RockConfig.DefaultLogoFile, StringComparison.OrdinalIgnoreCase)) { imgLogo.ImageData = ceTe.DynamicPDF.Imaging.ImageData.GetImage(rockConfig.LogoFile); } } catch (Exception ex) { throw new Exception("Error loading Logo Image: " + rockConfig.LogoFile + "\n\n" + ex.Message); } } } } Query query = report.GetQueryById("OuterQuery"); if (query == null) { throw new MissingReportElementException("Report requires a QueryElement named 'OuterQuery'"); } query.OpeningRecordSet += mainQuery_OpeningRecordSet; Query orgInfoQuery = report.GetQueryById("OrgInfoQuery"); if (orgInfoQuery == null) { throw new MissingReportElementException("Report requires a QueryElement named 'OrgInfoQuery'"); } orgInfoQuery.OpeningRecordSet += orgInfoQuery_OpeningRecordSet; _accountSummaryQuery = report.GetQueryById("AccountSummaryQuery"); if (_accountSummaryQuery == null) { // not required. Just don't do anything if it isn't there } else { _accountSummaryQuery.OpeningRecordSet += delegate(object s, OpeningRecordSetEventArgs ee) { // create a recordset for the _accountSummaryQuery which is the GroupBy summary of AccountName, Amount /* * The structure of _transactionsDataTable is * * DateTime TransactionDateTime * string CurrencyTypeValueName * string Summary (main transaction summary) * DataTable Details { * int AccountId * string AccountName * string Summary (detail summary) * decimal Amount * } */ var detailsData = new DataTable(); detailsData.Columns.Add("AccountId", typeof(int)); detailsData.Columns.Add("AccountName"); detailsData.Columns.Add("Amount", typeof(decimal)); foreach (var details in _transactionsDataTable.AsEnumerable().Select(a => (a["Details"] as DataTable))) { foreach (var row in details.AsEnumerable()) { detailsData.Rows.Add(row["AccountId"], row["AccountName"], row["Amount"]); } } var summaryTable = detailsData.AsEnumerable().GroupBy(g => g["AccountId"]).Select(a => new { AccountName = a.Max(x => x["AccountName"].ToString()), Amount = a.Sum(x => decimal.Parse(x["Amount"].ToString())) }).OrderBy(o => o.AccountName); ee.RecordSet = new EnumerableRecordSet(summaryTable); }; } UpdateProgress("Getting Data..."); // get outer query data from Rock database via REST now vs in mainQuery_OpeningRecordSet to make sure we have data DataSet personGroupAddressDataSet = _rockRestClient.PostDataWithResult <object, DataSet>("api/FinancialTransactions/GetContributionPersonGroupAddress", _contributionStatementOptionsREST); _personGroupAddressDataTable = personGroupAddressDataSet.Tables[0]; RecordCount = _personGroupAddressDataTable.Rows.Count; if (RecordCount > 0) { Document doc = report.Run(); return(doc); } else { return(null); } }
/// <summary> /// Loads the financial batches grid. /// </summary> private void LoadFinancialBatchesGrid() { RockConfig config = RockConfig.Load(); RockRestClient client = new RockRestClient( config.RockBaseUrl ); client.Login( config.Username, config.Password ); List<FinancialBatch> pendingBatches = client.GetDataByEnum<List<FinancialBatch>>( "api/FinancialBatches", "Status", BatchStatus.Pending ); grdBatches.DataContext = pendingBatches.OrderByDescending( a => a.BatchStartDateTime ).ThenBy( a => a.Name ); if ( pendingBatches.Count > 0 ) { if ( SelectedFinancialBatch != null ) { grdBatches.SelectedValue = pendingBatches.FirstOrDefault( a => a.Id.Equals( SelectedFinancialBatch.Id ) ); } else { grdBatches.SelectedIndex = 0; } } UpdateBatchUI( grdBatches.SelectedValue as FinancialBatch ); }
/// <summary> /// Updates the batch UI. /// </summary> /// <param name="selectedBatch">The selected batch.</param> private void UpdateBatchUI( FinancialBatch selectedBatch ) { if ( selectedBatch == null ) { grdBatchItems.DataContext = null; DisplayTransactionCount(); HideBatch(); return; } else { ShowBatch( false ); } RockConfig rockConfig = RockConfig.Load(); RockRestClient client = new RockRestClient( rockConfig.RockBaseUrl ); client.Login( rockConfig.Username, rockConfig.Password ); SelectedFinancialBatch = selectedBatch; lblBatchNameReadOnly.Content = selectedBatch.Name; lblBatchIdReadOnly.Content = string.Format( "Batch Id: {0}", selectedBatch.Id ); lblBatchCampusReadOnly.Content = selectedBatch.CampusId.HasValue ? client.GetData<Campus>( string.Format( "api/Campuses/{0}", selectedBatch.CampusId ?? 0 ) ).Name : string.Empty; lblBatchDateReadOnly.Content = selectedBatch.BatchStartDateTime.Value.ToString( "d" ); var createdByPerson = client.GetData<Person>( string.Format( "api/People/GetByPersonAliasId/{0}", selectedBatch.CreatedByPersonAliasId ?? 0 ) ); if ( createdByPerson != null ) { lblBatchCreatedByReadOnly.Content = string.Format("{0} {1}", createdByPerson.NickName, createdByPerson.LastName); } else { lblBatchCreatedByReadOnly.Content = string.Empty; } lblBatchControlAmountReadOnly.Content = selectedBatch.ControlAmount.ToString( "F" ); txtBatchName.Text = selectedBatch.Name; if ( selectedBatch.CampusId.HasValue ) { cbCampus.SelectedValue = selectedBatch.CampusId; } else { cbCampus.SelectedValue = 0; } dpBatchDate.SelectedDate = selectedBatch.BatchStartDateTime; lblCreatedBy.Content = lblBatchCreatedByReadOnly.Content as string; txtControlAmount.Text = selectedBatch.ControlAmount.ToString( "F" ); txtNote.Text = selectedBatch.Note; // start a background thread to download transactions since this could take a little while and we want a Wait cursor BackgroundWorker bw = new BackgroundWorker(); Rock.Wpf.WpfHelper.FadeOut( lblCount, 0 ); lblCount.Content = "Loading..."; Rock.Wpf.WpfHelper.FadeIn( lblCount, 300 ); List<FinancialTransaction> transactions = null; grdBatchItems.DataContext = null; bw.DoWork += delegate( object s, DoWorkEventArgs ee ) { ee.Result = null; transactions = client.GetData<List<FinancialTransaction>>( "api/FinancialTransactions/", string.Format( "BatchId eq {0}", selectedBatch.Id ) ); }; bw.RunWorkerCompleted += delegate( object s, RunWorkerCompletedEventArgs ee ) { this.Cursor = null; foreach ( var transaction in transactions ) { if ( transaction.FinancialPaymentDetailId.HasValue ) { transaction.FinancialPaymentDetail = transaction.FinancialPaymentDetail ?? client.GetData<FinancialPaymentDetail>( string.Format( "api/FinancialPaymentDetails/{0}", transaction.FinancialPaymentDetailId ?? 0 ) ); if ( transaction.FinancialPaymentDetail != null ) { transaction.FinancialPaymentDetail.CurrencyTypeValue = this.CurrencyValueList.FirstOrDefault( a => a.Id == transaction.FinancialPaymentDetail.CurrencyTypeValueId ); } } } // sort starting with most recent first var bindingList = new BindingList<FinancialTransaction>( transactions.OrderByDescending( a => a.CreatedDateTime ).ToList() ); bindingList.RaiseListChangedEvents = true; bindingList.ListChanged += bindingList_ListChanged; grdBatchItems.DataContext = bindingList; DisplayTransactionCount(); }; this.Cursor = Cursors.Wait; bw.RunWorkerAsync(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void btnSave_Click( object sender, RoutedEventArgs e ) { try { RockConfig rockConfig = RockConfig.Load(); RockRestClient client = new RockRestClient( rockConfig.RockBaseUrl ); client.Login( rockConfig.Username, rockConfig.Password ); FinancialBatch financialBatch = null; if ( SelectedFinancialBatch == null || SelectedFinancialBatch.Id == 0) { financialBatch = new FinancialBatch { Id = 0, Guid = Guid.NewGuid(), Status = BatchStatus.Pending, CreatedByPersonAliasId = LoggedInPerson.PrimaryAlias.Id }; } else { financialBatch = client.GetData<FinancialBatch>( string.Format( "api/FinancialBatches/{0}", SelectedFinancialBatch.Id ) ); } txtBatchName.Text = txtBatchName.Text.Trim(); financialBatch.Name = txtBatchName.Text; Campus selectedCampus = cbCampus.SelectedItem as Campus; if ( selectedCampus.Id > 0 ) { financialBatch.CampusId = selectedCampus.Id; } else { financialBatch.CampusId = null; } financialBatch.BatchStartDateTime = dpBatchDate.SelectedDate; if ( !string.IsNullOrWhiteSpace( txtControlAmount.Text ) ) { financialBatch.ControlAmount = decimal.Parse( txtControlAmount.Text.Replace( "$", string.Empty ) ); } else { financialBatch.ControlAmount = 0.00M; } if ( financialBatch.Id == 0 ) { client.PostData<FinancialBatch>( "api/FinancialBatches/", financialBatch ); } else { client.PutData<FinancialBatch>( "api/FinancialBatches/", financialBatch ); } if ( SelectedFinancialBatch == null || SelectedFinancialBatch.Id == 0 ) { // refetch the batch to get the Id if it was just Inserted financialBatch = client.GetDataByGuid<FinancialBatch>( "api/FinancialBatches", financialBatch.Guid ); SelectedFinancialBatch = financialBatch; } LoadFinancialBatchesGrid(); ShowBatch( false ); } catch ( Exception ex ) { MessageBox.Show( ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation ); } }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param> private void btnSave_Click(object sender, RoutedEventArgs e) { try { RockConfig rockConfig = RockConfig.Load(); RockRestClient client = new RockRestClient(rockConfig.RockBaseUrl); client.Login(rockConfig.Username, rockConfig.Password); FinancialBatch financialBatch = null; if (SelectedFinancialBatch == null || SelectedFinancialBatch.Id == 0) { financialBatch = new FinancialBatch { Id = 0, Guid = Guid.NewGuid(), Status = BatchStatus.Pending, CreatedByPersonAliasId = LoggedInPerson.PrimaryAliasId }; } else { financialBatch = client.GetData <FinancialBatch>(string.Format("api/FinancialBatches/{0}", SelectedFinancialBatch.Id)); } txtBatchName.Text = txtBatchName.Text.Trim(); if (string.IsNullOrWhiteSpace(txtBatchName.Text)) { txtBatchName.Style = this.FindResource("textboxStyleError") as Style; return; } else { txtBatchName.Style = this.FindResource("textboxStyle") as Style; } financialBatch.Name = txtBatchName.Text; Campus selectedCampus = cbCampus.SelectedItem as Campus; if (selectedCampus.Id > 0) { financialBatch.CampusId = selectedCampus.Id; } else { financialBatch.CampusId = null; } financialBatch.BatchStartDateTime = dpBatchDate.SelectedDate; if (!string.IsNullOrWhiteSpace(txtControlAmount.Text)) { financialBatch.ControlAmount = decimal.Parse(txtControlAmount.Text.Replace("$", string.Empty)); } else { financialBatch.ControlAmount = 0.00M; } txtNote.Text = txtNote.Text.Trim(); financialBatch.Note = txtNote.Text; if (financialBatch.Id == 0) { client.PostData <FinancialBatch>("api/FinancialBatches/", financialBatch); } else { client.PutData <FinancialBatch>("api/FinancialBatches/", financialBatch, financialBatch.Id); } if (SelectedFinancialBatch == null || SelectedFinancialBatch.Id == 0) { // refetch the batch to get the Id if it was just Inserted financialBatch = client.GetDataByGuid <FinancialBatch>("api/FinancialBatches", financialBatch.Guid); SelectedFinancialBatch = financialBatch; } LoadFinancialBatchesGrid(); UpdateBatchUI(financialBatch); ShowBatch(false); } catch (Exception ex) { ShowException(ex); } }
/// <summary> /// Updates the batch UI. /// </summary> /// <param name="selectedBatch">The selected batch.</param> private void UpdateBatchUI( FinancialBatch selectedBatch ) { if ( selectedBatch == null ) { HideBatch(); return; } else { ShowBatch( false ); } RockConfig rockConfig = RockConfig.Load(); RockRestClient client = new RockRestClient( rockConfig.RockBaseUrl ); client.Login( rockConfig.Username, rockConfig.Password ); SelectedFinancialBatch = selectedBatch; lblBatchNameReadOnly.Content = selectedBatch.Name; lblBatchCampusReadOnly.Content = selectedBatch.CampusId.HasValue ? client.GetData<Campus>( string.Format( "api/Campus/{0}", selectedBatch.CampusId ) ).Name : None.Text; lblBatchDateReadOnly.Content = selectedBatch.BatchStartDateTime.Value.ToString( "d" ); lblBatchCreatedByReadOnly.Content = client.GetData<Person>( string.Format( "api/People/GetByPersonAliasId/{0}", selectedBatch.CreatedByPersonAliasId ) ).FullName; lblBatchControlAmountReadOnly.Content = selectedBatch.ControlAmount.ToString( "F" ); txtBatchName.Text = selectedBatch.Name; if ( selectedBatch.CampusId.HasValue ) { cbCampus.SelectedValue = selectedBatch.CampusId; } else { cbCampus.SelectedValue = 0; } dpBatchDate.SelectedDate = selectedBatch.BatchStartDateTime; lblCreatedBy.Content = lblBatchCreatedByReadOnly.Content as string; txtControlAmount.Text = selectedBatch.ControlAmount.ToString( "F" ); List<FinancialTransaction> transactions = client.GetData<List<FinancialTransaction>>( "api/FinancialTransactions/", string.Format( "BatchId eq {0}", selectedBatch.Id ) ); foreach (var transaction in transactions) { transaction.TransactionDetails = client.GetData<List<FinancialTransactionDetail>>( "api/FinancialTransactionDetails/", string.Format( "TransactionId eq {0}", transaction.Id ) ); } grdBatchItems.DataContext = transactions.OrderByDescending( a => a.CreatedDateTime ); }