Ejemplo n.º 1
0
        /// <summary>
        /// Saves the changes.
        /// </summary>
        /// <param name="item">The item.</param>
        protected void SaveChanges(RepeaterItem item)
        {
            var hfGroupId = item.FindControl("hfGroupId") as HiddenField;
            var cbCommunicationListIsSubscribed = item.FindControl("cbCommunicationListIsSubscribed") as RockCheckBox;
            var tglCommunicationPreference      = item.FindControl("tglCommunicationPreference") as Toggle;
            var nbGroupNotification             = item.FindControl("nbGroupNotification") as NotificationBox;

            nbGroupNotification.Visible = false;

            using (var rockContext = new RockContext())
            {
                int groupId            = hfGroupId.Value.AsInteger();
                var groupMemberService = new GroupMemberService(rockContext);
                var group = new GroupService(rockContext).Get(groupId);
                var groupMemberRecordsForPerson = groupMemberService.Queryable().Where(a => a.GroupId == groupId && a.PersonId == this.CurrentPersonId).ToList();
                if (groupMemberRecordsForPerson.Any())
                {
                    // normally there would be at most 1 group member record for the person, but just in case, mark them all
                    foreach (var groupMember in groupMemberRecordsForPerson)
                    {
                        if (cbCommunicationListIsSubscribed.Checked)
                        {
                            if (groupMember.GroupMemberStatus == GroupMemberStatus.Inactive)
                            {
                                groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                                if (groupMember.Note == "Unsubscribed")
                                {
                                    groupMember.Note = string.Empty;
                                }
                            }
                        }
                        else
                        {
                            if (groupMember.GroupMemberStatus == GroupMemberStatus.Active)
                            {
                                groupMember.GroupMemberStatus = GroupMemberStatus.Inactive;
                                if (groupMember.Note.IsNullOrWhiteSpace())
                                {
                                    groupMember.Note = "Unsubscribed";
                                }
                            }
                        }

                        groupMember.LoadAttributes();
                        CommunicationType communicationType = tglCommunicationPreference.Checked ? CommunicationType.Email : CommunicationType.SMS;
                        groupMember.SetAttributeValue("PreferredCommunicationMedium", communicationType.ConvertToInt().ToString());
                        groupMember.SaveAttributeValue("PreferredCommunicationMedium", rockContext);
                    }
                }
                else
                {
                    // they are not currently in the Group
                    if (cbCommunicationListIsSubscribed.Checked)
                    {
                        var groupMember = new GroupMember();
                        groupMember.PersonId = this.CurrentPersonId.Value;
                        groupMember.GroupId  = group.Id;
                        int?defaultGroupRoleId = GroupTypeCache.Read(group.GroupTypeId).DefaultGroupRoleId;
                        if (defaultGroupRoleId.HasValue)
                        {
                            groupMember.GroupRoleId = defaultGroupRoleId.Value;
                        }
                        else
                        {
                            nbGroupNotification.Text                = "Unable to add to group.";
                            nbGroupNotification.Details             = "Group has no default group role";
                            nbGroupNotification.NotificationBoxType = NotificationBoxType.Danger;
                            nbGroupNotification.Visible             = true;
                        }

                        groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                        groupMember.LoadAttributes();
                        CommunicationType communicationType = tglCommunicationPreference.Checked ? CommunicationType.Email : CommunicationType.SMS;
                        groupMember.SetAttributeValue("PreferredCommunicationMedium", communicationType.ConvertToInt().ToString());

                        if (groupMember.IsValidGroupMember(rockContext))
                        {
                            groupMemberService.Add(groupMember);
                            rockContext.SaveChanges();
                            groupMember.SaveAttributeValue("PreferredCommunicationMedium", rockContext);

                            if (group.IsSecurityRole || group.GroupType.Guid.Equals(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid()))
                            {
                                Rock.Security.Role.Flush(group.Id);
                            }
                        }
                        else
                        {
                            // if the group member couldn't be added (for example, one of the group membership rules didn't pass), add the validation messages to the errormessages
                            nbGroupNotification.Text                = "Unable to add to group.";
                            nbGroupNotification.Details             = groupMember.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                            nbGroupNotification.NotificationBoxType = NotificationBoxType.Danger;
                            nbGroupNotification.Visible             = true;
                        }
                    }
                }

                rockContext.SaveChanges();
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            Guid?  groupGuid = null;
            Person person    = null;
            Group  group     = null;
            string noteValue = string.Empty;

            // get the group attribute
            Guid groupAttributeGuid = GetAttributeValue(action, "Group").AsGuid();

            if (!groupAttributeGuid.IsEmpty())
            {
                groupGuid = action.GetWorklowAttributeValue(groupAttributeGuid).AsGuidOrNull();

                if (groupGuid.HasValue)
                {
                    group = new GroupService(rockContext).Get(groupGuid.Value);

                    if (group == null)
                    {
                        errorMessages.Add("The group provided does not exist.");
                    }
                }
                else
                {
                    errorMessages.Add("Invalid group provided.");
                }
            }

            // get person alias guid
            Guid   personAliasGuid = Guid.Empty;
            string personAttribute = GetAttributeValue(action, "Person");

            Guid guid = personAttribute.AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Read(guid, rockContext);
                if (attribute != null)
                {
                    string value = action.GetWorklowAttributeValue(guid);
                    personAliasGuid = value.AsGuid();
                }

                if (personAliasGuid != Guid.Empty)
                {
                    person = new PersonAliasService(rockContext).Queryable()
                             .Where(p => p.Guid.Equals(personAliasGuid))
                             .Select(p => p.Person)
                             .FirstOrDefault();

                    if (person == null)
                    {
                        errorMessages.Add("The person could not be found.");
                    }
                }
                else
                {
                    errorMessages.Add("Invalid person provided.");
                }
            }

            // get group member note
            noteValue = GetAttributeValue(action, "Note");
            guid      = noteValue.AsGuid();
            if (guid.IsEmpty())
            {
                noteValue = noteValue.ResolveMergeFields(GetMergeFields(action));
            }
            else
            {
                var workflowAttributeValue = action.GetWorklowAttributeValue(guid);

                if (workflowAttributeValue != null)
                {
                    noteValue = workflowAttributeValue;
                }
            }

            // set note
            if (group != null && person != null)
            {
                var groupMembers = new GroupMemberService(rockContext).Queryable()
                                   .Where(m => m.Group.Guid == groupGuid && m.PersonId == person.Id).ToList();

                if (groupMembers.Count() > 0)
                {
                    foreach (var groupMember in groupMembers)
                    {
                        groupMember.Note = noteValue;
                        rockContext.SaveChanges();
                    }
                }
                else
                {
                    errorMessages.Add(string.Format("{0} is not a member of the group {1}.", person.FullName, group.Name));
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            var expireDays = dataMap.GetString("ExpireDate").AsIntegerOrNull() ?? 1;

            int remindersSent = 0;

            using (var rockContext = new RockContext())
            {
                DateTime now        = RockDateTime.Now;
                DateTime expireDate = now.AddDays(expireDays * -1);

                foreach (var instance in new RegistrationInstanceService(rockContext)
                         .Queryable("RegistrationTemplate,Registrations")
                         .Where(i =>
                                i.IsActive &&
                                i.RegistrationTemplate.IsActive &&
                                i.RegistrationTemplate.ReminderEmailTemplate != "" &&
                                !i.ReminderSent &&
                                i.SendReminderDateTime.HasValue &&
                                i.SendReminderDateTime <= now &&
                                i.SendReminderDateTime >= expireDate)
                         .ToList())
                {
                    var template = instance.RegistrationTemplate;

                    foreach (var registration in instance.Registrations
                             .Where(r =>
                                    !r.IsTemporary &&
                                    r.ConfirmationEmail != null &&
                                    r.ConfirmationEmail != ""))
                    {
                        var mergeFields = new Dictionary <string, object>();
                        mergeFields.Add("RegistrationInstance", registration.RegistrationInstance);
                        mergeFields.Add("Registration", registration);

                        var emailMessage = new RockEmailMessage();
                        emailMessage.AdditionalMergeFields = mergeFields;
                        emailMessage.AddRecipient(new RecipientData(registration.ConfirmationEmail, mergeFields));
                        emailMessage.FromEmail = template.ReminderFromEmail;
                        emailMessage.FromName  = template.ReminderFromName;
                        emailMessage.Subject   = template.ReminderSubject;
                        emailMessage.Message   = template.ReminderEmailTemplate;
                        emailMessage.Send();
                    }

                    instance.SendReminderDateTime = now;
                    instance.ReminderSent         = true;
                    remindersSent++;

                    rockContext.SaveChanges();
                }

                if (remindersSent == 0)
                {
                    context.Result = "No reminders to send";
                }
                else if (remindersSent == 1)
                {
                    context.Result = "1 reminder was sent";
                }
                else
                {
                    context.Result = string.Format("{0} reminders were sent", remindersSent);
                }
            }
        }
Ejemplo n.º 4
0
        protected void btnSaveGroup_Click(object sender, EventArgs e)
        {
            var          rockContext  = new RockContext();
            GroupService groupService = new GroupService(rockContext);

            Group group = groupService.Get(_groupId);

            if (group != null && group.IsAuthorized(Authorization.EDIT, CurrentPerson))
            {
                group.Name        = tbName.Text;
                group.Description = tbDescription.Text;
                group.IsActive    = cbIsActive.Checked;

                if (pnlSchedule.Visible)
                {
                    if (group.Schedule == null)
                    {
                        group.Schedule = new Schedule();
                        group.Schedule.iCalendarContent = null;
                    }
                    group.Schedule.WeeklyDayOfWeek = dowWeekly.SelectedDayOfWeek;
                    group.Schedule.WeeklyTimeOfDay = timeWeekly.SelectedTime;
                }

                // set attributes
                group.LoadAttributes(rockContext);
                Rock.Attribute.Helper.GetEditValues(phAttributes, group);

                // configure locations
                if (GetAttributeValue("EnableLocationEdit").AsBoolean())
                {
                    // get selected location
                    Location location            = null;
                    int?     memberPersonAliasId = null;

                    if (LocationTypeTab.Equals(MEMBER_LOCATION_TAB_TITLE))
                    {
                        if (ddlMember.SelectedValue != null)
                        {
                            var ids = ddlMember.SelectedValue.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                            if (ids.Length == 2)
                            {
                                var dbLocation = new LocationService(rockContext).Get(int.Parse(ids[0]));
                                if (dbLocation != null)
                                {
                                    location = dbLocation;
                                }

                                memberPersonAliasId = new PersonAliasService(rockContext).GetPrimaryAliasId(int.Parse(ids[1]));
                            }
                        }
                    }
                    else
                    {
                        if (locpGroupLocation.Location != null)
                        {
                            location = new LocationService(rockContext).Get(locpGroupLocation.Location.Id);
                        }
                    }

                    if (location != null)
                    {
                        GroupLocation groupLocation = group.GroupLocations.FirstOrDefault();

                        if (groupLocation == null)
                        {
                            groupLocation = new GroupLocation();
                            group.GroupLocations.Add(groupLocation);
                        }

                        groupLocation.GroupMemberPersonAliasId = memberPersonAliasId;
                        groupLocation.Location   = location;
                        groupLocation.LocationId = groupLocation.Location.Id;
                        groupLocation.GroupLocationTypeValueId = ddlLocationType.SelectedValueAsId();
                    }
                }

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

            this.IsEditingGroup = false;

            // reload the group info
            pnlGroupEdit.Visible = false;
            pnlGroupView.Visible = true;
            DisplayViewGroup();
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" />
        /// fires that is associated with the <see cref="IJob" />.
        /// </summary>
        /// <param name="context">The execution context.</param>
        /// <remarks>
        /// The implementation may wish to set a  result object on the
        /// JobExecutionContext before this method exits.  The result itself
        /// is meaningless to Quartz, but may be informative to
        /// <see cref="IJobListener" />s or
        /// <see cref="ITriggerListener" />s that are watching the job's
        /// execution.
        /// </remarks>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap    = context.JobDetail.JobDataMap;
            int        resendDays = dataMap.GetString("ResendInviteAfterNumberDays").AsIntegerOrNull() ?? 5;
            int        maxInvites = dataMap.GetString("MaxInvites").AsIntegerOrNull() ?? 2;
            int        checkDays  = dataMap.GetString("CheckForSignatureDays").AsIntegerOrNull() ?? 30;
            string     folderPath = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/Cache/SignNow");

            var errorMessages         = new List <string>();
            int signatureRequestsSent = 0;
            int documentsUpdated      = 0;

            // Send documents
            using (var rockContext = new RockContext())
            {
                var maxInviteDate  = RockDateTime.Today.AddDays(0 - resendDays);
                var maxCheckDays   = RockDateTime.Today.AddDays(0 - checkDays);
                var docTypeService = new SignatureDocumentTemplateService(rockContext);
                var docService     = new SignatureDocumentService(rockContext);

                // Check for status updates
                foreach (var document in new SignatureDocumentService(rockContext).Queryable()
                         .Where(d =>
                                (
                                    d.Status == SignatureDocumentStatus.Sent ||
                                    (d.Status == SignatureDocumentStatus.Signed && !d.BinaryFileId.HasValue)
                                ) &&
                                d.LastInviteDate.HasValue &&
                                d.LastInviteDate.Value > maxCheckDays)
                         .ToList())
                {
                    var updateErrorMessages = new List <string>();
                    var status       = document.Status;
                    int?binaryFileId = document.BinaryFileId;
                    if (docTypeService.UpdateDocumentStatus(document, folderPath, out updateErrorMessages))
                    {
                        if (status != document.Status || !binaryFileId.Equals(document.BinaryFileId))
                        {
                            rockContext.SaveChanges();
                            documentsUpdated++;
                        }
                    }
                    else
                    {
                        errorMessages.AddRange(updateErrorMessages);
                    }
                }

                // Send any needed signature requests
                var docsSent = new Dictionary <int, List <int> >();
                foreach (var gm in new GroupMemberService(rockContext).Queryable()
                         .Where(m =>
                                m.GroupMemberStatus == GroupMemberStatus.Active &&
                                m.Group.IsActive &&
                                m.Person.Email != null &&
                                m.Person.Email != "" &&
                                m.Group.RequiredSignatureDocumentTemplate != null &&
                                !m.Group.RequiredSignatureDocumentTemplate.Documents.Any(d =>
                                                                                         d.AppliesToPersonAlias.PersonId == m.PersonId &&
                                                                                         d.Status == SignatureDocumentStatus.Signed
                                                                                         )
                                )
                         .Select(m => new
                {
                    GroupName = m.Group.Name,
                    Person = m.Person,
                    DocumentType = m.Group.RequiredSignatureDocumentTemplate
                })
                         .ToList())
                {
                    if (docsSent.ContainsKey(gm.Person.Id))
                    {
                        if (docsSent[gm.Person.Id].Contains(gm.DocumentType.Id))
                        {
                            continue;
                        }
                        else
                        {
                            docsSent[gm.Person.Id].Add(gm.DocumentType.Id);
                        }
                    }
                    else
                    {
                        docsSent.Add(gm.Person.Id, new List <int> {
                            gm.DocumentType.Id
                        });
                    }

                    var document = docService.Queryable()
                                   .Where(d =>
                                          d.SignatureDocumentTemplateId == gm.DocumentType.Id &&
                                          d.AppliesToPersonAlias.PersonId == gm.Person.Id &&
                                          d.AssignedToPersonAlias.PersonId == gm.Person.Id &&
                                          d.Status != SignatureDocumentStatus.Signed
                                          )
                                   .OrderByDescending(d => d.CreatedDateTime)
                                   .FirstOrDefault();

                    if (document == null || (document.InviteCount < maxInvites && document.LastInviteDate < maxInviteDate))
                    {
                        string documentName = string.Format("{0}_{1}", gm.GroupName.RemoveSpecialCharacters(), gm.Person.FullName.RemoveSpecialCharacters());

                        var sendErrorMessages = new List <string>();
                        if (document != null)
                        {
                            docTypeService.SendDocument(document, gm.Person.Email, out sendErrorMessages);
                        }
                        else
                        {
                            docTypeService.SendDocument(gm.DocumentType, gm.Person, gm.Person, documentName, gm.Person.Email, out sendErrorMessages);
                        }

                        if (!errorMessages.Any())
                        {
                            rockContext.SaveChanges();
                            signatureRequestsSent++;
                        }
                        else
                        {
                            errorMessages.AddRange(sendErrorMessages);
                        }
                    }
                }
            }

            if (errorMessages.Any())
            {
                throw new Exception("One or more exceptions occurred processing signature documents..." + Environment.NewLine + errorMessages.AsDelimited(Environment.NewLine));
            }

            context.Result = string.Format("{0} signature requests sent; {1} existing document's status updated", signatureRequestsSent, documentsUpdated);
        }
Ejemplo n.º 6
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);
                });

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

                BindGrid();
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Sends the specified communication from the Communication Wizard in Rock.
        /// </summary>
        /// <param name="communication">The communication.</param>
        /// <param name="mediumEntityTypeId">The medium entity type identifier.</param>
        /// <param name="mediumAttributes">The medium attributes.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        public override void Send(Model.Communication communication, int mediumEntityTypeId, Dictionary <string, string> mediumAttributes)
        {
            using (var communicationRockContext = new RockContext())
            {
                // Requery the Communication
                communication = new CommunicationService(communicationRockContext)
                                .Queryable("CreatedByPersonAlias.Person")
                                .FirstOrDefault(c => c.Id == communication.Id);

                bool hasPendingRecipients;
                if (communication != null &&
                    communication.Status == Model.CommunicationStatus.Approved &&
                    (!communication.FutureSendDateTime.HasValue || communication.FutureSendDateTime.Value.CompareTo(RockDateTime.Now) <= 0))
                {
                    var qryRecipients = new CommunicationRecipientService(communicationRockContext).Queryable();
                    hasPendingRecipients = qryRecipients
                                           .Where(r =>
                                                  r.CommunicationId == communication.Id &&
                                                  r.Status == Model.CommunicationRecipientStatus.Pending &&
                                                  r.MediumEntityTypeId.HasValue &&
                                                  r.MediumEntityTypeId.Value == mediumEntityTypeId)
                                           .Any();
                }
                else
                {
                    hasPendingRecipients = false;
                }

                if (hasPendingRecipients)
                {
                    var    currentPerson    = communication.CreatedByPersonAlias?.Person;
                    var    globalAttributes = GlobalAttributesCache.Get();
                    string publicAppRoot    = globalAttributes.GetValue("PublicApplicationRoot").EnsureTrailingForwardslash();
                    var    mergeFields      = Lava.LavaHelper.GetCommonMergeFields(null, currentPerson);

                    var personEntityTypeId        = EntityTypeCache.Get("Rock.Model.Person").Id;
                    var communicationEntityTypeId = EntityTypeCache.Get("Rock.Model.Communication").Id;
                    var communicationCategoryId   = CategoryCache.Get(Rock.SystemGuid.Category.HISTORY_PERSON_COMMUNICATIONS.AsGuid(), communicationRockContext).Id;

                    bool recipientFound = true;
                    while (recipientFound)
                    {
                        // make a new rockContext per recipient
                        var recipientRockContext = new RockContext();
                        var recipient            = Model.Communication.GetNextPending(communication.Id, mediumEntityTypeId, recipientRockContext);
                        if (recipient != null)
                        {
                            if (ValidRecipient(recipient, communication.IsBulkCommunication))
                            {
                                if (recipient.PersonAliasId.HasValue)
                                {
                                    try
                                    {
                                        var             mergeObjects = recipient.CommunicationMergeValues(mergeFields);
                                        var             message      = ResolveText(communication.PushMessage, currentPerson, communication.EnabledLavaCommands, mergeObjects, publicAppRoot);
                                        var             title        = ResolveText(communication.PushTitle, currentPerson, communication.EnabledLavaCommands, mergeObjects, publicAppRoot);
                                        var             sound        = ResolveText(communication.PushSound, currentPerson, communication.EnabledLavaCommands, mergeObjects, publicAppRoot);
                                        var             data         = ResolveText(communication.PushData, currentPerson, communication.EnabledLavaCommands, mergeFields, publicAppRoot);
                                        var             jsonData     = Newtonsoft.Json.JsonConvert.DeserializeObject <PushData>(data);
                                        var             url          = jsonData.Url;
                                        string          appId        = GetAttributeValue("AppId");
                                        string          restApiKey   = GetAttributeValue("RestAPIKey");
                                        OneSignalClient client       = new OneSignalClient(restApiKey);

                                        var options = new NotificationCreateOptions
                                        {
                                            AppId = new Guid(appId),
                                            IncludeExternalUserIds = new List <string> {
                                                recipient.PersonAliasId.ToString()
                                            }
                                        };

                                        options.Headings.Add(LanguageCodes.English, title);
                                        options.Contents.Add(LanguageCodes.English, message);
                                        options.Url = url;
                                        NotificationCreateResult response = client.Notifications.Create(options);

                                        bool failed = !string.IsNullOrWhiteSpace(response.Error);

                                        var status = failed ? CommunicationRecipientStatus.Failed : CommunicationRecipientStatus.Delivered;

                                        if (failed)
                                        {
                                            recipient.StatusNote = "OneSignal failed to notify devices";
                                        }
                                        else
                                        {
                                            recipient.SendDateTime = RockDateTime.Now;
                                        }

                                        recipient.Status = status;
                                        recipient.TransportEntityTypeName = this.GetType().FullName;
                                        recipient.UniqueMessageId         = response.Id;

                                        try
                                        {
                                            var historyService = new HistoryService(recipientRockContext);
                                            historyService.Add(new History
                                            {
                                                CreatedByPersonAliasId = communication.SenderPersonAliasId,
                                                EntityTypeId           = personEntityTypeId,
                                                CategoryId             = communicationCategoryId,
                                                EntityId            = recipient.PersonAlias.PersonId,
                                                Verb                = History.HistoryVerb.Sent.ConvertToString().ToUpper(),
                                                ChangeType          = History.HistoryChangeType.Record.ToString(),
                                                ValueName           = "Push Notification",
                                                Caption             = message.Truncate(200),
                                                RelatedEntityTypeId = communicationEntityTypeId,
                                                RelatedEntityId     = communication.Id
                                            });
                                        }
                                        catch (Exception ex)
                                        {
                                            ExceptionLogService.LogException(ex, null);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        recipient.Status     = CommunicationRecipientStatus.Failed;
                                        recipient.StatusNote = "OneSignal Exception: " + ex.Message;
                                    }
                                }
                            }

                            recipientRockContext.SaveChanges();
                        }
                        else
                        {
                            recipientFound = false;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute(IJobExecutionContext context)
        {
            var exceptionMsgs = new List <string>();

            JobDataMap dataMap         = context.JobDetail.JobDataMap;
            Guid?      groupGuid       = dataMap.GetString("EligibleFollowers").AsGuidOrNull();
            Guid?      systemEmailGuid = dataMap.GetString("EmailTemplate").AsGuidOrNull();
            int        followingSuggestionsEmailsSent       = 0;
            int        followingSuggestionsSuggestionsTotal = 0;

            if (groupGuid.HasValue && systemEmailGuid.HasValue)
            {
                using (var rockContext = new RockContext())
                {
                    var followingService = new FollowingService(rockContext);

                    // The people who are eligible to get following suggestions based on the group type setting for this job
                    var eligiblePersonIds = new GroupMemberService(rockContext)
                                            .Queryable().AsNoTracking()
                                            .Where(m =>
                                                   m.Group != null &&
                                                   m.Group.Guid.Equals(groupGuid.Value) &&
                                                   m.GroupMemberStatus == GroupMemberStatus.Active &&
                                                   m.Person != null &&
                                                   m.Person.Email != null &&
                                                   m.Person.Email != string.Empty &&
                                                   m.Person.EmailPreference != EmailPreference.DoNotEmail &&
                                                   m.Person.IsEmailActive)
                                            .Select(m => m.PersonId)
                                            .Distinct();

                    // check to see if there are any event types that require notification
                    var followerPersonIds = new List <int>();
                    if (new FollowingEventTypeService(rockContext)
                        .Queryable().AsNoTracking()
                        .Any(e => e.IsNoticeRequired))
                    {
                        // if so, include all eligible people
                        followerPersonIds = eligiblePersonIds.ToList();
                    }
                    else
                    {
                        // if not, filter the list of eligible people down to only those that actually have subscribed to one or more following events
                        followerPersonIds = new FollowingEventSubscriptionService(rockContext)
                                            .Queryable().AsNoTracking()
                                            .Where(f => eligiblePersonIds.Contains(f.PersonAlias.PersonId))
                                            .Select(f => f.PersonAlias.PersonId)
                                            .Distinct()
                                            .ToList();
                    }

                    if (followerPersonIds.Any())
                    {
                        // Get the primary person alias id for each of the followers
                        var primaryAliasIds = new Dictionary <int, int>();
                        new PersonAliasService(rockContext)
                        .Queryable().AsNoTracking()
                        .Where(a =>
                               followerPersonIds.Contains(a.PersonId) &&
                               a.PersonId == a.AliasPersonId)
                        .ToList()
                        .ForEach(a => primaryAliasIds.AddOrIgnore(a.PersonId, a.Id));

                        // Get current date/time.
                        var timestamp = RockDateTime.Now;

                        var suggestionTypes = new FollowingSuggestionTypeService(rockContext)
                                              .Queryable().AsNoTracking()
                                              .Where(s => s.IsActive)
                                              .OrderBy(s => s.Name)
                                              .ToList();

                        var components        = new Dictionary <int, SuggestionComponent>();
                        var suggestedEntities = new Dictionary <int, Dictionary <int, IEntity> >();

                        foreach (var suggestionType in suggestionTypes)
                        {
                            try
                            {
                                // Get the suggestion type component
                                var suggestionComponent = suggestionType.GetSuggestionComponent();
                                if (suggestionComponent != null)
                                {
                                    components.Add(suggestionType.Id, suggestionComponent);

                                    // Get the entitytype for this suggestion type
                                    var suggestionEntityType = EntityTypeCache.Get(suggestionComponent.FollowedType);
                                    if (suggestionEntityType != null)
                                    {
                                        var entityIds = new List <int>();

                                        // Call the components method to return all of it's suggestions
                                        var personEntitySuggestions = suggestionComponent.GetSuggestions(suggestionType, followerPersonIds);

                                        // If any suggestions were returned by the component
                                        if (personEntitySuggestions.Any())
                                        {
                                            int    entityTypeId = suggestionEntityType.Id;
                                            string reasonNote   = suggestionType.ReasonNote;

                                            // Get the existing followings for any of the followers
                                            var existingFollowings = new Dictionary <int, List <int> >();
                                            foreach (var following in followingService.Queryable("PersonAlias").AsNoTracking()
                                                     .Where(f =>
                                                            f.EntityTypeId == entityTypeId &&
                                                            followerPersonIds.Contains(f.PersonAlias.PersonId)))
                                            {
                                                existingFollowings.AddOrIgnore(following.PersonAlias.PersonId, new List <int>());
                                                existingFollowings[following.PersonAlias.PersonId].Add(following.EntityId);
                                            }

                                            // Loop through each follower
                                            foreach (var followerPersonId in personEntitySuggestions
                                                     .Select(s => s.PersonId)
                                                     .Distinct())
                                            {
                                                using (var suggestionContext = new RockContext())
                                                {
                                                    var followingSuggestedService = new FollowingSuggestedService(suggestionContext);

                                                    // Read all the existing suggestions for this type and the returned followers
                                                    var existingSuggestions = followingSuggestedService
                                                                              .Queryable("PersonAlias")
                                                                              .Where(s =>
                                                                                     s.SuggestionTypeId == suggestionType.Id &&
                                                                                     s.PersonAlias.PersonId == followerPersonId)
                                                                              .ToList();

                                                    // Look  through the returned suggestions
                                                    foreach (var followedEntityId in personEntitySuggestions
                                                             .Where(s => s.PersonId == followerPersonId)
                                                             .Select(s => s.EntityId))
                                                    {
                                                        // Make sure person isn't already following this entity
                                                        if (!existingFollowings.ContainsKey(followerPersonId) ||
                                                            !existingFollowings[followerPersonId].Contains(followedEntityId))
                                                        {
                                                            // If this person had a primary alias id
                                                            if (primaryAliasIds.ContainsKey(followerPersonId))
                                                            {
                                                                entityIds.Add(followedEntityId);

                                                                // Look for existing suggestion for this person and entity
                                                                var suggestion = existingSuggestions
                                                                                 .Where(s => s.EntityId == followedEntityId)
                                                                                 .OrderByDescending(s => s.StatusChangedDateTime)
                                                                                 .FirstOrDefault();

                                                                // If not found, add one
                                                                if (suggestion == null)
                                                                {
                                                                    suggestion = new FollowingSuggested();
                                                                    suggestion.EntityTypeId          = entityTypeId;
                                                                    suggestion.EntityId              = followedEntityId;
                                                                    suggestion.PersonAliasId         = primaryAliasIds[followerPersonId];
                                                                    suggestion.SuggestionTypeId      = suggestionType.Id;
                                                                    suggestion.Status                = FollowingSuggestedStatus.PendingNotification;
                                                                    suggestion.StatusChangedDateTime = timestamp;
                                                                    followingSuggestedService.Add(suggestion);
                                                                }
                                                                else
                                                                {
                                                                    // If found, and it has not been ignored, and it's time to promote again, update the promote date
                                                                    if (suggestion.Status != FollowingSuggestedStatus.Ignored &&
                                                                        suggestionType.ReminderDays.HasValue &&
                                                                        (
                                                                            !suggestion.LastPromotedDateTime.HasValue ||
                                                                            suggestion.LastPromotedDateTime.Value.AddDays(suggestionType.ReminderDays.Value) <= timestamp
                                                                        ))
                                                                    {
                                                                        if (suggestion.Status != FollowingSuggestedStatus.PendingNotification)
                                                                        {
                                                                            suggestion.StatusChangedDateTime = timestamp;
                                                                            suggestion.Status = FollowingSuggestedStatus.PendingNotification;
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }

                                                    // Save the suggestions for this type
                                                    suggestionContext.SaveChanges();
                                                }
                                            }
                                        }

                                        // If any entities are being suggested for this type, query database for them and save to dictionary
                                        if (entityIds.Any())
                                        {
                                            if (suggestionEntityType.AssemblyName != null)
                                            {
                                                // get the actual type of what is being followed
                                                Type entityType = suggestionEntityType.GetEntityType();
                                                if (entityType != null)
                                                {
                                                    // Get generic queryable method and query all the entities that are being followed
                                                    Type[]             modelType          = { entityType };
                                                    Type               genericServiceType = typeof(Rock.Data.Service <>);
                                                    Type               modelServiceType   = genericServiceType.MakeGenericType(modelType);
                                                    Rock.Data.IService serviceInstance    = Activator.CreateInstance(modelServiceType, new object[] { rockContext }) as IService;
                                                    MethodInfo         qryMethod          = serviceInstance.GetType().GetMethod("Queryable", new Type[] { });
                                                    var entityQry  = qryMethod.Invoke(serviceInstance, new object[] { }) as IQueryable <IEntity>;
                                                    var entityList = entityQry.AsNoTracking().Where(q => entityIds.Contains(q.Id)).ToList();
                                                    if (entityList != null && entityList.Any())
                                                    {
                                                        var entities = new Dictionary <int, IEntity>();
                                                        entityList.ForEach(e => entities.Add(e.Id, e));
                                                        suggestedEntities.Add(suggestionType.Id, entities);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                exceptionMsgs.Add(string.Format("An exception occurred calculating suggestions for the '{0}' suggestion type:{1}    {2}", suggestionType.Name, Environment.NewLine, ex.Messages().AsDelimited(Environment.NewLine + "   ")));
                                ExceptionLogService.LogException(ex, System.Web.HttpContext.Current);
                            }
                        }

                        var allSuggestions = new FollowingSuggestedService(rockContext)
                                             .Queryable("PersonAlias")
                                             .Where(s => s.Status == FollowingSuggestedStatus.PendingNotification)
                                             .ToList();

                        var suggestionPersonIds = allSuggestions
                                                  .Where(s => followerPersonIds.Contains(s.PersonAlias.PersonId))
                                                  .Select(s => s.PersonAlias.PersonId)
                                                  .Distinct()
                                                  .ToList();

                        var appRoot = GlobalAttributesCache.Get().GetValue("PublicApplicationRoot", rockContext);

                        foreach (var person in new PersonService(rockContext)
                                 .Queryable().AsNoTracking()
                                 .Where(p => suggestionPersonIds.Contains(p.Id))
                                 .ToList())
                        {
                            try
                            {
                                var personSuggestionNotices = new List <FollowingSuggestionNotices>();

                                foreach (var suggestionType in suggestionTypes)
                                {
                                    var component = components.ContainsKey(suggestionType.Id) ? components[suggestionType.Id] : null;
                                    if (component != null && suggestedEntities.ContainsKey(suggestionType.Id))
                                    {
                                        var entities = new List <IEntity>();
                                        foreach (var suggestion in allSuggestions
                                                 .Where(s =>
                                                        s.PersonAlias.PersonId == person.Id &&
                                                        s.SuggestionTypeId == suggestionType.Id)
                                                 .ToList())
                                        {
                                            if (suggestedEntities[suggestionType.Id].ContainsKey(suggestion.EntityId))
                                            {
                                                entities.Add(suggestedEntities[suggestionType.Id][suggestion.EntityId]);
                                                suggestion.LastPromotedDateTime = timestamp;
                                                suggestion.Status = FollowingSuggestedStatus.Suggested;
                                            }
                                        }

                                        var notices = new List <string>();
                                        foreach (var entity in component.SortEntities(entities))
                                        {
                                            notices.Add(component.FormatEntityNotification(suggestionType, entity));
                                        }

                                        if (notices.Any())
                                        {
                                            personSuggestionNotices.Add(new FollowingSuggestionNotices(suggestionType, notices));
                                        }
                                    }
                                }

                                if (personSuggestionNotices.Any())
                                {
                                    // Send the notice
                                    var mergeFields = new Dictionary <string, object>();
                                    mergeFields.Add("Person", person);
                                    mergeFields.Add("Suggestions", personSuggestionNotices.OrderBy(s => s.SuggestionType.Order).ToList());

                                    var emailMessage = new RockEmailMessage(systemEmailGuid.Value);
                                    emailMessage.AddRecipient(new RecipientData(person.Email, mergeFields));
                                    var errors = new List <string>();
                                    emailMessage.Send(out errors);
                                    exceptionMsgs.AddRange(errors);

                                    followingSuggestionsEmailsSent       += 1;
                                    followingSuggestionsSuggestionsTotal += personSuggestionNotices.Count();
                                }

                                rockContext.SaveChanges();
                            }
                            catch (Exception ex)
                            {
                                exceptionMsgs.Add(string.Format("An exception occurred sending suggestions to '{0}':{1}    {2}", person.FullName, Environment.NewLine, ex.Messages().AsDelimited(Environment.NewLine + "   ")));
                                ExceptionLogService.LogException(ex, System.Web.HttpContext.Current);
                            }
                        }
                    }
                }
            }

            context.Result = string.Format("A total of {0} following suggestions sent to {1} people", followingSuggestionsSuggestionsTotal, followingSuggestionsEmailsSent);

            if (exceptionMsgs.Any())
            {
                throw new Exception("One or more exceptions occurred calculating suggestions..." + Environment.NewLine + exceptionMsgs.AsDelimited(Environment.NewLine));
            }
        }
Ejemplo n.º 9
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    personService = new PersonService(rockContext);
            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
            business.LastName = tbBusinessName.Text;

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

            var phoneNumber = business.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == businessPhoneTypeId);

            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;
            }
            else
            {
                if (phoneNumber != null)
                {
                    business.PhoneNumbers.Remove(phoneNumber);
                    new PhoneNumberService(rockContext).Delete(phoneNumber);
                }
            }

            // 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
            business.RecordStatusValueId = ddlRecordStatus.SelectedValueAsInt();;

            // 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();
            }
            business.RecordStatusReasonValueId = newRecordStatusReasonId;

            // Email
            business.IsEmailActive   = true;
            business.Email           = tbEmail.Text.Trim();
            business.EmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();

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

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

                // 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);
                    }
                }
                else
                {
                    var newLocation = new LocationService(rockContext).Get(
                        acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);
                    if (workLocation == null)
                    {
                        workLocation = new GroupLocation();
                        groupLocationService.Add(workLocation);
                        workLocation.GroupId = adultFamilyMember.Group.Id;
                        workLocation.GroupLocationTypeValueId = workLocationTypeId;
                    }
                    workLocation.Location          = newLocation;
                    workLocation.IsMailingLocation = true;
                }

                rockContext.SaveChanges();

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

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

            queryParams.Add("businessId", hfBusinessId.Value);
            NavigateToCurrentPage(queryParams);
        }
Ejemplo n.º 10
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.IsIndexEnabled = cbIndexCalendar.Checked;

                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);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// When implemented by a class, enables a server control to process an event raised when a form is posted to the server.
        /// </summary>
        /// <param name="eventArgument">A <see cref="T:System.String" /> that represents an optional event argument to be passed to the event handler.</param>
        public void RaisePostBackEvent(string eventArgument)
        {
            if (eventArgument == "StatusUpdate" && hfAction.Value.IsNotNullOrWhiteSpace())
            {
                var batchesSelected = new List <int>();

                gBatchList.SelectedKeys.ToList().ForEach(b => batchesSelected.Add(b.ToString().AsInteger()));

                if (batchesSelected.Any())
                {
                    var newStatus       = hfAction.Value == "OPEN" ? BatchStatus.Open : BatchStatus.Closed;
                    var rockContext     = new RockContext();
                    var batchService    = new FinancialBatchService(rockContext);
                    var batchesToUpdate = batchService.Queryable()
                                          .Where(b =>
                                                 batchesSelected.Contains(b.Id) &&
                                                 b.Status != newStatus)
                                          .ToList();

                    foreach (var batch in batchesToUpdate)
                    {
                        var changes = new History.HistoryChangeList();
                        History.EvaluateChange(changes, "Status", batch.Status, newStatus);

                        string errorMessage;
                        if (!batch.IsValidBatchStatusChange(batch.Status, newStatus, this.CurrentPerson, out errorMessage))
                        {
                            maWarningDialog.Show(errorMessage, ModalAlertType.Warning);
                            return;
                        }

                        if (batch.IsAutomated && batch.Status == BatchStatus.Pending && newStatus != BatchStatus.Pending)
                        {
                            errorMessage = string.Format("{0} is an automated batch and the status can not be modified when the status is pending. The system will automatically set this batch to OPEN when all transactions have been downloaded.", batch.Name);
                            maWarningDialog.Show(errorMessage, ModalAlertType.Warning);
                            return;
                        }

                        batch.Status = newStatus;

                        if (!batch.IsValid)
                        {
                            string message = string.Format("Unable to update status for the selected batches.<br/><br/>{0}", batch.ValidationResults.AsDelimited("<br/>"));
                            maWarningDialog.Show(message, ModalAlertType.Warning);
                            return;
                        }

                        HistoryService.SaveChanges(
                            rockContext,
                            typeof(FinancialBatch),
                            Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                            batch.Id,
                            changes,
                            false);
                    }

                    rockContext.SaveChanges();

                    nbResult.Text = string.Format(
                        "{0} batches were {1}.",
                        batchesToUpdate.Count().ToString("N0"),
                        newStatus == BatchStatus.Open ? "opened" : "closed");

                    nbResult.NotificationBoxType = NotificationBoxType.Success;
                    nbResult.Visible             = true;
                }
                else
                {
                    nbResult.Text = string.Format("There were not any batches selected.");
                    nbResult.NotificationBoxType = NotificationBoxType.Warning;
                    nbResult.Visible             = true;
                }

                ddlAction.SelectedIndex = 0;
                hfAction.Value          = string.Empty;
                BindGrid();
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Handles the Click event of the mdSaveTemplate 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 mdSaveTemplate_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid || !CommunicationId.HasValue)
            {
                return;
            }

            using (var rockContext = new RockContext())
            {
                var communication = new CommunicationService(rockContext).Get(CommunicationId.Value);
                if (communication == null)
                {
                    return;
                }

                var template = new CommunicationTemplate
                {
                    SenderPersonAliasId = CurrentPersonAliasId,
                    Name                  = tbTemplateName.Text,
                    CategoryId            = cpTemplateCategory.SelectedValue.AsIntegerOrNull(),
                    Description           = tbTemplateDescription.Text,
                    Subject               = communication.Subject,
                    FromName              = communication.FromName,
                    FromEmail             = communication.FromEmail,
                    ReplyToEmail          = communication.ReplyToEmail,
                    CCEmails              = communication.CCEmails,
                    BCCEmails             = communication.BCCEmails,
                    Message               = "{% raw %}" + communication.Message + "{% endraw %}",
                    MessageMetaData       = communication.MessageMetaData,
                    SMSFromDefinedValueId = communication.SMSFromDefinedValueId,
                    SMSMessage            = communication.SMSMessage,
                    PushTitle             = communication.PushTitle,
                    PushMessage           = communication.PushMessage,
                    PushSound             = communication.PushSound
                };

                foreach (var attachment in communication.Attachments.ToList())
                {
                    var newAttachment = new CommunicationTemplateAttachment
                    {
                        BinaryFileId      = attachment.BinaryFileId,
                        CommunicationType = attachment.CommunicationType
                    };
                    template.Attachments.Add(newAttachment);
                }

                var templateService = new CommunicationTemplateService(rockContext);
                templateService.Add(template);
                rockContext.SaveChanges();

                template = templateService.Get(template.Id);
                if (template != null)
                {
                    template.AllowPerson(Authorization.VIEW, CurrentPerson);
                    template.AllowPerson(Authorization.EDIT, CurrentPerson);
                    template.AllowPerson(Authorization.ADMINISTRATE, CurrentPerson);

                    var groupService = new GroupService(rockContext);
                    var communicationAdministrators = groupService.Get(Rock.SystemGuid.Group.GROUP_COMMUNICATION_ADMINISTRATORS.AsGuid());
                    if (communicationAdministrators != null)
                    {
                        template.AllowSecurityRole(Authorization.VIEW, communicationAdministrators, rockContext);
                        template.AllowSecurityRole(Authorization.EDIT, communicationAdministrators, rockContext);
                        template.AllowSecurityRole(Authorization.ADMINISTRATE, communicationAdministrators, rockContext);
                    }

                    var rockAdministrators = groupService.Get(Rock.SystemGuid.Group.GROUP_ADMINISTRATORS.AsGuid());
                    if (rockAdministrators != null)
                    {
                        template.AllowSecurityRole(Authorization.VIEW, rockAdministrators, rockContext);
                        template.AllowSecurityRole(Authorization.EDIT, rockAdministrators, rockContext);
                        template.AllowSecurityRole(Authorization.ADMINISTRATE, rockAdministrators, rockContext);
                    }
                }

                nbTemplateCreated.Visible = true;
            }

            HideDialog();
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Job that will sync groups.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            // Get the job setting(s)
            JobDataMap dataMap = context.JobDetail.JobDataMap;
            bool       requirePasswordReset = dataMap.GetBoolean("RequirePasswordReset");
            var        commandTimeout       = dataMap.GetString("CommandTimeout").AsIntegerOrNull() ?? 180;

            // Counters for displaying results
            int    groupsSynced  = 0;
            int    groupsChanged = 0;
            string groupName     = string.Empty;
            string dataViewName  = string.Empty;
            var    errors        = new List <string>();

            try
            {
                // get groups set to sync
                var activeSyncList = new List <GroupSyncInfo>();
                using (var rockContext = new RockContext())
                {
                    // Get groups that are not archived and are still active.
                    activeSyncList = new GroupSyncService(rockContext)
                                     .Queryable()
                                     .AsNoTracking()
                                     .AreNotArchived()
                                     .AreActive()
                                     .NeedToBeSynced()
                                     .Select(x => new GroupSyncInfo {
                        SyncId = x.Id, GroupName = x.Group.Name
                    })
                                     .ToList();
                }

                foreach (var syncInfo in activeSyncList)
                {
                    int  syncId         = syncInfo.SyncId;
                    bool hasSyncChanged = false;
                    context.UpdateLastStatusMessage($"Syncing group {syncInfo.GroupName}");

                    // Use a fresh rockContext per sync so that ChangeTracker doesn't get bogged down
                    using (var rockContext = new RockContext())
                    {
                        // increase the timeout just in case the data view source is slow
                        rockContext.Database.CommandTimeout = commandTimeout;
                        rockContext.SourceOfChange          = "Group Sync";

                        // Get the Sync
                        var sync = new GroupSyncService(rockContext)
                                   .Queryable()
                                   .Include(a => a.Group)
                                   .Include(a => a.SyncDataView)
                                   .AsNoTracking()
                                   .FirstOrDefault(s => s.Id == syncId);

                        if (sync == null || sync.SyncDataView.EntityTypeId != EntityTypeCache.Get(typeof(Person)).Id)
                        {
                            // invalid sync or invalid SyncDataView
                            continue;
                        }

                        dataViewName = sync.SyncDataView.Name;
                        groupName    = sync.Group.Name;

                        Stopwatch stopwatch = Stopwatch.StartNew();

                        // Get the person id's from the data view (source)
                        var dataViewGetQueryArgs = new DataViewGetQueryArgs
                        {
                            DbContext = rockContext,
                            DatabaseTimeoutSeconds = commandTimeout
                        };

                        List <int> sourcePersonIds;

                        try
                        {
                            var dataViewQry = sync.SyncDataView.GetQuery(dataViewGetQueryArgs);
                            sourcePersonIds = dataViewQry.Select(q => q.Id).ToList();
                        }
                        catch (Exception ex)
                        {
                            // If any error occurred trying get the 'where expression' from the sync-data-view,
                            // just skip trying to sync that particular group's Sync Data View for now.
                            var errorMessage = $"An error occurred while trying to GroupSync group '{groupName}' and data view '{dataViewName}' so the sync was skipped. Error: {ex.Message}";
                            errors.Add(errorMessage);
                            ExceptionLogService.LogException(new Exception(errorMessage, ex));
                            continue;
                        }

                        stopwatch.Stop();
                        DataViewService.AddRunDataViewTransaction(sync.SyncDataView.Id,
                                                                  Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds));

                        // Get the person id's in the group (target) for the role being synced.
                        // Note: targetPersonIds must include archived group members
                        // so we don't try to delete anyone who's already archived, and
                        // it must include deceased members so we can remove them if they
                        // are no longer in the data view.
                        var existingGroupMemberPersonList = new GroupMemberService(rockContext)
                                                            .Queryable(true, true).AsNoTracking()
                                                            .Where(gm => gm.GroupId == sync.GroupId)
                                                            .Where(gm => gm.GroupRoleId == sync.GroupTypeRoleId)
                                                            .Select(gm => new
                        {
                            PersonId   = gm.PersonId,
                            IsArchived = gm.IsArchived
                        })
                                                            .ToList();

                        var targetPersonIdsToDelete = existingGroupMemberPersonList.Where(t => !sourcePersonIds.Contains(t.PersonId) && t.IsArchived != true).ToList();
                        if (targetPersonIdsToDelete.Any())
                        {
                            context.UpdateLastStatusMessage($"Deleting {targetPersonIdsToDelete.Count()} group records in {syncInfo.GroupName} that are no longer in the sync data view");
                        }

                        int deletedCount = 0;

                        // Delete people from the group/role that are no longer in the data view --
                        // but not the ones that are already archived.
                        foreach (var targetPerson in targetPersonIdsToDelete)
                        {
                            deletedCount++;
                            if (deletedCount % 100 == 0)
                            {
                                context.UpdateLastStatusMessage($"Deleted {deletedCount} of {targetPersonIdsToDelete.Count()} group member records for group {syncInfo.GroupName}");
                            }

                            try
                            {
                                // Use a new context to limit the amount of change-tracking required
                                using (var groupMemberContext = new RockContext())
                                {
                                    // Delete the records for that person's group and role.
                                    // NOTE: just in case there are duplicate records, delete all group member records for that person and role
                                    var groupMemberService = new GroupMemberService(groupMemberContext);
                                    foreach (var groupMember in groupMemberService
                                             .Queryable(true, true)
                                             .Where(m =>
                                                    m.GroupId == sync.GroupId &&
                                                    m.GroupRoleId == sync.GroupTypeRoleId &&
                                                    m.PersonId == targetPerson.PersonId)
                                             .ToList())
                                    {
                                        groupMemberService.Delete(groupMember);
                                    }

                                    groupMemberContext.SaveChanges();

                                    // If the Group has an exit email, and person has an email address, send them the exit email
                                    if (sync.ExitSystemCommunication != null)
                                    {
                                        var person = new PersonService(groupMemberContext).Get(targetPerson.PersonId);
                                        if (person.CanReceiveEmail(false))
                                        {
                                            // Send the exit email
                                            var mergeFields = new Dictionary <string, object>();
                                            mergeFields.Add("Group", sync.Group);
                                            mergeFields.Add("Person", person);
                                            var emailMessage = new RockEmailMessage(sync.ExitSystemCommunication);
                                            emailMessage.AddRecipient(new RockEmailMessageRecipient(person, mergeFields));
                                            var emailErrors = new List <string>();
                                            emailMessage.Send(out emailErrors);
                                            errors.AddRange(emailErrors);
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                ExceptionLogService.LogException(ex);
                                continue;
                            }

                            hasSyncChanged = true;
                        }


                        // Now find all the people in the source list who are NOT already in the target list (as Unarchived)
                        var targetPersonIdsToAdd = sourcePersonIds.Where(s => !existingGroupMemberPersonList.Any(t => t.PersonId == s && t.IsArchived == false)).ToList();

                        // Make a list of PersonIds that have an Archived group member record
                        // if this person isn't already a member of the list as an Unarchived member, we can Restore the group member for that PersonId instead
                        var archivedTargetPersonIds = existingGroupMemberPersonList.Where(t => t.IsArchived == true).Select(a => a.PersonId).ToList();

                        context.UpdateLastStatusMessage($"Adding {targetPersonIdsToAdd.Count()} group member records for group {syncInfo.GroupName}");
                        int addedCount    = 0;
                        int notAddedCount = 0;
                        foreach (var personId in targetPersonIdsToAdd)
                        {
                            if ((addedCount + notAddedCount) % 100 == 0)
                            {
                                string notAddedMessage = string.Empty;
                                if (notAddedCount > 0)
                                {
                                    notAddedMessage = $"{Environment.NewLine} There are {notAddedCount} members that could not be added due to group requirements.";
                                }
                                context.UpdateLastStatusMessage($"Added {addedCount} of {targetPersonIdsToAdd.Count()} group member records for group {syncInfo.GroupName}. {notAddedMessage}");
                            }
                            try
                            {
                                // Use a new context to limit the amount of change-tracking required
                                using (var groupMemberContext = new RockContext())
                                {
                                    var groupMemberService = new GroupMemberService(groupMemberContext);
                                    var groupService       = new GroupService(groupMemberContext);

                                    // If this person is currently archived...
                                    if (archivedTargetPersonIds.Contains(personId))
                                    {
                                        // ...then we'll just restore them;
                                        GroupMember archivedGroupMember = groupService.GetArchivedGroupMember(sync.Group, personId, sync.GroupTypeRoleId);

                                        if (archivedGroupMember == null)
                                        {
                                            // shouldn't happen, but just in case
                                            continue;
                                        }

                                        archivedGroupMember.GroupMemberStatus = GroupMemberStatus.Active;
                                        if (archivedGroupMember.IsValidGroupMember(groupMemberContext))
                                        {
                                            addedCount++;
                                            groupMemberService.Restore(archivedGroupMember);
                                            groupMemberContext.SaveChanges();
                                        }
                                        else
                                        {
                                            notAddedCount++;
                                            // Validation errors will get added to the ValidationResults collection. Add those results to the log and then move on to the next person.
                                            var ex = new GroupMemberValidationException(string.Join(",", archivedGroupMember.ValidationResults.Select(r => r.ErrorMessage).ToArray()));
                                            ExceptionLogService.LogException(ex);
                                            continue;
                                        }
                                    }
                                    else
                                    {
                                        // ...otherwise we will add a new person to the group with the role specified in the sync.
                                        var newGroupMember = new GroupMember {
                                            Id = 0
                                        };
                                        newGroupMember.PersonId          = personId;
                                        newGroupMember.GroupId           = sync.GroupId;
                                        newGroupMember.GroupMemberStatus = GroupMemberStatus.Active;
                                        newGroupMember.GroupRoleId       = sync.GroupTypeRoleId;

                                        if (newGroupMember.IsValidGroupMember(groupMemberContext))
                                        {
                                            addedCount++;
                                            groupMemberService.Add(newGroupMember);
                                            groupMemberContext.SaveChanges();
                                        }
                                        else
                                        {
                                            notAddedCount++;
                                            // Validation errors will get added to the ValidationResults collection. Add those results to the log and then move on to the next person.
                                            var ex = new GroupMemberValidationException(string.Join(",", newGroupMember.ValidationResults.Select(r => r.ErrorMessage).ToArray()));
                                            ExceptionLogService.LogException(ex);
                                            continue;
                                        }
                                    }

                                    // If the Group has a welcome email, and person has an email address, send them the welcome email and possibly create a login
                                    if (sync.WelcomeSystemCommunication != null)
                                    {
                                        var person = new PersonService(groupMemberContext).Get(personId);
                                        if (person.CanReceiveEmail(false))
                                        {
                                            // If the group is configured to add a user account for anyone added to the group, and person does not yet have an
                                            // account, add one for them.
                                            string newPassword = string.Empty;
                                            bool   createLogin = sync.AddUserAccountsDuringSync;

                                            // Only create a login if requested, no logins exist and we have enough information to generate a user name.
                                            if (createLogin && !person.Users.Any() && !string.IsNullOrWhiteSpace(person.NickName) && !string.IsNullOrWhiteSpace(person.LastName))
                                            {
                                                newPassword = System.Web.Security.Membership.GeneratePassword(9, 1);
                                                string username = Rock.Security.Authentication.Database.GenerateUsername(person.NickName, person.LastName);

                                                UserLogin login = UserLoginService.Create(
                                                    groupMemberContext,
                                                    person,
                                                    AuthenticationServiceType.Internal,
                                                    EntityTypeCache.Get(Rock.SystemGuid.EntityType.AUTHENTICATION_DATABASE.AsGuid()).Id,
                                                    username,
                                                    newPassword,
                                                    true,
                                                    requirePasswordReset);
                                            }

                                            // Send the welcome email
                                            var mergeFields = new Dictionary <string, object>();
                                            mergeFields.Add("Group", sync.Group);
                                            mergeFields.Add("Person", person);
                                            mergeFields.Add("NewPassword", newPassword);
                                            mergeFields.Add("CreateLogin", createLogin);
                                            var emailMessage = new RockEmailMessage(sync.WelcomeSystemCommunication);
                                            emailMessage.AddRecipient(new RockEmailMessageRecipient(person, mergeFields));
                                            var emailErrors = new List <string>();
                                            emailMessage.Send(out emailErrors);
                                            errors.AddRange(emailErrors);
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                ExceptionLogService.LogException(ex);
                                continue;
                            }

                            hasSyncChanged = true;
                        }

                        // Increment Groups Changed Counter (if people were deleted or added to the group)
                        if (hasSyncChanged)
                        {
                            groupsChanged++;
                        }

                        // Increment the Groups Synced Counter
                        groupsSynced++;
                    }

                    // Update last refresh datetime in different context to avoid side-effects.
                    using (var rockContext = new RockContext())
                    {
                        var sync = new GroupSyncService(rockContext)
                                   .Queryable()
                                   .FirstOrDefault(s => s.Id == syncId);

                        sync.LastRefreshDateTime = RockDateTime.Now;

                        rockContext.SaveChanges();
                    }
                }

                // Format the result message
                var resultMessage = string.Empty;
                if (groupsSynced == 0)
                {
                    resultMessage = "No groups to sync";
                }
                else if (groupsSynced == 1)
                {
                    resultMessage = "1 group was synced";
                }
                else
                {
                    resultMessage = string.Format("{0} groups were synced", groupsSynced);
                }

                resultMessage += string.Format(" and {0} groups were changed", groupsChanged);

                if (errors.Any())
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine();
                    sb.Append("Errors: ");
                    errors.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                    string errorMessage = sb.ToString();
                    resultMessage += errorMessage;
                    throw new Exception(errorMessage);
                }

                context.Result = resultMessage;
            }
            catch (System.Exception ex)
            {
                HttpContext context2 = HttpContext.Current;
                ExceptionLogService.LogException(ex, context2);
                throw;
            }
        }
Ejemplo n.º 14
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    personService = new PersonService(rockContext);
            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
            business.LastName = tbBusinessName.Text;

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

            var phoneNumber = business.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == businessPhoneTypeId);

            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;
            }
            else
            {
                if (phoneNumber != null)
                {
                    business.PhoneNumbers.Remove(phoneNumber);
                    new PhoneNumberService(rockContext).Delete(phoneNumber);
                }
            }

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

            // Record Status
            business.RecordStatusValueId = dvpRecordStatus.SelectedValueAsInt();;

            // Record Status Reason
            int?newRecordStatusReasonId = null;

            if (business.RecordStatusValueId.HasValue && business.RecordStatusValueId.Value == DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id)
            {
                newRecordStatusReasonId = dvpReason.SelectedValueAsInt();
            }
            business.RecordStatusReasonValueId = newRecordStatusReasonId;

            // Email
            business.IsEmailActive   = true;
            business.Email           = tbEmail.Text.Trim();
            business.EmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();

            avcEditAttributes.GetEditValues(business);

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

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

                // 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.Get(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.Get(Rock.SystemGuid.GroupType.GROUPTYPE_PEER_NETWORK.AsGuid());
                int impliedRelationshipOwnerRoleId = impliedRelationshipGroupType.Roles
                                                     .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_PEER_NETWORK_OWNER.AsGuid()))
                                                     .Select(r => r.Id)
                                                     .FirstOrDefault();
                var impliedRelationshipOwner = UpdateGroupMember(business.Id, impliedRelationshipGroupType, "Implied Relationship", null, impliedRelationshipOwnerRoleId, rockContext);

                rockContext.SaveChanges();

                // Location
                int workLocationTypeId = DefinedValueCache.Get(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)
                    {
                        if (cbSaveFormerAddressAsPreviousAddress.Checked)
                        {
                            GroupLocationHistorical.CreateCurrentRowFromGroupLocation(workLocation, RockDateTime.Now);
                        }

                        groupLocationService.Delete(workLocation);
                    }
                }
                else
                {
                    var newLocation = new LocationService(rockContext).Get(acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);
                    if (workLocation == null)
                    {
                        workLocation = new GroupLocation();
                        groupLocationService.Add(workLocation);
                        workLocation.GroupId = adultFamilyMember.Group.Id;
                        workLocation.GroupLocationTypeValueId = workLocationTypeId;
                    }
                    else
                    {
                        // Save this to history if the box is checked and the new info is different than the current one.
                        if (cbSaveFormerAddressAsPreviousAddress.Checked && newLocation.Id != workLocation.Location.Id)
                        {
                            new GroupLocationHistoricalService(rockContext).Add(GroupLocationHistorical.CreateCurrentRowFromGroupLocation(workLocation, RockDateTime.Now));
                        }
                    }

                    workLocation.Location          = newLocation;
                    workLocation.IsMailingLocation = true;
                }

                rockContext.SaveChanges();

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

            /* Ethan Drotning 2022-01-11
             * Need save the PersonSearchKeys outside of the transaction since the DB might not have READ_COMMITTED_SNAPSHOT enabled.
             */

            // PersonSearchKey
            var personSearchKeyService = new PersonSearchKeyService(rockContext);
            var validSearchTypes       = GetValidSearchKeyTypes();
            var databaseSearchKeys     = personSearchKeyService.Queryable().Where(a => a.PersonAlias.PersonId == business.Id && validSearchTypes.Contains(a.SearchTypeValue.Guid)).ToList();

            foreach (var deletedSearchKey in databaseSearchKeys.Where(a => !PersonSearchKeysState.Any(p => p.Guid == a.Guid)))
            {
                personSearchKeyService.Delete(deletedSearchKey);
            }

            foreach (var personSearchKey in PersonSearchKeysState.Where(a => !databaseSearchKeys.Any(d => d.Guid == a.Guid)))
            {
                personSearchKey.PersonAliasId = business.PrimaryAliasId.Value;
                personSearchKeyService.Add(personSearchKey);
            }

            rockContext.SaveChanges();

            business.SaveAttributeValues();

            var queryParams = new Dictionary <string, string>
            {
                { "BusinessId", hfBusinessId.Value }
            };

            NavigateToCurrentPage(queryParams);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Execute method to write transaction to the database.
        /// </summary>
        public void Execute()
        {
            if (!this._logInteraction)
            {
                return;
            }

            if (!this.LogCrawlers)
            {
                // get user agent info
                var clientType = InteractionDeviceType.GetClientType(_userAgent);
                // don't log visits from crawlers
                if (clientType == "Crawler")
                {
                    return;
                }
            }

            var rockContext = new RockContext();

            // lookup the interaction channel, and create it if it doesn't exist
            var interactionChannelService = new InteractionChannelService(rockContext);
            var interactionChannelId      = interactionChannelService.Queryable()
                                            .Where(a =>
                                                   a.ChannelTypeMediumValueId == _channelMediumTypeValue.Id &&
                                                   a.ChannelEntityId == _channelEntityId)
                                            .Select(a => ( int? )a.Id)
                                            .FirstOrDefault();

            if (interactionChannelId == null)
            {
                var interactionChannel = new InteractionChannel();
                interactionChannel.Name = _channelName;
                interactionChannel.ChannelTypeMediumValueId = _channelMediumTypeValue.Id;
                interactionChannel.ChannelEntityId          = _channelEntityId;
                interactionChannel.ComponentEntityTypeId    = _componentEntityTypeId;
                interactionChannelService.Add(interactionChannel);
                rockContext.SaveChanges();
                interactionChannelId = interactionChannel.Id;
            }

            // check that the contentChannelItem exists as a component
            var interactionComponent = new InteractionComponentService(rockContext).GetComponentByEntityId(interactionChannelId.Value, _componentEntityId, _componentName);

            rockContext.SaveChanges();

            // Add the interaction
            if (interactionComponent != null)
            {
                var interactionService = new InteractionService(rockContext);
                var interaction        = interactionService.CreateInteraction(interactionComponent.Id, _userAgent, _url, _ipAddress, _browserSessionId);

                interaction.EntityId            = null;
                interaction.Operation           = "View";
                interaction.InteractionSummary  = InteractionSummary;
                interaction.InteractionData     = _url;
                interaction.PersonAliasId       = _currentPersonAliasId;
                interaction.InteractionDateTime = RockDateTime.Now;
                interactionService.Add(interaction);
                rockContext.SaveChanges();
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Handles the SaveClick event of the mdAddContact control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void mdAddContact_SaveClick(object sender, EventArgs e)
        {
            var rockContext        = new RockContext();
            var personService      = new PersonService(rockContext);
            var groupService       = new GroupService(rockContext);
            var groupMemberService = new GroupMemberService(rockContext);
            var business           = personService.Get(int.Parse(hfBusinessId.Value));
            int?contactId          = ppContact.PersonId;

            if (contactId.HasValue && contactId.Value > 0)
            {
                // Get the relationship roles to use
                var knownRelationshipGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid());
                int businessContactRoleId      = knownRelationshipGroupType.Roles
                                                 .Where(r =>
                                                        r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS_CONTACT.AsGuid()))
                                                 .Select(r => r.Id)
                                                 .FirstOrDefault();
                int businessRoleId = knownRelationshipGroupType.Roles
                                     .Where(r =>
                                            r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS.AsGuid()))
                                     .Select(r => r.Id)
                                     .FirstOrDefault();
                int ownerRoleId = knownRelationshipGroupType.Roles
                                  .Where(r =>
                                         r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid()))
                                  .Select(r => r.Id)
                                  .FirstOrDefault();

                if (ownerRoleId > 0 && businessContactRoleId > 0 && businessRoleId > 0)
                {
                    // get the known relationship group of the business contact
                    // add the business as a group member of that group using the group role of GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS
                    var contactKnownRelationshipGroup = groupMemberService.Queryable()
                                                        .Where(g =>
                                                               g.GroupRoleId == ownerRoleId &&
                                                               g.PersonId == contactId.Value)
                                                        .Select(g => g.Group)
                                                        .FirstOrDefault();
                    if (contactKnownRelationshipGroup == null)
                    {
                        // In some cases person may not yet have a know relationship group type
                        contactKnownRelationshipGroup = new Group();
                        groupService.Add(contactKnownRelationshipGroup);
                        contactKnownRelationshipGroup.Name        = "Known Relationship";
                        contactKnownRelationshipGroup.GroupTypeId = knownRelationshipGroupType.Id;

                        var ownerMember = new GroupMember();
                        ownerMember.PersonId    = contactId.Value;
                        ownerMember.GroupRoleId = ownerRoleId;
                        contactKnownRelationshipGroup.Members.Add(ownerMember);
                    }
                    var groupMember = new GroupMember();
                    groupMember.PersonId    = int.Parse(hfBusinessId.Value);
                    groupMember.GroupRoleId = businessRoleId;
                    contactKnownRelationshipGroup.Members.Add(groupMember);

                    // get the known relationship group of the business
                    // add the business contact as a group member of that group using the group role of GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS_CONTACT
                    var businessKnownRelationshipGroup = groupMemberService.Queryable()
                                                         .Where(g =>
                                                                g.GroupRole.Guid.Equals(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER)) &&
                                                                g.PersonId == business.Id)
                                                         .Select(g => g.Group)
                                                         .FirstOrDefault();
                    if (businessKnownRelationshipGroup == null)
                    {
                        // In some cases business may not yet have a know relationship group type
                        businessKnownRelationshipGroup = new Group();
                        groupService.Add(businessKnownRelationshipGroup);
                        businessKnownRelationshipGroup.Name        = "Known Relationship";
                        businessKnownRelationshipGroup.GroupTypeId = knownRelationshipGroupType.Id;

                        var ownerMember = new GroupMember();
                        ownerMember.PersonId    = int.Parse(hfBusinessId.Value);
                        ownerMember.GroupRoleId = ownerRoleId;
                        businessKnownRelationshipGroup.Members.Add(ownerMember);
                    }
                    var businessGroupMember = new GroupMember();
                    businessGroupMember.PersonId    = contactId.Value;
                    businessGroupMember.GroupRoleId = businessContactRoleId;
                    businessKnownRelationshipGroup.Members.Add(businessGroupMember);

                    rockContext.SaveChanges();
                }
            }

            mdAddContact.Hide();
            hfModalOpen.Value = string.Empty;
            BindContactListGrid(business);
        }
        /// <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.ContentStream    = uploadedBinaryFile.ContentStream;
                }
            }

            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>
        /// Saves the prayer request.
        /// </summary>
        private void SaveRequest()
        {
            var                  rockContext = new RockContext();
            PrayerRequest        prayerRequest;
            PrayerRequestService prayerRequestService = new PrayerRequestService(rockContext);

            int prayerRequestId = hfPrayerRequestId.Value.AsInteger();

            // Fetch the prayer request or create a new one if needed
            if (prayerRequestId == 0)
            {
                prayerRequest = new PrayerRequest();
                prayerRequestService.Add(prayerRequest);
                prayerRequest.EnteredDateTime = RockDateTime.Now;
            }
            else
            {
                prayerRequest = prayerRequestService.Get(prayerRequestId);
            }

            if (ppRequestor.PersonId.HasValue)
            {
                prayerRequest.RequestedByPersonAliasId = ppRequestor.PersonAliasId;
            }

            // If changing from NOT-approved to approved, record who and when
            if (!(prayerRequest.IsApproved ?? false) && hfApprovedStatus.Value.AsBoolean())
            {
                prayerRequest.ApprovedByPersonAliasId = CurrentPersonAliasId;
                prayerRequest.ApprovedOnDateTime      = RockDateTime.Now;

                // reset the flag count only to zero ONLY if it had a value previously.
                if (prayerRequest.FlagCount.HasValue && prayerRequest.FlagCount > 0)
                {
                    prayerRequest.FlagCount = 0;
                }
            }

            // If no expiration date was manually set, then use the default setting.
            if (!dpExpirationDate.SelectedDate.HasValue)
            {
                var expireDays = Convert.ToDouble(GetAttributeValue("ExpireDays"));
                prayerRequest.ExpirationDate = RockDateTime.Now.AddDays(expireDays);
            }
            else
            {
                prayerRequest.ExpirationDate = dpExpirationDate.SelectedDate;
            }

            prayerRequest.CampusId   = cpCampus.SelectedCampusId;
            prayerRequest.CategoryId = catpCategory.SelectedValueAsInt();

            // Now record all the bits...
            prayerRequest.IsApproved    = hfApprovedStatus.Value.AsBoolean();
            prayerRequest.IsActive      = cbIsActive.Checked;
            prayerRequest.IsUrgent      = cbIsUrgent.Checked;
            prayerRequest.AllowComments = cbAllowComments.Checked;
            prayerRequest.IsPublic      = cbIsPublic.Checked;
            prayerRequest.FirstName     = tbFirstName.Text;
            prayerRequest.LastName      = tbLastName.Text;
            prayerRequest.Text          = dtbText.Text.Trim();
            prayerRequest.Answer        = dtbAnswer.Text.Trim();

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

            if (!Page.IsValid)
            {
                return;
            }

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

            rockContext.SaveChanges();
            prayerRequest.SaveAttributeValues(rockContext);

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

            if (!string.IsNullOrWhiteSpace(PageParameter("PersonId")))
            {
                queryParms.Add("PersonId", PageParameter("PersonId"));
            }

            NavigateToParentPage(queryParms);
        }
Ejemplo n.º 19
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)
        {
            Category category;

            var             rockContext     = new RockContext();
            CategoryService categoryService = new CategoryService(rockContext);

            int categoryId = hfCategoryId.ValueAsInt();

            if (categoryId == 0)
            {
                category              = new Category();
                category.IsSystem     = false;
                category.EntityTypeId = entityTypeId;
                category.EntityTypeQualifierColumn = entityTypeQualifierProperty;
                category.EntityTypeQualifierValue  = entityTypeQualifierValue;
                category.Order = 0;
                categoryService.Add(category);
            }
            else
            {
                category = categoryService.Get(categoryId);
            }

            category.Name             = tbName.Text;
            category.ParentCategoryId = cpParentCategory.SelectedValueAsInt();
            category.IconCssClass     = tbIconCssClass.Text;
            category.HighlightColor   = tbHighlightColor.Text;

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

            if (!Page.IsValid)
            {
                return;
            }

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

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

            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.SaveChanges();
            CategoryCache.Flush(category.Id);

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

            qryParams["CategoryId"] = category.Id.ToString();
            NavigateToPage(RockPage.Guid, qryParams);
        }
Ejemplo n.º 20
0
        private int SyncVimeo(RockContext rockContext)
        {
            ContentChannelItem contentItem = GetContentItem(rockContext);

            if (contentItem != null)
            {
                if (contentItem.Attributes == null)
                {
                    contentItem.LoadAttributes();
                }

                long videoId = _vimeoId;

                if (_vimeoId == 0)
                {
                    videoId = this.tbVimeoId.Text.AsInteger();
                }

                if (contentItem.AttributeValues.ContainsKey(_vimeoIdKey))
                {
                    contentItem.AttributeValues[_vimeoIdKey].Value = videoId.ToString().AsInteger().ToString();
                }
                else
                {
                    contentItem.SetAttributeValue(_durationAttributeKey, videoId.ToString().AsInteger());
                }

                var client = new VimeoClient(_accessToken);
                var vimeo  = new Video();
                var width  = GetAttributeValue("ImageWidth").AsInteger();
                var video  = vimeo.GetVideoInfo(client, videoId, width);

                var cbName = cblSyncOptions.Items.FindByValue("Name");
                if (cbName != null && cbName.Selected == true)
                {
                    contentItem.Title = video.name;
                }

                var cbDescription = cblSyncOptions.Items.FindByValue("Description");
                if (cbDescription != null && cbDescription.Selected == true)
                {
                    contentItem.Content = video.description;
                }

                var cbImage = cblSyncOptions.Items.FindByValue("Image");
                if (cbImage != null && cbImage.Selected == true)
                {
                    if (contentItem.AttributeValues.ContainsKey(_imageAttributeKey))
                    {
                        contentItem.AttributeValues[_imageAttributeKey].Value = video.imageUrl;
                    }
                    else
                    {
                        contentItem.SetAttributeValue(_imageAttributeKey, video.imageUrl);
                    }
                }

                var cbDuration = cblSyncOptions.Items.FindByValue("Duration");
                if (cbDuration != null && cbDuration.Selected == true)
                {
                    if (contentItem.AttributeValues.ContainsKey(_durationAttributeKey))
                    {
                        contentItem.AttributeValues[_durationAttributeKey].Value = video.duration.ToString();
                    }
                    else
                    {
                        contentItem.SetAttributeValue(_durationAttributeKey, video.duration.ToString());
                    }
                }

                var cbHDVideo = cblSyncOptions.Items.FindByValue("HD Video");
                if (cbHDVideo != null && cbHDVideo.Selected == true && !string.IsNullOrWhiteSpace(video.hdLink))
                {
                    if (contentItem.AttributeValues.ContainsKey(_hdVideoAttributeKey))
                    {
                        contentItem.AttributeValues[_hdVideoAttributeKey].Value = video.hdLink;
                    }
                    else
                    {
                        contentItem.SetAttributeValue(_hdVideoAttributeKey, video.hdLink);
                    }
                }

                var cbSDVideo = cblSyncOptions.Items.FindByValue("SD Video");
                if (cbSDVideo != null && cbSDVideo.Selected == true && !string.IsNullOrWhiteSpace(video.sdLink))
                {
                    if (contentItem.AttributeValues.ContainsKey(_sdVideoAttributeKey))
                    {
                        contentItem.AttributeValues[_sdVideoAttributeKey].Value = video.sdLink;
                    }
                    else
                    {
                        contentItem.SetAttributeValue(_sdVideoAttributeKey, video.sdLink);
                    }
                }

                var cbHLSVideo = cblSyncOptions.Items.FindByValue("HLS Video");
                if (cbHLSVideo != null && cbHLSVideo.Selected == true && !string.IsNullOrWhiteSpace(video.hlsLink))
                {
                    if (contentItem.AttributeValues.ContainsKey(_hlsVideoAttributeKey))
                    {
                        contentItem.AttributeValues[_hlsVideoAttributeKey].Value = video.hlsLink;
                    }
                    else
                    {
                        contentItem.SetAttributeValue(_hlsVideoAttributeKey, video.hlsLink);
                    }
                }

                // Save Everything
                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    contentItem.SaveAttributeValues(rockContext);
                });
            }

            return(contentItem.Id);
        }
Ejemplo n.º 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)
        {
            var rockContext = new RockContext();

            rockContext.WrapTransaction(() =>
            {
                var personService = new PersonService(rockContext);

                var changes = new List <string>();

                var person = personService.Get(CurrentPersonId ?? 0);
                if (person != null)
                {
                    int?orphanedPhotoId = null;
                    if (person.PhotoId != imgPhoto.BinaryFileId)
                    {
                        orphanedPhotoId = person.PhotoId;
                        person.PhotoId  = imgPhoto.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.");
                        }
                    }

                    int?newTitleId      = dvpTitle.SelectedValueAsInt();
                    person.TitleValueId = newTitleId;

                    person.FirstName = tbFirstName.Text;

                    person.NickName = tbNickName.Text;

                    person.LastName = tbLastName.Text;

                    int?newSuffixId      = dvpSuffix.SelectedValueAsInt();
                    person.SuffixValueId = newSuffixId;

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


                    var newGender = rblGender.SelectedValue.ConvertToEnum <Gender>();
                    person.Gender = newGender;

                    var phoneNumberTypeIds = new List <int>();

                    bool smsSelected = false;

                    foreach (RepeaterItem item in rContactInfo.Items)
                    {
                        HiddenField hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                        PhoneNumberBox pnbPhone = item.FindControl("pnbPhone") as PhoneNumberBox;
                        CheckBox cbUnlisted     = item.FindControl("cbUnlisted") as CheckBox;
                        CheckBox cbSms          = item.FindControl("cbSms") as CheckBox;

                        if (hfPhoneType != null &&
                            pnbPhone != null &&
                            cbSms != null &&
                            cbUnlisted != 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;
                                    }

                                    phoneNumber.IsUnlisted = cbUnlisted.Checked;
                                    phoneNumberTypeIds.Add(phoneNumberTypeId);
                                }
                            }
                        }
                    }

                    // 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())
                    {
                        person.PhoneNumbers.Remove(phoneNumber);
                        phoneNumberService.Delete(phoneNumber);
                    }

                    person.Email = tbEmail.Text.Trim();

                    var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();
                    person.EmailPreference = newEmailPreference;

                    if (person.IsValid)
                    {
                        if (rockContext.SaveChanges() > 0)
                        {
                            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 (imgPhoto.CropBinaryFileId.HasValue)
                            {
                                if (imgPhoto.CropBinaryFileId != person.PhotoId)
                                {
                                    BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                                    var binaryFile = binaryFileService.Get(imgPhoto.CropBinaryFileId.Value);
                                    if (binaryFile != null && binaryFile.IsTemporary)
                                    {
                                        string errorMessage;
                                        if (binaryFileService.CanDelete(binaryFile, out errorMessage))
                                        {
                                            binaryFileService.Delete(binaryFile);
                                            rockContext.SaveChanges();
                                        }
                                    }
                                }
                            }
                        }

                        // save address
                        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("LocationType").AsGuidOrNull();
                                    if (addressTypeGuid.HasValue)
                                    {
                                        var groupLocationService = new GroupLocationService(rockContext);

                                        var dvHomeAddressType = DefinedValueCache.Get(addressTypeGuid.Value);
                                        var familyAddress     = groupLocationService.Queryable().Where(l => l.GroupId == familyGroup.Id && l.GroupLocationTypeValueId == dvHomeAddressType.Id).FirstOrDefault();
                                        if (familyAddress != null && string.IsNullOrWhiteSpace(acAddress.Street1))
                                        {
                                            // delete the current address
                                            groupLocationService.Delete(familyAddress);
                                            rockContext.SaveChanges();
                                        }
                                        else
                                        {
                                            if (!string.IsNullOrWhiteSpace(acAddress.Street1))
                                            {
                                                if (familyAddress == null)
                                                {
                                                    familyAddress = new GroupLocation();
                                                    groupLocationService.Add(familyAddress);
                                                    familyAddress.GroupLocationTypeValueId = dvHomeAddressType.Id;
                                                    familyAddress.GroupId           = familyGroup.Id;
                                                    familyAddress.IsMailingLocation = true;
                                                    familyAddress.IsMappedLocation  = true;
                                                }
                                                else if (hfStreet1.Value != string.Empty)
                                                {
                                                    // user clicked move so create a previous address
                                                    var previousAddress = new GroupLocation();
                                                    groupLocationService.Add(previousAddress);

                                                    var previousAddressValue = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());
                                                    if (previousAddressValue != null)
                                                    {
                                                        previousAddress.GroupLocationTypeValueId = previousAddressValue.Id;
                                                        previousAddress.GroupId = familyGroup.Id;

                                                        Location previousAddressLocation   = new Location();
                                                        previousAddressLocation.Street1    = hfStreet1.Value;
                                                        previousAddressLocation.Street2    = hfStreet2.Value;
                                                        previousAddressLocation.City       = hfCity.Value;
                                                        previousAddressLocation.State      = hfState.Value;
                                                        previousAddressLocation.PostalCode = hfPostalCode.Value;
                                                        previousAddressLocation.Country    = hfCountry.Value;

                                                        previousAddress.Location = previousAddressLocation;
                                                    }
                                                }

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

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

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

                        NavigateToParentPage();
                    }
                }
            });
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();
            var mergeFields = GetMergeFields(action);

            // Validate the person exists
            var personGuid = GetAttributeValue(action, AttributeKey.Person, true).AsGuidOrNull();

            if (!personGuid.HasValue)
            {
                errorMessages.Add("The person guid is required but was missing");
                return(LogMessagesForExit(action, errorMessages));
            }

            var personService = new PersonService(rockContext);
            var person        = personService.Queryable("Aliases").AsNoTracking()
                                .FirstOrDefault(p => p.Guid == personGuid.Value || p.Aliases.Any(pa => pa.Guid == personGuid.Value));

            if (person == null)
            {
                errorMessages.Add($"The person with the guid '{personGuid.Value}' was not found");
                return(LogMessagesForExit(action, errorMessages));
            }

            if (!person.PrimaryAliasId.HasValue)
            {
                errorMessages.Add($"{person.FullName} does not have a primary alias identifier");
                return(LogMessagesForExit(action, errorMessages));
            }

            // Validate the step type exists. Could be a step type id or a guid
            var stepType = GetStepType(rockContext, action, out var errorMessage);

            if (!errorMessage.IsNullOrWhiteSpace())
            {
                errorMessages.Add(errorMessage);
                return(LogMessagesForExit(action, errorMessages));
            }

            if (stepType == null)
            {
                errorMessages.Add("The step type could not be found");
                return(LogMessagesForExit(action, errorMessages));
            }

            // Validate the step status exists and is in the same program as the step type
            var stepStatus = GetStepStatus(stepType, action, out errorMessage);

            if (!errorMessage.IsNullOrWhiteSpace())
            {
                errorMessages.Add(errorMessage);
                return(LogMessagesForExit(action, errorMessages));
            }

            if (stepStatus == null)
            {
                errorMessages.Add("The step status could not be found");
                return(LogMessagesForExit(action, errorMessages));
            }

            // Get the start and end dates
            var startDate = GetLavaAttributeValue(action, AttributeKey.StartDate).AsDateTime() ?? RockDateTime.Now;
            var endDate   = GetLavaAttributeValue(action, AttributeKey.EndDate).AsDateTime();

            // The completed date is today or the end date if the status is a completed status
            var completedDate = stepStatus.IsCompleteStatus ? (endDate ?? RockDateTime.Now) : ( DateTime? )null;

            // Create the step object
            var step = new Step
            {
                StepTypeId        = stepType.Id,
                PersonAliasId     = person.PrimaryAliasId.Value,
                StartDateTime     = startDate,
                EndDateTime       = endDate,
                CompletedDateTime = completedDate,
                StepStatusId      = stepStatus.Id
            };

            // Validate the step
            if (!step.IsValid)
            {
                errorMessages.AddRange(step.ValidationResults.Select(a => a.ErrorMessage));
                return(LogMessagesForExit(action, errorMessages));
            }

            // Check if the step can be created because of Allow Multiple rules on the step type and also prerequisite requirements
            var stepService = new StepService(rockContext);
            var canAdd      = stepService.CanAdd(step, out errorMessage);

            if (!errorMessage.IsNullOrWhiteSpace())
            {
                errorMessages.Add(errorMessage);
            }
            else if (!canAdd)
            {
                errorMessages.Add("Cannot add the step for an unspecified reason");
            }
            else
            {
                try
                {
                    stepService.Add(step);
                    rockContext.SaveChanges();
                }
                catch (Exception exception)
                {
                    errorMessages.Add($"Exception thrown: {exception.Message}");
                    ExceptionLogService.LogException(exception);
                }
            }

            return(LogMessagesForExit(action, errorMessages));
        }
Ejemplo n.º 23
0
        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(this.CurrentGroupMemberId);

            if (this.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;
            groupMember.GroupMemberStatus = rblStatus.SelectedValueAsEnum <GroupMemberStatus>();

            groupMember.LoadAttributes();

            Rock.Attribute.Helper.GetEditValues(phAttributes, groupMember);

            // 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()))
            {
                Rock.Security.Role.Flush(group.Id);
            }

            pnlEditGroupMember.Visible = false;
            pnlGroupView.Visible       = true;
            DisplayViewGroup();
            this.IsEditingGroupMember = false;
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap   = context.JobDetail.JobDataMap;
            var        groupGuid = dataMap.Get("NotificationGroup").ToString().AsGuid();

            var rockContext = new RockContext();
            var group       = new GroupService(rockContext).Get(groupGuid);

            if (group != null)
            {
                var installedPackages = InstalledPackageService.GetInstalledPackages();

                var sparkLinkRequest = new SparkLinkRequest();
                sparkLinkRequest.RockInstanceId   = Rock.Web.SystemSettings.GetRockInstanceId();
                sparkLinkRequest.OrganizationName = GlobalAttributesCache.Value("OrganizationName");
                sparkLinkRequest.VersionIds       = installedPackages.Select(i => i.VersionId).ToList();
                sparkLinkRequest.RockVersion      = VersionInfo.VersionInfo.GetRockSemanticVersionNumber();

                var notifications = new List <Notification>();

                var sparkLinkRequestJson = JsonConvert.SerializeObject(sparkLinkRequest);

                var client = new RestClient("https://www.rockrms.com/api/SparkLink/update");
                //var client = new RestClient( "http://localhost:57822/api/SparkLink/update" );
                var request = new RestRequest(Method.POST);
                request.AddParameter("application/json", sparkLinkRequestJson, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
                if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Accepted)
                {
                    foreach (var notification in JsonConvert.DeserializeObject <List <Notification> >(response.Content))
                    {
                        notifications.Add(notification);
                    }
                }

                if (sparkLinkRequest.VersionIds.Any())
                {
                    client = new RestClient("https://www.rockrms.com/api/Packages/VersionNotifications");
                    //client = new RestClient( "http://localhost:57822/api/Packages/VersionNotifications" );
                    request = new RestRequest(Method.GET);
                    request.AddParameter("VersionIds", sparkLinkRequest.VersionIds.AsDelimited(","));
                    response = client.Execute(request);
                    if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Accepted)
                    {
                        foreach (var notification in JsonConvert.DeserializeObject <List <Notification> >(response.Content))
                        {
                            notifications.Add(notification);
                        }
                    }
                }

                if (notifications.Count == 0)
                {
                    return;
                }

                var notificationService = new NotificationService(rockContext);
                foreach (var notification in notifications.ToList())
                {
                    if (notificationService.Get(notification.Guid) == null)
                    {
                        notificationService.Add(notification);
                    }
                    else
                    {
                        notifications.Remove(notification);
                    }
                }
                rockContext.SaveChanges();

                var notificationRecipientService = new NotificationRecipientService(rockContext);
                foreach (var notification in notifications)
                {
                    foreach (var member in group.Members)
                    {
                        if (member.Person.PrimaryAliasId.HasValue)
                        {
                            var recipientNotification = new Rock.Model.NotificationRecipient();
                            recipientNotification.NotificationId = notification.Id;
                            recipientNotification.PersonAliasId  = member.Person.PrimaryAliasId.Value;
                            notificationRecipientService.Add(recipientNotification);
                        }
                    }
                }
                rockContext.SaveChanges();
            }
        }
Ejemplo n.º 25
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)
        {
            FinancialAccount account;
            var rockContext = new RockContext();

            var accountService = new Rock.Model.FinancialAccountService(rockContext);

            int accountId = hfAccountId.Value.AsInteger();

            if (accountId == 0)
            {
                account = new Rock.Model.FinancialAccount();
                accountService.Add(account);
                account.CreatedByPersonAliasId = CurrentPersonAliasId;
                account.CreatedDateTime        = RockDateTime.Now;
            }
            else
            {
                account = accountService.Get(accountId);
            }

            account.Name              = tbName.Text;
            account.IsActive          = cbIsActive.Checked;
            account.IsPublic          = cbIsPublic.Checked;
            account.Description       = tbDescription.Text;
            account.PublicDescription = cePublicDescription.Text;

            account.ParentAccountId    = apParentAccount.SelectedValueAsInt();
            account.AccountTypeValueId = dvpAccountType.SelectedValueAsInt();
            account.PublicName         = tbPublicName.Text;
            account.Url      = tbUrl.Text;
            account.CampusId = cpCampus.SelectedValueAsInt();

            account.GlCode          = tbGLCode.Text;
            account.StartDate       = dtpStartDate.SelectedDate;
            account.EndDate         = dtpEndDate.SelectedDate;
            account.IsTaxDeductible = cbIsTaxDeductible.Checked;

            account.ModifiedDateTime        = RockDateTime.Now;
            account.ModifiedByPersonAliasId = CurrentPersonAliasId;

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

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

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

            rockContext.SaveChanges();
            account.SaveAttributeValues(rockContext);

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

            qryParams["AccountId"]   = account.Id.ToString();
            qryParams["ExpandedIds"] = PageParameter("ExpandedIds");

            NavigateToPage(RockPage.Guid, qryParams);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Handles the Click event of the lbPrintAttendanceRoster 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 lbPrintAttendanceRoster_Click(object sender, EventArgs e)
        {
            // NOTE: lbPrintAttendanceRoster is a full postback since we are returning a download of the roster

            nbPrintRosterWarning.Visible = false;
            var rockContext = new RockContext();

            Dictionary <int, object> mergeObjectsDictionary = new Dictionary <int, object>();

            if (_attendees != null)
            {
                var personIdList = _attendees.Select(a => a.PersonId).ToList();
                var personList   = new PersonService(rockContext).GetByIds(personIdList);
                foreach (var person in personList.OrderBy(a => a.LastName).ThenBy(a => a.NickName))
                {
                    mergeObjectsDictionary.AddOrIgnore(person.Id, person);
                }
            }

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);

            mergeFields.Add("Group", this._group);
            mergeFields.Add("AttendanceDate", this._occurrence.OccurrenceDate);

            var mergeTemplate = new MergeTemplateService(rockContext).Get(this.GetAttributeValue("AttendanceRosterTemplate").AsGuid());

            if (mergeTemplate == null)
            {
                this.LogException(new Exception("No Merge Template specified in block settings"));
                nbPrintRosterWarning.Visible = true;
                nbPrintRosterWarning.Text    = "Unable to print Attendance Roster";
                return;
            }

            MergeTemplateType mergeTemplateType = mergeTemplate.GetMergeTemplateType();

            if (mergeTemplateType == null)
            {
                this.LogException(new Exception("Unable to determine Merge Template Type"));
                nbPrintRosterWarning.Visible = true;
                nbPrintRosterWarning.Text    = "Error printing Attendance Roster";
                return;
            }

            BinaryFile outputBinaryFileDoc = null;

            var mergeObjectList = mergeObjectsDictionary.Select(a => a.Value).ToList();

            outputBinaryFileDoc = mergeTemplateType.CreateDocument(mergeTemplate, mergeObjectList, mergeFields);

            // set the name of the output doc
            outputBinaryFileDoc          = new BinaryFileService(rockContext).Get(outputBinaryFileDoc.Id);
            outputBinaryFileDoc.FileName = _group.Name + " Attendance Roster" + Path.GetExtension(outputBinaryFileDoc.FileName ?? "") ?? ".docx";
            rockContext.SaveChanges();

            if (mergeTemplateType.Exceptions != null && mergeTemplateType.Exceptions.Any())
            {
                if (mergeTemplateType.Exceptions.Count == 1)
                {
                    this.LogException(mergeTemplateType.Exceptions[0]);
                }
                else if (mergeTemplateType.Exceptions.Count > 50)
                {
                    this.LogException(new AggregateException(string.Format("Exceptions merging template {0}. See InnerExceptions for top 50.", mergeTemplate.Name), mergeTemplateType.Exceptions.Take(50).ToList()));
                }
                else
                {
                    this.LogException(new AggregateException(string.Format("Exceptions merging template {0}. See InnerExceptions", mergeTemplate.Name), mergeTemplateType.Exceptions.ToList()));
                }
            }

            var uri = new UriBuilder(outputBinaryFileDoc.Url);
            var qry = System.Web.HttpUtility.ParseQueryString(uri.Query);

            qry["attachment"] = true.ToTrueFalse();
            uri.Query         = qry.ToString();
            Response.Redirect(uri.ToString(), false);
            Context.ApplicationInstance.CompleteRequest();
        }
Ejemplo n.º 27
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            batchService = new FinancialBatchService(rockContext);
            FinancialBatch batch        = null;

            var changes = new List <string>();

            int batchId = hfBatchId.Value.AsInteger();

            if (batchId == 0)
            {
                batch = new FinancialBatch();
                batchService.Add(batch);
                changes.Add("Created the batch");
            }
            else
            {
                batch = batchService.Get(batchId);
            }

            if (batch != null)
            {
                History.EvaluateChange(changes, "Batch Name", batch.Name, tbName.Text);
                batch.Name = tbName.Text;

                BatchStatus batchStatus = (BatchStatus)ddlStatus.SelectedIndex;
                History.EvaluateChange(changes, "Status", batch.Status, batchStatus);
                batch.Status = batchStatus;

                CampusCache oldCampus = null;
                if (batch.CampusId.HasValue)
                {
                    oldCampus = CampusCache.Read(batch.CampusId.Value);
                }

                CampusCache newCampus = null;
                if (campCampus.SelectedCampusId.HasValue)
                {
                    newCampus = CampusCache.Read(campCampus.SelectedCampusId.Value);
                }

                History.EvaluateChange(changes, "Campus", oldCampus != null ? oldCampus.Name : "None", newCampus != null ? newCampus.Name : "None");
                batch.CampusId = campCampus.SelectedCampusId;

                DateTime?startDateTime = dtpStart.SelectedDateTimeIsBlank ? null : dtpStart.SelectedDateTime;
                History.EvaluateChange(changes, "Start Date/Time", batch.BatchStartDateTime, startDateTime);
                batch.BatchStartDateTime = startDateTime;

                DateTime?endDateTime;
                if (dtpEnd.SelectedDateTimeIsBlank && batch.BatchStartDateTime.HasValue)
                {
                    endDateTime = batch.BatchStartDateTime.Value.AddDays(1);
                }
                else
                {
                    endDateTime = dtpEnd.SelectedDateTimeIsBlank ? null : dtpEnd.SelectedDateTime;
                }

                History.EvaluateChange(changes, "End Date/Time", batch.BatchEndDateTime, endDateTime);
                batch.BatchEndDateTime = endDateTime;

                decimal controlAmount = tbControlAmount.Text.AsDecimal();
                History.EvaluateChange(changes, "Control Amount", batch.ControlAmount.FormatAsCurrency(), controlAmount.FormatAsCurrency());
                batch.ControlAmount = controlAmount;

                History.EvaluateChange(changes, "Accounting System Code", batch.AccountingSystemCode, tbAccountingCode.Text);
                batch.AccountingSystemCode = tbAccountingCode.Text;

                History.EvaluateChange(changes, "Notes", batch.Note, tbNote.Text);
                batch.Note = tbNote.Text;

                cvBatch.IsValid = batch.IsValid;
                if (!Page.IsValid || !batch.IsValid)
                {
                    cvBatch.ErrorMessage = batch.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                    return;
                }

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

                if (batchId == 0)
                {
                    // If created a new batch, navigate to same page so that transaction list displays correctly
                    var pageReference = CurrentPageReference;
                    pageReference.Parameters.AddOrReplace("batchId", batch.Id.ToString());
                    NavigateToPage(pageReference);
                }
                else
                {
                    hfBatchId.SetValue(batch.Id);

                    // Requery the batch to support EF navigation properties
                    var savedBatch = GetBatch(batch.Id);
                    ShowReadonlyDetails(savedBatch);

                    // If there is a batch context item, update the context's properties with new values
                    var contextObjects = new Dictionary <string, object>();
                    foreach (var contextEntityType in RockPage.GetContextEntityTypes())
                    {
                        var contextEntity = RockPage.GetCurrentContext(contextEntityType);
                        if (contextEntity is FinancialBatch)
                        {
                            var contextBatch = contextEntity as FinancialBatch;
                            contextBatch.CopyPropertiesFrom(batch);
                        }
                    }

                    // Then refresh transaction list
                    RockPage.UpdateBlocks("~/Blocks/Finance/TransactionList.ascx");
                }
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Method to save attendance for use in two separate areas.
        /// </summary>
        protected bool SaveAttendance()
        {
            using (var rockContext = new RockContext())
            {
                var occurrenceService  = new AttendanceOccurrenceService(rockContext);
                var attendanceService  = new AttendanceService(rockContext);
                var personAliasService = new PersonAliasService(rockContext);
                var locationService    = new LocationService(rockContext);

                AttendanceOccurrence occurrence = null;

                if (_occurrence.Id != 0)
                {
                    occurrence = occurrenceService.Get(_occurrence.Id);
                }

                if (occurrence == null)
                {
                    var existingOccurrence = occurrenceService.Get(_occurrence.OccurrenceDate, _group.Id, _occurrence.LocationId, _occurrence.ScheduleId);
                    if (existingOccurrence != null)
                    {
                        nbNotice.Heading             = "Occurrence Already Exists";
                        nbNotice.Text                = "<p>An occurrence already exists for this group for the selected date, location, and schedule that you've selected. Please return to the list and select that occurrence to update it's attendance.</p>";
                        nbNotice.NotificationBoxType = NotificationBoxType.Danger;
                        nbNotice.Visible             = true;

                        return(false);
                    }
                    else
                    {
                        occurrence                = new AttendanceOccurrence();
                        occurrence.GroupId        = _occurrence.GroupId;
                        occurrence.LocationId     = _occurrence.LocationId;
                        occurrence.ScheduleId     = _occurrence.ScheduleId;
                        occurrence.OccurrenceDate = _occurrence.OccurrenceDate;
                        occurrenceService.Add(occurrence);
                    }
                }

                occurrence.Notes       = GetAttributeValue("ShowNotes").AsBoolean() ? dtNotes.Text : string.Empty;
                occurrence.DidNotOccur = cbDidNotMeet.Checked;

                var existingAttendees = occurrence.Attendees.ToList();

                // If did not meet was selected and this was a manually entered occurrence (not based on a schedule/location)
                // then just delete all the attendance records instead of tracking a 'did not meet' value
                if (cbDidNotMeet.Checked && !_occurrence.ScheduleId.HasValue)
                {
                    foreach (var attendance in existingAttendees)
                    {
                        attendanceService.Delete(attendance);
                    }
                }
                else
                {
                    int?campusId = locationService.GetCampusIdForLocation(_occurrence.LocationId) ?? _group.CampusId;
                    if (!campusId.HasValue && _allowCampusFilter)
                    {
                        var campus = CampusCache.Get(bddlCampus.SelectedValueAsInt() ?? 0);
                        if (campus != null)
                        {
                            campusId = campus.Id;
                        }
                    }

                    if (cbDidNotMeet.Checked)
                    {
                        // If the occurrence is based on a schedule, set the did not meet flags
                        foreach (var attendance in existingAttendees)
                        {
                            attendance.DidAttend = null;
                        }
                    }
                    else
                    {
                        foreach (var attendee in _attendees)
                        {
                            var attendance = existingAttendees
                                             .Where(a => a.PersonAlias.PersonId == attendee.PersonId)
                                             .FirstOrDefault();

                            if (attendance == null)
                            {
                                int?personAliasId = personAliasService.GetPrimaryAliasId(attendee.PersonId);
                                if (personAliasId.HasValue)
                                {
                                    attendance = new Attendance();
                                    attendance.PersonAliasId = personAliasId;
                                    attendance.CampusId      = campusId;
                                    attendance.StartDateTime = _occurrence.OccurrenceDate;

                                    // check that the attendance record is valid
                                    cvAttendance.IsValid = attendance.IsValid;
                                    if (!cvAttendance.IsValid)
                                    {
                                        cvAttendance.ErrorMessage = attendance.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                                        return(false);
                                    }

                                    occurrence.Attendees.Add(attendance);
                                }
                            }

                            if (attendance != null)
                            {
                                attendance.DidAttend = attendee.Attended;
                            }
                        }
                    }
                }

                rockContext.SaveChanges();

                if (occurrence.LocationId.HasValue)
                {
                    Rock.CheckIn.KioskLocationAttendance.Remove(occurrence.LocationId.Value);
                }


                Guid?workflowTypeGuid = GetAttributeValue("Workflow").AsGuidOrNull();
                if (workflowTypeGuid.HasValue)
                {
                    var workflowType = WorkflowTypeCache.Get(workflowTypeGuid.Value);
                    if (workflowType != null && (workflowType.IsActive ?? true))
                    {
                        try
                        {
                            var workflow = Workflow.Activate(workflowType, _group.Name);

                            workflow.SetAttributeValue("StartDateTime", _occurrence.OccurrenceDate.ToString("o"));
                            workflow.SetAttributeValue("Schedule", _group.Schedule.Guid.ToString());

                            List <string> workflowErrors;
                            new WorkflowService(rockContext).Process(workflow, _group, out workflowErrors);
                        }
                        catch (Exception ex)
                        {
                            ExceptionLogService.LogException(ex, this.Context);
                        }
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Handles the Click event of the btnSaveFinancialTransaction 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 lbSaveTransaction_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();
            var financialTransactionService = new Rock.Model.FinancialTransactionService(rockContext);

            Rock.Model.FinancialTransaction financialTransaction = null;
            int financialTransactionId = !string.IsNullOrEmpty(hfIdTransValue.Value) ? int.Parse(hfIdTransValue.Value) : 0;

            // null if not associated with a batch
            int?batchId = hfBatchId.Value.AsInteger();

            if (financialTransactionId == 0)
            {
                financialTransaction = new Rock.Model.FinancialTransaction();
                financialTransactionService.Add(financialTransaction);
                financialTransaction.BatchId = batchId;
            }
            else
            {
                financialTransaction = financialTransactionService.Get(financialTransactionId);
            }

            if (ppAuthorizedPerson.PersonId != null)
            {
                financialTransaction.AuthorizedPersonId = ppAuthorizedPerson.PersonId;
            }
            else
            {
                financialTransaction.AuthorizedPersonId = null;
            }

            if (ddlCurrencyType.SelectedItem.ToString() == "Credit Card")
            {
                financialTransaction.CreditCardTypeValueId = int.Parse(ddlCreditCardType.SelectedValue);
            }
            else
            {
                financialTransaction.CreditCardTypeValueId = null;
            }

            financialTransaction.CurrencyTypeValueId = int.Parse(ddlCurrencyType.SelectedValue);
            if (!string.IsNullOrEmpty(ddlPaymentGateway.SelectedValue))
            {
                var gatewayEntity = Rock.Web.Cache.EntityTypeCache.Read(new Guid(ddlPaymentGateway.SelectedValue));
                if (gatewayEntity != null)
                {
                    financialTransaction.GatewayEntityTypeId = gatewayEntity.Id;
                }
            }

            financialTransaction.SourceTypeValueId      = int.Parse(ddlSourceType.SelectedValue);
            financialTransaction.TransactionTypeValueId = int.Parse(ddlTransactionType.SelectedValue);

            financialTransaction.Summary             = tbSummary.Text;
            financialTransaction.TransactionCode     = tbTransactionCode.Text;
            financialTransaction.TransactionDateTime = dtTransactionDateTime.SelectedDateTime;

            rockContext.SaveChanges();

            if (batchId != null)
            {
                Dictionary <string, string> qryString = new Dictionary <string, string>();
                qryString["financialBatchid"] = hfBatchId.Value;
                NavigateToParentPage(qryString);
            }
            else
            {
                NavigateToParentPage();
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Gets the person.
        /// </summary>
        /// <param name="paymentInfo">The paymentInfo object to use as the base.</param>
        /// <param name="create">if set to <c>true</c> [create].</param>
        /// <returns></returns>
        private Person GetPerson(PaymentInfo paymentInfo, bool create)
        {
            Person person        = null;
            var    rockContext   = new RockContext();
            var    personService = new PersonService(rockContext);

            Group familyGroup = null;

            int personId = ViewState["PersonId"] as int? ?? 0;

            if (personId == 0 && _targetPerson != null)
            {
                personId = _targetPerson.Id;
            }

            if (personId != 0)
            {
                person = personService.Get(personId);
            }

            if (create)
            {
                if (person == null)
                {
                    // Check to see if there's only one person with same email, first name, and last name
                    if (!string.IsNullOrWhiteSpace(paymentInfo.Email) &&
                        !string.IsNullOrWhiteSpace(paymentInfo.FirstName) &&
                        !string.IsNullOrWhiteSpace(paymentInfo.LastName))
                    {
                        // Same logic as CreatePledge.ascx.cs
                        var personMatches = personService.FindPersons(paymentInfo.FirstName, paymentInfo.LastName, paymentInfo.Email);
                        if (personMatches.Count() == 1)
                        {
                            person = personMatches.FirstOrDefault();
                        }
                        else
                        {
                            person = null;
                        }
                    }

                    if (person == null)
                    {
                        DefinedValueCache dvcConnectionStatus = DefinedValueCache.Get(GetAttributeValue("ConnectionStatus").AsGuid());
                        DefinedValueCache dvcRecordStatus     = DefinedValueCache.Get(GetAttributeValue("RecordStatus").AsGuid());

                        // Create Person
                        person                   = new Person();
                        person.FirstName         = paymentInfo.FirstName;
                        person.LastName          = paymentInfo.LastName;
                        person.IsEmailActive     = true;
                        person.EmailPreference   = EmailPreference.EmailAllowed;
                        person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                        if (dvcConnectionStatus != null)
                        {
                            person.ConnectionStatusValueId = dvcConnectionStatus.Id;
                        }

                        if (dvcRecordStatus != null)
                        {
                            person.RecordStatusValueId = dvcRecordStatus.Id;
                        }

                        // Create Person/Family
                        familyGroup = PersonService.SaveNewPerson(person, rockContext, null, false);
                    }

                    ViewState["PersonId"] = person != null ? person.Id : 0;
                }
            }

            if (create && person != null)   // person should never be null at this point
            {
                person.Email = paymentInfo.Email;

                if (GetAttributeValue("DisplayPhone").AsBooleanOrNull() ?? false && !String.IsNullOrEmpty(paymentInfo.Phone))
                {
                    var numberTypeId = DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME)).Id;
                    var phone        = person.PhoneNumbers.FirstOrDefault(p => p.NumberTypeValueId == numberTypeId);
                    if (phone == null)
                    {
                        phone = new PhoneNumber();
                        person.PhoneNumbers.Add(phone);
                        phone.NumberTypeValueId = numberTypeId;
                    }
                    phone.Number = paymentInfo.Phone;
                }

                if (familyGroup == null)
                {
                    var groupLocationService = new GroupLocationService(rockContext);
                    if (GroupLocationId.HasValue)
                    {
                        familyGroup = groupLocationService.Queryable()
                                      .Where(gl => gl.Id == GroupLocationId.Value)
                                      .Select(gl => gl.Group)
                                      .FirstOrDefault();
                    }
                    else
                    {
                        familyGroup = personService.GetFamilies(person.Id).FirstOrDefault();
                    }
                }

                rockContext.SaveChanges();

                if (familyGroup != null)
                {
                    GroupService.AddNewGroupAddress(
                        rockContext,
                        familyGroup,
                        GetAttributeValue("AddressType"),
                        paymentInfo.Street1, paymentInfo.Street2, paymentInfo.City, paymentInfo.State, paymentInfo.PostalCode, paymentInfo.Country,
                        true);
                }
            }

            return(person);
        }