Inheritance: System.Configuration.ApplicationSettingsBase
Ejemplo n.º 1
0
        /// <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.Save();

            this.NavigationService.GoBack();
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Handles the Click event of the btnNext 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 btnNext_Click(object sender, RoutedEventArgs e)
        {
            var selected = lstLayouts.Items.OfType <RadioButton>().First(a => a.IsChecked == true);

            if (selected != null)
            {
                string fileName = selected.Tag.ToString();
                ReportOptions.Current.LayoutFile = fileName;
                var rockConfig = RockConfig.Load();
                rockConfig.LayoutFile = fileName;
                rockConfig.Save();
                ProgressPage nextPage = new ProgressPage();
                this.NavigationService.Navigate(nextPage);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockConfig = RockConfig.Load();

            List <FinancialStatementReportConfiguration> reportConfigurationList = null;

            try
            {
                if (rockConfig.ReportConfigurationListJson.IsNotNullOrWhiteSpace())
                {
                    reportConfigurationList = rockConfig.ReportConfigurationListJson.FromJsonOrNull <List <FinancialStatementReportConfiguration> >();
                }
            }
            catch
            {
                // ignore
            }

            if (reportConfigurationList == null)
            {
                // if this is the first time the generator has run, create a default.
                // If they delete this default, that is OK. See https://app.asana.com/0/0/1200266899611805/f
                reportConfigurationList = new List <FinancialStatementReportConfiguration>();
                var defaultConfiguration = new FinancialStatementReportConfiguration
                {
                    DestinationFolder             = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Statements"),
                    ExcludeOptedOutIndividuals    = true,
                    FilenamePrefix                = "statement-",
                    IncludeInternationalAddresses = false,
                    MaxStatementsPerChapter       = 500,
                    MinimumContributionAmount     = 1.00M,
                    PreventSplittingPrimarySortValuesAcrossChapters = true,
                    PrimarySortOrder             = Client.Enums.FinancialStatementOrderBy.PostalCode,
                    SecondarySortOrder           = Client.Enums.FinancialStatementOrderBy.LastName,
                    SplitFilesOnPrimarySortValue = true,
                    CreatedDateTime = DateTime.Now,
                    Guid            = Guid.NewGuid()
                };

                reportConfigurationList.Add(defaultConfiguration);
                rockConfig.ReportConfigurationListJson = reportConfigurationList.ToJson();
                rockConfig.Save();
            }

            ReportOptions.Current.ReportConfigurationList = reportConfigurationList;

            grdReportSettings.DataContext = reportConfigurationList.OrderBy(a => a.CreatedDateTime);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Saves the changes.
        /// </summary>
        /// <param name="showWarnings">if set to <c>true</c> [show warnings].</param>
        /// <returns></returns>
        private bool SaveChanges(bool showWarnings)
        {
            var rockConfig = RockConfig.Load();

            rockConfig.EnablePageCountPredetermination = cbEnablePageCountPredetermination.IsChecked == true;
            rockConfig.LastReportOptions = ReportOptions.Current;
            rockConfig.Save();
            ReportOptions.Current.EnablePageCountPredetermination = rockConfig.EnablePageCountPredetermination;

            if (cbSaveSettings.IsChecked == true)
            {
                this.SaveConfigurationAsSystemSetting(rockConfig);
            }

            return(true);
        }
Ejemplo n.º 5
0
        /// <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();

            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;
            }

            try
            {
                RestClient restClient = new RestClient(txtRockUrl.Text);
                restClient.LoginToRock(rockConfig.Username, rockConfig.Password);
            }
            catch (Exception ex)
            {
                lblAlert.Content    = ex.Message;
                lblAlert.Visibility = Visibility.Visible;
                return;
            }

            rockConfig.RockBaseUrl = txtRockUrl.Text;

            if (txtTemporaryDirectory.Text.IsNotNullOrWhiteSpace())
            {
                try
                {
                    Directory.CreateDirectory(txtTemporaryDirectory.Text);
                }
                catch (Exception ex)
                {
                    lblAlert.Content    = $"Error creating temporary directory: { ex.Message}";
                    lblAlert.Visibility = Visibility.Visible;
                    return;
                }
            }

            rockConfig.TemporaryDirectory = txtTemporaryDirectory.Text;

            rockConfig.Save();

            this.NavigationService.GoBack();
        }
Ejemplo n.º 6
0
        /// <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>;
            }
        }
Ejemplo n.º 7
0
        /// <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;
        }
Ejemplo n.º 9
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 rockConfig = RockConfig.Load();

            radAllPersons.IsChecked = rockConfig.PersonSelectionOption == PersonSelectionOption.AllIndividuals;
            radDataView.IsChecked   = rockConfig.PersonSelectionOption == PersonSelectionOption.DataView;
            radSingle.IsChecked     = rockConfig.PersonSelectionOption == PersonSelectionOption.SingleIndividual;

            ckExcludeInActiveIndividuals.IsChecked = ReportOptions.Current.ExcludeInActiveIndividuals;
            ckIncludeBusinesses.IsChecked          = ReportOptions.Current.IncludeBusinesses;

            if (ReportOptions.Current.DataViewId.HasValue)
            {
                ddlDataView.SelectedValue = ddlDataView.Items.OfType <Rock.Client.DataView>().FirstOrDefault(a => a.Id == ReportOptions.Current.DataViewId.Value);
            }

            radPersons_Checked(sender, e);
            lblWarning.Visibility = Visibility.Collapsed;
        }
Ejemplo n.º 10
0
        /// <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));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Saves the changes.
        /// </summary>
        /// <param name="showWarnings">if set to <c>true</c> [show warnings].</param>
        /// <returns></returns>
        private bool SaveChanges(bool showWarnings)
        {
            var selected = lstLavaTemplates.Items.OfType <RadioButton>().First(a => a.IsChecked == true);

            if (selected == null)
            {
                if (showWarnings)
                {
                    return(false);
                }
            }

            var rockConfig = RockConfig.Load();

            rockConfig.LayoutDefinedValueGuid = selected?.Tag as Guid?;
            rockConfig.Save();

            ReportOptions.Current.LayoutDefinedValueGuid = selected?.Tag as Guid?;

            return(true);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SelectPersonsPage"/> class.
        /// </summary>
        public SelectPersonsPage()
        {
            InitializeComponent();
            RockConfig rockConfig = RockConfig.Load();

            _restClient = new RestClient(rockConfig.RockBaseUrl);
            _restClient.LoginToRock(rockConfig.Username, rockConfig.Password);

            string queryParam           = "?$filter=EntityType/Name eq 'Rock.Model.Person'";
            var    getDataViewsRequest  = new RestRequest("api/DataViews" + queryParam);
            var    getDataViewsResponse = _restClient.Execute <List <Rock.Client.DataView> >(getDataViewsRequest);

            if (getDataViewsResponse.ErrorException != null)
            {
                throw getDataViewsResponse.ErrorException;
            }

            var dataViews = getDataViewsResponse.Data;

            ddlDataView.DisplayMemberPath = "Name";
            ddlDataView.ItemsSource       = dataViews;
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Populates the layout radio buttons from disk.
        /// </summary>
        private void PopulateLayoutRadioButtonsFromDisk()
        {
            List <RadioButton> radioButtonList = new List <RadioButton>();
            var           rockConfig           = RockConfig.Load();
            List <string> filenameList         = Directory.GetFiles(".", "*.dplx").ToList();

            foreach (var fileName in filenameList)
            {
                DplxFile       dplxFile       = new DplxFile(fileName);
                DocumentLayout documentLayout = new DocumentLayout(dplxFile);
                RadioButton    radLayout      = new RadioButton();
                if (!string.IsNullOrWhiteSpace(documentLayout.Title))
                {
                    radLayout.Content = documentLayout.Title.Trim();
                }
                else
                {
                    radLayout.Content = fileName;
                }

                radLayout.Tag       = fileName;
                radLayout.IsChecked = rockConfig.LayoutFile == fileName;
                radioButtonList.Add(radLayout);
            }

            if (!radioButtonList.Any(a => a.IsChecked ?? false))
            {
                if (radioButtonList.FirstOrDefault() != null)
                {
                    radioButtonList.First().IsChecked = true;
                }
            }

            lstLayouts.Items.Clear();
            foreach (var item in radioButtonList.OrderBy(a => a.Content))
            {
                lstLayouts.Items.Add(item);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Saves the changes.
        /// </summary>
        /// <param name="showWarnings">if set to <c>true</c> [show warnings].</param>
        /// <returns></returns>
        private bool SaveChanges(bool showWarnings)
        {
            var rockConfig = RockConfig.Load();

            rockConfig.ShowInactiveAccounts         = cbShowInactive.IsChecked == true;
            rockConfig.ShowTaxDeductibleAccounts    = cbShowTaxDeductible.IsChecked == true;
            rockConfig.ShowNonTaxDeductibleAccounts = cbShowNonTaxDeductible.IsChecked == true;

            ReportOptions.Current.TransactionAccountIds  = lstAccounts.Items.OfType <CheckBox>().Where(a => a.IsChecked == true).Select(s => ( int )s.Tag).ToList();
            ReportOptions.Current.CurrencyTypeIdsCash    = lstCashCurrencyTypes.Items.OfType <CheckBox>().Where(a => a.IsChecked == true).Select(s => ( int )s.Tag).ToList();
            ReportOptions.Current.CurrencyTypeIdsNonCash = lstNonCashCurrencyTypes.Items.OfType <CheckBox>().Where(a => a.IsChecked == true).Select(s => ( int )s.Tag).ToList();
            var currencySelected = ReportOptions.Current.CurrencyTypeIdsCash.Any() || ReportOptions.Current.CurrencyTypeIdsNonCash.Any();

            if (!ReportOptions.Current.TransactionAccountIds.Any() || !currencySelected)
            {
                if (showWarnings)
                {
                    if (!ReportOptions.Current.TransactionAccountIds.Any() && !currencySelected)
                    {
                        lblAccountsCurrencyTypesWarning.Content = "Please select at least one account and currency type.";
                    }
                    else if (!ReportOptions.Current.TransactionAccountIds.Any())
                    {
                        lblAccountsCurrencyTypesWarning.Content = "Please select at least one account.";
                    }
                    else if (!currencySelected)
                    {
                        lblAccountsCurrencyTypesWarning.Content = "Please select at least one currency type.";
                    }

                    lblAccountsCurrencyTypesWarning.Visibility = Visibility.Visible;
                    return(false);
                }
            }

            return(true);
        }
        /// <summary>
        /// Saves the changes.
        /// </summary>
        /// <param name="showWarnings">if set to <c>true</c> [show warnings].</param>
        /// <returns></returns>
        private bool SaveChanges(bool showWarnings)
        {
            var selected = lstFinancialStatementTemplates.Items.OfType <RadioButton>().Where(a => a.IsChecked == true).FirstOrDefault();

            if (selected == null)
            {
                if (showWarnings)
                {
                    lblWarning.Content    = "Please select a template.";
                    lblWarning.Visibility = Visibility.Visible;
                    return(false);
                }
            }

            var rockConfig = RockConfig.Load();
            var financialStatementTemplate = selected?.Tag as Rock.Client.FinancialStatementTemplate;

            rockConfig.FinancialStatementTemplateGuid = financialStatementTemplate?.Guid;
            rockConfig.Save();

            ReportOptions.Current.FinancialStatementTemplateId = financialStatementTemplate?.Id;

            return(true);
        }
Ejemplo n.º 16
0
        private void SaveConfigurationAsSystemSetting(RockConfig rockConfig)
        {
            // Login and setup options for REST calls
            var restClient = new RestClient(rockConfig.RockBaseUrl);

            restClient.LoginToRock(rockConfig.Username, rockConfig.Password);

            // Get the previous record and set up the one to be stored
            var isPost = true;
            var getStatementGeneratorConfig = new RestRequest($"api/Attributes?$filter=Guid eq guid'{Rock.Client.SystemGuid.Attribute.STATEMENT_GENERATOR_CONFIG}'");
            var storedSetting = restClient.Execute <List <Rock.Client.Attribute> >(getStatementGeneratorConfig).Data.FirstOrDefault();
            var systemSetting = new AttributeEntity()
            {
                IsSystem     = false,
                FieldTypeId  = 1,
                EntityTypeId = null,
                EntityTypeQualifierColumn = "SystemSetting",
                EntityTypeQualifierValue  = string.Empty,
                Key             = "core_StatementGeneratorConfig",
                Name            = "core _ Statement Generator Config",
                AbbreviatedName = "core _ Statement Generator Config",
                Description     = "Used to store common configuration settings for the Statement Generator application",
                Order           = 0,
                IsGridColumn    = false,
                IsMultiValue    = false,
                IsRequired      = false,
                Guid            = Rock.Client.SystemGuid.Attribute.STATEMENT_GENERATOR_CONFIG.AsGuid()
            };

            if (null != storedSetting)
            {
                isPost = false;
                systemSetting.CopyPropertiesFrom(storedSetting);
            }

            // Write the Config JSON
            systemSetting.DefaultValue = JsonConvert.SerializeObject(rockConfig, Formatting.None);

            // Post the data back to Rock
            var saveAttributeRequest = new RestRequest()
                                       .AddHeader("Accept", "application/json");

            if (isPost)
            {
                saveAttributeRequest.Resource = "api/Attributes";
                saveAttributeRequest.Method   = Method.POST;
            }
            else
            {   // If not nulled, this doesn't update
                systemSetting.ModifiedByPersonAliasId = null;
                systemSetting.ModifiedDateTime        = null;

                saveAttributeRequest.Resource = $"api/Attributes/{systemSetting.Id}";
                saveAttributeRequest.Method   = Method.PUT;
            }
            saveAttributeRequest.AddJsonBody(systemSetting);

            var saveAttributeResponse = restClient.Execute(saveAttributeRequest);

            if (saveAttributeResponse.ErrorException != null)
            {
                throw saveAttributeResponse.ErrorException;
            }
        }
Ejemplo n.º 17
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);
            }
        }
Ejemplo n.º 18
0
        /// <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();
            Uri rockUri      = new Uri(txtRockUrl.Text);
            var validSchemes = new string[] { Uri.UriSchemeHttp, Uri.UriSchemeHttps };

            if (!validSchemes.Contains(rockUri.Scheme))
            {
                txtRockUrl.Text = "https://" + rockUri.AbsoluteUri;
            }

            RestClient restClient = new RestClient(txtRockUrl.Text);

            string userName = txtUsername.Text;
            string password = txtPassword.Password;
            string rockUrl  = txtRockUrl.Text;

            if (string.IsNullOrWhiteSpace(userName))
            {
                lblLoginWarning.Content    = "Username cannot be blank";
                lblLoginWarning.Visibility = Visibility.Visible;
                return;
            }

            // 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;
                restClient.LoginToRock(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;

                if (ee.Error != null)
                {
                    lblRockUrl.Visibility      = Visibility.Visible;
                    txtRockUrl.Visibility      = Visibility.Visible;
                    lblLoginWarning.Content    = ee.Error.Message;
                    lblLoginWarning.Visibility = Visibility.Visible;
                    return;
                }

                var getByUserNameRequest  = new RestRequest(string.Format("api/People/GetByUserName/{0}", userName));
                var getByUserNameResponse = restClient.Execute <Rock.Client.Person>(getByUserNameRequest);
                if (getByUserNameResponse.ErrorException != null)
                {
                    string message = getByUserNameResponse.ErrorException.Message;
                    if (getByUserNameResponse.ErrorException.InnerException != null)
                    {
                        message += "\n" + getByUserNameResponse.ErrorException.InnerException.Message;
                    }

                    lblRockUrl.Visibility      = Visibility.Visible;
                    txtRockUrl.Visibility      = Visibility.Visible;
                    lblLoginWarning.Content    = message;
                    lblLoginWarning.Visibility = Visibility.Visible;
                    return;
                }

                Rock.Client.Person person     = getByUserNameResponse.Data;
                RockConfig         rockConfig = RockConfig.Load();
                rockConfig.RockBaseUrl = rockUrl;
                rockConfig.Username    = userName;
                rockConfig.Password    = password;

                // Load any stored configuration settings
                rockConfig = this.LoadConfigurationFromSystemSetting(rockConfig);
                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);
                }
            };

            // set the cursor to Wait, disable the login button, and start the login background process
            this.Cursor        = Cursors.Wait;
            btnLogin.IsEnabled = false;
            bw.RunWorkerAsync();
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Loads this instance.
        /// </summary>
        /// <returns></returns>
        public static RockConfig Load()
        {
            try
            {
                if ( _rockConfig != null )
                {
                    return _rockConfig;
                }

                if ( File.Exists( fileName ) )
                {
                    FileStream fs = new FileStream( fileName, FileMode.OpenOrCreate );
                    try
                    {
                        DataContractSerializer s = new DataContractSerializer( typeof( RockConfig ) );
                        _rockConfig = s.ReadObject( fs ) as RockConfig;
                        return _rockConfig;
                    }
                    finally
                    {
                        fs.Close();
                    }
                }

                return new RockConfig();
            }
            catch
            {
                return new RockConfig();
            }
        }
Ejemplo n.º 20
0
        /// <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();
            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();
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Runs the report returning the number of statements that were generated
        /// </summary>
        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);

            UpdateProgress("Getting Recipients...");
            var recipientList = _rockRestClient.PostDataWithResult <Rock.StatementGenerator.StatementGeneratorOptions, List <Rock.StatementGenerator.StatementGeneratorRecipient> >("api/FinancialTransactions/GetStatementGeneratorRecipients", this.Options);

            this.RecordCount = recipientList.Count;
            this.RecordIndex = 0;

            var tasks = new List <Task>();

            // initialize the pdfStreams list for all the recipients so that it can be populated safely in the pdf generation threads
            List <Stream> pdfStreams = recipientList.Select(a => ( Stream )null).ToList();

            UpdateProgress("Getting Statements...");
            foreach (var recipent in recipientList)
            {
                StringBuilder sbUrl = new StringBuilder();
                sbUrl.Append($"api/FinancialTransactions/GetStatementGeneratorRecipientResult?GroupId={recipent.GroupId}");
                if (recipent.PersonId.HasValue)
                {
                    sbUrl.Append($"&PersonId={recipent.PersonId.Value}");
                }

                var recipentResult = _rockRestClient.PostDataWithResult <Rock.StatementGenerator.StatementGeneratorOptions, Rock.StatementGenerator.StatementGeneratorRecipientResult>(sbUrl.ToString(), this.Options);

                int documentNumber = this.RecordIndex;
                if ((this.Options.ExcludeOptedOutIndividuals && recipentResult.OptedOut) || (recipentResult.Html == null))
                {
                    // don't generate a statement if opted out or no statement html
                    pdfStreams[documentNumber] = null;
                }
                else
                {
                    var html       = recipentResult.Html;
                    var footerHtml = recipentResult.FooterHtml;

                    var task = Task.Run(() =>
                    {
                        var pdfGenerator = Pdf.From(html);

                        string footerHtmlPath = Path.ChangeExtension(Path.GetTempFileName(), "html");
                        string footerUrl      = null;

                        if (!string.IsNullOrEmpty(footerHtml))
                        {
                            File.WriteAllText(footerHtmlPath, footerHtml);
                            footerUrl = "file:///" + footerHtmlPath.Replace('\\', '/');
                        }

                        if (footerUrl != null)
                        {
                            pdfGenerator = pdfGenerator.WithObjectSetting("footer.htmlUrl", footerUrl);
                        }
                        else
                        {
                            pdfGenerator = pdfGenerator.WithObjectSetting("footer.fontSize", "10");
                            pdfGenerator = pdfGenerator.WithObjectSetting("footer.right", "Page [page] of [topage]");
                        }

                        var pdfBytes = pdfGenerator
                                       .WithMargins(PaperMargins.All(Length.Millimeters(10)))
                                       .WithoutOutline()
                                       .Portrait()
                                       .Content();

                        var pdfStream = new MemoryStream(pdfBytes);
                        System.Diagnostics.Debug.Assert(pdfStreams[documentNumber] == null, "Threading issue: pdfStream shouldn't already be assigned");
                        pdfStreams[documentNumber] = pdfStream;

                        if (File.Exists(footerHtmlPath))
                        {
                            File.Delete(footerHtmlPath);
                        }
                    });

                    tasks.Add(task);

                    tasks = tasks.Where(a => a.Status != TaskStatus.RanToCompletion).ToList();
                }

                this.RecordIndex++;
                UpdateProgress("Processing...");
            }

            Task.WaitAll(tasks.ToArray());

            UpdateProgress("Creating PDF...");
            this.RecordIndex = 0;

            // remove any statements that didn't get generated due to OptedOut
            pdfStreams       = pdfStreams.Where(a => a != null).ToList();
            this.RecordCount = pdfStreams.Count();

            int maxStatementsPerChapter = RecordCount;

            bool useChapters = this.Options.StatementsPerChapter.HasValue;

            if (this.Options.StatementsPerChapter.HasValue)
            {
                maxStatementsPerChapter = this.Options.StatementsPerChapter.Value;
            }

            if (maxStatementsPerChapter < 1)
            {
                // just in case they entered 0 or a negative number
                useChapters             = false;
                maxStatementsPerChapter = RecordCount;
            }

            int statementsInChapter = 0;
            int chapterIndex        = 1;

            PdfDocument resultPdf = new PdfDocument();

            try
            {
                if (pdfStreams.Any())
                {
                    var lastPdfStream = pdfStreams.LastOrDefault();
                    foreach (var pdfStream in pdfStreams)
                    {
                        UpdateProgress("Creating PDF...");
                        this.RecordIndex++;
                        PdfDocument pdfDocument = PdfReader.Open(pdfStream, PdfDocumentOpenMode.Import);

                        foreach (var pdfPage in pdfDocument.Pages.OfType <PdfPage>())
                        {
                            resultPdf.Pages.Add(pdfPage);
                        }

                        statementsInChapter++;
                        if (useChapters && ((statementsInChapter >= maxStatementsPerChapter) || pdfStream == lastPdfStream))
                        {
                            string filePath = string.Format(@"{0}\{1}-chapter{2}.pdf", this.Options.SaveDirectory, this.Options.BaseFileName, chapterIndex);
                            SavePdfFile(resultPdf, filePath);
                            resultPdf.Dispose();
                            resultPdf           = new PdfDocument();
                            statementsInChapter = 0;
                            chapterIndex++;
                        }
                    }

                    if (useChapters)
                    {
                        // just in case we still have statements that haven't been written to a pdf
                        if (statementsInChapter > 0)
                        {
                            string filePath = string.Format(@"{0}\{1}-chapter{2}.pdf", this.Options.SaveDirectory, this.Options.BaseFileName, chapterIndex);
                            SavePdfFile(resultPdf, filePath);
                        }
                    }
                    else
                    {
                        string filePath = string.Format(@"{0}\{1}.pdf", this.Options.SaveDirectory, this.Options.BaseFileName);
                        SavePdfFile(resultPdf, filePath);
                    }
                }
            }
            finally
            {
                resultPdf.Dispose();
            }

            UpdateProgress("Complete");

            return(this.RecordCount);
        }
Ejemplo n.º 22
0
        private DocumentLayout GetReportLayout(RockConfig rockConfig)
        {
            // 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);
                };
            }

            return(report);
        }
Ejemplo n.º 23
0
        /// <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);
        }
Ejemplo n.º 24
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);

            _contributionStatementOptionsREST = new Rock.Net.RestParameters.ContributionStatementOptions
            {
                StartDate      = Options.StartDate,
                EndDate        = Options.EndDate,
                AccountIds     = Options.AccountIds,
                PersonId       = Options.PersonId,
                OrderByZipCode = true
            };

            var organizationAddressAttribute = _rockRestClient.GetData <List <Rock.Model.Attribute> >("api/attributes", "Key eq 'OrganizationAddress'").FirstOrDefault();

            if (organizationAddressAttribute != null)
            {
                Guid locationGuid = Guid.Empty;
                if (Guid.TryParse(organizationAddressAttribute.DefaultValue, out locationGuid))
                {
                    _organizationAddressLocation = _rockRestClient.GetDataByGuid <Rock.Model.Location>("api/locations", locationGuid);
                }
            }

            // If we don't have a _organizationAddressLocation, just create an empty location
            _organizationAddressLocation = _organizationAddressLocation ?? new Rock.Model.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
                    var summaryTable = _transactionsDataTable.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);
            }
        }
Ejemplo n.º 25
0
        /// <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);

            _financialAccountList = _rockRestClient.GetData <List <Rock.Client.FinancialAccount> >("api/FinancialAccounts");
            var currencyDefinedType = _rockRestClient.GetDataByGuid <Rock.Client.DefinedType>("api/DefinedTypes", Rock.Client.SystemGuid.DefinedType.FINANCIAL_CURRENCY_TYPE.AsGuid());

            _currencyTypes = _rockRestClient.GetData <List <Rock.Client.DefinedValue> >($"api/DefinedValues?$filter=DefinedTypeId eq {currencyDefinedType.Id}");
            lstCashCurrencyTypes.Items.Clear();
            var defaultUnselectedCashCurrencyGuids = new Guid[] {
                Rock.Client.SystemGuid.DefinedValue.CURRENCY_TYPE_NONCASH.AsGuid()
            };

            var defaultNonCashCurrencyGuids = new Guid[] {
                Rock.Client.SystemGuid.DefinedValue.CURRENCY_TYPE_NONCASH.AsGuid()
            };

            // Default Cash Currency Types to
            foreach (var currencyType in _currencyTypes)
            {
                var cashCurrencyCheckbox = new CheckBox {
                    Tag = currencyType.Id, Content = currencyType.Value
                };
                if (ReportOptions.Current.CurrencyTypeIdsCash != null)
                {
                    cashCurrencyCheckbox.IsChecked = ReportOptions.Current.CurrencyTypeIdsCash.Contains(currencyType.Id);
                }
                else
                {
                    cashCurrencyCheckbox.IsChecked = !defaultUnselectedCashCurrencyGuids.Contains(currencyType.Guid);
                }

                lstCashCurrencyTypes.Items.Add(cashCurrencyCheckbox);

                var nonCashCurrencyCheckbox = new CheckBox {
                    Tag = currencyType.Id, Content = currencyType.Value
                };
                if (ReportOptions.Current.CurrencyTypeIdsNonCash != null)
                {
                    nonCashCurrencyCheckbox.IsChecked = ReportOptions.Current.CurrencyTypeIdsNonCash.Contains(currencyType.Id);
                }
                else
                {
                    nonCashCurrencyCheckbox.IsChecked = defaultNonCashCurrencyGuids.Contains(currencyType.Guid);
                }

                lstNonCashCurrencyTypes.Items.Add(nonCashCurrencyCheckbox);
            }

            // default to the currently configured CashAccountsId (if configured), or default to all
            _selectedAccountIds = ReportOptions.Current.TransactionAccountIds ?? _financialAccountList.Select(a => a.Id).ToList();

            cbShowInactive.IsChecked         = rockConfig.ShowInactiveAccounts;
            cbShowTaxDeductible.IsChecked    = rockConfig.ShowTaxDeductibleAccounts;
            cbShowNonTaxDeductible.IsChecked = rockConfig.ShowNonTaxDeductibleAccounts;

            ApplyFilter();

            lblAccountsCurrencyTypesWarning.Visibility = Visibility.Hidden;
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Saves the changes.
        /// </summary>
        /// <param name="showWarnings">if set to <c>true</c> [show warnings].</param>
        /// <returns></returns>
        private bool SaveChanges(bool showWarnings)
        {
            var rockConfig = RockConfig.Load();

            if (radAllPersons.IsChecked ?? false)
            {
                rockConfig.PersonSelectionOption = PersonSelectionOption.AllIndividuals;
                ReportOptions.Current.DataViewId = null;
                ReportOptions.Current.PersonId   = null;
            }
            else if (radDataView.IsChecked ?? false)
            {
                rockConfig.PersonSelectionOption = PersonSelectionOption.DataView;
                var selectedDataView = ddlDataView.SelectedValue as Rock.Client.DataView;
                if (selectedDataView != null)
                {
                    ReportOptions.Current.DataViewId = selectedDataView.Id;
                    ReportOptions.Current.PersonId   = null;
                }
                else
                {
                    if (showWarnings)
                    {
                        // no dataview is selected, show a warning message
                        lblWarning.Content    = "Please select a Dataview when 'Dataview' is checked.";
                        lblWarning.Visibility = Visibility.Visible;
                        return(false);
                    }
                }
            }
            else
            {
                rockConfig.PersonSelectionOption = PersonSelectionOption.SingleIndividual;
                PersonSearchResult personSearchResult = grdPersons.SelectedValue as PersonSearchResult;
                if (personSearchResult == null && grdPersons.Items.Count == 1)
                {
                    personSearchResult = grdPersons.Items[0] as PersonSearchResult;
                }

                if (personSearchResult != null)
                {
                    ReportOptions.Current.PersonId = personSearchResult.Id;
                }
                else
                {
                    if (showWarnings)
                    {
                        // no person is selected, show a warning message
                        lblWarning.Content    = "Please select a person when 'Single individual' is checked.";
                        lblWarning.Visibility = Visibility.Visible;
                        return(false);
                    }
                }
            }

            ReportOptions.Current.IncludeIndividualsWithNoAddress = ckIncludeIndividualsWithNoAddress.IsChecked ?? false;
            ReportOptions.Current.ExcludeInActiveIndividuals      = ckExcludeInActiveIndividuals.IsChecked ?? false;
            ReportOptions.Current.ExcludeOptedOutIndividuals      = ckExcludeOptedOutIndividuals.IsChecked ?? false;
            ReportOptions.Current.IncludeBusinesses = ckIncludeBusinesses.IsChecked ?? false;
            return(true);
        }
Ejemplo n.º 27
0
 /// <summary>
 /// Loads from the rock configuration.
 /// </summary>
 /// <param name="rockConfig">The rock configuration.</param>
 public static void LoadFromConfig(RockConfig rockConfig)
 {
     _current = rockConfig.LastReportOptions;
 }