コード例 #1
0
        /// <summary>
        /// Handles the Click event of the btnSaveEditPreferences control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSaveEditPreferences_Click(object sender, EventArgs e)
        {
            var rockContext   = new RockContext();
            var groupMember   = new GroupMemberService(rockContext).Get(hfGroupMemberId.Value.AsInteger());
            var personService = new PersonService(rockContext);
            var person        = personService.Get(groupMember.PersonId);

            var changes = new List <string>();

            int?orphanedPhotoId = null;

            if (person.PhotoId != imgProfilePhoto.BinaryFileId)
            {
                orphanedPhotoId = person.PhotoId;
                person.PhotoId  = imgProfilePhoto.BinaryFileId;

                if (orphanedPhotoId.HasValue)
                {
                    if (person.PhotoId.HasValue)
                    {
                        changes.Add("Modified the photo.");
                    }
                    else
                    {
                        changes.Add("Deleted the photo.");
                    }
                }
                else if (person.PhotoId.HasValue)
                {
                    changes.Add("Added a photo.");
                }

                // add or update the Photo Verify group to have this person as Pending since the photo was changed or deleted
                using (var photoRequestRockContext = new RockContext())
                {
                    GroupMemberService groupMemberService = new GroupMemberService(photoRequestRockContext);
                    Group photoRequestGroup = new GroupService(photoRequestRockContext).Get(Rock.SystemGuid.Group.GROUP_PHOTO_REQUEST.AsGuid());

                    var photoRequestGroupMember = groupMemberService.Queryable().Where(a => a.GroupId == photoRequestGroup.Id && a.PersonId == person.Id).FirstOrDefault();
                    if (photoRequestGroupMember == null)
                    {
                        photoRequestGroupMember             = new GroupMember();
                        photoRequestGroupMember.GroupId     = photoRequestGroup.Id;
                        photoRequestGroupMember.PersonId    = person.Id;
                        photoRequestGroupMember.GroupRoleId = photoRequestGroup.GroupType.DefaultGroupRoleId ?? -1;
                        groupMemberService.Add(photoRequestGroupMember);
                    }

                    photoRequestGroupMember.GroupMemberStatus = GroupMemberStatus.Pending;

                    photoRequestRockContext.SaveChanges();
                }
            }

            // Save the GroupMember Attributes
            groupMember.LoadAttributes();
            Rock.Attribute.Helper.GetEditValues(phGroupMemberAttributes, groupMember);

            // Save selected Person Attributes (The ones picked in Block Settings)
            var personAttributes = this.GetAttributeValue("PersonAttributes").SplitDelimitedValues().AsGuidList().Select(a => AttributeCache.Read(a));

            if (personAttributes.Any())
            {
                person.LoadAttributes(rockContext);
                foreach (var personAttribute in personAttributes)
                {
                    Control attributeControl = phPersonAttributes.FindControl(string.Format("attribute_field_{0}", personAttribute.Id));
                    if (attributeControl != null)
                    {
                        string originalValue = person.GetAttributeValue(personAttribute.Key);
                        string newValue      = personAttribute.FieldType.Field.GetEditValue(attributeControl, personAttribute.QualifierValues);

                        // Save Attribute value to the database
                        Rock.Attribute.Helper.SaveAttributeValue(person, personAttribute, newValue, rockContext);

                        // Check for changes to write to history
                        if ((originalValue ?? string.Empty).Trim() != (newValue ?? string.Empty).Trim())
                        {
                            string formattedOriginalValue = string.Empty;
                            if (!string.IsNullOrWhiteSpace(originalValue))
                            {
                                formattedOriginalValue = personAttribute.FieldType.Field.FormatValue(null, originalValue, personAttribute.QualifierValues, false);
                            }

                            string formattedNewValue = string.Empty;
                            if (!string.IsNullOrWhiteSpace(newValue))
                            {
                                formattedNewValue = personAttribute.FieldType.Field.FormatValue(null, newValue, personAttribute.QualifierValues, false);
                            }

                            History.EvaluateChange(changes, personAttribute.Name, formattedOriginalValue, formattedNewValue, personAttribute.FieldType.Field.IsSensitive());
                        }
                    }
                }
            }

            // Save everything else to the database in a db transaction
            rockContext.WrapTransaction(() =>
            {
                rockContext.SaveChanges();
                groupMember.SaveAttributeValues(rockContext);

                if (changes.Any())
                {
                    HistoryService.SaveChanges(
                        rockContext,
                        typeof(Person),
                        Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                        person.Id,
                        changes);
                }

                if (orphanedPhotoId.HasValue)
                {
                    BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                    var binaryFile = binaryFileService.Get(orphanedPhotoId.Value);
                    if (binaryFile != null)
                    {
                        // marked the old images as IsTemporary so they will get cleaned up later
                        binaryFile.IsTemporary = true;
                        rockContext.SaveChanges();
                    }
                }

                // if they used the ImageEditor, and cropped it, the uncropped file is still in BinaryFile. So clean it up
                if (imgProfilePhoto.CropBinaryFileId.HasValue)
                {
                    if (imgProfilePhoto.CropBinaryFileId != person.PhotoId)
                    {
                        BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                        var binaryFile = binaryFileService.Get(imgProfilePhoto.CropBinaryFileId.Value);
                        if (binaryFile != null && binaryFile.IsTemporary)
                        {
                            string errorMessage;
                            if (binaryFileService.CanDelete(binaryFile, out errorMessage))
                            {
                                binaryFileService.Delete(binaryFile);
                                rockContext.SaveChanges();
                            }
                        }
                    }
                }
            });

            ShowView(hfGroupId.Value.AsInteger(), hfGroupMemberId.Value.AsInteger());
        }
コード例 #2
0
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();

            rockContext.WrapTransaction(() =>
            {
                var personService = new PersonService(rockContext);
                var changes       = new List <string>();
                Person business   = null;

                if (int.Parse(hfBusinessId.Value) != 0)
                {
                    business = personService.Get(int.Parse(hfBusinessId.Value));
                }

                if (business == null)
                {
                    business = new Person();
                    personService.Add(business);
                    tbBusinessName.Text = tbBusinessName.Text.FixCase();
                }

                // Business Name
                History.EvaluateChange(changes, "Last Name", business.LastName, tbBusinessName.Text);
                business.LastName = tbBusinessName.Text;

                // Phone Number
                var businessPhoneTypeId = new DefinedValueService(rockContext).GetByGuid(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK)).Id;

                string oldPhoneNumber = string.Empty;
                string newPhoneNumber = string.Empty;

                var phoneNumber = business.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == businessPhoneTypeId);
                if (phoneNumber != null)
                {
                    oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                }

                if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                {
                    if (phoneNumber == null)
                    {
                        phoneNumber = new PhoneNumber {
                            NumberTypeValueId = businessPhoneTypeId
                        };
                        business.PhoneNumbers.Add(phoneNumber);
                    }
                    phoneNumber.CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                    phoneNumber.Number             = PhoneNumber.CleanNumber(pnbPhone.Number);
                    phoneNumber.IsMessagingEnabled = cbSms.Checked;
                    phoneNumber.IsUnlisted         = cbUnlisted.Checked;

                    newPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                }
                else
                {
                    if (phoneNumber != null)
                    {
                        business.PhoneNumbers.Remove(phoneNumber);
                        new PhoneNumberService(rockContext).Delete(phoneNumber);
                    }
                }

                History.EvaluateChange(
                    changes,
                    string.Format("{0} Phone", DefinedValueCache.GetName(businessPhoneTypeId)),
                    oldPhoneNumber,
                    newPhoneNumber);

                // Record Type - this is always "business". it will never change.
                business.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid()).Id;

                // Record Status
                int?newRecordStatusId = ddlRecordStatus.SelectedValueAsInt();
                History.EvaluateChange(changes, "Record Status", DefinedValueCache.GetName(business.RecordStatusValueId), DefinedValueCache.GetName(newRecordStatusId));
                business.RecordStatusValueId = newRecordStatusId;

                // Record Status Reason
                int?newRecordStatusReasonId = null;
                if (business.RecordStatusValueId.HasValue && business.RecordStatusValueId.Value == DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id)
                {
                    newRecordStatusReasonId = ddlReason.SelectedValueAsInt();
                }

                History.EvaluateChange(changes, "Record Status Reason", DefinedValueCache.GetName(business.RecordStatusReasonValueId), DefinedValueCache.GetName(newRecordStatusReasonId));
                business.RecordStatusReasonValueId = newRecordStatusReasonId;

                // Email
                business.IsEmailActive = true;
                History.EvaluateChange(changes, "Email", business.Email, tbEmail.Text);
                business.Email = tbEmail.Text.Trim();

                var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();
                History.EvaluateChange(changes, "EmailPreference", business.EmailPreference, newEmailPreference);
                business.EmailPreference = newEmailPreference;

                if (business.IsValid)
                {
                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(Person),
                                Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                business.Id,
                                changes);
                        }
                    }
                }

                // Add/Update Family Group
                var familyGroupType = GroupTypeCache.GetFamilyGroupType();
                int adultRoleId     = familyGroupType.Roles
                                      .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()))
                                      .Select(r => r.Id)
                                      .FirstOrDefault();
                var adultFamilyMember = UpdateGroupMember(business.Id, familyGroupType, business.LastName + " Business", ddlCampus.SelectedValueAsInt(), adultRoleId, rockContext);
                business.GivingGroup  = adultFamilyMember.Group;

                // Add/Update Known Relationship Group Type
                var knownRelationshipGroupType   = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid());
                int knownRelationshipOwnerRoleId = knownRelationshipGroupType.Roles
                                                   .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid()))
                                                   .Select(r => r.Id)
                                                   .FirstOrDefault();
                var knownRelationshipOwner = UpdateGroupMember(business.Id, knownRelationshipGroupType, "Known Relationship", null, knownRelationshipOwnerRoleId, rockContext);

                // Add/Update Implied Relationship Group Type
                var impliedRelationshipGroupType   = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_IMPLIED_RELATIONSHIPS.AsGuid());
                int impliedRelationshipOwnerRoleId = impliedRelationshipGroupType.Roles
                                                     .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_IMPLIED_RELATIONSHIPS_OWNER.AsGuid()))
                                                     .Select(r => r.Id)
                                                     .FirstOrDefault();
                var impliedRelationshipOwner = UpdateGroupMember(business.Id, impliedRelationshipGroupType, "Implied Relationship", null, impliedRelationshipOwnerRoleId, rockContext);

                rockContext.SaveChanges();

                // Location
                int workLocationTypeId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK).Id;

                var groupLocationService = new GroupLocationService(rockContext);
                var workLocation         = groupLocationService.Queryable("Location")
                                           .Where(gl =>
                                                  gl.GroupId == adultFamilyMember.Group.Id &&
                                                  gl.GroupLocationTypeValueId == workLocationTypeId)
                                           .FirstOrDefault();

                if (string.IsNullOrWhiteSpace(acAddress.Street1))
                {
                    if (workLocation != null)
                    {
                        groupLocationService.Delete(workLocation);
                        History.EvaluateChange(changes, "Address", workLocation.Location.ToString(), string.Empty);
                    }
                }
                else
                {
                    var oldValue = string.Empty;

                    var newLocation = new LocationService(rockContext).Get(
                        acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);

                    if (workLocation != null)
                    {
                        oldValue = workLocation.Location.ToString();
                    }
                    else
                    {
                        workLocation = new GroupLocation();
                        groupLocationService.Add(workLocation);
                        workLocation.GroupId = adultFamilyMember.Group.Id;
                        workLocation.GroupLocationTypeValueId = workLocationTypeId;
                    }
                    workLocation.Location          = newLocation;
                    workLocation.IsMailingLocation = true;

                    History.EvaluateChange(changes, "Address", oldValue, newLocation.ToString());
                }

                rockContext.SaveChanges();

                hfBusinessId.Value = business.Id.ToString();
            });

            var queryParams = new Dictionary <string, string>();

            queryParams.Add("businessId", hfBusinessId.Value);
            NavigateToCurrentPage(queryParams);
        }
コード例 #3
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="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            PageRoute        pageRoute;
            var              rockContext      = new RockContext();
            PageRouteService pageRouteService = new PageRouteService(rockContext);

            int pageRouteId = int.Parse(hfPageRouteId.Value);

            if (pageRouteId == 0)
            {
                pageRoute = new PageRoute();
                pageRouteService.Add(pageRoute);
            }
            else
            {
                pageRoute = pageRouteService.Get(pageRouteId);
            }

            pageRoute.Route    = tbRoute.Text.Trim();
            pageRoute.IsGlobal = cbIsGlobal.Checked;

            int selectedPageId = int.Parse(ppPage.SelectedValue);

            pageRoute.PageId = selectedPageId;

            if (!pageRoute.IsValid)
            {
                // Controls will render the error messages
                return;
            }

            int?siteId    = null;
            var pageCache = PageCache.Get(selectedPageId);

            if (pageCache != null && pageCache.Layout != null)
            {
                siteId = pageCache.Layout.SiteId;
            }

            var duplicateRoutes = pageRouteService
                                  .Queryable().AsNoTracking()
                                  .Where(r =>
                                         r.Route == pageRoute.Route &&
                                         r.Id != pageRoute.Id);

            if (siteId.HasValue)
            {
                duplicateRoutes = duplicateRoutes
                                  .Where(r =>
                                         r.Page != null &&
                                         r.Page.Layout != null &&
                                         r.Page.Layout.SiteId == siteId.Value);
            }

            if (duplicateRoutes.Any())
            {
                // Duplicate
                nbErrorMessage.Title   = "Duplicate Route";
                nbErrorMessage.Text    = "<p>There is already an existing route with this name for the selected page's site. Route names must be unique per site. Please choose a different route name.</p>";
                nbErrorMessage.Visible = true;
            }
            else
            {
                pageRoute.LoadAttributes(rockContext);

                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    if (!pageRoute.IsSystem)
                    {
                        Rock.Attribute.Helper.GetEditValues(phAttributes, pageRoute);
                        pageRoute.SaveAttributeValues(rockContext);
                    }
                });

                PageCache.FlushPage(pageCache.Id);

                Rock.Web.RockRouteHandler.ReregisterRoutes();
                NavigateToParentPage();
            }
        }
コード例 #4
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="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            Campus campus;
            var    rockContext         = new RockContext();
            var    campusService       = new CampusService(rockContext);
            var    locationService     = new LocationService(rockContext);
            var    locationCampusValue = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.LOCATION_TYPE_CAMPUS.AsGuid());

            int campusId = int.Parse(hfCampusId.Value);

            if (campusId == 0)
            {
                campus = new Campus();
                campusService.Add(campus);
            }
            else
            {
                campus = campusService.Get(campusId);
            }

            campus.Name        = tbCampusName.Text;
            campus.IsActive    = cbIsActive.Checked;
            campus.Description = tbDescription.Text;
            campus.Url         = tbUrl.Text;

            campus.PhoneNumber = tbPhoneNumber.Text;
            if (campus.Location == null)
            {
                var location = locationService.Queryable()
                               .Where(l =>
                                      l.Name.Equals(campus.Name, StringComparison.OrdinalIgnoreCase) &&
                                      l.LocationTypeValueId == locationCampusValue.Id)
                               .FirstOrDefault();
                if (location == null)
                {
                    location = new Location();
                    locationService.Add(location);
                }

                campus.Location = location;
            }

            campus.Location.Name = campus.Name;
            campus.Location.LocationTypeValueId = locationCampusValue.Id;

            string preValue = campus.Location.GetFullStreetAddress();

            acAddress.GetValues(campus.Location);
            string postValue = campus.Location.GetFullStreetAddress();

            campus.ShortCode = tbCampusCode.Text;

            var personService = new PersonService(rockContext);
            var leaderPerson  = personService.Get(ppCampusLeader.SelectedValue ?? 0);

            campus.LeaderPersonAliasId = leaderPerson != null ? leaderPerson.PrimaryAliasId : null;

            campus.ServiceTimes = kvlServiceTimes.Value;

            campus.LoadAttributes(rockContext);
            Rock.Attribute.Helper.GetEditValues(phAttributes, campus);

            if (!campus.IsValid && campus.Location.IsValid)
            {
                // Controls will render the error messages
                return;
            }

            rockContext.WrapTransaction(() =>
            {
                rockContext.SaveChanges();
                campus.SaveAttributeValues(rockContext);

                if (preValue != postValue && !string.IsNullOrWhiteSpace(campus.Location.Street1))
                {
                    locationService.Verify(campus.Location, true);
                }
            });

            Rock.Web.Cache.CampusCache.Flush(campus.Id);

            NavigateToParentPage();
        }
コード例 #5
0
        /// <summary>
        /// Handles the SaveClick event of the modalDetails control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void mdDetails_SaveClick(object sender, EventArgs e)
        {
            int categoryId = 0;

            if (hfIdValue.Value != string.Empty && !int.TryParse(hfIdValue.Value, out categoryId))
            {
                categoryId = 0;
            }

            var      rockContext = new RockContext();
            var      service     = new CategoryService(rockContext);
            Category category    = null;

            if (categoryId != 0)
            {
                category = service.Get(categoryId);
            }

            if (category == null)
            {
                category = new Category();

                if (_hasEntityTypeBlockSetting)
                {
                    category.EntityTypeId = _entityTypeId;
                    category.EntityTypeQualifierColumn = _entityCol;
                    category.EntityTypeQualifierValue  = _entityVal;
                }
                else
                {
                    category.EntityTypeId = entityTypePicker.SelectedEntityTypeId ?? 0;
                    category.EntityTypeQualifierColumn = tbEntityQualifierField.Text;
                    category.EntityTypeQualifierValue  = tbEntityQualifierValue.Text;
                }

                var lastCategory = GetUnorderedCategories()
                                   .OrderByDescending(c => c.Order).FirstOrDefault();
                category.Order = lastCategory != null ? lastCategory.Order + 1 : 0;

                service.Add(category);
            }

            category.Name             = tbName.Text;
            category.Description      = tbDescription.Text;
            category.ParentCategoryId = catpParentCategory.SelectedValueAsInt();
            category.IconCssClass     = tbIconCssClass.Text;
            category.HighlightColor   = tbHighlightColor.Text;

            category.LoadAttributes(rockContext);
            Rock.Attribute.Helper.GetEditValues(phAttributes, category);

            List <int> orphanedBinaryFileIdList = new List <int>();

            if (category.IsValid)
            {
                BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                foreach (int binaryFileId in orphanedBinaryFileIdList)
                {
                    var binaryFile = binaryFileService.Get(binaryFileId);
                    if (binaryFile != null)
                    {
                        // marked the old images as IsTemporary so they will get cleaned up later
                        binaryFile.IsTemporary = true;
                    }
                }

                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    category.SaveAttributeValues(rockContext);
                });

                CategoryCache.Flush(category.Id);

                hfIdValue.Value = string.Empty;
                mdDetails.Hide();

                BindGrid();
            }
        }
コード例 #6
0
        protected void btnNext_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (CurrentPageIndex == 0)
                {
                    string locationKey = GetLocationKey();
                    if (!string.IsNullOrEmpty(locationKey) && !_verifiedLocations.ContainsKey(locationKey))
                    {
                        using (var rockContext = new RockContext())
                        {
                            var location = new LocationService(rockContext).Get(acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);
                            _verifiedLocations.AddOrIgnore(locationKey, (location != null ? location.Id : (int?)null));
                        }
                    }
                }

                if (CurrentPageIndex < (attributeControls.Count + 1))
                {
                    CurrentPageIndex++;
                    CreateControls(true);
                }
                else
                {
                    if (GroupMembers.Any())
                    {
                        if (CurrentPageIndex == (attributeControls.Count + 1) && FindDuplicates())
                        {
                            CurrentPageIndex++;
                            CreateControls(true);
                        }
                        else
                        {
                            var rockContext = new RockContext();

                            Guid?parentGroupGuid = GetAttributeValue("ParentGroup").AsGuidOrNull();

                            rockContext.WrapTransaction(() =>
                            {
                                Group group = null;
                                if (_isFamilyGroupType)
                                {
                                    group = GroupService.SaveNewFamily(rockContext, GroupMembers, cpCampus.SelectedValueAsInt(), true);
                                }
                                else
                                {
                                    group = GroupService.SaveNewGroup(rockContext, _groupType.Id, parentGroupGuid, tbGroupName.Text, GroupMembers, null, true);
                                }

                                if (group != null)
                                {
                                    string locationKey = GetLocationKey();
                                    if (!string.IsNullOrEmpty(locationKey) && _verifiedLocations.ContainsKey(locationKey))
                                    {
                                        GroupService.AddNewGroupAddress(rockContext, group, _locationType.Guid.ToString(), _verifiedLocations[locationKey]);
                                    }
                                }
                            });

                            Response.Redirect(string.Format("~/Person/{0}", GroupMembers[0].Person.Id), false);
                        }
                    }
                }
            }
        }
コード例 #7
0
        protected void btnExportToFinancialEdge_Click(object sender, EventArgs e)
        {
            if (_financialBatch != null)
            {
                var rockContext = new RockContext();
                var feJournal   = new FEJournal();

                var items = feJournal.GetGlEntries(rockContext, _financialBatch, GetAttributeValue("JournalType"));

                if (items.Count > 0)
                {
                    //
                    // Set session for export file
                    //
                    feJournal.SetFinancialEdgeSessions(items, _financialBatch.Id.ToString());

                    //
                    // vars we need now
                    //
                    var financialBatch = new FinancialBatchService(rockContext).Get(_batchId);
                    var changes        = new History.HistoryChangeList();

                    //
                    // Close Batch if we're supposed to
                    //
                    if (GetAttributeValue("CloseBatch").AsBoolean())
                    {
                        History.EvaluateChange(changes, "Status", financialBatch.Status, BatchStatus.Closed);
                        financialBatch.Status = BatchStatus.Closed;
                    }

                    //
                    // Set Date Exported
                    //
                    financialBatch.LoadAttributes();
                    var oldDate = financialBatch.GetAttributeValue("rocks.kfs.FinancialEdge.DateExported");
                    var newDate = RockDateTime.Now;
                    History.EvaluateChange(changes, "Date Exported", oldDate, newDate.ToString());

                    //
                    // Save the changes
                    //
                    rockContext.WrapTransaction(() =>
                    {
                        if (changes.Any())
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(FinancialBatch),
                                Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                                financialBatch.Id,
                                changes);
                        }
                    });

                    financialBatch.SetAttributeValue("rocks.kfs.FinancialEdge.DateExported", newDate);
                    financialBatch.SaveAttributeValue("rocks.kfs.FinancialEdge.DateExported", rockContext);
                }
            }

            Response.Redirect(Request.RawUrl);
        }
コード例 #8
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="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            DataView dataView = null;

            var             rockContext = new RockContext();
            DataViewService service     = new DataViewService(rockContext);

            int dataViewId           = int.Parse(hfDataViewId.Value);
            int?origDataViewFilterId = null;

            if (dataViewId == 0)
            {
                dataView          = new DataView();
                dataView.IsSystem = false;
            }
            else
            {
                dataView             = service.Get(dataViewId);
                origDataViewFilterId = dataView.DataViewFilterId;
            }

            dataView.Name                  = tbName.Text;
            dataView.Description           = tbDescription.Text;
            dataView.TransformEntityTypeId = ddlTransform.SelectedValueAsInt();
            dataView.EntityTypeId          = etpEntityType.SelectedEntityTypeId;
            dataView.CategoryId            = cpCategory.SelectedValueAsInt();

            var newDataViewFilter = ReportingHelper.GetFilterFromControls(phFilters);


            if (!Page.IsValid)
            {
                return;
            }

            if (!dataView.IsValid)
            {
                // Controls will render the error messages
                return;
            }

            var adding = dataView.Id.Equals(0);

            if (adding)
            {
                service.Add(dataView);
            }

            rockContext.WrapTransaction(() =>
            {
                if (origDataViewFilterId.HasValue)
                {
                    // delete old report filter so that we can add the new filter (but with original guids), then drop the old filter
                    DataViewFilterService dataViewFilterService = new DataViewFilterService(rockContext);
                    DataViewFilter origDataViewFilter           = dataViewFilterService.Get(origDataViewFilterId.Value);

                    dataView.DataViewFilterId = null;
                    rockContext.SaveChanges();

                    DeleteDataViewFilter(origDataViewFilter, dataViewFilterService);
                }

                dataView.DataViewFilter = newDataViewFilter;
                rockContext.SaveChanges();
            });

            if (adding)
            {
                // add EDIT and ADMINISTRATE to the person who added the dataView
                Rock.Security.Authorization.AllowPerson(dataView, Authorization.EDIT, this.CurrentPerson, rockContext);
                Rock.Security.Authorization.AllowPerson(dataView, Authorization.ADMINISTRATE, this.CurrentPerson, rockContext);
            }

            var qryParams = new Dictionary <string, string>();

            qryParams["DataViewId"] = dataView.Id.ToString();
            NavigateToPage(RockPage.Guid, qryParams);
        }
コード例 #9
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="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!ValidateCampus())
            {
                // Error messaging handled by ValidateCampus
                return;
            }

            if (!IsFormValid())
            {
                return;
            }

            Campus campus;
            var    rockContext     = new RockContext();
            var    campusService   = new CampusService(rockContext);
            var    locationService = new LocationService(rockContext);

            int campusId = HiddenCampusId;

            if (campusId == 0)
            {
                campus = new Campus();
                campusService.Add(campus);
                var orders = campusService.Queryable()
                             .AsNoTracking()
                             .Select(t => t.Order)
                             .ToList();

                campus.Order = orders.Any() ? orders.Max(t => t) + 1 : 0;
            }
            else
            {
                campus = campusService.Get(campusId);
            }

            campus.Name                = tbCampusName.Text;
            campus.IsActive            = cbIsActive.Checked;
            campus.Description         = tbDescription.Text;
            campus.CampusStatusValueId = dvpCampusStatus.SelectedValueAsInt();
            campus.CampusTypeValueId   = dvpCampusType.SelectedValueAsInt();
            campus.Url         = urlCampus.Text;
            campus.PhoneNumber = pnbPhoneNumber.Number;
            campus.LocationId  = lpLocation.Location.Id;
            campus.ShortCode   = tbCampusCode.Text;
            campus.TimeZoneId  = ddlTimeZone.SelectedValue;

            var personService = new PersonService(rockContext);
            var leaderPerson  = personService.GetNoTracking(ppCampusLeader.SelectedValue ?? 0);

            campus.LeaderPersonAliasId = leaderPerson != null ? leaderPerson.PrimaryAliasId : null;

            campus.ServiceTimes = kvlServiceTimes.Value;


            // Remove any CampusSchedules that were removed in the UI
            var selectedSchedules = CampusSchedulesState.Select(s => s.Guid);
            var locationsToRemove = campus.CampusSchedules.Where(s => !selectedSchedules.Contains(s.Guid)).ToList();
            CampusScheduleService campusScheduleService = null;

            foreach (var campusSchedule in locationsToRemove)
            {
                campusScheduleService = campusScheduleService ?? new CampusScheduleService(rockContext);
                campus.CampusSchedules.Remove(campusSchedule);
                campusScheduleService.Delete(campusSchedule);
            }

            // Add/Update any CampusSchedules that were added or changed in the UI.
            foreach (var campusScheduleState in CampusSchedulesState)
            {
                var campusSchedule = campus.CampusSchedules.Where(s => s.Guid == campusScheduleState.Guid).FirstOrDefault();
                if (campusSchedule == null)
                {
                    campusSchedule = new CampusSchedule()
                    {
                        CampusId            = campus.Id,
                        ScheduleId          = campusScheduleState.ScheduleId,
                        ScheduleTypeValueId = campusScheduleState.ScheduleTypeId,
                        Order = campusScheduleState.Order,
                        Guid  = Guid.NewGuid()
                    };
                    campus.CampusSchedules.Add(campusSchedule);
                }
                else
                {
                    campusSchedule.ScheduleId          = campusScheduleState.ScheduleId;
                    campusSchedule.ScheduleTypeValueId = campusScheduleState.ScheduleTypeId;
                }
            }

            SaveCampusTopics(campus, rockContext);

            avcAttributes.GetEditValues(campus);

            if (!campus.IsValid && campus.Location.IsValid)
            {
                // Controls will render the error messages
                return;
            }

            rockContext.WrapTransaction(() =>
            {
                rockContext.SaveChanges();
                campus.SaveAttributeValues(rockContext);
            });

            NavigateToCurrentPage(new Dictionary <string, string> {
                { "CampusId", campus.Id.ToString() }
            });
        }
コード例 #10
0
        /// <summary>
        /// Handles the OnSave event of the masterPage control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void masterPage_OnSave(object sender, EventArgs e)
        {
            bool reloadPage = false;
            int  blockId    = Convert.ToInt32(PageParameter("BlockId"));

            if (!Page.IsValid)
            {
                return;
            }

            var rockContext = new RockContext();

            rockContext.WrapTransaction(() =>
            {
                var blockService = new Rock.Model.BlockService(rockContext);
                var block        = blockService.Get(blockId);

                block.LoadAttributes();

                block.Name                = tbBlockName.Text;
                block.CssClass            = tbCssClass.Text;
                block.PreHtml             = cePreHtml.Text;
                block.PostHtml            = cePostHtml.Text;
                block.OutputCacheDuration = 0; //Int32.Parse( tbCacheDuration.Text );

                avcAttributes.GetEditValues(block);
                avcMobileAttributes.GetEditValues(block);
                avcAdvancedAttributes.GetEditValues(block);

                foreach (var kvp in CustomSettingsProviders)
                {
                    kvp.Key.WriteSettingsToEntity(block, kvp.Value, rockContext);
                }

                SaveCustomColumnsConfigToViewState();
                if (this.CustomGridColumnsConfigState != null && this.CustomGridColumnsConfigState.ColumnsConfig.Any())
                {
                    if (!block.Attributes.Any(a => a.Key == CustomGridColumnsConfig.AttributeKey))
                    {
                        block.Attributes.Add(CustomGridColumnsConfig.AttributeKey, null);
                    }

                    var customGridColumnsJSON = this.CustomGridColumnsConfigState.ToJson();
                    if (block.GetAttributeValue(CustomGridColumnsConfig.AttributeKey) != customGridColumnsJSON)
                    {
                        block.SetAttributeValue(CustomGridColumnsConfig.AttributeKey, customGridColumnsJSON);

                        // if the CustomColumns changed, reload the whole page so that we can avoid issues with columns changing between postbacks
                        reloadPage = true;
                    }
                }
                else
                {
                    if (block.Attributes.Any(a => a.Key == CustomGridColumnsConfig.AttributeKey))
                    {
                        if (block.GetAttributeValue(CustomGridColumnsConfig.AttributeKey) != null)
                        {
                            // if the CustomColumns were removed, reload the whole page so that we can avoid issues with columns changing between postbacks
                            reloadPage = true;
                        }

                        block.SetAttributeValue(CustomGridColumnsConfig.AttributeKey, null);
                    }
                }

                // Save the custom action configs
                SaveCustomActionsConfigToViewState();

                if (CustomActionsConfigState != null && CustomActionsConfigState.Any())
                {
                    if (!block.Attributes.Any(a => a.Key == CustomGridOptionsConfig.CustomActionsConfigsAttributeKey))
                    {
                        block.Attributes.Add(CustomGridOptionsConfig.CustomActionsConfigsAttributeKey, null);
                    }

                    var json = CustomActionsConfigState.ToJson();

                    if (block.GetAttributeValue(CustomGridOptionsConfig.CustomActionsConfigsAttributeKey) != json)
                    {
                        block.SetAttributeValue(CustomGridOptionsConfig.CustomActionsConfigsAttributeKey, json);

                        // if the actions changed, reload the whole page so that we can avoid issues with launchers changing between postbacks
                        reloadPage = true;
                    }
                }
                else
                {
                    if (block.Attributes.Any(a => a.Key == CustomGridOptionsConfig.CustomActionsConfigsAttributeKey))
                    {
                        if (block.GetAttributeValue(CustomGridOptionsConfig.CustomActionsConfigsAttributeKey) != null)
                        {
                            // if the actions were removed, reload the whole page so that we can avoid issues with launchers changing between postbacks
                            reloadPage = true;
                        }

                        block.SetAttributeValue(CustomGridOptionsConfig.CustomActionsConfigsAttributeKey, null);
                    }
                }

                if (tglEnableStickyHeader.Checked)
                {
                    if (!block.Attributes.Any(a => a.Key == CustomGridOptionsConfig.EnableStickyHeadersAttributeKey))
                    {
                        block.Attributes.Add(CustomGridOptionsConfig.EnableStickyHeadersAttributeKey, null);
                    }
                }

                if (block.GetAttributeValue(CustomGridOptionsConfig.EnableStickyHeadersAttributeKey).AsBoolean() != tglEnableStickyHeader.Checked)
                {
                    block.SetAttributeValue(CustomGridOptionsConfig.EnableStickyHeadersAttributeKey, tglEnableStickyHeader.Checked.ToTrueFalse());

                    // if EnableStickyHeaders changed, reload the page
                    reloadPage = true;
                }

                // Save the default launcher enabled setting
                var isDefaultLauncherEnabled = tglEnableDefaultWorkflowLauncher.Checked;

                if (isDefaultLauncherEnabled && !block.Attributes.Any(a => a.Key == CustomGridOptionsConfig.EnableDefaultWorkflowLauncherAttributeKey))
                {
                    block.Attributes.Add(CustomGridOptionsConfig.EnableDefaultWorkflowLauncherAttributeKey, null);
                }

                if (block.GetAttributeValue(CustomGridOptionsConfig.EnableDefaultWorkflowLauncherAttributeKey).AsBoolean() != isDefaultLauncherEnabled)
                {
                    block.SetAttributeValue(CustomGridOptionsConfig.EnableDefaultWorkflowLauncherAttributeKey, isDefaultLauncherEnabled.ToTrueFalse());

                    // since the setting changed, reload the page
                    reloadPage = true;
                }

                rockContext.SaveChanges();
                block.SaveAttributeValues(rockContext);

                // If this is a page menu block then we need to also flush the LavaTemplateCache for the block ID
                if (block.BlockType.Guid == Rock.SystemGuid.BlockType.PAGE_MENU.AsGuid())
                {
                    var cacheKey = string.Format("Rock:PageMenu:{0}", block.Id);
                    LavaTemplateCache.Remove(cacheKey);
                }

                StringBuilder scriptBuilder = new StringBuilder();

                if (reloadPage)
                {
                    scriptBuilder.AppendLine("window.parent.location.reload();");
                }
                else
                {
                    scriptBuilder.AppendLine(string.Format("window.parent.Rock.controls.modal.close('BLOCK_UPDATED:{0}');", blockId));
                }

                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "close-modal", scriptBuilder.ToString(), true);
            });
        }
コード例 #11
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="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            EventCalendar eventCalendar;

            using (var rockContext = new RockContext())
            {
                EventCalendarService eventCalendarService = new EventCalendarService(rockContext);
                EventCalendarContentChannelService eventCalendarContentChannelService = new EventCalendarContentChannelService(rockContext);
                ContentChannelService     contentChannelService = new ContentChannelService(rockContext);
                AttributeService          attributeService      = new AttributeService(rockContext);
                AttributeQualifierService qualifierService      = new AttributeQualifierService(rockContext);

                int eventCalendarId = int.Parse(hfEventCalendarId.Value);

                if (eventCalendarId == 0)
                {
                    eventCalendar = new EventCalendar();
                    eventCalendarService.Add(eventCalendar);
                }
                else
                {
                    eventCalendar = eventCalendarService.Get(eventCalendarId);
                }

                eventCalendar.IsActive     = cbActive.Checked;
                eventCalendar.Name         = tbName.Text;
                eventCalendar.Description  = tbDescription.Text;
                eventCalendar.IconCssClass = tbIconCssClass.Text;

                eventCalendar.LoadAttributes();
                Rock.Attribute.Helper.GetEditValues(phAttributes, eventCalendar);

                if (!eventCalendar.IsValid)
                {
                    // Controls will render the error messages
                    return;
                }

                // need WrapTransaction due to Attribute saves
                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    eventCalendar.SaveAttributeValues(rockContext);

                    var dbChannelGuids = eventCalendarContentChannelService.Queryable()
                                         .Where(c => c.EventCalendarId == eventCalendar.Id)
                                         .Select(c => c.Guid)
                                         .ToList();

                    var uiChannelGuids = ContentChannelsState.Select(c => c.Key).ToList();

                    var toDelete = eventCalendarContentChannelService
                                   .Queryable()
                                   .Where(c =>
                                          dbChannelGuids.Contains(c.Guid) &&
                                          !uiChannelGuids.Contains(c.Guid));

                    eventCalendarContentChannelService.DeleteRange(toDelete);
                    contentChannelService.Queryable()
                    .Where(c =>
                           uiChannelGuids.Contains(c.Guid) &&
                           !dbChannelGuids.Contains(c.Guid))
                    .ToList()
                    .ForEach(c =>
                    {
                        var eventCalendarContentChannel              = new EventCalendarContentChannel();
                        eventCalendarContentChannel.EventCalendarId  = eventCalendar.Id;
                        eventCalendarContentChannel.ContentChannelId = c.Id;
                        eventCalendarContentChannelService.Add(eventCalendarContentChannel);
                    });

                    rockContext.SaveChanges();

                    /* Save Event Attributes */
                    string qualifierValue = eventCalendar.Id.ToString();
                    SaveAttributes(new EventCalendarItem().TypeId, "EventCalendarId", qualifierValue, EventAttributesState, rockContext);

                    // Reload calendar and make sure that the person who may have just added a calendar has security to view/edit/administrate the calendar
                    eventCalendar = eventCalendarService.Get(eventCalendar.Id);
                    if (eventCalendar != null)
                    {
                        if (!eventCalendar.IsAuthorized(Authorization.VIEW, CurrentPerson))
                        {
                            eventCalendar.AllowPerson(Authorization.VIEW, CurrentPerson, rockContext);
                        }
                        if (!eventCalendar.IsAuthorized(Authorization.EDIT, CurrentPerson))
                        {
                            eventCalendar.AllowPerson(Authorization.EDIT, CurrentPerson, rockContext);
                        }
                        if (!eventCalendar.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson))
                        {
                            eventCalendar.AllowPerson(Authorization.ADMINISTRATE, CurrentPerson, rockContext);
                        }
                    }
                });
            }

            // Redirect back to same page so that item grid will show any attributes that were selected to show on grid
            var qryParams = new Dictionary <string, string>();

            qryParams["EventCalendarId"] = eventCalendar.Id.ToString();
            NavigateToPage(RockPage.Guid, qryParams);
        }
コード例 #12
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="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            PageRoute        pageRoute;
            var              rockContext      = new RockContext();
            PageRouteService pageRouteService = new PageRouteService(rockContext);

            int pageRouteId = int.Parse(hfPageRouteId.Value);

            if (pageRouteId == 0)
            {
                pageRoute = new PageRoute();
                pageRouteService.Add(pageRoute);
            }
            else
            {
                pageRoute = pageRouteService.Get(pageRouteId);
            }

            pageRoute.Route = tbRoute.Text.Trim();
            int selectedPageId = int.Parse(ppPage.SelectedValue);

            pageRoute.PageId = selectedPageId;

            if (!pageRoute.IsValid)
            {
                // Controls will render the error messages
                return;
            }

            int?siteId    = null;
            var pageCache = PageCache.Get(selectedPageId);

            if (pageCache != null && pageCache.Layout != null)
            {
                siteId = pageCache.Layout.SiteId;
            }

            var duplicateRoutes = pageRouteService
                                  .Queryable().AsNoTracking()
                                  .Where(r =>
                                         r.Route == pageRoute.Route &&
                                         r.Id != pageRoute.Id);

            if (siteId.HasValue)
            {
                duplicateRoutes = duplicateRoutes
                                  .Where(r =>
                                         r.Page != null &&
                                         r.Page.Layout != null &&
                                         r.Page.Layout.SiteId == siteId.Value);
            }

            if (duplicateRoutes.Any())
            {
                // Duplicate
                nbErrorMessage.Title   = "Duplicate Route";
                nbErrorMessage.Text    = "<p>There is already an existing route with this name for the selected page's site. Route names must be unique per site. Please choose a different route name.</p>";
                nbErrorMessage.Visible = true;
            }
            else
            {
                pageRoute.LoadAttributes(rockContext);

                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    if (!pageRoute.IsSystem)
                    {
                        Rock.Attribute.Helper.GetEditValues(phAttributes, pageRoute);
                        pageRoute.SaveAttributeValues(rockContext);
                    }
                });
                // Remove previous route
                var oldRoute = RouteTable.Routes.OfType <Route>().FirstOrDefault(a => a.RouteIds().Contains(pageRoute.Id));
                if (oldRoute != null)
                {
                    var pageAndRouteIds = oldRoute.DataTokens["PageRoutes"] as List <Rock.Web.PageAndRouteId>;
                    pageAndRouteIds = pageAndRouteIds.Where(p => p.RouteId != pageRoute.Id).ToList();
                    if (pageAndRouteIds.Any())
                    {
                        oldRoute.DataTokens["PageRoutes"] = pageAndRouteIds;
                    }
                    else
                    {
                        RouteTable.Routes.Remove(oldRoute);
                    }
                }

                // Remove the '{shortlink}' route (will be added back after specific routes)
                var shortLinkRoute = RouteTable.Routes.OfType <Route>().Where(r => r.Url == "{shortlink}").FirstOrDefault();
                if (shortLinkRoute != null)
                {
                    RouteTable.Routes.Remove(shortLinkRoute);
                }

                // Add new route
                var pageAndRouteId = new Rock.Web.PageAndRouteId {
                    PageId = pageRoute.PageId, RouteId = pageRoute.Id
                };
                var existingRoute = RouteTable.Routes.OfType <Route>().FirstOrDefault(r => r.Url == pageRoute.Route);
                if (existingRoute != null)
                {
                    var pageAndRouteIds = existingRoute.DataTokens["PageRoutes"] as List <Rock.Web.PageAndRouteId>;
                    pageAndRouteIds.Add(pageAndRouteId);
                    existingRoute.DataTokens["PageRoutes"] = pageAndRouteIds;
                }
                else
                {
                    RouteTable.Routes.AddPageRoute(pageRoute.Route, pageAndRouteId);
                }

                RouteTable.Routes.Add(new Route("{shortlink}", new Rock.Web.RockRouteHandler()));

                NavigateToParentPage();
            }
        }
コード例 #13
0
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();

            var txnService        = new FinancialTransactionService(rockContext);
            var txnDetailService  = new FinancialTransactionDetailService(rockContext);
            var txnImageService   = new FinancialTransactionImageService(rockContext);
            var binaryFileService = new BinaryFileService(rockContext);

            FinancialTransaction txn = null;

            int?txnId   = hfTransactionId.Value.AsIntegerOrNull();
            int?batchId = hfBatchId.Value.AsIntegerOrNull();

            if (txnId.HasValue)
            {
                txn = txnService.Get(txnId.Value);
            }

            if (txn == null)
            {
                txn = new FinancialTransaction();
                txnService.Add(txn);
                txn.BatchId = batchId;
            }

            if (txn != null)
            {
                if (ppAuthorizedPerson.PersonId.HasValue)
                {
                    txn.AuthorizedPersonAliasId = ppAuthorizedPerson.PersonAliasId;
                }

                txn.TransactionDateTime    = dtTransactionDateTime.SelectedDateTime;
                txn.TransactionTypeValueId = ddlTransactionType.SelectedValue.AsInteger();
                txn.SourceTypeValueId      = ddlSourceType.SelectedValueAsInt();

                Guid?gatewayGuid = cpPaymentGateway.SelectedValueAsGuid();
                if (gatewayGuid.HasValue)
                {
                    var gatewayEntity = EntityTypeCache.Read(gatewayGuid.Value);
                    if (gatewayEntity != null)
                    {
                        txn.GatewayEntityTypeId = gatewayEntity.Id;
                    }
                    else
                    {
                        txn.GatewayEntityTypeId = null;
                    }
                }
                else
                {
                    txn.GatewayEntityTypeId = null;
                }

                txn.TransactionCode       = tbTransactionCode.Text;
                txn.CurrencyTypeValueId   = ddlCurrencyType.SelectedValueAsInt();
                txn.CreditCardTypeValueId = ddlCreditCardType.SelectedValueAsInt();
                txn.Summary = tbSummary.Text;

                if (!Page.IsValid || !txn.IsValid)
                {
                    return;
                }

                foreach (var txnDetail in TransactionDetailsState)
                {
                    if (!txnDetail.IsValid)
                    {
                        return;
                    }
                }

                rockContext.WrapTransaction(() =>
                {
                    // Save the transaction
                    rockContext.SaveChanges();

                    // Delete any transaction details that were removed
                    var txnDetailsInDB = txnDetailService.Queryable().Where(a => a.TransactionId.Equals(txn.Id)).ToList();
                    var deletedDetails = from txnDetail in txnDetailsInDB
                                         where !TransactionDetailsState.Select(d => d.Guid).Contains(txnDetail.Guid)
                                         select txnDetail;
                    deletedDetails.ToList().ForEach(txnDetail =>
                    {
                        txnDetailService.Delete(txnDetail);
                    });
                    rockContext.SaveChanges();

                    // Save Transaction Details
                    foreach (var editorTxnDetail in TransactionDetailsState)
                    {
                        // Add or Update the activity type
                        var txnDetail = txn.TransactionDetails.FirstOrDefault(d => d.Guid.Equals(editorTxnDetail.Guid));
                        if (txnDetail == null)
                        {
                            txnDetail      = new FinancialTransactionDetail();
                            txnDetail.Guid = editorTxnDetail.Guid;
                            txn.TransactionDetails.Add(txnDetail);
                        }
                        txnDetail.AccountId = editorTxnDetail.AccountId;
                        txnDetail.Amount    = UseSimpleAccountMode ? tbSingleAccountAmount.Text.AsDecimal() : editorTxnDetail.Amount;
                        txnDetail.Summary   = editorTxnDetail.Summary;
                    }
                    rockContext.SaveChanges();

                    // Delete any transaction images that were removed
                    var orphanedBinaryFileIds = new List <int>();
                    var txnImagesInDB         = txnImageService.Queryable().Where(a => a.TransactionId.Equals(txn.Id)).ToList();
                    foreach (var txnImage in txnImagesInDB.Where(i => !TransactionImagesState.Contains(i.BinaryFileId)))
                    {
                        orphanedBinaryFileIds.Add(txnImage.BinaryFileId);
                        txnImageService.Delete(txnImage);
                    }

                    // Save Transaction Images
                    int imageOrder = 0;
                    foreach (var binaryFileId in TransactionImagesState)
                    {
                        // Add or Update the activity type
                        var txnImage = txnImagesInDB.FirstOrDefault(i => i.BinaryFileId == binaryFileId);
                        if (txnImage == null)
                        {
                            txnImage = new FinancialTransactionImage();
                            txnImage.TransactionId = txn.Id;
                            txn.Images.Add(txnImage);
                        }
                        txnImage.BinaryFileId = binaryFileId;
                        txnImage.Order        = imageOrder;
                        imageOrder++;
                    }
                    rockContext.SaveChanges();

                    // Make sure updated binary files are not temporary
                    foreach (var binaryFile in binaryFileService.Queryable().Where(f => TransactionImagesState.Contains(f.Id)))
                    {
                        binaryFile.IsTemporary = false;
                    }

                    // Delete any orphaned images
                    foreach (var binaryFile in binaryFileService.Queryable().Where(f => orphanedBinaryFileIds.Contains(f.Id)))
                    {
                        binaryFileService.Delete(binaryFile);
                    }

                    rockContext.SaveChanges();
                });

                // Save selected options to session state in order to prefill values for next added txn
                Session["NewTxnDefault_BatchId"]             = txn.BatchId;
                Session["NewTxnDefault_TransactionDateTime"] = txn.TransactionDateTime;
                Session["NewTxnDefault_TransactionType"]     = txn.TransactionTypeValueId;
                Session["NewTxnDefault_SourceType"]          = txn.SourceTypeValueId;
                Session["NewTxnDefault_CurrencyType"]        = txn.CurrencyTypeValueId;
                Session["NewTxnDefault_CreditCardType"]      = txn.CreditCardTypeValueId;
                if (TransactionDetailsState.Count() == 1)
                {
                    Session["NewTxnDefault_Account"] = TransactionDetailsState.First().AccountId;
                }
                else
                {
                    Session.Remove("NewTxnDefault_Account");
                }

                // Requery the batch to support EF navigation properties
                var savedTxn = GetTransaction(txn.Id);
                ShowReadOnlyDetails(savedTxn);
            }
        }
コード例 #14
0
        /// <summary>
        /// Handles the Click event to save the prayer request.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!IsValid())
            {
                return;
            }

            bool isAutoApproved          = GetAttributeValue("EnableAutoApprove").AsBoolean();
            bool defaultAllowComments    = GetAttributeValue("DefaultAllowCommentsSetting").AsBoolean();
            bool isPersonMatchingEnabled = GetAttributeValue("EnablePersonMatching").AsBoolean();
            bool isNoteCreated           = false;

            PrayerRequest prayerRequest = new PrayerRequest {
                Id = 0, IsActive = true, IsApproved = isAutoApproved, AllowComments = defaultAllowComments
            };

            var rockContext = new RockContext();
            PrayerRequestService prayerRequestService = new PrayerRequestService(rockContext);

            prayerRequestService.Add(prayerRequest);
            prayerRequest.EnteredDateTime = RockDateTime.Now;

            if (isAutoApproved)
            {
                prayerRequest.ApprovedByPersonAliasId = CurrentPersonAliasId;
                prayerRequest.ApprovedOnDateTime      = RockDateTime.Now;
                var expireDays = Convert.ToDouble(GetAttributeValue("ExpireDays"));
                prayerRequest.ExpirationDate = RockDateTime.Now.AddDays(expireDays);
            }

            // Now record all the bits...
            // Make sure the Category is hydrated so it's included for any Lava processing
            Category category;
            int?     categoryId          = bddlCategory.SelectedValueAsInt();
            Guid     defaultCategoryGuid = GetAttributeValue("DefaultCategory").AsGuid();

            if (categoryId == null && !defaultCategoryGuid.IsEmpty())
            {
                category   = new CategoryService(rockContext).Get(defaultCategoryGuid);
                categoryId = category.Id;
            }
            else
            {
                category = new CategoryService(rockContext).Get(categoryId.Value);
            }

            prayerRequest.CategoryId = categoryId;
            prayerRequest.Category   = category;

            var personContext = this.ContextEntity <Person>();

            if (personContext == null)
            {
                Person person = null;
                if (isPersonMatchingEnabled)
                {
                    var personService = new PersonService(new RockContext());
                    person = personService.FindPerson(new PersonService.PersonMatchQuery(tbFirstName.Text, tbLastName.Text, tbEmail.Text, pnbPhone.Number), false, true, false);
                }

                if (person != null)
                {
                    prayerRequest.RequestedByPersonAliasId = person.PrimaryAliasId;
                    prayerRequest.FirstName = string.IsNullOrEmpty(person.NickName) ? person.FirstName : person.NickName;
                    prayerRequest.LastName  = person.LastName;
                    prayerRequest.Email     = person.Email;
                }
                else
                {
                    prayerRequest.RequestedByPersonAliasId = CurrentPersonAliasId;
                    prayerRequest.FirstName = tbFirstName.Text;
                    prayerRequest.LastName  = tbLastName.Text;
                    prayerRequest.Email     = tbEmail.Text;
                    if (!string.IsNullOrEmpty(pnbPhone.Text))
                    {
                        isNoteCreated = true;
                    }
                }
            }
            else
            {
                prayerRequest.RequestedByPersonAliasId = personContext.PrimaryAliasId;
                prayerRequest.FirstName = string.IsNullOrEmpty(personContext.NickName) ? personContext.FirstName : personContext.NickName;
                prayerRequest.LastName  = personContext.LastName;
                prayerRequest.Email     = personContext.Email;
            }

            prayerRequest.CampusId = cpCampus.SelectedCampusId;

            prayerRequest.Text = dtbRequest.Text;

            if (this.EnableUrgentFlag)
            {
                prayerRequest.IsUrgent = cbIsUrgent.Checked;
            }
            else
            {
                prayerRequest.IsUrgent = false;
            }

            if (this.EnableCommentsFlag)
            {
                prayerRequest.AllowComments = cbAllowComments.Checked;
            }

            if (this.EnablePublicDisplayFlag)
            {
                prayerRequest.IsPublic = cbAllowPublicDisplay.Checked;
            }
            else
            {
                prayerRequest.IsPublic = this.DefaultToPublic;
            }

            if (!Page.IsValid)
            {
                return;
            }

            prayerRequest.LoadAttributes(rockContext);
            Rock.Attribute.Helper.GetEditValues(phAttributes, prayerRequest);

            if (!prayerRequest.IsValid)
            {
                // field controls render error messages
                return;
            }

            rockContext.WrapTransaction(() =>
            {
                rockContext.SaveChanges();
                prayerRequest.SaveAttributeValues(rockContext);

                if (isNoteCreated)
                {
                    var noteService = new NoteService(rockContext);
                    var noteType    = new NoteTypeService(rockContext).Get(Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid());
                    var note        = new Note()
                    {
                        Caption    = "Mobile Phone",
                        Text       = pnbPhone.Text,
                        EntityId   = prayerRequest.Id,
                        NoteTypeId = noteType.Id
                    };
                    noteService.Add(note);
                    rockContext.SaveChanges();
                }
            });


            StartWorkflow(prayerRequest, rockContext);

            bool isNavigateToParent = GetAttributeValue("NavigateToParentOnSave").AsBoolean();

            if (isNavigateToParent)
            {
                NavigateToParentPage();
            }
            else if (GetAttributeValue("RefreshPageOnSave").AsBoolean())
            {
                NavigateToCurrentPage(this.PageParameters().Where(a => a.Value is string).ToDictionary(k => k.Key, v => v.Value.ToString()));
            }
            else
            {
                pnlForm.Visible    = false;
                pnlReceipt.Visible = true;

                // Build success text that is Lava capable
                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                mergeFields.Add("PrayerRequest", prayerRequest);
                nbMessage.Text = GetAttributeValue("SaveSuccessText").ResolveMergeFields(mergeFields);

                // Resolve any dynamic url references
                string appRoot   = ResolveRockUrl("~/");
                string themeRoot = ResolveRockUrl("~~/");
                nbMessage.Text = nbMessage.Text.Replace("~~/", themeRoot).Replace("~/", appRoot);
            }
        }
コード例 #15
0
        /// <summary>
        /// Updates the workflow.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="recommendation">The recommendation.</param>
        /// <param name="reportLink">The report link.</param>
        /// <param name="reportStatus">The report status.</param>
        /// <param name="rockContext">The rock context.</param>
        private static void UpdateWorkflow(int id, string recommendation, string documentId, string reportStatus, RockContext rockContext)
        {
            var workflowService = new WorkflowService(rockContext);
            var workflow        = new WorkflowService(rockContext).Get(id);

            if (workflow != null && workflow.IsActive)
            {
                workflow.LoadAttributes();
                if (workflow.Attributes.ContainsKey("ReportStatus"))
                {
                    if (workflow.GetAttributeValue("ReportStatus").IsNotNullOrWhiteSpace() && reportStatus.IsNullOrWhiteSpace())
                    {
                        // Don't override current values if Webhook is older than current values
                        return;
                    }
                }

                if (workflow.Attributes.ContainsKey("Report"))
                {
                    if (workflow.GetAttributeValue("Report").IsNotNullOrWhiteSpace() && documentId.IsNullOrWhiteSpace())
                    {
                        // Don't override current values if Webhook is older than current values
                        return;
                    }
                }

                // Save the recommendation
                if (!string.IsNullOrWhiteSpace(recommendation))
                {
                    if (SaveAttributeValue(workflow, "ReportRecommendation", recommendation,
                                           FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT.AsGuid()), rockContext,
                                           new Dictionary <string, string> {
                        { "ispassword", "false" }
                    }))
                    {
                    }
                }
                // Save the report link
                if (documentId.IsNotNullOrWhiteSpace())
                {
                    int entityTypeId = EntityTypeCache.Get(typeof(Checkr)).Id;
                    if (SaveAttributeValue(workflow, "Report", $"{entityTypeId},{documentId}",
                                           FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT.AsGuid()), rockContext,
                                           new Dictionary <string, string> {
                        { "ispassword", "false" }
                    }))
                    {
                    }
                }

                if (!string.IsNullOrWhiteSpace(reportStatus))
                {
                    // Save the status
                    if (SaveAttributeValue(workflow, "ReportStatus", reportStatus,
                                           FieldTypeCache.Get(Rock.SystemGuid.FieldType.SINGLE_SELECT.AsGuid()), rockContext,
                                           new Dictionary <string, string> {
                        { "fieldtype", "ddl" }, { "values", "Pass,Fail,Review" }
                    }))
                    {
                    }
                }

                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    workflow.SaveAttributeValues(rockContext);
                    foreach (var activity in workflow.Activities)
                    {
                        activity.SaveAttributeValues(rockContext);
                    }
                });
            }

            rockContext.SaveChanges();

            List <string> workflowErrors;

            workflowService.Process(workflow, out workflowErrors);
        }
コード例 #16
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="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            EventItem eventItem = null;

            using (var rockContext = new RockContext())
            {
                var validationMessages = new List <string>();

                var eventItemService         = new EventItemService(rockContext);
                var eventCalendarItemService = new EventCalendarItemService(rockContext);
                var eventItemAudienceService = new EventItemAudienceService(rockContext);

                int eventItemId = hfEventItemId.ValueAsInt();
                if (eventItemId != 0)
                {
                    eventItem = eventItemService
                                .Queryable("EventItemAudiences,EventItemOccurrences.Linkages,EventItemOccurrences")
                                .Where(i => i.Id == eventItemId)
                                .FirstOrDefault();
                }

                if (eventItem == null)
                {
                    eventItem = new EventItem();
                    eventItemService.Add(eventItem);
                }

                eventItem.Name     = tbName.Text;
                eventItem.IsActive = cbIsActive.Checked;

                if (!eventItem.IsApproved && cbIsApproved.Checked)
                {
                    eventItem.ApprovedByPersonAliasId = CurrentPersonAliasId;
                    eventItem.ApprovedOnDateTime      = RockDateTime.Now;
                }
                eventItem.IsApproved = cbIsApproved.Checked;
                if (!eventItem.IsApproved)
                {
                    eventItem.ApprovedByPersonAliasId = null;
                    eventItem.ApprovedByPersonAlias   = null;
                    eventItem.ApprovedOnDateTime      = null;
                }
                eventItem.Description = htmlDescription.Text;
                eventItem.Summary     = tbSummary.Text;
                eventItem.DetailsUrl  = tbDetailUrl.Text;

                int?orphanedImageId = null;
                if (eventItem.PhotoId != imgupPhoto.BinaryFileId)
                {
                    orphanedImageId   = eventItem.PhotoId;
                    eventItem.PhotoId = imgupPhoto.BinaryFileId;
                }

                // Remove any audiences that were removed in the UI
                foreach (var eventItemAudience in eventItem.EventItemAudiences.Where(r => !AudiencesState.Contains(r.DefinedValueId)).ToList())
                {
                    eventItem.EventItemAudiences.Remove(eventItemAudience);
                    eventItemAudienceService.Delete(eventItemAudience);
                }

                // Add or Update audiences from the UI
                foreach (int audienceId in AudiencesState)
                {
                    EventItemAudience eventItemAudience = eventItem.EventItemAudiences.Where(a => a.DefinedValueId == audienceId).FirstOrDefault();
                    if (eventItemAudience == null)
                    {
                        eventItemAudience = new EventItemAudience();
                        eventItemAudience.DefinedValueId = audienceId;
                        eventItem.EventItemAudiences.Add(eventItemAudience);
                    }
                }

                // remove any calendar items that removed in the UI
                var calendarIds = new List <int>();
                calendarIds.AddRange(cblCalendars.SelectedValuesAsInt);
                var uiCalendarGuids = ItemsState.Where(i => calendarIds.Contains(i.EventCalendarId)).Select(a => a.Guid);
                foreach (var eventCalendarItem in eventItem.EventCalendarItems.Where(a => !uiCalendarGuids.Contains(a.Guid)).ToList())
                {
                    // Make sure user is authorized to remove calendar (they may not have seen every calendar due to security)
                    if (UserCanEdit || eventCalendarItem.EventCalendar.IsAuthorized(Authorization.EDIT, CurrentPerson))
                    {
                        eventItem.EventCalendarItems.Remove(eventCalendarItem);
                        eventCalendarItemService.Delete(eventCalendarItem);
                    }
                }

                // Add or Update calendar items from the UI
                foreach (var calendar in ItemsState.Where(i => calendarIds.Contains(i.EventCalendarId)))
                {
                    var eventCalendarItem = eventItem.EventCalendarItems.Where(a => a.Guid == calendar.Guid).FirstOrDefault();
                    if (eventCalendarItem == null)
                    {
                        eventCalendarItem = new EventCalendarItem();
                        eventItem.EventCalendarItems.Add(eventCalendarItem);
                    }
                    eventCalendarItem.CopyPropertiesFrom(calendar);
                }

                if (!eventItem.EventCalendarItems.Any())
                {
                    validationMessages.Add("At least one calendar is required.");
                }

                if (!Page.IsValid)
                {
                    return;
                }

                if (!eventItem.IsValid)
                {
                    // Controls will render the error messages
                    return;
                }

                if (validationMessages.Any())
                {
                    nbValidation.Text    = "Please Correct the Following<ul><li>" + validationMessages.AsDelimited("</li><li>") + "</li></ul>";
                    nbValidation.Visible = true;
                    return;
                }

                // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges()
                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    foreach (EventCalendarItem eventCalendarItem in eventItem.EventCalendarItems)
                    {
                        eventCalendarItem.LoadAttributes();
                        Rock.Attribute.Helper.GetEditValues(phAttributes, eventCalendarItem);
                        eventCalendarItem.SaveAttributeValues();
                    }

                    if (orphanedImageId.HasValue)
                    {
                        BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                        var binaryFile = binaryFileService.Get(orphanedImageId.Value);
                        if (binaryFile != null)
                        {
                            // marked the old images as IsTemporary so they will get cleaned up later
                            binaryFile.IsTemporary = true;
                            rockContext.SaveChanges();
                        }
                    }
                });


                // Redirect back to same page so that item grid will show any attributes that were selected to show on grid
                var qryParams = new Dictionary <string, string>();
                if (_calendarId.HasValue)
                {
                    qryParams["EventCalendarId"] = _calendarId.Value.ToString();
                }
                qryParams["EventItemId"] = eventItem.Id.ToString();
                NavigateToPage(RockPage.Guid, qryParams);
            }
        }
コード例 #17
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="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (RegistrantState != null)
            {
                RockContext            rockContext                    = new RockContext();
                var                    personService                  = new PersonService(rockContext);
                var                    registrantService              = new RegistrationRegistrantService(rockContext);
                var                    registrantFeeService           = new RegistrationRegistrantFeeService(rockContext);
                var                    registrationTemplateFeeService = new RegistrationTemplateFeeService(rockContext);
                RegistrationRegistrant registrant = null;
                if (RegistrantState.Id > 0)
                {
                    registrant = registrantService.Get(RegistrantState.Id);
                }

                bool newRegistrant     = false;
                var  registrantChanges = new List <string>();

                if (registrant == null)
                {
                    newRegistrant             = true;
                    registrant                = new RegistrationRegistrant();
                    registrant.RegistrationId = RegistrantState.RegistrationId;
                    registrantService.Add(registrant);
                    registrantChanges.Add("Created Registrant");
                }

                if (!registrant.PersonAliasId.Equals(ppPerson.PersonAliasId))
                {
                    string prevPerson = (registrant.PersonAlias != null && registrant.PersonAlias.Person != null) ?
                                        registrant.PersonAlias.Person.FullName : string.Empty;
                    string newPerson = ppPerson.PersonName;
                    History.EvaluateChange(registrantChanges, "Person", prevPerson, newPerson);
                }
                int?personId = ppPerson.PersonId.Value;
                registrant.PersonAliasId = ppPerson.PersonAliasId.Value;

                // Get the name of registrant for history
                string registrantName = "Unknown";
                if (ppPerson.PersonId.HasValue)
                {
                    var person = personService.Get(ppPerson.PersonId.Value);
                    if (person != null)
                    {
                        registrantName = person.FullName;
                    }
                }

                History.EvaluateChange(registrantChanges, "Cost", registrant.Cost, cbCost.Text.AsDecimal());
                registrant.Cost = cbCost.Text.AsDecimal();

                if (!Page.IsValid)
                {
                    return;
                }

                // Remove/delete any registrant fees that are no longer in UI with quantity
                foreach (var dbFee in registrant.Fees.ToList())
                {
                    if (!RegistrantState.FeeValues.Keys.Contains(dbFee.RegistrationTemplateFeeId) ||
                        RegistrantState.FeeValues[dbFee.RegistrationTemplateFeeId] == null ||
                        !RegistrantState.FeeValues[dbFee.RegistrationTemplateFeeId]
                        .Any(f =>
                             f.Option == dbFee.Option &&
                             f.Quantity > 0))
                    {
                        registrantChanges.Add(string.Format("Removed '{0}' Fee (Quantity:{1:N0}, Cost:{2:C2}, Option:{3}",
                                                            dbFee.RegistrationTemplateFee.Name, dbFee.Quantity, dbFee.Cost, dbFee.Option));

                        registrant.Fees.Remove(dbFee);
                        registrantFeeService.Delete(dbFee);
                    }
                }

                // Add/Update any of the fees from UI
                foreach (var uiFee in RegistrantState.FeeValues.Where(f => f.Value != null))
                {
                    foreach (var uiFeeOption in uiFee.Value)
                    {
                        var dbFee = registrant.Fees
                                    .Where(f =>
                                           f.RegistrationTemplateFeeId == uiFee.Key &&
                                           f.Option == uiFeeOption.Option)
                                    .FirstOrDefault();

                        if (dbFee == null)
                        {
                            dbFee = new RegistrationRegistrantFee();
                            dbFee.RegistrationTemplateFeeId = uiFee.Key;
                            dbFee.Option = uiFeeOption.Option;
                            registrant.Fees.Add(dbFee);
                        }

                        var templateFee = dbFee.RegistrationTemplateFee;
                        if (templateFee == null)
                        {
                            templateFee = registrationTemplateFeeService.Get(uiFee.Key);
                        }

                        string feeName = templateFee != null ? templateFee.Name : "Fee";
                        if (!string.IsNullOrWhiteSpace(uiFeeOption.Option))
                        {
                            feeName = string.Format("{0} ({1})", feeName, uiFeeOption.Option);
                        }

                        if (dbFee.Id <= 0)
                        {
                            registrantChanges.Add(feeName + " Fee Added");
                        }

                        History.EvaluateChange(registrantChanges, feeName + " Quantity", dbFee.Quantity, uiFeeOption.Quantity);
                        dbFee.Quantity = uiFeeOption.Quantity;

                        History.EvaluateChange(registrantChanges, feeName + " Cost", dbFee.Cost, uiFeeOption.Cost);
                        dbFee.Cost = uiFeeOption.Cost;
                    }
                }

                if (TemplateState.RequiredSignatureDocumentTemplate != null)
                {
                    var person = new PersonService(rockContext).Get(personId.Value);

                    var documentService        = new SignatureDocumentService(rockContext);
                    var binaryFileService      = new BinaryFileService(rockContext);
                    SignatureDocument document = null;

                    int?signatureDocumentId = hfSignedDocumentId.Value.AsIntegerOrNull();
                    int?binaryFileId        = fuSignedDocument.BinaryFileId;
                    if (signatureDocumentId.HasValue)
                    {
                        document = documentService.Get(signatureDocumentId.Value);
                    }

                    if (document == null && binaryFileId.HasValue)
                    {
                        var instance = new RegistrationInstanceService(rockContext).Get(RegistrationInstanceId);

                        document = new SignatureDocument();
                        document.SignatureDocumentTemplateId = TemplateState.RequiredSignatureDocumentTemplate.Id;
                        document.AppliesToPersonAliasId      = registrant.PersonAliasId.Value;
                        document.AssignedToPersonAliasId     = registrant.PersonAliasId.Value;
                        document.Name = string.Format("{0}_{1}",
                                                      (instance != null ? instance.Name : TemplateState.Name),
                                                      (person != null ? person.FullName.RemoveSpecialCharacters() : string.Empty));
                        document.Status         = SignatureDocumentStatus.Signed;
                        document.LastStatusDate = RockDateTime.Now;
                        documentService.Add(document);
                    }

                    if (document != null)
                    {
                        int?origBinaryFileId = document.BinaryFileId;
                        document.BinaryFileId = binaryFileId;

                        if (origBinaryFileId.HasValue && origBinaryFileId.Value != document.BinaryFileId)
                        {
                            // if a new the binaryFile was uploaded, mark the old one as Temporary so that it gets cleaned up
                            var oldBinaryFile = binaryFileService.Get(origBinaryFileId.Value);
                            if (oldBinaryFile != null && !oldBinaryFile.IsTemporary)
                            {
                                oldBinaryFile.IsTemporary = true;
                            }
                        }

                        // ensure the IsTemporary is set to false on binaryFile associated with this document
                        if (document.BinaryFileId.HasValue)
                        {
                            var binaryFile = binaryFileService.Get(document.BinaryFileId.Value);
                            if (binaryFile != null && binaryFile.IsTemporary)
                            {
                                binaryFile.IsTemporary = false;
                            }
                        }
                    }
                }

                if (!registrant.IsValid)
                {
                    // Controls will render the error messages
                    return;
                }

                // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges()
                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();

                    registrant.LoadAttributes();
                    foreach (var field in TemplateState.Forms
                             .SelectMany(f => f.Fields
                                         .Where(t =>
                                                t.FieldSource == RegistrationFieldSource.RegistrationAttribute &&
                                                t.AttributeId.HasValue)))
                    {
                        var attribute = AttributeCache.Read(field.AttributeId.Value);
                        if (attribute != null)
                        {
                            string originalValue = registrant.GetAttributeValue(attribute.Key);
                            var fieldValue       = RegistrantState.FieldValues
                                                   .Where(f => f.Key == field.Id)
                                                   .Select(f => f.Value.FieldValue)
                                                   .FirstOrDefault();
                            string newValue = fieldValue != null ? fieldValue.ToString() : string.Empty;

                            if ((originalValue ?? string.Empty).Trim() != (newValue ?? string.Empty).Trim())
                            {
                                string formattedOriginalValue = string.Empty;
                                if (!string.IsNullOrWhiteSpace(originalValue))
                                {
                                    formattedOriginalValue = attribute.FieldType.Field.FormatValue(null, originalValue, attribute.QualifierValues, false);
                                }

                                string formattedNewValue = string.Empty;
                                if (!string.IsNullOrWhiteSpace(newValue))
                                {
                                    formattedNewValue = attribute.FieldType.Field.FormatValue(null, newValue, attribute.QualifierValues, false);
                                }

                                History.EvaluateChange(registrantChanges, attribute.Name, formattedOriginalValue, formattedNewValue);
                            }

                            if (fieldValue != null)
                            {
                                registrant.SetAttributeValue(attribute.Key, fieldValue.ToString());
                            }
                        }
                    }

                    registrant.SaveAttributeValues(rockContext);
                });

                if (newRegistrant && TemplateState.GroupTypeId.HasValue && ppPerson.PersonId.HasValue)
                {
                    using (var newRockContext = new RockContext())
                    {
                        var reloadedRegistrant = new RegistrationRegistrantService(newRockContext).Get(registrant.Id);
                        if (reloadedRegistrant != null &&
                            reloadedRegistrant.Registration != null &&
                            reloadedRegistrant.Registration.Group != null &&
                            reloadedRegistrant.Registration.Group.GroupTypeId == TemplateState.GroupTypeId.Value)
                        {
                            int?groupRoleId = TemplateState.GroupMemberRoleId.HasValue ?
                                              TemplateState.GroupMemberRoleId.Value :
                                              reloadedRegistrant.Registration.Group.GroupType.DefaultGroupRoleId;
                            if (groupRoleId.HasValue)
                            {
                                var groupMemberService = new GroupMemberService(newRockContext);
                                var groupMember        = groupMemberService
                                                         .Queryable().AsNoTracking()
                                                         .Where(m =>
                                                                m.GroupId == reloadedRegistrant.Registration.Group.Id &&
                                                                m.PersonId == reloadedRegistrant.PersonId &&
                                                                m.GroupRoleId == groupRoleId.Value)
                                                         .FirstOrDefault();
                                if (groupMember == null)
                                {
                                    groupMember = new GroupMember();
                                    groupMemberService.Add(groupMember);
                                    groupMember.GroupId           = reloadedRegistrant.Registration.Group.Id;
                                    groupMember.PersonId          = ppPerson.PersonId.Value;
                                    groupMember.GroupRoleId       = groupRoleId.Value;
                                    groupMember.GroupMemberStatus = TemplateState.GroupMemberStatus;

                                    newRockContext.SaveChanges();

                                    registrantChanges.Add(string.Format("Registrant added to {0} group", reloadedRegistrant.Registration.Group.Name));
                                }
                                else
                                {
                                    registrantChanges.Add(string.Format("Registrant group member reference updated to existing person in {0} group", reloadedRegistrant.Registration.Group.Name));
                                }

                                reloadedRegistrant.GroupMemberId = groupMember.Id;
                                newRockContext.SaveChanges();
                            }
                        }
                    }
                }

                HistoryService.SaveChanges(
                    rockContext,
                    typeof(Registration),
                    Rock.SystemGuid.Category.HISTORY_EVENT_REGISTRATION.AsGuid(),
                    registrant.RegistrationId,
                    registrantChanges,
                    "Registrant: " + registrantName,
                    null, null);
            }

            NavigateToRegistration();
        }
コード例 #18
0
        /// <summary>
        /// Copies the specified connection type.
        /// </summary>
        /// <param name="connectionTypeId">The connection type identifier.</param>
        /// <returns>
        /// Return the new ConnectionType ID
        /// </returns>
        public int Copy(int connectionTypeId)
        {
            var              connectionType      = this.Get(connectionTypeId);
            RockContext      rockContext         = ( RockContext )Context;
            int              newConnectionTypeId = 0;
            AttributeService attributeService    = new AttributeService(rockContext);
            var              authService         = new AuthService(rockContext);

            // Get current Opportunity attributes
            var opportunityAttributes = attributeService
                                        .GetByEntityTypeId(new ConnectionOpportunity().TypeId, true).AsQueryable()
                                        .Where(a =>
                                               a.EntityTypeQualifierColumn.Equals("ConnectionTypeId", StringComparison.OrdinalIgnoreCase) &&
                                               a.EntityTypeQualifierValue.Equals(connectionType.Id.ToString()))
                                        .OrderBy(a => a.Order)
                                        .ThenBy(a => a.Name)
                                        .ToList();

            ConnectionType newConnectionType = new ConnectionType();

            rockContext.WrapTransaction(() =>
            {
                newConnectionType.CopyPropertiesFrom(connectionType);
                InitModel(ref newConnectionType);
                newConnectionType.Name = connectionType.Name + " - Copy";
                this.Add(newConnectionType);
                rockContext.SaveChanges();
                newConnectionTypeId = newConnectionType.Id;

                foreach (var connectionActivityTypeState in connectionType.ConnectionActivityTypes)
                {
                    ConnectionActivityType newConnectionActivityType = new ConnectionActivityType();
                    newConnectionActivityType.CopyPropertiesFrom(connectionActivityTypeState);
                    InitModel(ref newConnectionActivityType);
                    newConnectionType.ConnectionActivityTypes.Add(newConnectionActivityType);
                }

                foreach (var connectionStatusState in connectionType.ConnectionStatuses)
                {
                    ConnectionStatus newConnectionStatus = new ConnectionStatus();
                    newConnectionStatus.CopyPropertiesFrom(connectionStatusState);
                    InitModel(ref newConnectionStatus);
                    newConnectionType.ConnectionStatuses.Add(newConnectionStatus);
                    newConnectionStatus.ConnectionTypeId = newConnectionType.Id;
                }

                foreach (ConnectionWorkflow connectionWorkflowState in connectionType.ConnectionWorkflows)
                {
                    ConnectionWorkflow newConnectionWorkflow = new ConnectionWorkflow();
                    newConnectionWorkflow.CopyPropertiesFrom(connectionWorkflowState);
                    InitModel(ref newConnectionWorkflow);
                    newConnectionType.ConnectionWorkflows.Add(newConnectionWorkflow);
                    newConnectionWorkflow.ConnectionTypeId = newConnectionType.Id;
                }

                rockContext.SaveChanges();

                // Clone the Opportunity attributes
                List <Attribute> newAttributesState = new List <Attribute>();
                foreach (var attribute in opportunityAttributes)
                {
                    var newAttribute = attribute.Clone(false);
                    InitModel(ref newAttribute);
                    newAttribute.IsSystem = false;
                    newAttributesState.Add(newAttribute);

                    foreach (var qualifier in attribute.AttributeQualifiers)
                    {
                        var newQualifier      = qualifier.Clone(false);
                        newQualifier.Id       = 0;
                        newQualifier.Guid     = Guid.NewGuid();
                        newQualifier.IsSystem = false;
                        newAttribute.AttributeQualifiers.Add(qualifier);
                    }
                }

                // Save Attributes
                string qualifierValue = newConnectionType.Id.ToString();
                Rock.Attribute.Helper.SaveAttributeEdits(newAttributesState, new ConnectionOpportunity().TypeId, "ConnectionTypeId", qualifierValue, rockContext);

                // Copy Security
                Rock.Security.Authorization.CopyAuthorization(connectionType, newConnectionType, rockContext);
            });

            CopyConnectionOpportunities(connectionType, newConnectionType);
            ConnectionWorkflowService.RemoveCachedTriggers();
            return(newConnectionTypeId);
        }
コード例 #19
0
        /// <summary>
        /// Handles the Click event of the btnSaveDefinedValue control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSaveValue_Click(object sender, EventArgs e)
        {
            DefinedValue        definedValue;
            var                 rockContext         = new RockContext();
            DefinedValueService definedValueService = new DefinedValueService(rockContext);

            int definedValueId = hfDefinedValueId.ValueAsInt();

            if (definedValueId.Equals(0))
            {
                int definedTypeId = hfDefinedTypeId.ValueAsInt();
                definedValue = new DefinedValue {
                    Id = 0
                };
                definedValue.DefinedTypeId = definedTypeId;
                definedValue.IsSystem      = false;

                var orders = definedValueService.Queryable()
                             .Where(d => d.DefinedTypeId == definedTypeId)
                             .Select(d => d.Order)
                             .ToList();

                definedValue.Order = orders.Any() ? orders.Max() + 1 : 0;
            }
            else
            {
                definedValue = definedValueService.Get(definedValueId);
            }

            definedValue.Value       = tbValueName.Text;
            definedValue.Description = tbValueDescription.Text;
            definedValue.LoadAttributes();
            Rock.Attribute.Helper.GetEditValues(phDefinedValueAttributes, definedValue);

            if (!Page.IsValid)
            {
                return;
            }

            if (!definedValue.IsValid)
            {
                // Controls will render the error messages
                return;
            }

            Rock.Web.Cache.DefinedTypeCache.Flush(definedValue.DefinedTypeId);
            Rock.Web.Cache.DefinedValueCache.Flush(definedValue.Id);

            rockContext.WrapTransaction(() =>
            {
                if (definedValue.Id.Equals(0))
                {
                    definedValueService.Add(definedValue);
                }

                rockContext.SaveChanges();

                definedValue.SaveAttributeValues(rockContext);
            });

            BindDefinedValuesGrid();

            hfDefinedValueId.Value = string.Empty;
            modalValue.Hide();
        }
コード例 #20
0
        /// <summary>
        /// Saves the individuals.
        /// </summary>
        /// <param name="newFamilyList">The family list.</param>
        /// <param name="visitorList">The optional visitor list.</param>
        private void SaveIndividuals(List <Group> newFamilyList, List <Group> visitorList = null, List <Note> newNoteList = null)
        {
            if (newFamilyList.Any())
            {
                var rockContext = new RockContext();
                rockContext.WrapTransaction(() =>
                {
                    rockContext.Groups.AddRange(newFamilyList);
                    rockContext.SaveChanges(DisableAuditing);

                    ImportedPeople.AddRange(newFamilyList);

                    foreach (var familyGroups in newFamilyList.GroupBy <Group, string>(g => g.ForeignKey))
                    {
                        bool visitorsExist = visitorList.Any() && familyGroups.Any();
                        foreach (var newFamilyGroup in familyGroups)
                        {
                            foreach (var person in newFamilyGroup.Members.Select(m => m.Person))
                            {
                                // Set notes on this person
                                if (newNoteList.Any(n => n.ForeignKey == person.ForeignKey))
                                {
                                    newNoteList.Where(n => n.ForeignKey == person.ForeignKey).ToList()
                                    .ForEach(n => n.EntityId = person.Id);
                                }

                                // Set attributes on this person
                                foreach (var attributeCache in person.Attributes.Select(a => a.Value))
                                {
                                    var existingValue     = rockContext.AttributeValues.FirstOrDefault(v => v.Attribute.Key == attributeCache.Key && v.EntityId == person.Id);
                                    var newAttributeValue = person.AttributeValues[attributeCache.Key];

                                    // set the new value and add it to the database
                                    if (existingValue == null)
                                    {
                                        existingValue             = new AttributeValue();
                                        existingValue.AttributeId = newAttributeValue.AttributeId;
                                        existingValue.EntityId    = person.Id;
                                        existingValue.Value       = newAttributeValue.Value;

                                        rockContext.AttributeValues.Add(existingValue);
                                    }
                                    else
                                    {
                                        existingValue.Value = newAttributeValue.Value;
                                        rockContext.Entry(existingValue).State = EntityState.Modified;
                                    }
                                }

                                // Set aliases on this person
                                if (!person.Aliases.Any(a => a.AliasPersonId == person.Id))
                                {
                                    person.Aliases.Add(new PersonAlias
                                    {
                                        AliasPersonId   = person.Id,
                                        AliasPersonGuid = person.Guid,
                                        ForeignKey      = person.ForeignKey,
                                        ForeignId       = person.ForeignId
                                    });
                                }

                                person.GivingGroupId = newFamilyGroup.Id;

                                if (visitorsExist)
                                {
                                    var groupTypeRoleService = new GroupTypeRoleService(rockContext);
                                    var ownerRole            = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER));
                                    int inviteeRoleId        = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_INVITED)).Id;
                                    int invitedByRoleId      = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_INVITED_BY)).Id;
                                    int canCheckInRoleId     = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_CAN_CHECK_IN)).Id;
                                    int allowCheckInByRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_ALLOW_CHECK_IN_BY)).Id;

                                    // Retrieve or create the group this person is an owner of
                                    var ownerGroup = new GroupMemberService(rockContext).Queryable()
                                                     .Where(m => m.PersonId == person.Id && m.GroupRoleId == ownerRole.Id)
                                                     .Select(m => m.Group).FirstOrDefault();
                                    if (ownerGroup == null)
                                    {
                                        var ownerGroupMember         = new GroupMember();
                                        ownerGroupMember.PersonId    = person.Id;
                                        ownerGroupMember.GroupRoleId = ownerRole.Id;

                                        ownerGroup             = new Group();
                                        ownerGroup.Name        = ownerRole.GroupType.Name;
                                        ownerGroup.GroupTypeId = ownerRole.GroupTypeId.Value;
                                        ownerGroup.Members.Add(ownerGroupMember);
                                        rockContext.Groups.Add(ownerGroup);
                                    }

                                    // Visitor, add relationships to the family members
                                    if (visitorList.Where(v => v.ForeignKey == newFamilyGroup.ForeignKey)
                                        .Any(v => v.Members.Any(m => m.Person.ForeignKey.Equals(person.ForeignKey))))
                                    {
                                        var familyMembers = familyGroups.Except(visitorList).SelectMany(g => g.Members);
                                        foreach (var familyMember in familyMembers)
                                        {
                                            // Add visitor invitedBy relationship
                                            var invitedByMember         = new GroupMember();
                                            invitedByMember.PersonId    = familyMember.Person.Id;
                                            invitedByMember.GroupRoleId = invitedByRoleId;
                                            ownerGroup.Members.Add(invitedByMember);

                                            if (person.Age < 18 && familyMember.Person.Age > 15)
                                            {
                                                // Add visitor allowCheckInBy relationship
                                                var allowCheckinMember         = new GroupMember();
                                                allowCheckinMember.PersonId    = familyMember.Person.Id;
                                                allowCheckinMember.GroupRoleId = allowCheckInByRoleId;
                                                ownerGroup.Members.Add(allowCheckinMember);
                                            }
                                        }
                                    }
                                    else
                                    {   // Family member, add relationships to the visitor(s)
                                        var familyVisitors = visitorList.Where(v => v.ForeignKey == newFamilyGroup.ForeignKey).SelectMany(g => g.Members).ToList();
                                        foreach (var visitor in familyVisitors)
                                        {
                                            // Add invited visitor relationship
                                            var inviteeMember         = new GroupMember();
                                            inviteeMember.PersonId    = visitor.Person.Id;
                                            inviteeMember.GroupRoleId = inviteeRoleId;
                                            ownerGroup.Members.Add(inviteeMember);

                                            if (visitor.Person.Age < 18 && person.Age > 15)
                                            {
                                                // Add canCheckIn visitor relationship
                                                var canCheckInMember         = new GroupMember();
                                                canCheckInMember.PersonId    = visitor.Person.Id;
                                                canCheckInMember.GroupRoleId = canCheckInRoleId;
                                                ownerGroup.Members.Add(canCheckInMember);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // Save notes and all changes
                    rockContext.Notes.AddRange(newNoteList);
                    rockContext.SaveChanges(DisableAuditing);
                });
            }
        }
コード例 #21
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="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            Site site;

            if (Page.IsValid)
            {
                var               rockContext       = new RockContext();
                SiteService       siteService       = new SiteService(rockContext);
                SiteDomainService siteDomainService = new SiteDomainService(rockContext);
                bool              newSite           = false;

                int siteId = hfSiteId.Value.AsInteger();

                if (siteId == 0)
                {
                    newSite = true;
                    site    = new Rock.Model.Site();
                    siteService.Add(site);
                }
                else
                {
                    site = siteService.Get(siteId);
                }

                site.Name                        = tbSiteName.Text;
                site.Description                 = tbDescription.Text;
                site.Theme                       = ddlTheme.Text;
                site.DefaultPageId               = ppDefaultPage.PageId;
                site.DefaultPageRouteId          = ppDefaultPage.PageRouteId;
                site.LoginPageId                 = ppLoginPage.PageId;
                site.LoginPageRouteId            = ppLoginPage.PageRouteId;
                site.ChangePasswordPageId        = ppChangePasswordPage.PageId;
                site.ChangePasswordPageRouteId   = ppChangePasswordPage.PageRouteId;
                site.CommunicationPageId         = ppCommunicationPage.PageId;
                site.CommunicationPageRouteId    = ppCommunicationPage.PageRouteId;
                site.RegistrationPageId          = ppRegistrationPage.PageId;
                site.RegistrationPageRouteId     = ppRegistrationPage.PageRouteId;
                site.PageNotFoundPageId          = ppPageNotFoundPage.PageId;
                site.PageNotFoundPageRouteId     = ppPageNotFoundPage.PageRouteId;
                site.ErrorPage                   = tbErrorPage.Text;
                site.GoogleAnalyticsCode         = tbGoogleAnalytics.Text;
                site.EnableMobileRedirect        = cbEnableMobileRedirect.Checked;
                site.MobilePageId                = ppMobilePage.PageId;
                site.ExternalUrl                 = tbExternalURL.Text;
                site.AllowedFrameDomains         = tbAllowedFrameDomains.Text;
                site.RedirectTablets             = cbRedirectTablets.Checked;
                site.EnablePageViews             = cbEnablePageViews.Checked;
                site.PageViewRetentionPeriodDays = nbPageViewRetentionPeriodDays.Text.AsIntegerOrNull();

                site.AllowIndexing     = cbAllowIndexing.Checked;
                site.PageHeaderContent = cePageHeaderContent.Text;

                var currentDomains = tbSiteDomains.Text.SplitDelimitedValues().ToList <string>();
                site.SiteDomains = site.SiteDomains ?? new List <SiteDomain>();

                // Remove any deleted domains
                foreach (var domain in site.SiteDomains.Where(w => !currentDomains.Contains(w.Domain)).ToList())
                {
                    site.SiteDomains.Remove(domain);
                    siteDomainService.Delete(domain);
                }

                foreach (string domain in currentDomains)
                {
                    SiteDomain sd = site.SiteDomains.Where(d => d.Domain == domain).FirstOrDefault();
                    if (sd == null)
                    {
                        sd        = new SiteDomain();
                        sd.Domain = domain;
                        sd.Guid   = Guid.NewGuid();
                        site.SiteDomains.Add(sd);
                    }
                }

                if (!site.DefaultPageId.HasValue && !newSite)
                {
                    ppDefaultPage.ShowErrorMessage("Default Page is required.");
                    return;
                }

                if (!site.IsValid)
                {
                    // Controls will render the error messages
                    return;
                }

                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();

                    if (newSite)
                    {
                        Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.EDIT);
                        Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.ADMINISTRATE);
                        Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.APPROVE);
                    }
                });

                SiteCache.Flush(site.Id);

                // Create the default page is this is a new site
                if (!site.DefaultPageId.HasValue && newSite)
                {
                    var siteCache = SiteCache.Read(site.Id);

                    // Create the layouts for the site, and find the first one
                    LayoutService.RegisterLayouts(Request.MapPath("~"), siteCache);

                    var    layoutService = new LayoutService(rockContext);
                    var    layouts       = layoutService.GetBySiteId(siteCache.Id);
                    Layout layout        = layouts.FirstOrDefault(l => l.FileName.Equals("FullWidth", StringComparison.OrdinalIgnoreCase));
                    if (layout == null)
                    {
                        layout = layouts.FirstOrDefault();
                    }

                    if (layout != null)
                    {
                        var pageService = new PageService(rockContext);
                        var page        = new Page();
                        page.LayoutId              = layout.Id;
                        page.PageTitle             = siteCache.Name + " Home Page";
                        page.InternalName          = page.PageTitle;
                        page.BrowserTitle          = page.PageTitle;
                        page.EnableViewState       = true;
                        page.IncludeAdminFooter    = true;
                        page.MenuDisplayChildPages = true;

                        var lastPage = pageService.GetByParentPageId(null).OrderByDescending(b => b.Order).FirstOrDefault();

                        page.Order = lastPage != null ? lastPage.Order + 1 : 0;
                        pageService.Add(page);

                        rockContext.SaveChanges();

                        site = siteService.Get(siteCache.Id);
                        site.DefaultPageId = page.Id;

                        rockContext.SaveChanges();

                        SiteCache.Flush(site.Id);
                    }
                }

                var qryParams = new Dictionary <string, string>();
                qryParams["siteId"] = site.Id.ToString();

                NavigateToPage(RockPage.Guid, qryParams);
            }
        }
コード例 #22
0
        /// <summary>
        /// Handles the Click event of the btnSaveGroupMember control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSaveGroupMember_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();
            GroupMemberService groupMemberService = new GroupMemberService(rockContext);

            GroupTypeRole role = new GroupTypeRoleService(rockContext).Get(ddlGroupRole.SelectedValueAsInt() ?? 0);

            var groupMember = groupMemberService.Get(CurrentGroupMemberId);

            if (CurrentGroupMemberId == 0)
            {
                groupMember = new GroupMember {
                    Id = 0
                };
                groupMember.GroupId = _groupId;

                // check to see if the person is alread a member of the gorup/role
                var existingGroupMember = groupMemberService.GetByGroupIdAndPersonIdAndGroupRoleId(
                    _groupId, ppGroupMemberPerson.SelectedValue ?? 0, ddlGroupRole.SelectedValueAsId() ?? 0);

                if (existingGroupMember != null)
                {
                    // if so, don't add and show error message
                    var person = new PersonService(rockContext).Get(( int )ppGroupMemberPerson.PersonId);

                    nbGroupMemberErrorMessage.Title = "Person Already In Group";
                    nbGroupMemberErrorMessage.Text  = string.Format(
                        "{0} already belongs to the {1} role for this {2}, and cannot be added again with the same role.",
                        person.FullName,
                        ddlGroupRole.SelectedItem.Text,
                        role.GroupType.GroupTerm,
                        RockPage.PageId,
                        existingGroupMember.Id);
                    return;
                }
            }

            groupMember.PersonId    = ppGroupMemberPerson.PersonId.Value;
            groupMember.GroupRoleId = role.Id;

            // set their status.  If HideInactiveGroupMemberStatus is True, and they are already Inactive, keep their status as Inactive;
            bool hideGroupMemberInactiveStatus = GetAttributeValue("HideInactiveGroupMemberStatus").AsBooleanOrNull() ?? false;
            var  selectedStatus = rblStatus.SelectedValueAsEnumOrNull <GroupMemberStatus>();

            if (!selectedStatus.HasValue)
            {
                if (hideGroupMemberInactiveStatus)
                {
                    selectedStatus = GroupMemberStatus.Inactive;
                }
                else
                {
                    selectedStatus = GroupMemberStatus.Active;
                }
            }

            groupMember.GroupMemberStatus = selectedStatus.Value;

            groupMember.LoadAttributes();

            Helper.GetEditValues(phAttributes, groupMember);

            if (!Page.IsValid)
            {
                return;
            }

            // if the groupMember IsValid is false, and the UI controls didn't report any errors, it is probably because the custom rules of GroupMember didn't pass.
            // So, make sure a message is displayed in the validation summary
            cvEditGroupMember.IsValid = groupMember.IsValid;

            if (!cvEditGroupMember.IsValid)
            {
                cvEditGroupMember.ErrorMessage = groupMember.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                return;
            }

            // using WrapTransaction because there are two Saves
            rockContext.WrapTransaction(() =>
            {
                if (groupMember.Id.Equals(0))
                {
                    groupMemberService.Add(groupMember);
                }

                rockContext.SaveChanges();
                groupMember.SaveAttributeValues(rockContext);
            });

            Group group = new GroupService(rockContext).Get(groupMember.GroupId);

            if (group.IsSecurityRole || group.GroupType.Guid.Equals(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid()))
            {
                Role.Flush(group.Id);
            }

            pnlEditGroupMember.Visible = false;
            pnlGroupView.Visible       = true;
            DisplayViewGroup();
            IsEditingGroupMember = false;
        }
コード例 #23
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="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            BinaryFileType binaryFileType;

            var rockContext = new RockContext();
            BinaryFileTypeService     binaryFileTypeService     = new BinaryFileTypeService(rockContext);
            AttributeService          attributeService          = new AttributeService(rockContext);
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext);
            CategoryService           categoryService           = new CategoryService(rockContext);

            int binaryFileTypeId = int.Parse(hfBinaryFileTypeId.Value);

            if (binaryFileTypeId == 0)
            {
                binaryFileType = new BinaryFileType();
                binaryFileTypeService.Add(binaryFileType);
            }
            else
            {
                binaryFileType = binaryFileTypeService.Get(binaryFileTypeId);
            }

            binaryFileType.Name                 = tbName.Text;
            binaryFileType.Description          = tbDescription.Text;
            binaryFileType.IconCssClass         = tbIconCssClass.Text;
            binaryFileType.AllowCaching         = cbAllowCaching.Checked;
            binaryFileType.RequiresViewSecurity = cbRequiresViewSecurity.Checked;
            binaryFileType.MaxWidth             = nbMaxWidth.Text.AsInteger();
            binaryFileType.MaxHeight            = nbMaxHeight.Text.AsInteger();
            binaryFileType.PreferredFormat      = ddlPreferredFormat.SelectedValueAsEnum <Format>();
            binaryFileType.PreferredResolution  = ddlPreferredResolution.SelectedValueAsEnum <Resolution>();
            binaryFileType.PreferredColorDepth  = ddlPreferredColorDepth.SelectedValueAsEnum <ColorDepth>();
            binaryFileType.PreferredRequired    = cbPreferredRequired.Checked;

            if (!string.IsNullOrWhiteSpace(cpStorageType.SelectedValue))
            {
                var entityTypeService = new EntityTypeService(rockContext);
                var storageEntityType = entityTypeService.Get(new Guid(cpStorageType.SelectedValue));

                if (storageEntityType != null)
                {
                    binaryFileType.StorageEntityTypeId = storageEntityType.Id;
                }
            }

            binaryFileType.LoadAttributes(rockContext);
            Rock.Attribute.Helper.GetEditValues(phAttributes, binaryFileType);

            if (!binaryFileType.IsValid)
            {
                // Controls will render the error messages
                return;
            }

            rockContext.WrapTransaction(() =>
            {
                rockContext.SaveChanges();

                // get it back to make sure we have a good Id for it for the Attributes
                binaryFileType = binaryFileTypeService.Get(binaryFileType.Guid);

                /* Take care of Binary File Attributes */
                var entityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(BinaryFile)).Id;

                // delete BinaryFileAttributes that are no longer configured in the UI
                var attributes             = attributeService.Get(entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString());
                var selectedAttributeGuids = BinaryFileAttributesState.Select(a => a.Guid);
                foreach (var attr in attributes.Where(a => !selectedAttributeGuids.Contains(a.Guid)))
                {
                    Rock.Web.Cache.AttributeCache.Flush(attr.Id);
                    attributeService.Delete(attr);
                }
                rockContext.SaveChanges();

                // add/update the BinaryFileAttributes that are assigned in the UI
                foreach (var attributeState in BinaryFileAttributesState)
                {
                    Rock.Attribute.Helper.SaveAttributeEdits(attributeState, entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString(), rockContext);
                }

                // SaveAttributeValues for the BinaryFileType
                binaryFileType.SaveAttributeValues(rockContext);
            });

            AttributeCache.FlushEntityAttributes();

            NavigateToParentPage();
        }
コード例 #24
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="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }

            GroupType groupType = null;

            var rockContext = new RockContext();
            GroupTypeService          groupTypeService          = new GroupTypeService(rockContext);
            AttributeService          attributeService          = new AttributeService(rockContext);
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext);

            int?groupTypeId = hfGroupTypeId.ValueAsInt();

            if (groupTypeId.HasValue && groupTypeId.Value > 0)
            {
                groupType = groupTypeService.Get(groupTypeId.Value);
            }

            bool newGroupType = false;

            if (groupType == null)
            {
                groupType = new GroupType();
                groupTypeService.Add(groupType);

                var templatePurpose = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE.AsGuid());
                if (templatePurpose != null)
                {
                    groupType.GroupTypePurposeValueId = templatePurpose.Id;
                }

                newGroupType = true;
            }

            if (groupType != null)
            {
                groupType.Name        = tbName.Text;
                groupType.Description = tbDescription.Text;

                groupType.LoadAttributes(rockContext);
                Rock.Attribute.Helper.GetEditValues(phAttributeEdits, groupType);

                groupType.SetAttributeValue("core_checkin_AgeRequired", cbAgeRequired.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_GradeRequired", cbGradeRequired.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_HidePhotos", cbHidePhotos.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_PreventDuplicateCheckin", cbPreventDuplicateCheckin.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_PreventInactivePeople", cbPreventInactivePeople.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_CheckInType", ddlType.SelectedValue);
                groupType.SetAttributeValue("core_checkin_DisplayLocationCount", cbDisplayLocCount.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_EnableManagerOption", cbEnableManager.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_EnableOverride", cbEnableOverride.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_MaximumPhoneSearchLength", nbMaxPhoneLength.Text);
                groupType.SetAttributeValue("core_checkin_MaxSearchResults", nbMaxResults.Text);
                groupType.SetAttributeValue("core_checkin_MinimumPhoneSearchLength", nbMinPhoneLength.Text);
                groupType.SetAttributeValue("core_checkin_UseSameOptions", cbUseSameOptions.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_PhoneSearchType", ddlPhoneSearchType.SelectedValue);
                groupType.SetAttributeValue("core_checkin_RefreshInterval", nbRefreshInterval.Text);
                groupType.SetAttributeValue("core_checkin_RegularExpressionFilter", tbSearchRegex.Text);
                groupType.SetAttributeValue("core_checkin_ReuseSameCode", cbReuseCode.Checked.ToString());

                var searchType = DefinedValueCache.Read(ddlSearchType.SelectedValueAsInt() ?? 0);
                if (searchType != null)
                {
                    groupType.SetAttributeValue("core_checkin_SearchType", searchType.Guid.ToString());
                }
                else
                {
                    groupType.SetAttributeValue("core_checkin_SearchType", Rock.SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_PHONE_NUMBER);
                }

                groupType.SetAttributeValue("core_checkin_SecurityCodeLength", nbCodeAlphaNumericLength.Text);
                groupType.SetAttributeValue("core_checkin_SecurityCodeAlphaLength", nbCodeAlphaLength.Text);
                groupType.SetAttributeValue("core_checkin_SecurityCodeNumericLength", nbCodeNumericLength.Text);
                groupType.SetAttributeValue("core_checkin_SecurityCodeNumericRandom", cbCodeRandom.Checked.ToString());
                groupType.SetAttributeValue("core_checkin_AutoSelectDaysBack", nbAutoSelectDaysBack.Text);

                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    groupType.SaveAttributeValues(rockContext);
                });

                if (newGroupType)
                {
                    var pageRef = new PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId);
                    pageRef.Parameters.Add("CheckinTypeId", groupType.Id.ToString());
                    NavigateToPage(pageRef);
                }
                else
                {
                    groupType = groupTypeService.Get(groupType.Id);
                    ShowReadonlyDetails(groupType);
                }

                GroupTypeCache.Flush(groupType.Id);
                Rock.CheckIn.KioskDevice.FlushAll();
            }
        }
コード例 #25
0
        private bool HydrateObjects()
        {
            LoadWorkflowType();

            // Set the note type if this is first request
            if (!Page.IsPostBack)
            {
                var noteType = new NoteTypeService(_rockContext).Get(Rock.SystemGuid.NoteType.WORKFLOW_NOTE.AsGuid());
                ncWorkflowNotes.NoteTypeId = noteType.Id;
            }

            if (_workflowType == null)
            {
                ShowMessage(NotificationBoxType.Danger, "Configuration Error", "Workflow type was not configured or specified correctly.");
                return(false);
            }

            if (!_workflowType.IsAuthorized(Authorization.VIEW, CurrentPerson))
            {
                ShowMessage(NotificationBoxType.Warning, "Sorry", "You are not authorized to view this type of workflow.");
                return(false);
            }

            // If operating against an existing workflow, get the workflow and load attributes
            if (!WorkflowId.HasValue)
            {
                WorkflowId = PageParameter("WorkflowId").AsIntegerOrNull();
                if (!WorkflowId.HasValue)
                {
                    Guid guid = PageParameter("WorkflowGuid").AsGuid();
                    if (!guid.IsEmpty())
                    {
                        _workflow = _workflowService.Queryable()
                                    .Where(w => w.Guid.Equals(guid) && w.WorkflowTypeId == _workflowType.Id)
                                    .FirstOrDefault();
                        if (_workflow != null)
                        {
                            WorkflowId = _workflow.Id;
                        }
                    }
                }
            }

            if (WorkflowId.HasValue)
            {
                if (_workflow == null)
                {
                    _workflow = _workflowService.Queryable()
                                .Where(w => w.Id == WorkflowId.Value && w.WorkflowTypeId == _workflowType.Id)
                                .FirstOrDefault();
                }
                if (_workflow != null)
                {
                    _workflow.LoadAttributes();
                    foreach (var activity in _workflow.Activities)
                    {
                        activity.LoadAttributes();
                    }
                }
            }

            // If an existing workflow was not specified, activate a new instance of workflow and start processing
            if (_workflow == null)
            {
                string workflowName = PageParameter("WorkflowName");
                if (string.IsNullOrWhiteSpace(workflowName))
                {
                    workflowName = "New " + _workflowType.WorkTerm;
                }

                _workflow = Rock.Model.Workflow.Activate(_workflowType, workflowName);
                if (_workflow != null)
                {
                    // If a PersonId or GroupId parameter was included, load the corresponding
                    // object and pass that to the actions for processing
                    object entity   = null;
                    int?   personId = PageParameter("PersonId").AsIntegerOrNull();
                    if (personId.HasValue)
                    {
                        entity = new PersonService(_rockContext).Get(personId.Value);
                    }
                    else
                    {
                        int?groupId = PageParameter("GroupId").AsIntegerOrNull();
                        if (groupId.HasValue)
                        {
                            entity = new GroupService(_rockContext).Get(groupId.Value);
                        }
                    }

                    // Loop through all the query string parameters and try to set any workflow
                    // attributes that might have the same key
                    foreach (string key in Request.QueryString.AllKeys)
                    {
                        _workflow.SetAttributeValue(key, Request.QueryString[key]);
                    }

                    List <string> errorMessages;

                    bool success = _workflow.Process(_rockContext, entity, out errorMessages);

                    // If errors were encountered while processing the workflow, display them and disallow further processing.
                    if (!success)
                    {
                        ShowMessage(NotificationBoxType.Danger, "Workflow Processing Error(s):", "<ul><li>" + errorMessages.AsDelimited("</li><li>") + "</li></ul>");
                        ShowNotes(false);
                        return(false);
                    }

                    // If the workflow type is persisted, save the workflow
                    if (_workflow.IsPersisted || _workflowType.IsPersisted)
                    {
                        if (_workflow.Id == 0)
                        {
                            _workflowService.Add(_workflow);
                        }

                        _rockContext.WrapTransaction(() =>
                        {
                            _rockContext.SaveChanges();
                            _workflow.SaveAttributeValues(_rockContext);
                            foreach (var activity in _workflow.Activities)
                            {
                                activity.SaveAttributeValues(_rockContext);
                            }
                        });

                        WorkflowId = _workflow.Id;
                    }
                }
            }

            if (_workflow == null)
            {
                ShowMessage(NotificationBoxType.Danger, "Workflow Activation Error", "Workflow could not be activated.");
                return(false);
            }

            if (_workflow.IsActive)
            {
                if (ActionTypeId.HasValue)
                {
                    foreach (var activity in _workflow.ActiveActivities)
                    {
                        _action = activity.Actions.Where(a => a.ActionTypeId == ActionTypeId.Value).FirstOrDefault();
                        if (_action != null)
                        {
                            _activity = activity;
                            _activity.LoadAttributes();

                            _actionType  = _action.ActionType;
                            ActionTypeId = _actionType.Id;
                            return(true);
                        }
                    }
                }

                var canEdit = IsUserAuthorized(Authorization.EDIT);

                // Find first active action form
                int personId = CurrentPerson != null ? CurrentPerson.Id : 0;
                foreach (var activity in _workflow.Activities
                         .Where(a =>
                                a.IsActive &&
                                (
                                    (!a.AssignedGroupId.HasValue && !a.AssignedPersonAliasId.HasValue) ||
                                    (a.AssignedPersonAlias != null && a.AssignedPersonAlias.PersonId == personId) ||
                                    (a.AssignedGroup != null && a.AssignedGroup.Members.Any(m => m.PersonId == personId))
                                )
                                )
                         .OrderBy(a => a.ActivityType.Order))
                {
                    if (canEdit || (activity.ActivityType.IsAuthorized(Authorization.VIEW, CurrentPerson)))
                    {
                        foreach (var action in activity.ActiveActions)
                        {
                            if (action.ActionType.WorkflowForm != null && action.IsCriteriaValid)
                            {
                                _activity = activity;
                                _activity.LoadAttributes();

                                _action      = action;
                                _actionType  = _action.ActionType;
                                ActionTypeId = _actionType.Id;
                                return(true);
                            }
                        }
                    }
                }
            }

            ShowNotes(false);
            ShowMessage(NotificationBoxType.Warning, string.Empty, "The selected workflow is not in a state that requires you to enter information.");
            return(false);
        }
コード例 #26
0
        /// <summary>
        /// Handles the Click event of the btnSave control. Perform a save operation on
        /// the person being edited and then navigate to the return page.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            RockContext rockContext           = new RockContext();
            Person      person                = new PersonService(rockContext).Get(TargetPersonId);
            Guid        emailWorkflowTypeGuid = Guid.Empty;

            rockContext.WrapTransaction(() =>
            {
                var changes = new List <string>();

                //
                // Process the nick name.
                //
                if (GetAttributeValue("EditNickName").AsBoolean(true))
                {
                    History.EvaluateChange(changes, "Nick Name", person.NickName, tbNickName.Text.Trim());
                    person.NickName = tbNickName.Text.Trim();
                }

                //
                // Process the gender.
                //
                var newGender = rblGender.SelectedValue.ConvertToEnum <Gender>();
                History.EvaluateChange(changes, "Gender", person.Gender, newGender);
                person.Gender = newGender;

                //
                // Process the birthday.
                //
                if (GetAttributeValue("EditBirthday").AsBoolean(true))
                {
                    var birthMonth = person.BirthMonth;
                    var birthDay   = person.BirthDay;
                    var birthYear  = person.BirthYear;
                    var birthday   = bpBirthDay.SelectedDate;

                    if (birthday.HasValue)
                    {
                        // If setting a future birthdate, subtract a century until birthdate is not greater than today.
                        var today = RockDateTime.Today;
                        while (birthday.Value.CompareTo(today) > 0)
                        {
                            birthday = birthday.Value.AddYears(-100);
                        }

                        person.BirthMonth = birthday.Value.Month;
                        person.BirthDay   = birthday.Value.Day;
                        if (birthday.Value.Year != DateTime.MinValue.Year)
                        {
                            person.BirthYear = birthday.Value.Year;
                        }
                        else
                        {
                            person.BirthYear = null;
                        }
                    }
                    else
                    {
                        person.SetBirthDate(null);
                    }

                    History.EvaluateChange(changes, "Birth Month", birthMonth, person.BirthMonth);
                    History.EvaluateChange(changes, "Birth Day", birthDay, person.BirthDay);
                    History.EvaluateChange(changes, "Birth Year", birthYear, person.BirthYear);
                }

                //
                // Process the grade / graduation year.
                //
                if (GetAttributeValue("EditGrade").AsBoolean(true))
                {
                    int?graduationYear = null;
                    if (ypGraduation.SelectedYear.HasValue)
                    {
                        graduationYear = ypGraduation.SelectedYear.Value;
                    }

                    History.EvaluateChange(changes, "Graduation Year", person.GraduationYear, graduationYear);
                    person.GraduationYear = graduationYear;
                }

                //
                // Process the marital status and anniversary date.
                //
                if (GetAttributeValue("EditMaritalStatus").AsBoolean(true))
                {
                    int?newMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Marital Status", DefinedValueCache.GetName(person.MaritalStatusValueId), DefinedValueCache.GetName(newMaritalStatusId));
                    person.MaritalStatusValueId = newMaritalStatusId;

                    History.EvaluateChange(changes, "Anniversary Date", person.AnniversaryDate, dpAnniversaryDate.SelectedDate);
                    person.AnniversaryDate = dpAnniversaryDate.SelectedDate;
                }

                //
                // Process the e-mail address.
                //
                if (GetAttributeValue("EditEmail").AsBoolean(true))
                {
                    emailWorkflowTypeGuid = GetAttributeValue("EmailChangeWorkflow").AsGuid();

                    if (emailWorkflowTypeGuid == Guid.Empty)
                    {
                        History.EvaluateChange(changes, "Email", person.Email, tbEmail.Text.Trim());
                        person.Email = tbEmail.Text.Trim();
                    }
                }

                //
                // Process all the phone numbers for this person.
                //
                bool smsSelected       = false;
                var phoneNumberTypeIds = new List <int>();
                foreach (RepeaterItem item in rContactInfo.Items)
                {
                    HiddenField hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                    PhoneNumberBox pnbPhone = item.FindControl("pnbPhone") as PhoneNumberBox;
                    CheckBox cbSms          = item.FindControl("cbSms") as CheckBox;

                    if (hfPhoneType != null &&
                        pnbPhone != null &&
                        cbSms != null)
                    {
                        if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                        {
                            int phoneNumberTypeId;
                            if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                            {
                                var phoneNumber       = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId);
                                string oldPhoneNumber = string.Empty;
                                if (phoneNumber == null)
                                {
                                    phoneNumber = new PhoneNumber {
                                        NumberTypeValueId = phoneNumberTypeId
                                    };
                                    person.PhoneNumbers.Add(phoneNumber);
                                }
                                else
                                {
                                    oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                                }

                                phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                                phoneNumber.Number      = PhoneNumber.CleanNumber(pnbPhone.Number);

                                // Only allow one number to have SMS selected
                                if (smsSelected)
                                {
                                    phoneNumber.IsMessagingEnabled = false;
                                }
                                else
                                {
                                    phoneNumber.IsMessagingEnabled = cbSms.Checked;
                                    smsSelected = cbSms.Checked;
                                }

                                phoneNumberTypeIds.Add(phoneNumberTypeId);

                                History.EvaluateChange(
                                    changes,
                                    string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumberTypeId)),
                                    oldPhoneNumber,
                                    phoneNumber.NumberFormattedWithCountryCode);
                            }
                        }
                    }
                }

                //
                // Remove any blank numbers.
                //
                var phoneNumberService = new PhoneNumberService(rockContext);
                foreach (var phoneNumber in person.PhoneNumbers
                         .Where(n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains(n.NumberTypeValueId.Value))
                         .ToList())
                {
                    History.EvaluateChange(
                        changes,
                        string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumber.NumberTypeValueId)),
                        phoneNumber.ToString(),
                        string.Empty);

                    person.PhoneNumbers.Remove(phoneNumber);
                    phoneNumberService.Delete(phoneNumber);
                }

                //
                // If the person is valid then save the person and begin
                // working on the family (address).
                //
                if (person.IsValid)
                {
                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(Person),
                                Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                person.Id,
                                changes);

                            changes.Clear();
                        }
                    }

                    //
                    // Save the family address information.
                    //
                    if (pnlAddress.Visible)
                    {
                        Guid?familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull();
                        if (familyGroupTypeGuid.HasValue)
                        {
                            var familyGroup = new GroupService(rockContext).Queryable()
                                              .Where(f => f.GroupType.Guid == familyGroupTypeGuid.Value &&
                                                     f.Members.Any(m => m.PersonId == person.Id))
                                              .FirstOrDefault();
                            if (familyGroup != null)
                            {
                                Guid?addressTypeGuid = GetAttributeValue("AddressType").AsGuidOrNull();
                                if (addressTypeGuid.HasValue)
                                {
                                    var groupLocationService = new GroupLocationService(rockContext);

                                    var addressTypeDv = DefinedValueCache.Read(addressTypeGuid.Value);
                                    var familyAddress = groupLocationService.Queryable().Where(l => l.GroupId == familyGroup.Id && l.GroupLocationTypeValueId == addressTypeDv.Id).FirstOrDefault();
                                    if (familyAddress != null && string.IsNullOrWhiteSpace(acAddress.Street1))
                                    {
                                        // delete the current address
                                        History.EvaluateChange(changes, familyAddress.GroupLocationTypeValue.Value + " Location", familyAddress.Location.ToString(), string.Empty);
                                        groupLocationService.Delete(familyAddress);
                                        rockContext.SaveChanges();
                                    }
                                    else
                                    {
                                        if (!string.IsNullOrWhiteSpace(acAddress.Street1))
                                        {
                                            var previousAddressValue = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());

                                            if (familyAddress == null)
                                            {
                                                familyAddress = new GroupLocation();
                                                groupLocationService.Add(familyAddress);
                                                familyAddress.GroupLocationTypeValueId = addressTypeDv.Id;
                                                familyAddress.GroupId           = familyGroup.Id;
                                                familyAddress.IsMailingLocation = true;
                                                familyAddress.IsMappedLocation  = true;
                                            }
                                            else if (addressTypeDv.Guid == Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid() && previousAddressValue != null)
                                            {
                                                var isChanged = familyAddress.Location.Street1 != acAddress.Street1 ||
                                                                familyAddress.Location.Street2 != acAddress.Street2 ||
                                                                familyAddress.Location.City != acAddress.City ||
                                                                familyAddress.Location.State != acAddress.State ||
                                                                familyAddress.Location.PostalCode != acAddress.PostalCode;

                                                var hasPrevious = groupLocationService
                                                                  .Queryable("Location")
                                                                  .Where(l => l.GroupLocationTypeValueId == previousAddressValue.Id && l.GroupId == familyGroup.Id)
                                                                  .Where(l => l.Location.Street1 == familyAddress.Location.Street1)
                                                                  .Where(l => l.Location.Street2 == familyAddress.Location.Street2)
                                                                  .Where(l => l.Location.City == familyAddress.Location.City)
                                                                  .Where(l => l.Location.State == familyAddress.Location.State)
                                                                  .Where(l => l.Location.PostalCode == familyAddress.Location.PostalCode)
                                                                  .Where(l => l.Location.Country == familyAddress.Location.Country)
                                                                  .Any();

                                                //
                                                // Only save the previous address if it has actually changed and there is not
                                                // already a matching previous address.
                                                //
                                                if (isChanged && !hasPrevious)
                                                {
                                                    var previousAddress = new GroupLocation();
                                                    groupLocationService.Add(previousAddress);

                                                    previousAddress.GroupLocationTypeValueId = previousAddressValue.Id;
                                                    previousAddress.GroupId = familyGroup.Id;

                                                    Location previousAddressLocation   = new Location();
                                                    previousAddressLocation.Street1    = familyAddress.Location.Street1;
                                                    previousAddressLocation.Street2    = familyAddress.Location.Street2;
                                                    previousAddressLocation.City       = familyAddress.Location.City;
                                                    previousAddressLocation.State      = familyAddress.Location.State;
                                                    previousAddressLocation.PostalCode = familyAddress.Location.PostalCode;
                                                    previousAddressLocation.Country    = familyAddress.Location.Country;

                                                    previousAddress.Location = previousAddressLocation;
                                                }
                                            }

                                            familyAddress.IsMailingLocation = cbIsMailingAddress.Checked;
                                            familyAddress.IsMappedLocation  = cbIsPhysicalAddress.Checked;

                                            var updatedHomeAddress = new Location();
                                            acAddress.GetValues(updatedHomeAddress);

                                            History.EvaluateChange(changes, addressTypeDv.Value + " Location", familyAddress.Location != null ? familyAddress.Location.ToString() : string.Empty, updatedHomeAddress.ToString());

                                            familyAddress.Location = updatedHomeAddress;
                                            rockContext.SaveChanges();
                                        }
                                    }

                                    HistoryService.SaveChanges(
                                        rockContext,
                                        typeof(Person),
                                        Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                        person.Id,
                                        changes);
                                }
                            }
                        }
                    }
                }
            });

            if (emailWorkflowTypeGuid != Guid.Empty)
            {
                LaunchEmailWorkflow(emailWorkflowTypeGuid, person, tbEmail.Text.Trim());
            }

            if (!string.IsNullOrWhiteSpace(GetAttributeValue("SuccessTemplate")))
            {
                pnlEdit.Visible    = false;
                pnlSuccess.Visible = true;

                nbSuccess.Text = GetAttributeValue("SuccessTemplate").ResolveMergeFields(new Dictionary <string, object>());
            }
            else
            {
                NavigateToParentPage();
            }
        }
コード例 #27
0
        /// <summary>
        /// Handles the Click event to save the prayer request.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!IsValid())
            {
                return;
            }

            bool isAutoApproved          = GetAttributeValue("EnableAutoApprove").AsBoolean();
            bool defaultAllowComments    = GetAttributeValue("DefaultAllowCommentsSetting").AsBoolean();
            bool isPersonMatchingEnabled = GetAttributeValue("EnablePersonMatching").AsBoolean();

            PrayerRequest prayerRequest = new PrayerRequest {
                Id = 0, IsActive = true, IsApproved = isAutoApproved, AllowComments = defaultAllowComments
            };

            var rockContext = new RockContext();

            prayerRequest.EnteredDateTime = RockDateTime.Now;

            if (isAutoApproved)
            {
                prayerRequest.ApprovedByPersonAliasId = CurrentPersonAliasId;
                prayerRequest.ApprovedOnDateTime      = RockDateTime.Now;
                var expireDays = Convert.ToDouble(GetAttributeValue("ExpireDays"));
                prayerRequest.ExpirationDate = RockDateTime.Now.AddDays(expireDays);
            }

            // Now record all the bits...
            // Make sure the Category is hydrated so it's included for any Lava processing
            Category category;
            int?     categoryId          = bddlCategory.SelectedValueAsInt();
            Guid     defaultCategoryGuid = GetAttributeValue("DefaultCategory").AsGuid();

            if (categoryId == null && !defaultCategoryGuid.IsEmpty())
            {
                category   = new CategoryService(rockContext).Get(defaultCategoryGuid);
                categoryId = category.Id;
            }
            else
            {
                category = new CategoryService(rockContext).Get(categoryId.Value);
            }

            prayerRequest.CategoryId = categoryId;
            prayerRequest.Category   = category;

            var personContext = this.ContextEntity <Person>();

            if (personContext == null)
            {
                Person person = null;
                if (isPersonMatchingEnabled)
                {
                    var personService = new PersonService(new RockContext());
                    person = personService.FindPerson(new PersonService.PersonMatchQuery(tbFirstName.Text, tbLastName.Text, tbEmail.Text, pnbPhone.Number), false, true, false);

                    if (person == null && (!string.IsNullOrWhiteSpace(tbEmail.Text) || !string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number))))
                    {
                        var personRecordTypeId  = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                        var personStatusPending = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid()).Id;

                        person                     = new Person();
                        person.IsSystem            = false;
                        person.RecordTypeValueId   = personRecordTypeId;
                        person.RecordStatusValueId = personStatusPending;
                        person.FirstName           = tbFirstName.Text;
                        person.LastName            = tbLastName.Text;
                        person.Gender              = Gender.Unknown;

                        if (!string.IsNullOrWhiteSpace(tbEmail.Text))
                        {
                            person.Email           = tbEmail.Text;
                            person.IsEmailActive   = true;
                            person.EmailPreference = EmailPreference.EmailAllowed;
                        }

                        PersonService.SaveNewPerson(person, rockContext, cpCampus.SelectedCampusId);

                        if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                        {
                            var mobilePhoneType = DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE));

                            var phoneNumber = new PhoneNumber {
                                NumberTypeValueId = mobilePhoneType.Id
                            };
                            phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                            phoneNumber.Number      = PhoneNumber.CleanNumber(pnbPhone.Number);
                            person.PhoneNumbers.Add(phoneNumber);
                        }
                    }
                }

                prayerRequest.FirstName = tbFirstName.Text;
                prayerRequest.LastName  = tbLastName.Text;
                prayerRequest.Email     = tbEmail.Text;
                if (person != null)
                {
                    prayerRequest.RequestedByPersonAliasId = person.PrimaryAliasId;

                    // If there is no active user, set the CreatedBy field to show that this record was created by the requester.
                    if (CurrentPersonAliasId == null)
                    {
                        prayerRequest.CreatedByPersonAliasId = person.PrimaryAliasId;
                    }
                }
                else
                {
                    prayerRequest.RequestedByPersonAliasId = CurrentPersonAliasId;
                }
            }
            else
            {
                prayerRequest.RequestedByPersonAliasId = personContext.PrimaryAliasId;
                prayerRequest.FirstName = string.IsNullOrEmpty(personContext.NickName) ? personContext.FirstName : personContext.NickName;
                prayerRequest.LastName  = personContext.LastName;
                prayerRequest.Email     = personContext.Email;
            }

            prayerRequest.CampusId = cpCampus.SelectedCampusId;

            prayerRequest.Text = dtbRequest.Text;

            if (this.EnableUrgentFlag)
            {
                prayerRequest.IsUrgent = cbIsUrgent.Checked;
            }
            else
            {
                prayerRequest.IsUrgent = false;
            }

            if (this.EnableCommentsFlag)
            {
                prayerRequest.AllowComments = cbAllowComments.Checked;
            }

            if (this.EnablePublicDisplayFlag)
            {
                prayerRequest.IsPublic = cbAllowPublicDisplay.Checked;
            }
            else
            {
                prayerRequest.IsPublic = this.DefaultToPublic;
            }

            if (!Page.IsValid)
            {
                return;
            }

            PrayerRequestService prayerRequestService = new PrayerRequestService(rockContext);

            prayerRequestService.Add(prayerRequest);
            prayerRequest.LoadAttributes(rockContext);
            avcEditAttributes.GetEditValues(prayerRequest);

            if (!prayerRequest.IsValid)
            {
                // field controls render error messages
                return;
            }

            rockContext.WrapTransaction(() =>
            {
                rockContext.SaveChanges();
                prayerRequest.SaveAttributeValues(rockContext);
            });

            PrepareObjectForLavaContext(prayerRequest, rockContext);

            StartWorkflow(prayerRequest, rockContext);

            bool isNavigateToParent = GetAttributeValue("NavigateToParentOnSave").AsBoolean();

            if (isNavigateToParent)
            {
                NavigateToParentPage();
            }
            else if (GetAttributeValue("RefreshPageOnSave").AsBoolean())
            {
                NavigateToCurrentPage(this.PageParameters().Where(a => a.Value is string).ToDictionary(k => k.Key, v => v.Value.ToString()));
            }
            else
            {
                pnlForm.Visible    = false;
                pnlReceipt.Visible = true;

                // Build success text that is Lava capable
                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                mergeFields.Add("PrayerRequest", prayerRequest);
                nbMessage.Text = GetAttributeValue("SaveSuccessText").ResolveMergeFields(mergeFields);

                // Resolve any dynamic url references
                string appRoot   = ResolveRockUrl("~/");
                string themeRoot = ResolveRockUrl("~~/");
                nbMessage.Text = nbMessage.Text.Replace("~~/", themeRoot).Replace("~/", appRoot);
            }
        }
コード例 #28
0
ファイル: SiteDetail.ascx.cs プロジェクト: sjison/Rock
        /// <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="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            Site site;

            if (Page.IsValid)
            {
                var               rockContext       = new RockContext();
                PageService       pageService       = new PageService(rockContext);
                SiteService       siteService       = new SiteService(rockContext);
                SiteDomainService siteDomainService = new SiteDomainService(rockContext);
                bool              newSite           = false;

                int siteId = hfSiteId.Value.AsInteger();

                if (siteId == 0)
                {
                    newSite = true;
                    site    = new Rock.Model.Site();
                    siteService.Add(site);
                }
                else
                {
                    site = siteService.Get(siteId);
                }

                site.Name                      = tbSiteName.Text;
                site.Description               = tbDescription.Text;
                site.Theme                     = ddlTheme.Text;
                site.DefaultPageId             = ppDefaultPage.PageId;
                site.DefaultPageRouteId        = ppDefaultPage.PageRouteId;
                site.LoginPageId               = ppLoginPage.PageId;
                site.LoginPageRouteId          = ppLoginPage.PageRouteId;
                site.ChangePasswordPageId      = ppChangePasswordPage.PageId;
                site.ChangePasswordPageRouteId = ppChangePasswordPage.PageRouteId;
                site.CommunicationPageId       = ppCommunicationPage.PageId;
                site.CommunicationPageRouteId  = ppCommunicationPage.PageRouteId;
                site.RegistrationPageId        = ppRegistrationPage.PageId;
                site.RegistrationPageRouteId   = ppRegistrationPage.PageRouteId;
                site.PageNotFoundPageId        = ppPageNotFoundPage.PageId;
                site.PageNotFoundPageRouteId   = ppPageNotFoundPage.PageRouteId;
                site.ErrorPage                 = tbErrorPage.Text;
                site.GoogleAnalyticsCode       = tbGoogleAnalytics.Text;
                site.RequiresEncryption        = cbRequireEncryption.Checked;
                site.EnabledForShortening      = cbEnableForShortening.Checked;
                site.EnableMobileRedirect      = cbEnableMobileRedirect.Checked;
                site.MobilePageId              = ppMobilePage.PageId;
                site.ExternalUrl               = tbExternalURL.Text;
                site.AllowedFrameDomains       = tbAllowedFrameDomains.Text;
                site.RedirectTablets           = cbRedirectTablets.Checked;
                site.EnablePageViews           = cbEnablePageViews.Checked;

                site.AllowIndexing         = cbAllowIndexing.Checked;
                site.IsIndexEnabled        = cbEnableIndexing.Checked;
                site.IndexStartingLocation = tbIndexStartingLocation.Text;

                site.PageHeaderContent = cePageHeaderContent.Text;

                int?existingIconId = null;
                if (site.FavIconBinaryFileId != imgSiteIcon.BinaryFileId)
                {
                    existingIconId           = site.FavIconBinaryFileId;
                    site.FavIconBinaryFileId = imgSiteIcon.BinaryFileId;
                }

                var currentDomains = tbSiteDomains.Text.SplitDelimitedValues().ToList <string>();
                site.SiteDomains = site.SiteDomains ?? new List <SiteDomain>();

                // Remove any deleted domains
                foreach (var domain in site.SiteDomains.Where(w => !currentDomains.Contains(w.Domain)).ToList())
                {
                    site.SiteDomains.Remove(domain);
                    siteDomainService.Delete(domain);
                }

                int order = 0;
                foreach (string domain in currentDomains)
                {
                    SiteDomain sd = site.SiteDomains.Where(d => d.Domain == domain).FirstOrDefault();
                    if (sd == null)
                    {
                        sd        = new SiteDomain();
                        sd.Domain = domain;
                        sd.Guid   = Guid.NewGuid();
                        site.SiteDomains.Add(sd);
                    }
                    sd.Order = order++;
                }

                if (!site.DefaultPageId.HasValue && !newSite)
                {
                    ppDefaultPage.ShowErrorMessage("Default Page is required.");
                    return;
                }

                if (!site.IsValid)
                {
                    // Controls will render the error messages
                    return;
                }

                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();

                    SaveAttributes(new Page().TypeId, "SiteId", site.Id.ToString(), PageAttributesState, rockContext);

                    if (existingIconId.HasValue)
                    {
                        BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                        var binaryFile = binaryFileService.Get(existingIconId.Value);
                        if (binaryFile != null)
                        {
                            // marked the old images as IsTemporary so they will get cleaned up later
                            binaryFile.IsTemporary = true;
                            rockContext.SaveChanges();
                        }
                    }

                    if (newSite)
                    {
                        Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.EDIT);
                        Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.ADMINISTRATE);
                        Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.APPROVE);
                    }
                });

                // add/update for the InteractionChannel for this site and set the RetentionPeriod
                var interactionChannelService   = new InteractionChannelService(rockContext);
                int channelMediumWebsiteValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id;
                var interactionChannelForSite   = interactionChannelService.Queryable()
                                                  .Where(a => a.ChannelTypeMediumValueId == channelMediumWebsiteValueId && a.ChannelEntityId == site.Id).FirstOrDefault();

                if (interactionChannelForSite == null)
                {
                    interactionChannelForSite = new InteractionChannel();
                    interactionChannelForSite.ChannelTypeMediumValueId = channelMediumWebsiteValueId;
                    interactionChannelForSite.ChannelEntityId          = site.Id;
                    interactionChannelService.Add(interactionChannelForSite);
                }

                interactionChannelForSite.Name = site.Name;
                interactionChannelForSite.RetentionDuration     = nbPageViewRetentionPeriodDays.Text.AsIntegerOrNull();
                interactionChannelForSite.ComponentEntityTypeId = EntityTypeCache.Read <Rock.Model.Page>().Id;

                rockContext.SaveChanges();

                foreach (int pageId in pageService.GetBySiteId(site.Id)
                         .Select(p => p.Id)
                         .ToList())
                {
                    PageCache.Flush(pageId);
                }
                SiteCache.Flush(site.Id);
                AttributeCache.FlushEntityAttributes();

                // Create the default page is this is a new site
                if (!site.DefaultPageId.HasValue && newSite)
                {
                    var siteCache = SiteCache.Read(site.Id);

                    // Create the layouts for the site, and find the first one
                    LayoutService.RegisterLayouts(Request.MapPath("~"), siteCache);

                    var    layoutService = new LayoutService(rockContext);
                    var    layouts       = layoutService.GetBySiteId(siteCache.Id);
                    Layout layout        = layouts.FirstOrDefault(l => l.FileName.Equals("FullWidth", StringComparison.OrdinalIgnoreCase));
                    if (layout == null)
                    {
                        layout = layouts.FirstOrDefault();
                    }

                    if (layout != null)
                    {
                        var page = new Page();
                        page.LayoutId              = layout.Id;
                        page.PageTitle             = siteCache.Name + " Home Page";
                        page.InternalName          = page.PageTitle;
                        page.BrowserTitle          = page.PageTitle;
                        page.EnableViewState       = true;
                        page.IncludeAdminFooter    = true;
                        page.MenuDisplayChildPages = true;

                        var lastPage = pageService.GetByParentPageId(null).OrderByDescending(b => b.Order).FirstOrDefault();

                        page.Order = lastPage != null ? lastPage.Order + 1 : 0;
                        pageService.Add(page);

                        rockContext.SaveChanges();

                        site = siteService.Get(siteCache.Id);
                        site.DefaultPageId = page.Id;

                        rockContext.SaveChanges();

                        SiteCache.Flush(site.Id);
                    }
                }

                var qryParams = new Dictionary <string, string>();
                qryParams["siteId"] = site.Id.ToString();

                NavigateToPage(RockPage.Guid, qryParams);
            }
        }
コード例 #29
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="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            BinaryFile        binaryFile;
            var               rockContext       = new RockContext();
            BinaryFileService binaryFileService = new BinaryFileService(rockContext);
            AttributeService  attributeService  = new AttributeService(rockContext);

            int?prevBinaryFileTypeId = null;

            int binaryFileId = int.Parse(hfBinaryFileId.Value);

            if (binaryFileId == 0)
            {
                binaryFile = new BinaryFile();
                binaryFileService.Add(binaryFile);
            }
            else
            {
                binaryFile           = binaryFileService.Get(binaryFileId);
                prevBinaryFileTypeId = binaryFile != null ? binaryFile.BinaryFileTypeId : (int?)null;
            }

            // if a new file was uploaded, copy the uploaded file to this binaryFile (uploaded files are always new temporary binaryFiles)
            if (fsFile.BinaryFileId != binaryFile.Id)
            {
                var uploadedBinaryFile = binaryFileService.Get(fsFile.BinaryFileId ?? 0);
                if (uploadedBinaryFile != null)
                {
                    binaryFile.BinaryFileTypeId = uploadedBinaryFile.BinaryFileTypeId;
                    binaryFile.FileSize         = uploadedBinaryFile.FileSize;
                    var memoryStream = new MemoryStream();
                    uploadedBinaryFile.ContentStream.CopyTo(memoryStream);
                    binaryFile.ContentStream = memoryStream;
                }
            }

            binaryFile.IsTemporary      = false;
            binaryFile.FileName         = tbName.Text;
            binaryFile.Description      = tbDescription.Text;
            binaryFile.MimeType         = tbMimeType.Text;
            binaryFile.BinaryFileTypeId = ddlBinaryFileType.SelectedValueAsInt();

            binaryFile.LoadAttributes(rockContext);
            Rock.Attribute.Helper.GetEditValues(phAttributes, binaryFile);

            if (!Page.IsValid)
            {
                return;
            }

            if (!binaryFile.IsValid)
            {
                // Controls will render the error messages
                return;
            }

            rockContext.WrapTransaction(() =>
            {
                foreach (var id in OrphanedBinaryFileIdList)
                {
                    var tempBinaryFile = binaryFileService.Get(id);
                    if (tempBinaryFile != null && tempBinaryFile.IsTemporary)
                    {
                        binaryFileService.Delete(tempBinaryFile);
                    }
                }

                rockContext.SaveChanges();
                binaryFile.SaveAttributeValues(rockContext);
            });

            Rock.CheckIn.KioskLabel.Flush(binaryFile.Guid);

            if (!prevBinaryFileTypeId.Equals(binaryFile.BinaryFileTypeId))
            {
                var checkInBinaryFileType = new BinaryFileTypeService(rockContext)
                                            .Get(Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL.AsGuid());
                if (checkInBinaryFileType != null && (
                        (prevBinaryFileTypeId.HasValue && prevBinaryFileTypeId.Value == checkInBinaryFileType.Id) ||
                        (binaryFile.BinaryFileTypeId.HasValue && binaryFile.BinaryFileTypeId.Value == checkInBinaryFileType.Id)))
                {
                    Rock.CheckIn.KioskDevice.FlushAll();
                }
            }

            NavigateToParentPage();
        }
        /// <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="EventArgs"/> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            AttributeMatrixTemplate attributeMatrixTemplate;
            var rockContext = new RockContext();
            var attributeMatrixTemplateService = new AttributeMatrixTemplateService(rockContext);

            int attributeMatrixTemplateId = int.Parse(hfAttributeMatrixTemplateId.Value);

            if (attributeMatrixTemplateId == 0)
            {
                attributeMatrixTemplate = new AttributeMatrixTemplate();
                attributeMatrixTemplateService.Add(attributeMatrixTemplate);
            }
            else
            {
                attributeMatrixTemplate = attributeMatrixTemplateService.Get(attributeMatrixTemplateId);
            }

            attributeMatrixTemplate.Name          = tbName.Text;
            attributeMatrixTemplate.IsActive      = cbIsActive.Checked;
            attributeMatrixTemplate.Description   = tbDescription.Text;
            attributeMatrixTemplate.MinimumRows   = tbMinimumRows.Text.AsIntegerOrNull();
            attributeMatrixTemplate.MaximumRows   = tbMaximumRows.Text.AsIntegerOrNull();
            attributeMatrixTemplate.FormattedLava = ceFormattedLava.Text;

            // need WrapTransaction due to Attribute saves
            rockContext.WrapTransaction(() =>
            {
                rockContext.SaveChanges();

                /* Save Attributes */

                var entityTypeIdAttributeMatrix = EntityTypeCache.GetId <AttributeMatrixItem>();

                // Get the existing attributes for this entity type and qualifier value
                var attributeService = new AttributeService(rockContext);
                var regFieldService  = new RegistrationTemplateFormFieldService(rockContext);
                var attributes       = attributeService.GetByEntityTypeQualifier(entityTypeIdAttributeMatrix, "AttributeMatrixTemplateId", attributeMatrixTemplate.Id.ToString(), true);

                // Delete any of those attributes that were removed in the UI
                var selectedAttributeGuids = AttributesState.Select(a => a.Guid);
                foreach (var attr in attributes.Where(a => !selectedAttributeGuids.Contains(a.Guid)))
                {
                    foreach (var field in regFieldService.Queryable().Where(f => f.AttributeId.HasValue && f.AttributeId.Value == attr.Id).ToList())
                    {
                        regFieldService.Delete(field);
                    }

                    attributeService.Delete(attr);
                    rockContext.SaveChanges();
                }

                // Update the Attributes that were assigned in the UI
                foreach (var attributeState in AttributesState)
                {
                    Helper.SaveAttributeEdits(attributeState, entityTypeIdAttributeMatrix, "AttributeMatrixTemplateId", attributeMatrixTemplate.Id.ToString(), rockContext);
                }
            });

            NavigateToParentPage();
        }