コード例 #1
0
        /// <summary>
        /// Creates the child controls.
        /// </summary>
        /// <param name="parentControl"></param>
        /// <returns></returns>
        public override System.Web.UI.Control[] CreateChildControls(System.Web.UI.Control parentControl)
        {
            var cblNoteTypes = new RockListBox();

            cblNoteTypes.ID    = parentControl.GetChildControlInstanceName(_CtlNoteTypes);
            cblNoteTypes.Label = "Note Types";
            cblNoteTypes.Help  = "The type of note to filter by. Leave blank to include all note types.";
            parentControl.Controls.Add(cblNoteTypes);

            var noteTypeService    = new NoteTypeService(new RockContext());
            var entityTypeIdPerson = EntityTypeCache.GetId <Rock.Model.Person>();
            var noteTypes          = noteTypeService.Queryable()
                                     .Where(a => a.EntityTypeId == entityTypeIdPerson)
                                     .OrderBy(a => a.Order)
                                     .ThenBy(a => a.Name)
                                     .Select(a => new
            {
                a.Id,
                a.Name
            }).ToList();

            cblNoteTypes.Items.Clear();
            cblNoteTypes.Items.AddRange(noteTypes.Select(a => new ListItem(a.Name, a.Id.ToString())).ToArray());

            var slidingDateRangePicker = new SlidingDateRangePicker();

            slidingDateRangePicker.ID       = parentControl.GetChildControlInstanceName(_CtlSlidingDateRangePicker);
            slidingDateRangePicker.Label    = "Date Range";
            slidingDateRangePicker.Help     = "The date range that the note was created during.";
            slidingDateRangePicker.Required = false;
            parentControl.Controls.Add(slidingDateRangePicker);

            return(new System.Web.UI.Control[] { cblNoteTypes, slidingDateRangePicker });
        }
コード例 #2
0
        /// <summary>
        /// Gets the type of the note.
        /// </summary>
        private void GetNoteType()
        {
            var rockContext = new RockContext();
            var service     = new NoteTypeService(rockContext);

            noteType = service.Get(Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid());
        }
コード例 #3
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>();

            if (action != null && action.Activity != null &&
                action.Activity.Workflow != null && action.Activity.Workflow.Id > 0)
            {
                var noteType = new NoteTypeService(rockContext).Get(Rock.SystemGuid.NoteType.WORKFLOW_NOTE.AsGuid());

                var text = GetAttributeValue(action, "Note").ResolveMergeFields(GetMergeFields(action));

                var note = new Note();
                note.IsSystem   = false;
                note.IsAlert    = GetAttributeValue(action, "IsAlert").AsBoolean();
                note.NoteTypeId = noteType.Id;
                note.EntityId   = action.Activity.Workflow.Id;
                note.Caption    = string.Empty;
                note.Text       = text;

                var sourceType = DefinedValueCache.Read(GetAttributeValue(action, "NoteType"));
                if (sourceType != null)
                {
                    note.SourceTypeValueId = sourceType.Id;
                }

                new NoteService(rockContext).Add(note);

                return(true);
            }
            else
            {
                errorMessages.Add("A Note can only be added to a persisted workflow with a valid ID.");
                return(false);
            }
        }
コード例 #4
0
        /// <summary>
        /// Handles the Delete event of the gNoteTypes control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
        protected void gNoteTypes_Delete(object sender, RowEventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                var service  = new NoteTypeService(rockContext);
                var noteType = service.Get(e.RowKeyId);
                if (noteType != null && !noteType.IsSystem)
                {
                    string errorMessage = string.Empty;
                    if (service.CanDelete(noteType, out errorMessage))
                    {
                        int noteTypeId = noteType.Id;

                        service.Delete(noteType);
                        rockContext.SaveChanges();
                    }
                    else
                    {
                        mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                    }
                }
            }

            BindFilter();
            BindGrid();
        }
コード例 #5
0
        private static EntityNoteTypesCache QueryDbWithContext(RockContext rockContext)
        {
            var entityNoteTypes = new NoteTypeService(rockContext)
                                  .Queryable().AsNoTracking()
                                  .GroupBy(a => new
            {
                a.EntityTypeId,
                a.EntityTypeQualifierColumn,
                a.EntityTypeQualifierValue
            })
                                  .Select(a => new EntityNoteTypes()
            {
                EntityTypeId = a.Key.EntityTypeId,
                EntityTypeQualifierColumn = a.Key.EntityTypeQualifierColumn,
                EntityTypeQualifierValue  = a.Key.EntityTypeQualifierValue,
                NoteTypeIds = a.Select(v => v.Id).ToList()
            })
                                  .ToList();

            var value = new EntityNoteTypesCache {
                EntityNoteTypes = entityNoteTypes
            };

            return(value);
        }
コード例 #6
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>();

            if ( action != null && action.Activity != null &&
                action.Activity.Workflow != null && action.Activity.Workflow.Id > 0 )
            {
                var noteType = new NoteTypeService( rockContext ).Get( Rock.SystemGuid.NoteType.WORKFLOW_NOTE.AsGuid() );

                var text = GetAttributeValue( action, "Note" ).ResolveMergeFields( GetMergeFields( action ) );

                var note = new Note();
                note.IsSystem = false;
                note.IsAlert = GetAttributeValue( action, "IsAlert" ).AsBoolean();
                note.NoteTypeId = noteType.Id;
                note.EntityId = action.Activity.Workflow.Id;
                note.Caption = string.Empty;
                note.Text = text;

                var  sourceType = DefinedValueCache.Read( GetAttributeValue( action, "NoteType" ) );
                if ( sourceType != null )
                {
                    note.SourceTypeValueId = sourceType.Id;
                }

                new NoteService( rockContext ).Add( note );

                return true;
            }
            else
            {
                errorMessages.Add( "A Note can only be added to a persisted workflow with a valid ID." );
                return false;
            }
        }
コード例 #7
0
        /// <summary>
        /// Handles the Delete event of the rGrid control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void rGrid_Delete(object sender, RowEventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                var service  = new NoteTypeService(rockContext);
                var noteType = service.Get(e.RowKeyId);
                if (noteType != null)
                {
                    string errorMessage = string.Empty;
                    if (service.CanDelete(noteType, out errorMessage))
                    {
                        int id = noteType.Id;

                        service.Delete(noteType);
                        rockContext.SaveChanges();

                        NoteTypeCache.Flush(id);
                        NoteTypeCache.FlushEntityNoteTypes();
                    }
                    else
                    {
                        nbMessage.Text    = errorMessage;
                        nbMessage.Visible = true;
                    }
                }
            }

            BindFilter();
            BindGrid();
        }
コード例 #8
0
        /// <summary>
        /// Formats the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override string FormatSelection(Type entityType, string selection)
        {
            string result = "Person Note";

            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 2)
            {
                int noteTypeId       = selectionValues[0].AsInteger();
                var selectedNoteType = new NoteTypeService(new RockContext()).Get(noteTypeId);
                if (selectedNoteType != null)
                {
                    result = $"Has a {selectedNoteType.Name} note";
                }
                else
                {
                    result = "Has a note";
                }

                var containingText = selectionValues[1];
                if (containingText.IsNotNullOrWhitespace())
                {
                    result += $" containing '{containingText}'";
                }
            }

            return(result);
        }
コード例 #9
0
        /// <summary>
        /// Creates the child controls.
        /// </summary>
        /// <returns></returns>
        public override Control[] CreateChildControls(Type entityType, FilterField filterControl)
        {
            RockDropDownList ddlNoteType = new RockDropDownList();

            ddlNoteType.ID       = filterControl.ID + "_ddlNoteType";
            ddlNoteType.CssClass = "js-notetype";
            ddlNoteType.Label    = "Note Type";
            filterControl.Controls.Add(ddlNoteType);

            var noteTypeService    = new NoteTypeService(new RockContext());
            var entityTypeIdPerson = EntityTypeCache.GetId <Rock.Model.Person>();
            var noteTypes          = noteTypeService.Queryable().Where(a => a.EntityTypeId == entityTypeIdPerson)
                                     .OrderBy(a => a.Order)
                                     .ThenBy(a => a.Name)
                                     .Select(a => new
            {
                a.Id,
                a.Name
            }).ToList();

            ddlNoteType.Items.Clear();
            ddlNoteType.Items.Add(new ListItem());
            ddlNoteType.Items.AddRange(noteTypes.Select(a => new ListItem(a.Name, a.Id.ToString())).ToArray());

            var tbContains = new RockTextBox();

            tbContains.Label    = "Contains";
            tbContains.ID       = filterControl.ID + "_tbContains";
            tbContains.CssClass = "js-notecontains";
            filterControl.Controls.Add(tbContains);

            return(new System.Web.UI.Control[2] {
                ddlNoteType, tbContains
            });
        }
コード例 #10
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="attributeId">The attribute id.</param>
        protected void ShowEdit(int?noteTypeId)
        {
            NoteType noteType = null;

            if (noteTypeId.HasValue)
            {
                noteType = new NoteTypeService(new RockContext()).Get(noteTypeId.Value);
            }

            if (noteType != null)
            {
                tbName.Text = noteType.Name;
                cbUserSelectable.Checked = noteType.UserSelectable;
                tbCssClass.Text          = noteType.CssClass;
                tbIconCssClass.Text      = noteType.IconCssClass;
                entityTypePicker.SelectedEntityTypeId = noteType.EntityTypeId;
            }
            else
            {
                tbName.Text = string.Empty;
                cbUserSelectable.Checked = true;
                tbCssClass.Text          = string.Empty;
                tbIconCssClass.Text      = string.Empty;
                entityTypePicker.SelectedEntityTypeId = entityTypeFilter.SelectedValueAsInt(false);
            }

            hfIdValue.Value = noteTypeId.ToString();
            modalDetails.Show();
        }
コード例 #11
0
        /// <summary>
        /// Binds the comments grid.
        /// </summary>
        private void BindCommentsGrid()
        {
            var rockContext = new RockContext();

            var noteTypeService = new NoteTypeService(rockContext);
            var noteType        = noteTypeService.Get(Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid());

            // TODO log exception if noteType is null

            var noteService    = new NoteService(rockContext);
            var prayerComments = noteService.GetByNoteTypeId(noteType.Id);

            SortProperty sortProperty = gPrayerComments.SortProperty;

            if (_blockInstancePrayerRequestCategoryGuid.HasValue)
            {
                // if filtered by category, only show comments for prayer requests in that category or any of its decendent categories
                var categoryService = new CategoryService(rockContext);

                if (_blockInstancePrayerRequestCategoryGuid.HasValue)
                {
                    var categories = new CategoryService(rockContext).GetAllDescendents(_blockInstancePrayerRequestCategoryGuid.Value).Select(a => a.Id).ToList();

                    var prayerRequestQry = new PrayerRequestService(rockContext).Queryable().Where(a => a.CategoryId.HasValue &&
                                                                                                   (a.Category.Guid == _blockInstancePrayerRequestCategoryGuid.Value || categories.Contains(a.CategoryId.Value)))
                                           .Select(a => a.Id);

                    prayerComments = prayerComments.Where(a => a.EntityId.HasValue && prayerRequestQry.Contains(a.EntityId.Value));
                }
            }

            // Filter by Date Range
            if (drpDateRange.LowerValue.HasValue)
            {
                DateTime startDate = drpDateRange.LowerValue.Value.Date;
                prayerComments = prayerComments.Where(a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value >= startDate);
            }

            if (drpDateRange.UpperValue.HasValue)
            {
                // Add one day in order to include everything up to the end of the selected datetime.
                var endDate = drpDateRange.UpperValue.Value.AddDays(1);
                prayerComments = prayerComments.Where(a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value < endDate);
            }

            // Sort by the given property otherwise sort by the EnteredDate
            if (sortProperty != null)
            {
                gPrayerComments.DataSource = prayerComments.Sort(sortProperty).ToList();
            }
            else
            {
                gPrayerComments.DataSource = prayerComments.OrderBy(n => n.CreatedDateTime).ToList();
            }

            gPrayerComments.DataBind();
        }
コード例 #12
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var expirationDateAttributeGuid = GetAttributeValue("ExpirationDateAttribute").AsGuid();

            if (expirationDateAttributeGuid != Guid.Empty)
            {
                _expirationDateKey = AttributeCache.Read(expirationDateAttributeGuid, _rockContext).Key;
            }

            if (!Page.IsPostBack)
            {
                List <string> errors           = new List <string>();
                string        workflowActivity = GetAttributeValue("WorkflowActivity");
                try
                {
                    bool test = ProcessActivity(workflowActivity, out errors);
                }
                catch (Exception ex)
                {
                    LogException(ex);
                    NavigateToPreviousPage();
                    return;
                }

                if (CurrentCheckInState == null)
                {
                    NavigateToPreviousPage();
                    return;
                }

                //people can be preselected coming out of the workflow, we want to unselect them
                foreach (var person in CurrentCheckInState.CheckIn.Families.Where(s => s.Selected).SelectMany(f => f.People))
                {
                    person.Selected = false;
                }
                SaveState();
            }

            _noteTypeId = ( int? )GetCacheItem("NoteTypeId") ?? 0;

            if (_noteTypeId == 0)
            {
                var groupMemberEntityId = new EntityTypeService(_rockContext).Get(Rock.SystemGuid.EntityType.GROUP_MEMBER.AsGuid()).Id;
                var groupMemberNoteType = new NoteTypeService(_rockContext).Queryable()
                                          .Where(nt => nt.EntityTypeId == groupMemberEntityId).FirstOrDefault();
                if (groupMemberNoteType != null)
                {
                    _noteTypeId = groupMemberNoteType.Id;
                    AddCacheItem(_noteTypeId);
                }
            }

            BuildMemberCards();
        }
コード例 #13
0
        private static int LoadByGuid2(Guid guid, RockContext rockContext)
        {
            var NoteTypeService = new NoteTypeService(rockContext);

            return(NoteTypeService
                   .Queryable().AsNoTracking()
                   .Where(c => c.Guid.Equals(guid))
                   .Select(c => c.Id)
                   .FirstOrDefault());
        }
コード例 #14
0
ファイル: NoteTypeDetail.ascx.cs プロジェクト: waldo2590/Rock
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            int noteTypeId = hfNoteTypeId.Value.AsInteger();

            var      rockContext = new RockContext();
            var      service     = new NoteTypeService(rockContext);
            NoteType noteType    = null;

            if (noteTypeId != 0)
            {
                noteType = service.Get(noteTypeId);
            }

            int entityTypeId = epEntityType.SelectedEntityTypeId ?? 0;

            if (noteType == null)
            {
                int?maxNoteTypeOrderForEntity = service.Queryable().Where(t => t.EntityTypeId == entityTypeId).Max(a => ( int? )a.Order);

                noteType       = new NoteType();
                noteType.Order = (maxNoteTypeOrderForEntity ?? 0) + 1;
                service.Add(noteType);
            }

            noteType.Name         = tbName.Text;
            noteType.EntityTypeId = entityTypeId;
            noteType.EntityTypeQualifierColumn = string.Empty;
            noteType.EntityTypeQualifierValue  = string.Empty;

            noteType.IconCssClass    = tbIconCssClass.Text;
            noteType.BackgroundColor = cpBackgroundColor.Text;
            noteType.FontColor       = cpFontColor.Text;
            noteType.BorderColor     = cpBorderColor.Text;

            noteType.UserSelectable            = cbUserSelectable.Checked;
            noteType.RequiresApprovals         = cbRequiresApprovals.Checked;
            noteType.SendApprovalNotifications = cbSendApprovalNotifications.Checked;
            noteType.AllowsWatching            = cbAllowsWatching.Checked;
            noteType.AutoWatchAuthors          = cbAutoWatchAuthors.Checked;

            noteType.AllowsReplies = cbAllowsReplies.Checked;
            noteType.MaxReplyDepth = nbMaxReplyDepth.Text.AsIntegerOrNull();

            noteType.AllowsAttachments = cbAllowsAttachments.Checked;
            noteType.BinaryFileTypeId  = noteType.AllowsAttachments ? bftpAttachmentType.SelectedValueAsId() : null;

            noteType.ApprovalUrlTemplate = ceApprovalUrlTemplate.Text;

            if (noteType.IsValid)
            {
                rockContext.SaveChanges();
            }

            NavigateToParentPage();
        }
コード例 #15
0
        /// <summary>
        /// Gets the configured NoteType for the PrayerRequest entity.
        /// </summary>
        private void GetNoteType()
        {
            string noteTypeName = GetAttributeValue("NoteType");

            var _prayerRequestEntityTypeId = Rock.Web.Cache.EntityTypeCache.GetId(new PrayerRequest().GetType().FullName);
            var noteTypeService            = new NoteTypeService();
            var noteType = noteTypeService.Get((int)_prayerRequestEntityTypeId, noteTypeName);

            // all that work to get this... for use later.
            PrayerCommentNoteTypeId = noteType.Id;
        }
コード例 #16
0
        /// <summary>
        /// Creates the control(s) necessary for prompting user for a new value
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id"></param>
        /// <returns>
        /// The control
        /// </returns>
        public override Control EditControl(Dictionary <string, ConfigurationValue> configurationValues, string id)
        {
            int    entityTypeId    = 0;
            string qualifierColumn = string.Empty;
            string qualifierValue  = string.Empty;

            if (configurationValues != null)
            {
                if (configurationValues.ContainsKey(ENTITY_TYPE_NAME_KEY))
                {
                    string entityTypeName = configurationValues[ENTITY_TYPE_NAME_KEY].Value;
                    if (!string.IsNullOrWhiteSpace(entityTypeName) && entityTypeName != None.IdValue)
                    {
                        var entityType = EntityTypeCache.Read(entityTypeName);
                        if (entityType != null)
                        {
                            entityTypeId = entityType.Id;
                        }
                    }
                }
                if (configurationValues.ContainsKey(QUALIFIER_COLUMN_KEY))
                {
                    qualifierColumn = configurationValues[QUALIFIER_COLUMN_KEY].Value;
                }

                if (configurationValues.ContainsKey(QUALIFIER_VALUE_KEY))
                {
                    qualifierValue = configurationValues[QUALIFIER_VALUE_KEY].Value;
                }
            }

            RockCheckBoxList editControl = new RockCheckBoxList {
                ID = id
            };

            editControl.RepeatDirection = RepeatDirection.Horizontal;

            using (var rockContext = new RockContext())
            {
                var noteTypes = new NoteTypeService(rockContext).Get(entityTypeId, qualifierColumn, qualifierValue).ToList();
                if (noteTypes.Any())
                {
                    foreach (var noteType in noteTypes)
                    {
                        ListItem listItem = new ListItem(noteType.Name, noteType.Guid.ToString().ToUpper());
                        editControl.Items.Add(listItem);
                    }

                    return(editControl);
                }
            }

            return(null);
        }
コード例 #17
0
        /// <summary>
        /// Deletes all related notes.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        private void DeleteAllRelatedNotes(PrayerRequest prayerRequest, RockContext rockContext)
        {
            var noteTypeService = new NoteTypeService(rockContext);
            var noteType        = noteTypeService.Get(Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid());
            var noteService     = new NoteService(rockContext);
            var prayerComments  = noteService.Get(noteType.Id, prayerRequest.Id);

            foreach (Note prayerComment in prayerComments)
            {
                noteService.Delete(prayerComment);
            }
        }
コード例 #18
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 modalDetails_SaveClick(object sender, EventArgs e)
        {
            int noteTypeId = 0;

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

            var      rockContext = new RockContext();
            var      service     = new NoteTypeService(rockContext);
            NoteType noteType    = null;

            if (noteTypeId != 0)
            {
                noteType = service.Get(noteTypeId);
            }

            if (noteType == null)
            {
                var orders = service.Queryable()
                             .Where(t => t.EntityTypeId == (entityTypePicker.SelectedEntityTypeId ?? 0))
                             .Select(t => t.Order)
                             .ToList();

                noteType       = new NoteType();
                noteType.Order = orders.Any() ? orders.Max(t => t) + 1 : 0;
                service.Add(noteType);
            }

            noteType.Name         = tbName.Text;
            noteType.EntityTypeId = entityTypePicker.SelectedEntityTypeId ?? 0;
            noteType.EntityTypeQualifierColumn = "";
            noteType.EntityTypeQualifierValue  = "";
            noteType.UserSelectable            = cbUserSelectable.Checked;
            noteType.CssClass     = tbCssClass.Text;
            noteType.IconCssClass = tbIconCssClass.Text;

            if (noteType.IsValid)
            {
                rockContext.SaveChanges();

                NoteTypeCache.Flush(noteType.Id);
                NoteTypeCache.FlushEntityNoteTypes();

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

                BindFilter();
                BindGrid();
            }
        }
コード例 #19
0
        private IQueryable <NoteType> GetUnorderedNoteTypes(int?entityTypeId, RockContext rockContext = null)
        {
            rockContext = rockContext ?? new RockContext();

            var queryable = new NoteTypeService(rockContext).Queryable();

            if (entityTypeId.HasValue)
            {
                queryable = queryable.Where(t => t.EntityTypeId == entityTypeId.Value);
            }

            return(queryable);
        }
コード例 #20
0
        private void DeleteAllRelatedNotes(PrayerRequest prayerRequest)
        {
            var noteTypeService = new NoteTypeService();
            var noteType        = noteTypeService.Get((int)_prayerRequestEntityTypeId, "Prayer Comment");
            var noteService     = new NoteService();
            var prayerComments  = noteService.Get(noteType.Id, prayerRequest.Id);

            foreach (Note prayerComment in prayerComments)
            {
                noteService.Delete(prayerComment, CurrentPersonId);
                noteService.Save(prayerComment, CurrentPersonId);
            }
        }
コード例 #21
0
ファイル: NoteTypes.ascx.cs プロジェクト: NewPointe/Rockit
        /// <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 modalDetails_SaveClick( object sender, EventArgs e )
        {
            int noteTypeId = 0;
            if ( hfIdValue.Value != string.Empty && !int.TryParse( hfIdValue.Value, out noteTypeId ) )
            {
                noteTypeId = 0;
            }

            var rockContext = new RockContext();
            var service = new NoteTypeService( rockContext );
            NoteType noteType = null;

            if ( noteTypeId != 0 )
            {
                noteType = service.Get( noteTypeId );
            }

            if ( noteType == null )
            {
                var orders = service.Queryable()
                    .Where( t => t.EntityTypeId == ( entityTypePicker.SelectedEntityTypeId ?? 0 ) )
                    .Select( t => t.Order )
                    .ToList();

                noteType = new NoteType();
                noteType.Order = orders.Any() ? orders.Max( t => t ) + 1 : 0;
                service.Add( noteType );
            }

            noteType.Name = tbName.Text;
            noteType.EntityTypeId = entityTypePicker.SelectedEntityTypeId ?? 0;
            noteType.EntityTypeQualifierColumn = "";
            noteType.EntityTypeQualifierValue = "";
            noteType.UserSelectable = cbUserSelectable.Checked;
            noteType.CssClass = tbCssClass.Text;
            noteType.IconCssClass = tbIconCssClass.Text;

            if ( noteType.IsValid )
            {
                rockContext.SaveChanges();

                NoteTypeCache.Flush( noteType.Id );
                NoteTypeCache.FlushEntityNoteTypes();

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

                BindFilter();
                BindGrid();
            }
        }
コード例 #22
0
        /// <summary>
        /// Deletes all related notes.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        private void DeleteAllRelatedNotes(PrayerRequest prayerRequest)
        {
            var rockContext     = new RockContext();
            var noteTypeService = new NoteTypeService(rockContext);
            var noteType        = noteTypeService.Get(_prayerRequestEntityTypeId.Value, "Prayer Comment");
            var noteService     = new NoteService(rockContext);
            var prayerComments  = noteService.Get(noteType.Id, prayerRequest.Id);

            foreach (Note prayerComment in prayerComments)
            {
                noteService.Delete(prayerComment);
                rockContext.SaveChanges();
            }
        }
コード例 #23
0
        /// <summary>
        /// Binds the comments grid.
        /// </summary>
        private void BindCommentsGrid()
        {
            var noteTypeService = new NoteTypeService();
            var noteType        = noteTypeService.Get((int)_prayerRequestEntityTypeId, "Prayer Comment");
            // TODO log exception if noteType is null

            var noteService    = new NoteService();
            var prayerComments = noteService.GetByNoteTypeId(noteType.Id);

            SortProperty sortProperty = gPrayerComments.SortProperty;

            // TODO: filter out comments that do not belong to the configured "category" grouping.
            //if ( _blockInstanceGroupCategoryId != All.Id )
            //{
            //    prayerComments = prayerComments.Where( c => c.CategoryId == _blockInstanceGroupCategoryId );
            //}

            // TODO: Filter by approved/unapproved
            //if ( rblApprovedFilter.SelectedValue == "unapproved" )
            //{
            //    prayerComments = prayerComments.Where( a => a.IsApproved == false || !a.IsApproved.HasValue );
            //}
            //else if ( rblApprovedFilter.SelectedValue == "approved" )
            //{
            //    prayerComments = prayerComments.Where( a => a.IsApproved == true );
            //}

            // Filter by EnteredDate
            if (dtDateRangeStartDate.SelectedDate != null)
            {
                prayerComments = prayerComments.Where(a => a.CreationDateTime >= dtDateRangeStartDate.SelectedDate);
            }
            if (dtDateRangeEndDate.SelectedDate != null)
            {
                prayerComments = prayerComments.Where(a => a.CreationDateTime <= dtDateRangeEndDate.SelectedDate);
            }

            // Sort by the given property otherwise sort by the EnteredDate
            if (sortProperty != null)
            {
                gPrayerComments.DataSource = prayerComments.Sort(sortProperty).ToList();
            }
            else
            {
                gPrayerComments.DataSource = prayerComments.OrderBy(n => n.CreationDateTime).ToList();
            }

            gPrayerComments.DataBind();
        }
コード例 #24
0
        /// <summary>
        /// Creates the child controls.
        /// </summary>
        /// <returns></returns>
        public override Control[] CreateChildControls(Type entityType, FilterField filterControl)
        {
            var cblNoteTypes = new RockListBox();

            cblNoteTypes.ID       = filterControl.GetChildControlInstanceName(_CtlNoteTypes);
            cblNoteTypes.CssClass = "js-notetypes";
            cblNoteTypes.Label    = "Note Types";
            cblNoteTypes.Help     = "The type of note to filter by. Leave blank to include all note types.";
            filterControl.Controls.Add(cblNoteTypes);

            var noteTypeService    = new NoteTypeService(new RockContext());
            var entityTypeIdPerson = EntityTypeCache.GetId <Rock.Model.Person>();
            var noteTypes          = noteTypeService.Queryable().Where(a => a.EntityTypeId == entityTypeIdPerson)
                                     .OrderBy(a => a.Order)
                                     .ThenBy(a => a.Name)
                                     .Select(a => new
            {
                a.Id,
                a.Name
            }).ToList();

            cblNoteTypes.Items.Clear();
            cblNoteTypes.Items.AddRange(noteTypes.Select(a => new ListItem(a.Name, a.Id.ToString())).ToArray());

            var slidingDateRangePicker = new SlidingDateRangePicker();

            slidingDateRangePicker.ID = filterControl.GetChildControlInstanceName(_CtlSlidingDateRangePicker);
            slidingDateRangePicker.AddCssClass("js-sliding-date-range");
            slidingDateRangePicker.Label    = "Date Range";
            slidingDateRangePicker.Help     = "The date range that the note was created during.";
            slidingDateRangePicker.Required = false;
            filterControl.Controls.Add(slidingDateRangePicker);

            var nbMinimumCount = new NumberBox();

            nbMinimumCount.ID           = filterControl.GetChildControlInstanceName(_CtlMinimumCount);
            nbMinimumCount.NumberType   = ValidationDataType.Integer;
            nbMinimumCount.MinimumValue = "1";
            nbMinimumCount.Label        = "Minimum Count";
            nbMinimumCount.Help         = "The minimum number of notes created during the date range to be considered a match.";
            nbMinimumCount.Required     = true;
            nbMinimumCount.AddCssClass("js-minimum-count");
            filterControl.Controls.Add(nbMinimumCount);

            return(new System.Web.UI.Control[3] {
                cblNoteTypes, slidingDateRangePicker, nbMinimumCount
            });
        }
コード例 #25
0
        /// <summary>
        /// Binds the filter.
        /// </summary>
        private void BindFilter()
        {
            var rockContext = new RockContext();

            // Load Entity Type Filter
            var noteTypeEntityTypes = new NoteTypeService(rockContext).Queryable()
                                      .AsNoTracking()
                                      .Select(c => c.EntityType)
                                      .Where(t => t.IsEntity)
                                      .Distinct()
                                      .OrderBy(t => t.FriendlyName)
                                      .ToList();

            entityTypeFilter.EntityTypes = noteTypeEntityTypes;
            entityTypeFilter.SetValue(gfNoteTypes.GetUserPreference(AttributeKey.EntityType));
        }
コード例 #26
0
ファイル: Notes.ascx.cs プロジェクト: klee66/Rock-CentralAZ
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            var contextEntity = this.ContextEntity();

            if (contextEntity != null)
            {
                string noteTypeName = GetAttributeValue("NoteType");

                var rockContext = new RockContext();
                var service     = new NoteTypeService(rockContext);
                var noteType    = service.Get(contextEntity.TypeId, noteTypeName);

                // If a note type with the specified name does not exist for the context entity type, create one
                if (noteType == null)
                {
                    noteType              = new NoteType();
                    noteType.IsSystem     = false;
                    noteType.EntityTypeId = contextEntity.TypeId;
                    noteType.EntityTypeQualifierColumn = string.Empty;
                    noteType.EntityTypeQualifierValue  = string.Empty;
                    noteType.Name = noteTypeName;
                    service.Add(noteType);
                    rockContext.SaveChanges();
                }

                notesTimeline.NoteTypeId = noteType.Id;
                notesTimeline.EntityId   = contextEntity.Id;
                notesTimeline.Title      = GetAttributeValue("Heading");
                if (string.IsNullOrWhiteSpace(notesTimeline.Title))
                {
                    notesTimeline.Title = noteType.Name;
                }
                notesTimeline.TitleIconCssClass = GetAttributeValue("HeadingIcon");
                notesTimeline.Term                = GetAttributeValue("NoteTerm");
                notesTimeline.DisplayType         = GetAttributeValue("DisplayType") == "Light" ? NoteDisplayType.Light : NoteDisplayType.Full;
                notesTimeline.UsePersonIcon       = GetAttributeValue("UsePersonIcon").AsBoolean();
                notesTimeline.ShowAlertCheckBox   = GetAttributeValue("ShowAlertCheckbox").AsBoolean();
                notesTimeline.ShowPrivateCheckBox = GetAttributeValue("ShowPrivateCheckbox").AsBoolean();
                notesTimeline.ShowSecurityButton  = GetAttributeValue("ShowSecurityButton").AsBoolean();
                notesTimeline.AllowAnonymousEntry = GetAttributeValue("Allow Anonymous").AsBoolean();
                notesTimeline.AddAlwaysVisible    = GetAttributeValue("AddAlwaysVisible").AsBoolean();
                notesTimeline.SortDirection       = GetAttributeValue("DisplayOrder") == "Ascending" ? ListSortDirection.Ascending : ListSortDirection.Descending;
            }
        }
コード例 #27
0
        /// <summary>
        /// Binds the comments grid.
        /// </summary>
        private void BindCommentsGrid()
        {
            var rockContext = new RockContext();

            var noteTypeService = new NoteTypeService(rockContext);
            var noteType        = noteTypeService.Get((int)_prayerRequestEntityTypeId, "Prayer Comment");
            // TODO log exception if noteType is null

            var noteService    = new NoteService(rockContext);
            var prayerComments = noteService.GetByNoteTypeId(noteType.Id);

            SortProperty sortProperty = gPrayerComments.SortProperty;

            // TODO: filter out comments that do not belong to the configured "category" grouping.
            //if ( _blockInstanceGroupCategoryId != All.Id )
            //{
            //    prayerComments = prayerComments.Where( c => c.CategoryId == _blockInstanceGroupCategoryId );
            //}

            // Filter by Date Range
            if (drpDateRange.LowerValue.HasValue)
            {
                DateTime startDate = drpDateRange.LowerValue.Value.Date;
                prayerComments = prayerComments.Where(a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value >= startDate);
            }

            if (drpDateRange.UpperValue.HasValue)
            {
                // Add one day in order to include everything up to the end of the selected datetime.
                var endDate = drpDateRange.UpperValue.Value.AddDays(1);
                prayerComments = prayerComments.Where(a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value < endDate);
            }

            // Sort by the given property otherwise sort by the EnteredDate
            if (sortProperty != null)
            {
                gPrayerComments.DataSource = prayerComments.Sort(sortProperty).ToList();
            }
            else
            {
                gPrayerComments.DataSource = prayerComments.OrderBy(n => n.CreatedDateTime).ToList();
            }

            gPrayerComments.DataBind();
        }
コード例 #28
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

            var contextEntity = this.ContextEntity();
            if ( contextEntity != null )
            {
                string noteTypeName = GetAttributeValue( "NoteType" );

                var rockContext = new RockContext();
                var service = new NoteTypeService( rockContext );
                var noteType = service.Get( contextEntity.TypeId, noteTypeName );

                // If a note type with the specified name does not exist for the context entity type, create one
                if ( noteType == null )
                {
                    noteType = new NoteType();
                    noteType.IsSystem = false;
                    noteType.EntityTypeId = contextEntity.TypeId;
                    noteType.EntityTypeQualifierColumn = string.Empty;
                    noteType.EntityTypeQualifierValue = string.Empty;
                    noteType.Name = noteTypeName;
                    service.Add( noteType );
                    rockContext.SaveChanges();
                }

                notesTimeline.NoteTypeId = noteType.Id;
                notesTimeline.EntityId = contextEntity.Id;
                notesTimeline.Title = GetAttributeValue( "Heading" );
                if ( string.IsNullOrWhiteSpace( notesTimeline.Title ) )
                {
                    notesTimeline.Title = noteType.Name;
                }
                notesTimeline.TitleIconCssClass = GetAttributeValue( "HeadingIcon" );
                notesTimeline.Term = GetAttributeValue( "NoteTerm" );
                notesTimeline.DisplayType = GetAttributeValue( "DisplayType" ) == "Light" ? NoteDisplayType.Light : NoteDisplayType.Full;
                notesTimeline.UsePersonIcon = GetAttributeValue( "UsePersonIcon" ).AsBoolean();
                notesTimeline.ShowAlertCheckBox = GetAttributeValue( "ShowAlertCheckbox" ).AsBoolean();
                notesTimeline.ShowPrivateCheckBox = GetAttributeValue( "ShowPrivateCheckbox" ).AsBoolean();
                notesTimeline.ShowSecurityButton = GetAttributeValue( "ShowSecurityButton" ).AsBoolean();
                notesTimeline.AllowAnonymousEntry = GetAttributeValue( "Allow Anonymous" ).AsBoolean();
                notesTimeline.AddAlwaysVisible = GetAttributeValue( "AddAlwaysVisible" ).AsBoolean();
                notesTimeline.SortDirection = GetAttributeValue( "DisplayOrder" ) == "Ascending" ? ListSortDirection.Ascending : ListSortDirection.Descending;
            }
        }
コード例 #29
0
        /// <summary>
        /// Binds the filter.
        /// </summary>
        private void BindFilter()
        {
            var rockContext = new RockContext();
            var entityTypes = new EntityTypeService(rockContext).GetEntities()
                              .OrderBy(t => t.FriendlyName)
                              .ToList();

            entityTypePicker.EntityTypes = entityTypes;

            // Load Entity Type Filter
            var noteTypeEntities = new NoteTypeService(rockContext).Queryable()
                                   .Select(c => c.EntityTypeId)
                                   .Distinct()
                                   .ToList();

            entityTypeFilter.EntityTypes = entityTypes.Where(e => noteTypeEntities.Contains(e.Id)).ToList();
            entityTypeFilter.SetValue(rFilter.GetUserPreference("EntityType"));
        }
コード例 #30
0
        /// <summary>
        /// Creates the child controls.
        /// </summary>
        /// <returns></returns>
        public override Control[] CreateChildControls(Type entityType, FilterField filterControl)
        {
            RockDropDownList ddlNoteType = new RockDropDownList();

            ddlNoteType.ID       = filterControl.ID + "_ddlNoteType";
            ddlNoteType.CssClass = "js-notetype";
            ddlNoteType.Label    = "Note Type";
            filterControl.Controls.Add(ddlNoteType);

            var noteTypeService    = new NoteTypeService(new RockContext());
            var entityTypeIdPerson = EntityTypeCache.GetId <Rock.Model.Person>();
            var noteTypes          = noteTypeService.Queryable().Where(a => a.EntityTypeId == entityTypeIdPerson)
                                     .OrderBy(a => a.Order)
                                     .ThenBy(a => a.Name)
                                     .Select(a => new
            {
                a.Id,
                a.Name
            }).ToList();

            ddlNoteType.Items.Clear();
            ddlNoteType.Items.Add(new ListItem());
            ddlNoteType.Items.AddRange(noteTypes.Select(a => new ListItem(a.Name, a.Id.ToString())).ToArray());

            var tbContains = new RockTextBox();

            tbContains.Label    = "Contains";
            tbContains.ID       = filterControl.ID + "_tbContains";
            tbContains.CssClass = "js-notecontains";
            filterControl.Controls.Add(tbContains);

            var slidingDateRangePicker = new SlidingDateRangePicker();

            slidingDateRangePicker.ID = filterControl.ID + "_slidingDateRangePicker";
            slidingDateRangePicker.AddCssClass("js-sliding-date-range");
            slidingDateRangePicker.Label    = "Date Range";
            slidingDateRangePicker.Help     = "The date range of the note's creation date";
            slidingDateRangePicker.Required = false;
            filterControl.Controls.Add(slidingDateRangePicker);

            return(new System.Web.UI.Control[3] {
                ddlNoteType, tbContains, slidingDateRangePicker
            });
        }
コード例 #31
0
        private Note GetNoteForAttendanceDate(RockContext rockContext, bool createNew = false)
        {
            NoteTypeService noteTypeService = new NoteTypeService(rockContext);
            NoteType        noteType        = noteTypeService.Queryable().FirstOrDefault(nt => nt.Guid == new Guid("FFFC3644-60CD-4D14-A714-E8DCC202A0E1"));

            NoteService noteService = new NoteService(rockContext);
            var         notes       = noteService.Queryable().Where(n => n.NoteType.Guid == noteType.Guid && n.EntityId == CurrentGroup.Id).ToList();

            foreach (Note note in notes)
            {
                note.LoadAttributes();
                var      dateString = note.GetAttributeValue("NoteDate");
                DateTime parseDate;
                try
                {
                    parseDate = DateTime.Parse(dateString);
                }
                catch
                {
                    continue;
                }
                //if ( dateString != null && _occurrence != null && parseDate == _occurrence.Date )
                //{
                //    return note;
                //}
            }
            if (createNew)
            {
                //Create new note if one does not exist.
                Note newNote = new Note();
                newNote.NoteType = noteType;
                newNote.EntityId = CurrentGroup.Id;
                noteService.Add(newNote);
                rockContext.SaveChanges();
                newNote.LoadAttributes();
                //newNote.SetAttributeValue( "NoteDate", _occurrence.Date );
                newNote.SaveAttributeValues(rockContext);

                rockContext.SaveChanges();
                return(newNote);
            }
            return(null);
        }
コード例 #32
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            var contextEntity = this.ContextEntity();

            if (contextEntity != null)
            {
                upNotes.Visible = true;

                string noteTypeName = GetAttributeValue("NoteType");

                using (var rockContext = new RockContext())
                {
                    var service  = new NoteTypeService(rockContext);
                    var noteType = service.Get(contextEntity.TypeId, noteTypeName);

                    notesTimeline.NoteTypeId = noteType.Id;
                    notesTimeline.EntityId   = contextEntity.Id;
                    notesTimeline.Title      = GetAttributeValue("Heading");
                    if (string.IsNullOrWhiteSpace(notesTimeline.Title))
                    {
                        notesTimeline.Title = noteType.Name;
                    }
                    notesTimeline.TitleIconCssClass = GetAttributeValue("HeadingIcon");
                    notesTimeline.Term                = GetAttributeValue("NoteTerm");
                    notesTimeline.DisplayType         = GetAttributeValue("DisplayType") == "Light" ? NoteDisplayType.Light : NoteDisplayType.Full;
                    notesTimeline.UsePersonIcon       = GetAttributeValue("UsePersonIcon").AsBoolean();
                    notesTimeline.ShowAlertCheckBox   = GetAttributeValue("ShowAlertCheckbox").AsBoolean();
                    notesTimeline.ShowPrivateCheckBox = GetAttributeValue("ShowPrivateCheckbox").AsBoolean();
                    notesTimeline.ShowSecurityButton  = GetAttributeValue("ShowSecurityButton").AsBoolean();
                    notesTimeline.AllowAnonymousEntry = GetAttributeValue("Allow Anonymous").AsBoolean();
                    notesTimeline.AddAlwaysVisible    = GetAttributeValue("AddAlwaysVisible").AsBoolean();
                    notesTimeline.SortDirection       = GetAttributeValue("DisplayOrder") == "Ascending" ? ListSortDirection.Ascending : ListSortDirection.Descending;
                }
            }
            else
            {
                upNotes.Visible = false;
            }
        }
コード例 #33
0
        private void GetNoteType()
        {
            string noteTypeName = GetAttributeValue("NoteType");

            var service = new NoteTypeService();

            noteType = service.Get(contextEntity.TypeId, noteTypeName);

            // If a note type with the specified name does not exist for the context entity type, create one
            if (noteType == null)
            {
                noteType              = new NoteType();
                noteType.IsSystem     = false;
                noteType.EntityTypeId = contextEntity.TypeId;
                noteType.EntityTypeQualifierColumn = string.Empty;
                noteType.EntityTypeQualifierValue  = string.Empty;
                noteType.Name = noteTypeName;
                service.Add(noteType, CurrentPersonId);
                service.Save(noteType, CurrentPersonId);
            }
        }
コード例 #34
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

            var contextEntity = this.ContextEntity();
            if ( contextEntity != null )
            {
                upNotes.Visible = true;

                string noteTypeName = GetAttributeValue( "NoteType" );

                using ( var rockContext = new RockContext() )
                {
                    var service = new NoteTypeService( rockContext );
                    var noteType = service.Get( contextEntity.TypeId, noteTypeName );

                    notesTimeline.NoteTypeId = noteType.Id;
                    notesTimeline.EntityId = contextEntity.Id;
                    notesTimeline.Title = GetAttributeValue( "Heading" );
                    if ( string.IsNullOrWhiteSpace( notesTimeline.Title ) )
                    {
                        notesTimeline.Title = noteType.Name;
                    }
                    notesTimeline.TitleIconCssClass = GetAttributeValue( "HeadingIcon" );
                    notesTimeline.Term = GetAttributeValue( "NoteTerm" );
                    notesTimeline.DisplayType = GetAttributeValue( "DisplayType" ) == "Light" ? NoteDisplayType.Light : NoteDisplayType.Full;
                    notesTimeline.UsePersonIcon = GetAttributeValue( "UsePersonIcon" ).AsBoolean();
                    notesTimeline.ShowAlertCheckBox = GetAttributeValue( "ShowAlertCheckbox" ).AsBoolean();
                    notesTimeline.ShowPrivateCheckBox = GetAttributeValue( "ShowPrivateCheckbox" ).AsBoolean();
                    notesTimeline.ShowSecurityButton = GetAttributeValue( "ShowSecurityButton" ).AsBoolean();
                    notesTimeline.AllowAnonymousEntry = GetAttributeValue( "Allow Anonymous" ).AsBoolean();
                    notesTimeline.AddAlwaysVisible = GetAttributeValue( "AddAlwaysVisible" ).AsBoolean();
                    notesTimeline.SortDirection = GetAttributeValue( "DisplayOrder" ) == "Ascending" ? ListSortDirection.Ascending : ListSortDirection.Descending;
                }
            }
            else
            {
                upNotes.Visible = false;
            }
        }
        /// <summary>
        /// Binds the comments grid.
        /// </summary>
        private void BindCommentsGrid()
        {
            var rockContext = new RockContext();

            var noteTypeService = new NoteTypeService( rockContext );
            var noteType = noteTypeService.Get( Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid() );

            // TODO log exception if noteType is null

            var noteService = new NoteService( rockContext );
            var prayerComments = noteService.GetByNoteTypeId( noteType.Id );

            SortProperty sortProperty = gPrayerComments.SortProperty;

            if ( _blockInstancePrayerRequestCategoryGuid.HasValue )
            {
                // if filtered by category, only show comments for prayer requests in that category or any of its decendent categories
                var categoryService = new CategoryService( rockContext );

                if ( _blockInstancePrayerRequestCategoryGuid.HasValue )
                {
                    var categories = new CategoryService( rockContext ).GetAllDescendents( _blockInstancePrayerRequestCategoryGuid.Value ).Select( a => a.Id ).ToList();

                    var prayerRequestQry = new PrayerRequestService( rockContext ).Queryable().Where( a => a.CategoryId.HasValue &&
                        ( a.Category.Guid == _blockInstancePrayerRequestCategoryGuid.Value || categories.Contains( a.CategoryId.Value ) ) )
                        .Select( a => a.Id );

                    prayerComments = prayerComments.Where( a => a.EntityId.HasValue && prayerRequestQry.Contains( a.EntityId.Value ) );
                }
            }

            // Filter by Date Range
            if ( drpDateRange.LowerValue.HasValue )
            {
                DateTime startDate = drpDateRange.LowerValue.Value.Date;
                prayerComments = prayerComments.Where( a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value >= startDate );
            }

            if ( drpDateRange.UpperValue.HasValue )
            {
                // Add one day in order to include everything up to the end of the selected datetime.
                var endDate = drpDateRange.UpperValue.Value.AddDays( 1 );
                prayerComments = prayerComments.Where( a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value < endDate );
            }

            // Sort by the given property otherwise sort by the EnteredDate
            if ( sortProperty != null )
            {
                gPrayerComments.DataSource = prayerComments.Sort( sortProperty ).ToList();
            }
            else
            {
                gPrayerComments.DataSource = prayerComments.OrderBy( n => n.CreatedDateTime ).ToList();
            }

            gPrayerComments.DataBind();
        }
        /// <summary>
        /// Processes the confirmation.
        /// </summary>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        private bool ProcessConfirmation( out string errorMessage )
        {
            var rockContext = new RockContext();
            if ( string.IsNullOrWhiteSpace( TransactionCode ) )
            {
                GatewayComponent gateway = hfPaymentTab.Value == "ACH" ? _achGateway : _ccGateway;
                if ( gateway == null )
                {
                    errorMessage = "There was a problem creating the payment gateway information";
                    return false;
                }

                Person person = GetPerson( true );
                if ( person == null )
                {
                    errorMessage = "There was a problem creating the person information";
                    return false;
                }

                if ( !person.PrimaryAliasId.HasValue)
                {
                    errorMessage = "There was a problem creating the person's primary alias";
                    return false;
                }

                PaymentInfo paymentInfo = GetPaymentInfo();
                if ( paymentInfo == null )
                {
                    errorMessage = "There was a problem creating the payment information";
                    return false;
                }
                else
                {
                    paymentInfo.FirstName = person.FirstName;
                    paymentInfo.LastName = person.LastName;
                }

                if ( paymentInfo.CreditCardTypeValue != null )
                {
                    CreditCardTypeValueId = paymentInfo.CreditCardTypeValue.Id;
                }

                PaymentSchedule schedule = GetSchedule();
                if ( schedule != null )
                {
                    schedule.PersonId = person.Id;

                    var scheduledTransaction = gateway.AddScheduledPayment( schedule, paymentInfo, out errorMessage );
                    if ( scheduledTransaction != null  )
                    {
                        scheduledTransaction.TransactionFrequencyValueId = schedule.TransactionFrequencyValue.Id;
                        scheduledTransaction.AuthorizedPersonAliasId = person.PrimaryAliasId.Value;
                        scheduledTransaction.GatewayEntityTypeId = EntityTypeCache.Read( gateway.TypeGuid ).Id;
                        scheduledTransaction.CurrencyTypeValueId = paymentInfo.CurrencyTypeValue.Id;
                        scheduledTransaction.CreditCardTypeValueId = CreditCardTypeValueId;

                        var changeSummary = new StringBuilder();
                        changeSummary.AppendFormat( "{0} starting {1}", schedule.TransactionFrequencyValue.Value, schedule.StartDate.ToShortDateString() );
                        changeSummary.AppendLine();
                        changeSummary.Append( paymentInfo.CurrencyTypeValue.Value );
                        if (paymentInfo.CreditCardTypeValue != null)
                        {
                            changeSummary.AppendFormat( " - {0}", paymentInfo.CreditCardTypeValue.Value );
                        }
                        changeSummary.AppendFormat( " {0}", paymentInfo.MaskedNumber );
                        changeSummary.AppendLine();

                        foreach ( var account in SelectedAccounts.Where( a => a.Amount > 0 ) )
                        {
                            var transactionDetail = new FinancialScheduledTransactionDetail();
                            transactionDetail.Amount = account.Amount;
                            transactionDetail.AccountId = account.Id;
                            scheduledTransaction.ScheduledTransactionDetails.Add( transactionDetail );
                            changeSummary.AppendFormat( "{0}: {1:C2}", account.Name, account.Amount );
                            changeSummary.AppendLine();
                        }

                        var transactionService = new FinancialScheduledTransactionService( rockContext );
                        transactionService.Add( scheduledTransaction );
                        rockContext.SaveChanges();

                        // Add a note about the change
                        var noteTypeService = new NoteTypeService( rockContext );
                        var noteType = noteTypeService.Get( scheduledTransaction.TypeId, "Note" );

                        var noteService = new NoteService( rockContext );
                        var note = new Note();
                        note.NoteTypeId = noteType.Id;
                        note.EntityId = scheduledTransaction.Id;
                        note.Caption = "Created Transaction";
                        note.Text = changeSummary.ToString();
                        noteService.Add( note );

                        rockContext.SaveChanges();

                        ScheduleId = scheduledTransaction.GatewayScheduleId;
                        TransactionCode = scheduledTransaction.TransactionCode;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    var transaction = gateway.Charge( paymentInfo, out errorMessage );
                    if ( transaction != null )
                    {
                        transaction.TransactionDateTime = RockDateTime.Now;
                        transaction.AuthorizedPersonAliasId = person.PrimaryAliasId;
                        transaction.GatewayEntityTypeId = gateway.TypeId;
                        transaction.TransactionTypeValueId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION ) ).Id;
                        transaction.CurrencyTypeValueId = paymentInfo.CurrencyTypeValue.Id;
                        transaction.CreditCardTypeValueId = CreditCardTypeValueId;

                        Guid sourceGuid = Guid.Empty;
                        if ( Guid.TryParse( GetAttributeValue( "Source" ), out sourceGuid ) )
                        {
                            transaction.SourceTypeValueId = DefinedValueCache.Read( sourceGuid ).Id;
                        }

                        foreach ( var account in SelectedAccounts.Where( a => a.Amount > 0 ) )
                        {
                            var transactionDetail = new FinancialTransactionDetail();
                            transactionDetail.Amount = account.Amount;
                            transactionDetail.AccountId = account.Id;
                            transaction.TransactionDetails.Add( transactionDetail );
                        }

                        var batchService = new FinancialBatchService( rockContext );

                        // Get the batch
                        var batch = batchService.Get(
                            GetAttributeValue( "BatchNamePrefix" ),
                            paymentInfo.CurrencyTypeValue,
                            paymentInfo.CreditCardTypeValue,
                            transaction.TransactionDateTime.Value,
                            gateway.BatchTimeOffset );

                        batch.ControlAmount += transaction.TotalAmount;

                        transaction.BatchId = batch.Id;
                        batch.Transactions.Add( transaction );
                        rockContext.SaveChanges();

                        TransactionCode = transaction.TransactionCode;
                    }
                    else
                    {
                        return false;
                    }
                }

                tdTransactionCodeReceipt.Description = TransactionCode;
                tdTransactionCodeReceipt.Visible = !string.IsNullOrWhiteSpace( TransactionCode );

                tdScheduleId.Description = ScheduleId;
                tdScheduleId.Visible = !string.IsNullOrWhiteSpace( ScheduleId );

                tdNameReceipt.Description = paymentInfo.FullName;
                tdPhoneReceipt.Description = paymentInfo.Phone;
                tdEmailReceipt.Description = paymentInfo.Email;
                tdAddressReceipt.Description = string.Format( "{0} {1}, {2} {3}", paymentInfo.Street1, paymentInfo.City, paymentInfo.State, paymentInfo.PostalCode );

                rptAccountListReceipt.DataSource = SelectedAccounts.Where( a => a.Amount != 0 );
                rptAccountListReceipt.DataBind();

                tdTotalReceipt.Description = paymentInfo.Amount.ToString( "C" );

                tdPaymentMethodReceipt.Description = paymentInfo.CurrencyTypeValue.Description;
                tdAccountNumberReceipt.Description = paymentInfo.MaskedNumber;
                tdWhenReceipt.Description = schedule != null ? schedule.ToString() : "Today";

                // If there was a transaction code returned and this was not already created from a previous saved account,
                // show the option to save the account.
                if ( !( paymentInfo is ReferencePaymentInfo ) && !string.IsNullOrWhiteSpace( TransactionCode ) )
                {
                    cbSaveAccount.Visible = true;
                    pnlSaveAccount.Visible = true;
                    txtSaveAccount.Visible = true;

                    // If current person does not have a login, have them create a username and password
                    phCreateLogin.Visible = !new UserLoginService( rockContext ).GetByPersonId( person.Id ).Any();
                }
                else
                {
                    pnlSaveAccount.Visible = false;
                }

                return true;
            }
            else
            {
                pnlDupWarning.Visible = true;
                divActions.Visible = false;
                errorMessage = string.Empty;
                return false;
            }
        }
        /// <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 userLoginService = new UserLoginService( rockContext );

            var userLogin = userLoginService.Queryable().Where( a => a.ApiKey == tbKey.Text ).FirstOrDefault();
            if ( userLogin != null && userLogin.PersonId != int.Parse( hfRestUserId.Value ) )
            {
                // this key already exists in the database. Show the error and get out of here.
                nbWarningMessage.Text = "This API Key already exists. Please enter a different one, or generate one by clicking the 'Generate Key' button below. ";
                nbWarningMessage.Visible = true;
                return;
            }

            rockContext.WrapTransaction( () =>
            {
                var personService = new PersonService( rockContext );
                var changes = new List<string>();
                var restUser = new Person();
                if ( int.Parse( hfRestUserId.Value ) != 0 )
                {
                    restUser = personService.Get( int.Parse( hfRestUserId.Value ) );
                }
                else
                {
                    personService.Add( restUser );
                    rockContext.SaveChanges();
                    restUser.Aliases.Add( new PersonAlias { AliasPersonId = restUser.Id, AliasPersonGuid = restUser.Guid } );
                }

                // the rest user name gets saved as the last name on a person
                History.EvaluateChange( changes, "Last Name", restUser.LastName, tbName.Text );
                restUser.LastName = tbName.Text;
                restUser.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_RESTUSER.AsGuid() ).Id;
                if ( cbActive.Checked )
                {
                    restUser.RecordStatusValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid() ).Id;
                }
                else
                {
                    restUser.RecordStatusValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid() ).Id;
                }

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

                // the description gets saved as a system note for the person
                var noteType = new NoteTypeService( rockContext )
                    .Get( Rock.SystemGuid.NoteType.PERSON_TIMELINE.AsGuid() );
                var noteService = new NoteService( rockContext );
                var note = noteService.Get( noteType.Id, restUser.Id ).FirstOrDefault();
                if ( note == null )
                {
                    note = new Note();
                    noteService.Add( note );
                }

                note.NoteTypeId = noteType.Id;
                note.EntityId = restUser.Id;
                note.Text = tbDescription.Text;
                rockContext.SaveChanges();

                // the key gets saved in the api key field of a user login (which you have to create if needed)
                var entityType = new EntityTypeService( rockContext )
                    .Get( "Rock.Security.Authentication.Database" );
                userLogin = userLoginService.GetByPersonId( restUser.Id ).FirstOrDefault();
                if ( userLogin == null )
                {
                    userLogin = new UserLogin();
                    userLoginService.Add( userLogin );
                }

                if ( string.IsNullOrWhiteSpace( userLogin.UserName ) )
                {
                    userLogin.UserName = Guid.NewGuid().ToString();
                }

                userLogin.IsConfirmed = true;
                userLogin.ApiKey = tbKey.Text;
                userLogin.PersonId = restUser.Id;
                userLogin.EntityTypeId = entityType.Id;
                rockContext.SaveChanges();
            } );
            NavigateToParentPage();
        }
コード例 #38
0
        /// <summary>
        /// Processes the confirmation.
        /// </summary>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        private bool ProcessConfirmation( out string errorMessage )
        {
            var rockContext = new RockContext();
            errorMessage = string.Empty;

            if ( string.IsNullOrWhiteSpace( TransactionCode ) )
            {
                if ( Gateway == null )
                {
                    errorMessage = "There was a problem creating the payment gateway information";
                    return false;
                }

                var personService = new PersonService( rockContext );
                var transactionService = new FinancialScheduledTransactionService( rockContext );
                var transactionDetailService = new FinancialScheduledTransactionDetailService( rockContext );

                FinancialScheduledTransaction scheduledTransaction = null;

                if ( ScheduledTransactionId.HasValue )
                {
                    scheduledTransaction = transactionService.Get( ScheduledTransactionId.Value );
                }

                if ( scheduledTransaction == null )
                {
                    errorMessage = "There was a problem getting the transaction information";
                    return false;
                }

                if ( scheduledTransaction.AuthorizedPerson == null )
                {
                    errorMessage = "There was a problem determining the person associated with the transaction";
                    return false;
                }

                var changeSummary = new StringBuilder();

                // Get the payment schedule
                scheduledTransaction.TransactionFrequencyValueId = btnFrequency.SelectedValueAsId().Value;
                changeSummary.Append( DefinedValueCache.Read( scheduledTransaction.TransactionFrequencyValueId, rockContext ) );

                if ( dtpStartDate.SelectedDate.HasValue && dtpStartDate.SelectedDate > RockDateTime.Today )
                {
                    scheduledTransaction.StartDate = dtpStartDate.SelectedDate.Value;
                    changeSummary.AppendFormat( " starting {0}", scheduledTransaction.StartDate.ToShortDateString() );
                }
                else
                {
                    scheduledTransaction.StartDate = DateTime.MinValue;
                }

                changeSummary.AppendLine();

                PaymentInfo paymentInfo = GetPaymentInfo( personService, scheduledTransaction );
                if ( paymentInfo == null )
                {
                    errorMessage = "There was a problem creating the payment information";
                    return false;
                }
                else
                {
                }

                // If transaction is not active, attempt to re-activate it first
                if ( !scheduledTransaction.IsActive )
                {
                    if ( !transactionService.Reactivate( scheduledTransaction, out errorMessage ) )
                    {
                        return false;
                    }
                }

                if ( Gateway.UpdateScheduledPayment( scheduledTransaction, paymentInfo, out errorMessage ) )
                {
                    if ( paymentInfo.CurrencyTypeValue != null )
                    {
                        changeSummary.Append( paymentInfo.CurrencyTypeValue.Value );
                        scheduledTransaction.CurrencyTypeValueId = paymentInfo.CurrencyTypeValue.Id;

                        DefinedValueCache creditCardTypeValue = paymentInfo.CreditCardTypeValue;
                        if ( creditCardTypeValue != null )
                        {
                            changeSummary.AppendFormat( " - {0}", creditCardTypeValue.Value );
                            scheduledTransaction.CreditCardTypeValueId = creditCardTypeValue.Id;
                        }
                        else
                        {
                            scheduledTransaction.CreditCardTypeValueId = null;
                        }
                        changeSummary.AppendFormat( " {0}", paymentInfo.MaskedNumber );
                        changeSummary.AppendLine();
                    }

                    var selectedAccountIds = SelectedAccounts
                        .Where( a => a.Amount > 0 )
                        .Select( a => a.Id ).ToList();

                    var deletedAccounts = scheduledTransaction.ScheduledTransactionDetails
                        .Where( a => !selectedAccountIds.Contains( a.AccountId ) ).ToList();

                    foreach ( var deletedAccount in deletedAccounts )
                    {
                        scheduledTransaction.ScheduledTransactionDetails.Remove( deletedAccount );
                        transactionDetailService.Delete( deletedAccount );
                    }

                    foreach ( var account in SelectedAccounts )
                    {
                        var detail = scheduledTransaction.ScheduledTransactionDetails
                            .Where( d => d.AccountId == account.Id ).FirstOrDefault();
                        if ( detail == null )
                        {
                            detail = new FinancialScheduledTransactionDetail();
                            detail.AccountId = account.Id;
                            scheduledTransaction.ScheduledTransactionDetails.Add( detail );
                        }

                        detail.Amount = account.Amount;

                        changeSummary.AppendFormat( "{0}: {1:C2}", account.Name, account.Amount );
                        changeSummary.AppendLine();
                    }

                    rockContext.SaveChanges();

                    // Add a note about the change
                    var noteTypeService = new NoteTypeService( rockContext );
                    var noteType = noteTypeService.Get( scheduledTransaction.TypeId, "Note" );

                    var noteService = new NoteService( rockContext );
                    var note = new Note();
                    note.NoteTypeId = noteType.Id;
                    note.EntityId = scheduledTransaction.Id;
                    note.Caption = "Updated Transaction";
                    note.Text = changeSummary.ToString();
                    noteService.Add( note );

                    rockContext.SaveChanges();

                    ScheduleId = scheduledTransaction.GatewayScheduleId;
                    TransactionCode = scheduledTransaction.TransactionCode;

                    if (transactionService.GetStatus( scheduledTransaction, out errorMessage ))
                    {
                        rockContext.SaveChanges();
                    }
                }
                else
                {
                    return false;
                }

                tdTransactionCode.Description = TransactionCode;
                tdTransactionCode.Visible = !string.IsNullOrWhiteSpace( TransactionCode );

                tdScheduleId.Description = ScheduleId;
                tdScheduleId.Visible = !string.IsNullOrWhiteSpace( ScheduleId );

                return true;
            }
            else
            {
                pnlDupWarning.Visible = true;
                return false;
            }
        }
コード例 #39
0
ファイル: Individual.cs プロジェクト: NewSpring/Excavator
        /// <summary>
        /// Loads the individual data.
        /// </summary>
        /// <param name="csvData">The CSV data.</param>
        private int LoadIndividuals( CSVInstance csvData )
        {
            var lookupContext = new RockContext();
            var groupTypeRoleService = new GroupTypeRoleService( lookupContext );
            var groupMemberService = new GroupMemberService( lookupContext );

            // Marital statuses: Married, Single, Separated, etc
            var maritalStatusTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS ), lookupContext ).DefinedValues;

            // Connection statuses: Member, Visitor, Attendee, etc
            var connectionStatusTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS ), lookupContext ).DefinedValues;
            int memberConnectionStatusId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER ) ).Id;
            int visitorConnectionStatusId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_VISITOR ) ).Id;
            int attendeeConnectionStatusId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_ATTENDEE ) ).Id;

            // Suffix type: Dr., Jr., II, etc
            var suffixTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_SUFFIX ), lookupContext ).DefinedValues;

            // Title type: Mr., Mrs. Dr., etc
            var titleTypes = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_TITLE ), lookupContext ).DefinedValues;

            // Record statuses: Active, Inactive, Pending
            int? recordStatusActiveId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE ), lookupContext ).Id;
            int? recordStatusInactiveId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ), lookupContext ).Id;
            int? recordStatusPendingId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING ), lookupContext ).Id;

            // Deceased record status reason (others available: No Activity, Moved, etc)
            var recordStatusDeceasedId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_REASON_DECEASED ) ).Id;

            // Record type: Person
            int? personRecordTypeId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON ), lookupContext ).Id;

            // Group roles: Owner, Adult, Child, others
            GroupTypeRole ownerRole = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER ) );
            int adultRoleId = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ).Id;
            int childRoleId = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD ) ).Id;

            // Phone types: Home, Work, Mobile
            var numberTypeValues = DefinedTypeCache.Read( new Guid( Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE ), lookupContext ).DefinedValues;

            // Personal note type id
            var personalNoteTypeId = new NoteTypeService( lookupContext ).Get( new Guid( Rock.SystemGuid.NoteType.PERSON_TIMELINE_NOTE ) ).Id;

            // School defined type
            var schoolDefinedType = DefinedTypeCache.Read( new Guid( "576FF1E2-6225-4565-A16D-230E26167A3D" ) );

            // Look up existing Person attributes
            var personAttributes = new AttributeService( lookupContext ).GetByEntityTypeId( PersonEntityTypeId ).ToList();
            var schoolAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "School" ) );

            // Text field type id
            int textFieldTypeId = FieldTypeCache.Read( new Guid( Rock.SystemGuid.FieldType.TEXT ), lookupContext ).Id;
            int dateFieldTypeId = FieldTypeCache.Read( new Guid( Rock.SystemGuid.FieldType.DATE ), lookupContext ).Id;

            // Attribute entity type id
            int attributeEntityTypeId = EntityTypeCache.Read( "Rock.Model.Attribute" ).Id;

            // Visit info category
            var visitInfoCategory = new CategoryService( lookupContext ).GetByEntityTypeId( attributeEntityTypeId )
                    .Where( c => c.Name == "Visit Information" ).FirstOrDefault();

            // Look for custom attributes in the Individual file
            var allFields = csvData.TableNodes.FirstOrDefault().Children.Select( ( node, index ) => new { node = node, index = index } ).ToList();
            Dictionary<int, string> customAttributes = allFields
                .Where( f => f.index > SecurityNote )
                .ToDictionary( f => f.index, f => f.node.Name.RemoveWhitespace() );

            // Add any attributes if they don't already exist
            if ( customAttributes.Any() )
            {
                var newAttributes = new List<Rock.Model.Attribute>();
                foreach ( var newAttributePair in customAttributes.Where( ca => !personAttributes.Any( a => a.Key == ca.Value ) ) )
                {
                    var newAttribute = new Rock.Model.Attribute();
                    newAttribute.Name = newAttributePair.Value;
                    newAttribute.Key = newAttributePair.Value.RemoveWhitespace();
                    newAttribute.Description = newAttributePair.Value + " created by CSV import";
                    newAttribute.EntityTypeQualifierValue = string.Empty;
                    newAttribute.EntityTypeQualifierColumn = string.Empty;
                    newAttribute.EntityTypeId = PersonEntityTypeId;
                    newAttribute.FieldTypeId = textFieldTypeId;
                    newAttribute.DefaultValue = string.Empty;
                    newAttribute.IsMultiValue = false;
                    newAttribute.IsGridColumn = false;
                    newAttribute.IsRequired = false;
                    newAttribute.Order = 0;
                    newAttributes.Add( newAttribute );
                }

                lookupContext.Attributes.AddRange( newAttributes );
                lookupContext.SaveChanges( DisableAuditing );
                personAttributes.AddRange( newAttributes );
            }

            // Set the supported date formats
            var dateFormats = new[] { "yyyy-MM-dd", "MM/dd/yyyy", "MM/dd/yy" };

            var currentFamilyGroup = new Group();
            var newFamilyList = new List<Group>();
            var newVisitorList = new List<Group>();
            var newNoteList = new List<Note>();

            int completed = 0;
            int newFamilies = 0;
            int newPeople = 0;
            ReportProgress( 0, string.Format( "Starting Individual import ({0:N0} already exist).", ImportedPeopleKeys.Count() ) );

            string[] row;
            row = csvData.Database.FirstOrDefault();
            while ( row != null )
            {
                int groupRoleId = adultRoleId;
                bool isFamilyRelationship = true;

                string rowFamilyName = row[FamilyName];
                string rowFamilyKey = row[FamilyId];
                string rowPersonKey = row[PersonId];
                int? rowFamilyId = rowFamilyKey.AsType<int?>();
                int? rowPersonId = rowPersonKey.AsType<int?>();

                // Check that this person isn't already in our data
                var personExists = ImportedFamilies.Any( g => g.Members.Any( m => m.Person.ForeignKey == rowPersonKey ) );
                if ( !personExists )
                {
                    #region person create

                    var person = new Person();
                    person.ForeignKey = rowPersonKey;
                    person.ForeignId = rowPersonId;
                    person.SystemNote = string.Format( "Imported via Excavator on {0}", ImportDateTime );
                    person.RecordTypeValueId = personRecordTypeId;
                    person.CreatedByPersonAliasId = ImportPersonAliasId;
                    string firstName = row[FirstName].Left( 50 );
                    string nickName = row[NickName].Left( 50 );
                    person.FirstName = firstName;
                    person.NickName = string.IsNullOrWhiteSpace( nickName ) ? firstName : nickName;
                    person.MiddleName = row[MiddleName].Left( 50 );
                    person.LastName = row[LastName].Left( 50 );

                    DateTime createdDateValue;
                    if ( DateTime.TryParseExact( row[CreatedDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out createdDateValue ) )
                    {
                        person.CreatedDateTime = createdDateValue;
                        person.ModifiedDateTime = ImportDateTime;
                    }
                    else
                    {
                        person.CreatedDateTime = ImportDateTime;
                        person.ModifiedDateTime = ImportDateTime;
                    }

                    DateTime birthDate;
                    if ( DateTime.TryParseExact( row[DateOfBirth], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out birthDate ) )
                    {
                        person.BirthDay = birthDate.Day;
                        person.BirthMonth = birthDate.Month;
                        person.BirthYear = birthDate.Year;
                    }

                    DateTime graduationDate;
                    if ( DateTime.TryParseExact( row[GraduationDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out graduationDate ) )
                    {
                        person.GraduationYear = graduationDate.Year;
                    }

                    DateTime anniversary;
                    if ( DateTime.TryParseExact( row[Anniversary], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out anniversary ) )
                    {
                        person.AnniversaryDate = anniversary;
                    }

                    string gender = row[Gender];
                    if ( gender != null )
                    {
                        switch ( gender.Trim().ToLower() )
                        {
                            case "m":
                            case "male":
                                person.Gender = Rock.Model.Gender.Male;
                                break;

                            case "f":
                            case "female":
                                person.Gender = Rock.Model.Gender.Female;
                                break;

                            default:
                                person.Gender = Rock.Model.Gender.Unknown;
                                break;
                        }
                    }

                    string prefix = row[Prefix];
                    if ( !string.IsNullOrWhiteSpace( prefix ) )
                    {
                        prefix = prefix.RemoveSpecialCharacters().Trim();
                        person.TitleValueId = titleTypes.Where( s => prefix == s.Value.RemoveSpecialCharacters() )
                            .Select( s => (int?)s.Id ).FirstOrDefault();
                    }

                    string suffix = row[Suffix];
                    if ( !string.IsNullOrWhiteSpace( suffix ) )
                    {
                        suffix = suffix.RemoveSpecialCharacters().Trim();
                        person.SuffixValueId = suffixTypes.Where( s => suffix == s.Value.RemoveSpecialCharacters() )
                            .Select( s => (int?)s.Id ).FirstOrDefault();
                    }

                    string maritalStatus = row[MaritalStatus];
                    if ( !string.IsNullOrWhiteSpace( maritalStatus ) )
                    {
                        person.MaritalStatusValueId = maritalStatusTypes.Where( dv => dv.Value == maritalStatus )
                            .Select( dv => (int?)dv.Id ).FirstOrDefault();
                    }
                    else
                    {
                        person.MaritalStatusValueId = maritalStatusTypes.Where( dv => dv.Value == "Unknown" )
                            .Select( dv => ( int? )dv.Id ).FirstOrDefault();
                    }

                    string familyRole = row[FamilyRole];
                    if ( !string.IsNullOrWhiteSpace( familyRole ) )
                    {
                        if ( familyRole == "Visitor" )
                        {
                            isFamilyRelationship = false;
                        }

                        if ( familyRole == "Child" || person.Age < 18 )
                        {
                            groupRoleId = childRoleId;
                        }
                    }

                    string connectionStatus = row[ConnectionStatus];
                    if ( !string.IsNullOrWhiteSpace( connectionStatus ) )
                    {
                        if ( connectionStatus == "Member" )
                        {
                            person.ConnectionStatusValueId = memberConnectionStatusId;
                        }
                        else if ( connectionStatus == "Visitor" )
                        {
                            person.ConnectionStatusValueId = visitorConnectionStatusId;
                        }
                        else
                        {
                            // look for user-defined connection type or default to Attendee
                            var customConnectionType = connectionStatusTypes.Where( dv => dv.Value == connectionStatus )
                                .Select( dv => (int?)dv.Id ).FirstOrDefault();

                            person.ConnectionStatusValueId = customConnectionType ?? attendeeConnectionStatusId;
                            person.RecordStatusValueId = recordStatusActiveId;
                        }
                    }

                    string recordStatus = row[RecordStatus];
                    if ( !string.IsNullOrWhiteSpace( recordStatus ) )
                    {
                        switch ( recordStatus.Trim().ToLower() )
                        {
                            case "active":
                                person.RecordStatusValueId = recordStatusActiveId;
                                break;

                            case "inactive":
                                person.RecordStatusValueId = recordStatusInactiveId;
                                break;

                            default:
                                person.RecordStatusValueId = recordStatusPendingId;
                                break;
                        }
                    }

                    string isDeceasedValue = row[IsDeceased];
                    if ( !string.IsNullOrWhiteSpace( isDeceasedValue ) )
                    {
                        switch ( isDeceasedValue.Trim().ToLower() )
                        {
                            case "y":
                            case "yes":
                                person.IsDeceased = true;
                                person.RecordStatusReasonValueId = recordStatusDeceasedId;
                                person.RecordStatusValueId = recordStatusInactiveId;
                                break;

                            default:
                                person.IsDeceased = false;
                                break;
                        }
                    }

                    var personNumbers = new Dictionary<string, string>();
                    personNumbers.Add( "Home", row[HomePhone] );
                    personNumbers.Add( "Mobile", row[MobilePhone] );
                    personNumbers.Add( "Work", row[WorkPhone] );
                    string smsAllowed = row[AllowSMS];

                    foreach ( var numberPair in personNumbers.Where( n => !string.IsNullOrWhiteSpace( n.Value ) ) )
                    {
                        var extension = string.Empty;
                        var countryCode = Rock.Model.PhoneNumber.DefaultCountryCode();
                        var normalizedNumber = string.Empty;
                        var countryIndex = numberPair.Value.IndexOf( '+' );
                        int extensionIndex = numberPair.Value.LastIndexOf( 'x' ) > 0 ? numberPair.Value.LastIndexOf( 'x' ) : numberPair.Value.Length;
                        if ( countryIndex >= 0 )
                        {
                            countryCode = numberPair.Value.Substring( countryIndex, countryIndex + 3 ).AsNumeric();
                            normalizedNumber = numberPair.Value.Substring( countryIndex + 3, extensionIndex - 3 ).AsNumeric().TrimStart( new Char[] { '0' } );
                            extension = numberPair.Value.Substring( extensionIndex );
                        }
                        else if ( extensionIndex > 0 )
                        {
                            normalizedNumber = numberPair.Value.Substring( 0, extensionIndex ).AsNumeric();
                            extension = numberPair.Value.Substring( extensionIndex ).AsNumeric();
                        }
                        else
                        {
                            normalizedNumber = numberPair.Value.AsNumeric();
                        }

                        if ( !string.IsNullOrWhiteSpace( normalizedNumber ) )
                        {
                            var currentNumber = new PhoneNumber();
                            currentNumber.CountryCode = countryCode;
                            currentNumber.CreatedByPersonAliasId = ImportPersonAliasId;
                            currentNumber.Extension = extension.Left( 20 );
                            currentNumber.Number = normalizedNumber.TrimStart( new Char[] { '0' } ).Left( 20 );
                            currentNumber.NumberFormatted = PhoneNumber.FormattedNumber( currentNumber.CountryCode, currentNumber.Number );
                            currentNumber.NumberTypeValueId = numberTypeValues.Where( v => v.Value.Equals( numberPair.Key ) )
                                .Select( v => ( int? )v.Id ).FirstOrDefault();
                            if ( numberPair.Key == "Mobile" )
                            {
                                switch ( smsAllowed.Trim().ToLower() )
                                {
                                    case "y":
                                    case "yes":
                                    case "active":
                                        currentNumber.IsMessagingEnabled = true;
                                        break;

                                    default:
                                        currentNumber.IsMessagingEnabled = false;
                                        break;
                                }
                            }

                            person.PhoneNumbers.Add( currentNumber );
                        }
                    }

                    // Map Person attributes
                    person.Attributes = new Dictionary<string, AttributeCache>();
                    person.AttributeValues = new Dictionary<string, AttributeValueCache>();

                    bool isEmailActive;
                    switch ( row[IsEmailActive].Trim().ToLower() )
                    {
                        case "n":
                        case "no":
                        case "inactive":
                            isEmailActive = false;
                            break;

                        default:
                            isEmailActive = true;
                            break;
                    }

                    EmailPreference emailPreference;
                    switch ( row[AllowBulkEmail].Trim().ToLower() )
                    {
                        case "n":
                        case "no":
                        case "inactive":
                            emailPreference = EmailPreference.NoMassEmails;
                            break;

                        default:
                            emailPreference = EmailPreference.EmailAllowed;
                            break;
                    }

                    person.EmailPreference = emailPreference;
                    string primaryEmail = row[Email].Trim().Left( 75 );
                    if ( !string.IsNullOrWhiteSpace( primaryEmail ) )
                    {
                        if ( primaryEmail.IsEmail() )
                        {
                            person.Email = primaryEmail;
                            person.IsEmailActive = isEmailActive;
                        }
                        else
                        {
                            LogException( "InvalidPrimaryEmail", string.Format( "PersonId: {0} - Email: {1}", rowPersonKey, primaryEmail ) );
                        }
                    }

                    string schoolName = row[School];
                    if ( !string.IsNullOrWhiteSpace( schoolName ) )
                    {
                        // Add school if it doesn't exist
                        Guid schoolGuid;
                        var schoolExists = lookupContext.DefinedValues.Any( s => s.DefinedTypeId == schoolDefinedType.Id && s.Value.Equals( schoolName ) );
                        if ( !schoolExists )
                        {
                            var newSchool = new DefinedValue();
                            newSchool.DefinedTypeId = schoolDefinedType.Id;
                            newSchool.Value = schoolName;
                            newSchool.Order = 0;

                            lookupContext.DefinedValues.Add( newSchool );
                            lookupContext.SaveChanges();

                            schoolGuid = newSchool.Guid;
                        }
                        else
                        {
                            schoolGuid = lookupContext.DefinedValues.FirstOrDefault( s => s.Value.Equals( schoolName ) ).Guid;
                        }

                        AddPersonAttribute( schoolAttribute, person, schoolGuid.ToString().ToUpper() );
                    }

                    foreach ( var attributePair in customAttributes )
                    {
                        string newAttributeValue = row[attributePair.Key];
                        if ( !string.IsNullOrWhiteSpace( newAttributeValue ) )
                        {
                            // check if this attribute value is a date
                            DateTime valueAsDateTime;
                            if ( DateTime.TryParseExact( newAttributeValue, dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out valueAsDateTime ) )
                            {
                                newAttributeValue = valueAsDateTime.ToString( "yyyy-MM-dd" );
                            }

                            int? newAttributeId = personAttributes.Where( a => a.Key == attributePair.Value.RemoveWhitespace() )
                                .Select( a => (int?)a.Id ).FirstOrDefault();
                            if ( newAttributeId != null )
                            {
                                var newAttribute = AttributeCache.Read( (int)newAttributeId );
                                AddPersonAttribute( newAttribute, person, newAttributeValue );
                            }
                        }
                    }

                    // Add notes to timeline
                    var notePairs = new Dictionary<string, string>();
                    notePairs.Add( "General", row[GeneralNote] );
                    notePairs.Add( "Medical", row[MedicalNote] );
                    notePairs.Add( "Security", row[SecurityNote] );

                    foreach ( var notePair in notePairs.Where( n => !string.IsNullOrWhiteSpace( n.Value ) ) )
                    {
                        var newNote = new Note();
                        newNote.NoteTypeId = personalNoteTypeId;
                        newNote.CreatedByPersonAliasId = ImportPersonAliasId;
                        newNote.CreatedDateTime = ImportDateTime;
                        newNote.Text = notePair.Value;
                        newNote.ForeignKey = rowPersonKey;
                        newNote.ForeignId = rowPersonId;
                        newNote.Caption = string.Format( "{0} Note", notePair.Key );

                        if ( !notePair.Key.Equals( "General" ) )
                        {
                            newNote.IsAlert = true;
                        }

                        newNoteList.Add( newNote );
                    }

                    #endregion person create

                    var groupMember = new GroupMember();
                    groupMember.Person = person;
                    groupMember.GroupRoleId = groupRoleId;
                    groupMember.CreatedDateTime = ImportDateTime;
                    groupMember.ModifiedDateTime = ImportDateTime;
                    groupMember.CreatedByPersonAliasId = ImportPersonAliasId;
                    groupMember.GroupMemberStatus = GroupMemberStatus.Active;

                    if ( rowFamilyKey != currentFamilyGroup.ForeignKey )
                    {
                        // person not part of the previous family, see if that family exists or create a new one
                        currentFamilyGroup = ImportedFamilies.FirstOrDefault( g => g.ForeignKey == rowFamilyKey );
                        if ( currentFamilyGroup == null )
                        {
                            currentFamilyGroup = CreateFamilyGroup( row[FamilyName], rowFamilyKey );
                            newFamilyList.Add( currentFamilyGroup );
                            newFamilies++;
                        }
                        else
                        {
                            lookupContext.Groups.Attach( currentFamilyGroup );
                            lookupContext.Entry( currentFamilyGroup ).State = EntityState.Modified;
                        }

                        currentFamilyGroup.Members.Add( groupMember );
                    }
                    else
                    {
                        // person is part of this family group, check if they're a visitor
                        if ( isFamilyRelationship || currentFamilyGroup.Members.Count() < 1 )
                        {
                            currentFamilyGroup.Members.Add( groupMember );
                        }
                        else
                        {
                            var visitorFamily = CreateFamilyGroup( person.LastName + " Family", rowFamilyKey );
                            visitorFamily.Members.Add( groupMember );
                            newFamilyList.Add( visitorFamily );
                            newVisitorList.Add( visitorFamily );
                            newFamilies++;
                        }
                    }

                    // look ahead 1 row
                    string rowNextFamilyKey = "-1";
                    if ( (row = csvData.Database.FirstOrDefault()) != null )
                    {
                        rowNextFamilyKey = row[FamilyId];
                    }

                    newPeople++;
                    completed++;
                    if ( completed % (ReportingNumber * 10) < 1 )
                    {
                        ReportProgress( 0, string.Format( "{0:N0} people imported.", completed ) );
                    }

                    if ( newPeople >= ReportingNumber && rowNextFamilyKey != currentFamilyGroup.ForeignKey )
                    {
                        SaveIndividuals( newFamilyList, newVisitorList, newNoteList );
                        lookupContext.SaveChanges();
                        ReportPartialProgress();

                        // Clear out variables
                        currentFamilyGroup = new Group();
                        newFamilyList.Clear();
                        newVisitorList.Clear();
                        newNoteList.Clear();
                        newPeople = 0;
                    }
                }
                else
                {
                    row = csvData.Database.FirstOrDefault();
                }
            }

            // Save any changes to new families
            if ( newFamilyList.Any() )
            {
                SaveIndividuals( newFamilyList, newVisitorList, newNoteList );
            }

            // Save any changes to existing families
            lookupContext.SaveChanges();
            DetachAllInContext( lookupContext );
            lookupContext.Dispose();

            ReportProgress( 0, string.Format( "Finished individual import: {0:N0} families and {1:N0} people added.", newFamilies, completed ) );
            return completed;
        }
コード例 #40
0
 /// <summary>
 /// Deletes all related notes.
 /// </summary>
 /// <param name="prayerRequest">The prayer request.</param>
 private void DeleteAllRelatedNotes( PrayerRequest prayerRequest )
 {
     var rockContext = new RockContext();
     var noteTypeService = new NoteTypeService( rockContext );
     var noteType = noteTypeService.Get( _prayerRequestEntityTypeId.Value, "Prayer Comment" );
     var noteService = new NoteService( rockContext );
     var prayerComments = noteService.Get( noteType.Id, prayerRequest.Id );
     foreach ( Note prayerComment in prayerComments )
     {
         noteService.Delete( prayerComment );
         rockContext.SaveChanges();
     }
 }
コード例 #41
0
ファイル: NoteTypesFieldType.cs プロジェクト: azturner/Rock
        /// <summary>
        /// Creates the control(s) necessary for prompting user for a new value
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id"></param>
        /// <returns>
        /// The control
        /// </returns>
        public override Control EditControl( Dictionary<string, ConfigurationValue> configurationValues, string id )
        {
            int entityTypeId = 0;
            string qualifierColumn = string.Empty;
            string qualifierValue = string.Empty;

            if ( configurationValues != null )
            {
                if ( configurationValues.ContainsKey( ENTITY_TYPE_NAME_KEY ) )
                {
                    string entityTypeName = configurationValues[ENTITY_TYPE_NAME_KEY].Value;
                    if ( !string.IsNullOrWhiteSpace( entityTypeName ) && entityTypeName != None.IdValue )
                    {
                        var entityType = EntityTypeCache.Read( entityTypeName );
                        if ( entityType != null )
                        {
                            entityTypeId = entityType.Id;
                        }
                    }
                }
                if ( configurationValues.ContainsKey( QUALIFIER_COLUMN_KEY ) )
                {
                    qualifierColumn = configurationValues[QUALIFIER_COLUMN_KEY].Value;
                }

                if ( configurationValues.ContainsKey( QUALIFIER_VALUE_KEY ) )
                {
                    qualifierValue = configurationValues[QUALIFIER_VALUE_KEY].Value;
                }
            }

            RockCheckBoxList editControl = new RockCheckBoxList { ID = id };
            editControl.RepeatDirection = RepeatDirection.Horizontal;

            using ( var rockContext = new RockContext() )
            {
                var noteTypes = new NoteTypeService( rockContext ).Get( entityTypeId, qualifierColumn, qualifierValue ).ToList();
                if ( noteTypes.Any() )
                {
                    foreach ( var noteType in noteTypes )
                    {
                        ListItem listItem = new ListItem( noteType.Name, noteType.Guid.ToString().ToUpper() );
                        editControl.Items.Add( listItem );
                    }

                    return editControl;
                }
            }

            return null;
        }
コード例 #42
0
        /// <summary>
        /// Maps the notes.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        private void MapNotes( IQueryable<Row> tableData )
        {
            var lookupContext = new RockContext();
            var categoryService = new CategoryService( lookupContext );
            var personService = new PersonService( lookupContext );

            var noteTypes = new NoteTypeService( lookupContext ).Queryable().ToList();
            int noteTimelineTypeId = noteTypes.Where( nt => nt.Guid == new Guid( "7E53487C-D650-4D85-97E2-350EB8332763" ) )
                .Select( nt => nt.Id ).FirstOrDefault();

            var importedUsers = new UserLoginService( lookupContext ).Queryable()
                .Where( u => u.ForeignId != null )
                .Select( u => new { UserId = u.ForeignId, PersonId = u.PersonId } )
                .ToDictionary( t => t.UserId.AsType<int?>(), t => t.PersonId );

            var noteList = new List<Note>();

            int completed = 0;
            int totalRows = tableData.Count();
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Verifying note import ({0:N0} found).", totalRows ) );
            foreach ( var row in tableData )
            {
                string text = row["Note_Text"] as string;
                int? individualId = row["Individual_ID"] as int?;
                int? householdId = row["Household_ID"] as int?;
                int? personId = GetPersonAliasId( individualId, householdId );
                if ( personId != null && !string.IsNullOrWhiteSpace( text ) )
                {
                    int? userId = row["NoteCreatedByUserID"] as int?;
                    if ( userId != null && importedUsers.ContainsKey( userId ) )
                    {
                        DateTime? dateCreated = row["NoteCreated"] as DateTime?;
                        string noteType = row["Note_Type_Name"] as string;

                        var note = new Note();
                        note.CreatedByPersonAliasId = (int)importedUsers[userId];
                        note.CreatedDateTime = dateCreated;
                        note.EntityId = personId;
                        note.Text = text;

                        if ( !string.IsNullOrWhiteSpace( noteType ) )
                        {
                            int? noteTypeId = noteTypes.Where( nt => nt.Name == noteType ).Select( i => (int?)i.Id ).FirstOrDefault();
                            note.NoteTypeId = noteTypeId ?? noteTimelineTypeId;
                        }
                        else
                        {
                            note.NoteTypeId = noteTimelineTypeId;
                        }
                        /*var rockContext = new RockContext();
                        rockContext.WrapTransaction( () =>
                        {
                            rockContext.Configuration.AutoDetectChangesEnabled = false;
                            rockContext.Notes.Add( note );
                            rockContext.SaveChanges( DisableAudit );
                        } );*/

                        noteList.Add( note );
                        completed++;

                        if ( completed % percentage < 1 )
                        {
                            int percentComplete = completed / percentage;
                            ReportProgress( percentComplete, string.Format( "{0:N0} notes imported ({1}% complete).", completed, percentComplete ) );
                        }
                        else if ( completed % ReportingNumber < 1 )
                        {
                            SaveNotes( noteList );
                            ReportPartialProgress();
                            noteList.Clear();
                        }
                    }
                }
            }

            if ( noteList.Any() )
            {
                SaveNotes( noteList );
            }

            ReportProgress( 100, string.Format( "Finished note import: {0:N0} notes imported.", completed ) );
        }
コード例 #43
0
 /// <summary>
 /// Sets the type of the note.
 /// </summary>
 private void SetNoteType()
 {
     var rockContext = new RockContext();
     var service = new NoteTypeService( rockContext );
     var noteType = service.Get( Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid() );
     NoteTypeId = noteType.Id;
 }
        /// <summary>
        /// Shows the view.
        /// </summary>
        /// <param name="txn">The TXN.</param>
        private void ShowView( FinancialScheduledTransaction txn )
        {
            if ( txn != null )
            {
                hlStatus.Text = txn.IsActive ? "Active" : "Inactive";
                hlStatus.LabelType = txn.IsActive ? LabelType.Success : LabelType.Danger;

                string rockUrlRoot = ResolveRockUrl( "/" );

                var detailsLeft = new DescriptionList()
                    .Add( "Person", ( txn.AuthorizedPersonAlias != null && txn.AuthorizedPersonAlias.Person != null ) ?
                        txn.AuthorizedPersonAlias.Person.GetAnchorTag( rockUrlRoot ) : string.Empty );

                var detailsRight = new DescriptionList()
                    .Add( "Amount", ( txn.ScheduledTransactionDetails.Sum( d => (decimal?)d.Amount ) ?? 0.0M ).ToString( "C2" ) )
                    .Add( "Frequency", txn.TransactionFrequencyValue != null ? txn.TransactionFrequencyValue.Value : string.Empty )
                    .Add( "Start Date", txn.StartDate.ToShortDateString() )
                    .Add( "End Date", txn.EndDate.HasValue ? txn.EndDate.Value.ToShortDateString() : string.Empty )
                    .Add( "Next Payment Date", txn.NextPaymentDate.HasValue ? txn.NextPaymentDate.Value.ToShortDateString() : string.Empty )
                    .Add( "Last Status Refresh", txn.LastStatusUpdateDateTime.HasValue ? txn.LastStatusUpdateDateTime.Value.ToString( "g" ) : string.Empty );

                if ( txn.CurrencyTypeValue != null )
                {
                    string currencyType = txn.CurrencyTypeValue.Value;
                    if ( txn.CurrencyTypeValue.Guid.Equals( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD.AsGuid() ) )
                    {
                        currencyType += txn.CreditCardTypeValue != null ? ( " - " + txn.CreditCardTypeValue.Value ) : string.Empty;
                    }
                    detailsLeft.Add( "Currency Type", currencyType );
                }

                if ( txn.GatewayEntityType != null )
                {
                    detailsLeft.Add( "Payment Gateway", Rock.Financial.GatewayContainer.GetComponentName( txn.GatewayEntityType.Name ) );
                }

                detailsLeft
                    .Add( "Transaction Code", txn.TransactionCode )
                    .Add( "Schedule Id", txn.GatewayScheduleId );

                lDetailsLeft.Text = detailsLeft.Html;
                lDetailsRight.Text = detailsRight.Html;

                gAccountsView.DataSource = txn.ScheduledTransactionDetails.ToList();
                gAccountsView.DataBind();

                var rockContext = new RockContext();
                var noteType = new NoteTypeService( rockContext ).Get( txn.TypeId, "Note" );
                rptrNotes.DataSource = new NoteService( rockContext ).Get( noteType.Id, txn.Id )
                    .Where( n => n.CreatedDateTime.HasValue )
                    .OrderBy( n => n.CreatedDateTime )
                    .ToList()
                    .Select( n => new
                    {
                        n.Caption,
                        Text = n.Text.ConvertCrLfToHtmlBr(),
                        Person = ( n.CreatedByPersonAlias != null && n.CreatedByPersonAlias.Person != null ) ? n.CreatedByPersonAlias.Person.FullName : "",
                        Date = n.CreatedDateTime.HasValue ? n.CreatedDateTime.Value.ToShortDateString() : "",
                        Time = n.CreatedDateTime.HasValue ? n.CreatedDateTime.Value.ToShortTimeString() : ""
                    } )
                    .ToList();
                rptrNotes.DataBind();

                lbCancelSchedule.Visible = txn.IsActive;
                lbReactivateSchedule.Visible = !txn.IsActive;
            }
        }
コード例 #45
0
 private void DeleteAllRelatedNotes( PrayerRequest prayerRequest )
 {
     var noteTypeService = new NoteTypeService();
     var noteType = noteTypeService.Get( (int)_prayerRequestEntityTypeId, "Prayer Comment" );
     var noteService = new NoteService();
     var prayerComments = noteService.Get( noteType.Id, prayerRequest.Id );
     foreach ( Note prayerComment in prayerComments )
     {
         noteService.Delete( prayerComment, CurrentPersonId );
         noteService.Save( prayerComment, CurrentPersonId );
     }
 }
コード例 #46
0
        /// <summary>
        /// Deletes all related notes.
        /// </summary>
        /// <param name="prayerRequest">The prayer request.</param>
        private void DeleteAllRelatedNotes( PrayerRequest prayerRequest, RockContext rockContext )
        {
            var noteTypeService = new NoteTypeService( rockContext );
            var noteType = noteTypeService.Get( Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid() );
            var noteService = new NoteService( rockContext );
            var prayerComments = noteService.Get( noteType.Id, prayerRequest.Id );
            foreach ( Note prayerComment in prayerComments )
            {
                noteService.Delete( prayerComment );
            }

            rockContext.SaveChanges();
        }
コード例 #47
0
        /// <summary>
        /// Add a note on the given person's record.
        /// </summary>
        /// <param name="personId"></param>
        /// <param name="noteTypeName"></param>
        /// <param name="noteText"></param>
        /// <param name="noteDate">(optional) The date the note was created</param>
        /// <param name="byPersonGuid">(optional) The guid of the person who created the note</param>
        /// <param name="rockContext"></param>
        private void AddNote( int personId, string noteTypeName, string noteText, string noteDate, string byPersonGuid, string isPrivate, RockContext rockContext )
        {
            var service = new NoteTypeService( rockContext );
            var noteType = service.Get( _personEntityTypeId, noteTypeName );
            // if the note type does not exist, create it
            if ( noteType == null )
            {
                noteType = new NoteType();
                noteType.IsSystem = false;
                noteType.EntityTypeId = _personEntityTypeId;
                noteType.EntityTypeQualifierColumn = string.Empty;
                noteType.EntityTypeQualifierValue = string.Empty;
                noteType.Name = noteTypeName;
                service.Add( noteType );
                rockContext.SaveChanges();
            }

            // Find the person's alias
            int? createdByPersonAliasId = null;
            if ( byPersonGuid != null )
            {
                createdByPersonAliasId = _personCache[byPersonGuid.AsGuid()].PrimaryAliasId;
            }

            var noteService = new NoteService( rockContext );
            var note = new Note()
            {
                IsSystem = false,
                NoteTypeId = noteType.Id,
                EntityId = personId,
                Caption = string.Empty,
                CreatedByPersonAliasId = createdByPersonAliasId,
                Text = noteText,
                CreatedDateTime = DateTime.Parse( noteDate ?? RockDateTime.Now.ToString() )
            };

            noteService.Add( note );

            if ( isPrivate.AsBoolean() )
            {
                rockContext.SaveChanges( disablePrePostProcessing: true );
                note.MakePrivate( Rock.Security.Authorization.VIEW, _personCache[byPersonGuid.AsGuid()] );
            }
        }
コード例 #48
0
ファイル: SampleData.ascx.cs プロジェクト: NewPointe/Rockit
        /// <summary>
        /// Add a note on the given person's record.
        /// </summary>
        /// <param name="personId"></param>
        /// <param name="noteTypeName"></param>
        /// <param name="noteText"></param>
        /// <param name="noteDate">(optional) The date the note was created</param>
        /// <param name="byPersonGuid">(optional) The guid of the person who created the note</param>
        /// <param name="rockContext"></param>
        private void AddNote( int personId, string noteTypeName, string noteText, string noteDate, string byPersonGuid, string isPrivate, string isAlert, RockContext rockContext )
        {
            var service = new NoteTypeService( rockContext );
            var noteType = service.Get( _personEntityTypeId, noteTypeName );

            if ( noteType != null )
            {
                // Find the person's alias
                int? createdByPersonAliasId = null;
                if ( byPersonGuid != null )
                {
                    createdByPersonAliasId = _personCache[byPersonGuid.AsGuid()].PrimaryAliasId;
                }

                var noteService = new NoteService( rockContext );
                var note = new Note()
                {
                    IsSystem = false,
                    NoteTypeId = noteType.Id,
                    EntityId = personId,
                    Caption = string.Empty,
                    CreatedByPersonAliasId = createdByPersonAliasId,
                    Text = noteText,
                    IsAlert = isAlert.AsBoolean(),
                    IsPrivateNote = isPrivate.AsBoolean(),
                    CreatedDateTime = string.IsNullOrWhiteSpace( noteDate ) ? RockDateTime.Now : DateTime.Parse( noteDate, new CultureInfo( "en-US" ) )
                };

                noteService.Add( note );
            }
        }
コード例 #49
0
        /// <summary>
        /// Binds the comments grid.
        /// </summary>
        private void BindCommentsGrid()
        {
            var rockContext = new RockContext();

            var noteTypeService = new NoteTypeService( rockContext );
            var noteType = noteTypeService.Get( Rock.SystemGuid.NoteType.PRAYER_COMMENT.AsGuid() );
            var noteService = new NoteService( rockContext );
            var prayerComments = noteService.GetByNoteTypeId( noteType.Id );

            SortProperty sortProperty = gPrayerComments.SortProperty;

            // Filter by Category.  First see if there is a Block Setting, otherwise use the Grid Filter
            CategoryCache categoryFilter = null;
            var blockCategoryGuid = GetAttributeValue( "PrayerRequestCategory" ).AsGuidOrNull();
            if ( blockCategoryGuid.HasValue )
            {
                categoryFilter = CategoryCache.Read( blockCategoryGuid.Value );
            }

            if ( categoryFilter == null && catpPrayerCategoryFilter.Visible )
            {
                int? filterCategoryId = catpPrayerCategoryFilter.SelectedValue.AsIntegerOrNull();
                if ( filterCategoryId.HasValue )
                {
                    categoryFilter = CategoryCache.Read( filterCategoryId.Value );
                }
            }

            if ( categoryFilter != null )
            {
                // if filtered by category, only show comments for prayer requests in that category or any of its decendent categories
                var categoryService = new CategoryService( rockContext );
                var categories = new CategoryService( rockContext ).GetAllDescendents( categoryFilter.Guid ).Select( a => a.Id ).ToList();

                var prayerRequestQry = new PrayerRequestService( rockContext ).Queryable().Where( a => a.CategoryId.HasValue &&
                    ( a.Category.Guid == categoryFilter.Guid || categories.Contains( a.CategoryId.Value ) ) )
                    .Select( a => a.Id );

                prayerComments = prayerComments.Where( a => a.EntityId.HasValue && prayerRequestQry.Contains( a.EntityId.Value ) );
            }

            // Filter by Date Range
            if ( drpDateRange.LowerValue.HasValue )
            {
                DateTime startDate = drpDateRange.LowerValue.Value.Date;
                prayerComments = prayerComments.Where( a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value >= startDate );
            }

            if ( drpDateRange.UpperValue.HasValue )
            {
                // Add one day in order to include everything up to the end of the selected datetime.
                var endDate = drpDateRange.UpperValue.Value.AddDays( 1 );
                prayerComments = prayerComments.Where( a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value < endDate );
            }

            // Sort by the given property otherwise sort by the EnteredDate
            if ( sortProperty != null )
            {
                gPrayerComments.DataSource = prayerComments.Sort( sortProperty ).ToList();
            }
            else
            {
                gPrayerComments.DataSource = prayerComments.OrderByDescending( n => n.CreatedDateTime ).ToList();
            }

            gPrayerComments.DataBind();
        }
コード例 #50
0
        private bool HydrateObjects()
        {
            LoadWorkflowType();

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

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

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

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

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

            }

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

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

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

                    List<string> errorMessages;
                    if ( _workflow.Process( _rockContext, entity, out errorMessages ) )
                    {
                        // If the workflow type is persisted, save the workflow
                        if ( _workflow.IsPersisted || _workflowType.IsPersisted )
                        {
                            if ( _workflow.Id == 0 )
                            {
                                _workflowService.Add( _workflow );
                            }

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

                            WorkflowId = _workflow.Id;
                        }
                    }
                }
            }

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

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

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

                var canEdit = IsUserAuthorized( Authorization.EDIT );

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

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

            ShowNotes( false );
            ShowMessage( NotificationBoxType.Warning, string.Empty, "The selected workflow is not in a state that requires you to enter information." );
            return false;
        }
コード例 #51
0
ファイル: Notes.cs プロジェクト: NewSpring/Excavator
        /// <summary>
        /// Maps the notes.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        public void MapNotes( IQueryable<Row> tableData )
        {
            var lookupContext = new RockContext();
            var categoryService = new CategoryService( lookupContext );
            var personService = new PersonService( lookupContext );

            var noteTypes = new NoteTypeService( lookupContext ).Queryable().AsNoTracking().ToList();
            var personalNoteType = noteTypes.FirstOrDefault( nt => nt.Guid == new Guid( Rock.SystemGuid.NoteType.PERSON_TIMELINE_NOTE ) );

            var importedUsers = new UserLoginService( lookupContext ).Queryable().AsNoTracking()
                .Where( u => u.ForeignId != null )
                .ToDictionary( t => t.ForeignId, t => t.PersonId );

            var noteList = new List<Note>();

            int completed = 0;
            int totalRows = tableData.Count();
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Verifying note import ({0:N0} found).", totalRows ) );
            foreach ( var row in tableData.Where( r => r != null ) )
            {
                string text = row["Note_Text"] as string;
                int? individualId = row["Individual_ID"] as int?;
                int? householdId = row["Household_ID"] as int?;
                var noteTypeActive = row["NoteTypeActive"] as Boolean?;

                bool noteArchived = false;
                if ( row.Columns.FirstOrDefault( v => v.Name.Equals( "IsInactive" ) ) != null )
                {
                    /* =====================================================================
                    *  the NoteArchived column *should* work, but OrcaMDF won't read it...
                    *  instead check for a manually added column: IsInactive int null
                    *       var noteActive = row["NoteArchived"] as Boolean?;
                    *       if ( noteActive == null ) throw new NullReferenceException();
                    /* ===================================================================== */
                    var rowInactiveValue = row["IsInactive"] as int?;
                    noteArchived = rowInactiveValue.Equals( 1 );
                }

                var personKeys = GetPersonKeys( individualId, householdId );
                if ( personKeys != null && !string.IsNullOrWhiteSpace( text ) && noteTypeActive == true && !noteArchived )
                {
                    DateTime? dateCreated = row["NoteCreated"] as DateTime?;
                    string noteType = row["Note_Type_Name"] as string;

                    var note = new Note();
                    note.CreatedDateTime = dateCreated;
                    note.EntityId = personKeys.PersonId;

                    // These replace methods don't like being chained together
                    text = Regex.Replace( text, @"\t|\&nbsp;", " " );
                    text = text.Replace( "&#45;", "-" );
                    text = text.Replace( "&lt;", "<" );
                    text = text.Replace( "&gt;", ">" );
                    text = text.Replace( "&amp;", "&" );
                    text = text.Replace( "&quot;", @"""" );
                    text = text.Replace( "&#x0D", string.Empty );

                    note.Text = text.Trim();

                    int? userId = row["NoteCreatedByUserID"] as int?;
                    if ( userId != null && importedUsers.ContainsKey( userId ) )
                    {
                        var userKeys = ImportedPeople.FirstOrDefault( p => p.PersonId == (int)importedUsers[userId] );
                        if ( userKeys != null )
                        {
                            note.CreatedByPersonAliasId = userKeys.PersonAliasId;
                        }
                    }

                    int? matchingNoteTypeId = null;
                    if ( !noteType.StartsWith( "General", StringComparison.InvariantCultureIgnoreCase ) )
                    {
                        matchingNoteTypeId = noteTypes.Where( nt => nt.Name == noteType ).Select( i => (int?)i.Id ).FirstOrDefault();
                    }
                    else
                    {
                        matchingNoteTypeId = personalNoteType.Id;
                    }

                    if ( matchingNoteTypeId != null )
                    {
                        note.NoteTypeId = (int)matchingNoteTypeId;
                    }
                    else
                    {
                        // create the note type
                        var newNoteType = new NoteType();
                        newNoteType.EntityTypeId = personalNoteType.EntityTypeId;
                        newNoteType.EntityTypeQualifierColumn = string.Empty;
                        newNoteType.EntityTypeQualifierValue = string.Empty;
                        newNoteType.UserSelectable = true;
                        newNoteType.IsSystem = false;
                        newNoteType.Name = noteType;
                        newNoteType.Order = 0;

                        lookupContext.NoteTypes.Add( newNoteType );
                        lookupContext.SaveChanges( DisableAuditing );

                        noteTypes.Add( newNoteType );
                        note.NoteTypeId = newNoteType.Id;
                    }

                    noteList.Add( note );
                    completed++;

                    if ( completed % percentage < 1 )
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress( percentComplete, string.Format( "{0:N0} notes imported ({1}% complete).", completed, percentComplete ) );
                    }
                    else if ( completed % ReportingNumber < 1 )
                    {
                        SaveNotes( noteList );
                        ReportPartialProgress();
                        noteList.Clear();
                    }
                }
            }

            if ( noteList.Any() )
            {
                SaveNotes( noteList );
            }

            ReportProgress( 100, string.Format( "Finished note import: {0:N0} notes imported.", completed ) );
        }
コード例 #52
0
ファイル: People.cs プロジェクト: secc/Excavator
        /// <summary>
        /// Maps the person.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <param name="selectedColumns">The selected columns.</param>
        private void MapPerson( IQueryable<Row> tableData, List<string> selectedColumns = null )
        {
            var groupTypeRoleService = new GroupTypeRoleService();
            var attributeService = new AttributeService();
            var dvService = new DefinedValueService();
            var familyList = new List<Group>();

            // Marital statuses: Married, Single, Separated, etc
            List<DefinedValue> maritalStatusTypes = dvService.Queryable()
                .Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS ) ).ToList();

            // Connection statuses: Member, Visitor, Attendee, etc
            List<DefinedValue> connectionStatusTypes = dvService.Queryable()
                .Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS ) ).ToList();

            // Record status reasons: No Activity, Moved, Deceased, etc
            List<DefinedValue> recordStatusReasons = dvService.Queryable()
                .Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.PERSON_RECORD_STATUS_REASON ) ).ToList();

            // Record statuses: Active, Inactive, Pending
            int? statusActiveId = dvService.Get( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE ) ).Id;
            int? statusInactiveId = dvService.Get( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ) ).Id;
            int? statusPendingId = dvService.Get( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING ) ).Id;

            // Record type: Person
            int? personRecordTypeId = dvService.Get( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON ) ).Id;

            // Suffix type: Dr., Jr., II, etc
            List<DefinedValue> suffixTypes = dvService.Queryable()
                .Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.PERSON_SUFFIX ) ).ToList();

            // Title type: Mr., Mrs. Dr., etc
            List<DefinedValue> titleTypes = dvService.Queryable()
                .Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.PERSON_TITLE ) ).ToList();

            // Note type: Comment
            int noteCommentTypeId = new NoteTypeService().Get( new Guid( "7E53487C-D650-4D85-97E2-350EB8332763" ) ).Id;

            // Group roles: Adult, Child, others
            int adultRoleId = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ).Id;
            int childRoleId = groupTypeRoleService.Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD ) ).Id;

            // Group type: Family
            int familyGroupTypeId = GroupTypeCache.GetFamilyGroupType().Id;

            // Look up additional Person attributes (existing)
            var personAttributes = attributeService.GetByEntityTypeId( PersonEntityTypeId ).ToList();

            // Cached F1 attributes: IndividualId, HouseholdId, PreviousChurch, Position, Employer, School
            var individualIdAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "F1IndividualId" ) );
            var householdIdAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "F1HouseholdId" ) );
            var previousChurchAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "PreviousChurch" ) );
            var employerAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "Employer" ) );
            var positionAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "Position" ) );
            var firstVisitAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "FirstVisit" ) );
            var schoolAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "School" ) );
            var membershipDateAttribute = AttributeCache.Read( personAttributes.FirstOrDefault( a => a.Key == "MembershipDate" ) );

            int completed = 0;
            int totalRows = tableData.Count();
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Checking person import ({0:N0} found, {1:N0} already exist).", totalRows, ImportedPeople.Count() ) );

            foreach ( var groupedRows in tableData.GroupBy<Row, int?>( r => r["Household_ID"] as int? ) )
            {
                var familyGroup = new Group();
                var householdCampusList = new List<string>();

                foreach ( var row in groupedRows )
                {
                    int? individualId = row["Individual_ID"] as int?;
                    int? householdId = row["Household_ID"] as int?;
                    if ( GetPersonId( individualId, householdId ) == null )
                    {
                        var person = new Person();
                        person.FirstName = row["First_Name"] as string;
                        person.MiddleName = row["Middle_Name"] as string;
                        person.NickName = row["Goes_By"] as string ?? person.FirstName;
                        person.LastName = row["Last_Name"] as string;
                        person.BirthDate = row["Date_Of_Birth"] as DateTime?;
                        person.CreatedByPersonAliasId = ImportPersonAlias.Id;
                        person.RecordTypeValueId = personRecordTypeId;
                        int groupRoleId = adultRoleId;

                        var gender = row["Gender"] as string;
                        if ( gender != null )
                        {
                            person.Gender = (Gender)Enum.Parse( typeof( Gender ), gender );
                        }

                        string prefix = row["Prefix"] as string;
                        if ( prefix != null )
                        {
                            prefix = prefix.RemoveSpecialCharacters().Trim();
                            person.TitleValueId = titleTypes.Where( s => prefix == s.Name.RemoveSpecialCharacters() )
                                .Select( s => (int?)s.Id ).FirstOrDefault();
                        }

                        string suffix = row["Suffix"] as string;
                        if ( suffix != null )
                        {
                            suffix = suffix.RemoveSpecialCharacters().Trim();
                            person.SuffixValueId = suffixTypes.Where( s => suffix == s.Name.RemoveSpecialCharacters() )
                                .Select( s => (int?)s.Id ).FirstOrDefault();
                        }

                        string maritalStatus = row["Marital_Status"] as string;
                        if ( maritalStatus != null )
                        {
                            person.MaritalStatusValueId = maritalStatusTypes.Where( dv => dv.Name == maritalStatus )
                                .Select( dv => (int?)dv.Id ).FirstOrDefault();
                        }
                        else
                        {
                            person.MaritalStatusValueId = maritalStatusTypes.Where( dv => dv.Name == "Unknown" )
                                .Select( dv => (int?)dv.Id ).FirstOrDefault();
                        }

                        string familyRole = row["Household_Position"] as string;
                        if ( familyRole != null )
                        {
                            if ( familyRole == "Child" || person.Age < 18 )
                            {
                                groupRoleId = childRoleId;
                            }
                            else if ( familyRole == "Visitor" )
                            {
                                // assign person as a known relationship of this family/group
                            }
                        }

                        string memberStatus = row["Status_Name"] as string;
                        if ( memberStatus == "Member" )
                        {
                            person.ConnectionStatusValueId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER ) ).Id;
                            person.RecordStatusValueId = statusActiveId;
                        }
                        else if ( memberStatus == "Visitor" )
                        {
                            person.ConnectionStatusValueId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_VISITOR ) ).Id;
                            person.RecordStatusValueId = statusActiveId;
                        }
                        else if ( memberStatus == "Deceased" )
                        {
                            person.IsDeceased = true;
                            person.RecordStatusValueId = statusInactiveId;
                            person.RecordStatusReasonValueId = recordStatusReasons.Where( dv => dv.Name == "Deceased" )
                                .Select( dv => dv.Id ).FirstOrDefault();
                        }
                        else
                        {
                            // F1 defaults are Member & Visitor; all others are user-defined
                            var customConnectionType = connectionStatusTypes.Where( dv => dv.Name == memberStatus )
                                .Select( dv => (int?)dv.Id ).FirstOrDefault();

                            int attendeeId = connectionStatusTypes.FirstOrDefault( dv => dv.Guid == new Guid( "39F491C5-D6AC-4A9B-8AC0-C431CB17D588" ) ).Id;
                            person.ConnectionStatusValueId = customConnectionType ?? attendeeId;
                            person.RecordStatusValueId = statusActiveId;
                        }

                        string campus = row["SubStatus_Name"] as string;
                        if ( campus != null )
                        {
                            householdCampusList.Add( campus );
                        }

                        string status_comment = row["Status_Comment"] as string;
                        if ( status_comment != null )
                        {
                            var comment = new Note();
                            comment.Text = status_comment;
                            comment.NoteTypeId = noteCommentTypeId;
                            RockTransactionScope.WrapTransaction( () =>
                            {
                                var noteService = new NoteService();
                                noteService.Save( comment );
                            } );
                        }

                        // Map F1 attributes
                        person.Attributes = new Dictionary<string, AttributeCache>();
                        person.AttributeValues = new Dictionary<string, List<AttributeValue>>();

                        // individual_id already defined in scope
                        if ( individualId != null )
                        {
                            person.Attributes.Add( "F1IndividualId", individualIdAttribute );
                            person.AttributeValues.Add( "F1IndividualId", new List<AttributeValue>() );
                            person.AttributeValues["F1IndividualId"].Add( new AttributeValue()
                            {
                                AttributeId = individualIdAttribute.Id,
                                Value = individualId.ToString(),
                                Order = 0
                            } );
                        }

                        // household_id already defined in scope
                        if ( householdId != null )
                        {
                            person.Attributes.Add( "F1HouseholdId", householdIdAttribute );
                            person.AttributeValues.Add( "F1HouseholdId", new List<AttributeValue>() );
                            person.AttributeValues["F1HouseholdId"].Add( new AttributeValue()
                            {
                                AttributeId = householdIdAttribute.Id,
                                Value = householdId.ToString(),
                                Order = 0
                            } );
                        }

                        string previousChurch = row["Former_Church"] as string;
                        if ( previousChurch != null )
                        {
                            person.Attributes.Add( "PreviousChurch", previousChurchAttribute );
                            person.AttributeValues.Add( "PreviousChurch", new List<AttributeValue>() );
                            person.AttributeValues["PreviousChurch"].Add( new AttributeValue()
                            {
                                AttributeId = previousChurchAttribute.Id,
                                Value = previousChurch,
                                Order = 0
                            } );
                        }

                        string employer = row["Employer"] as string;
                        if ( employer != null )
                        {
                            person.Attributes.Add( "Employer", employerAttribute );
                            person.AttributeValues.Add( "Employer", new List<AttributeValue>() );
                            person.AttributeValues["Employer"].Add( new AttributeValue()
                            {
                                AttributeId = employerAttribute.Id,
                                Value = employer,
                                Order = 0
                            } );
                        }

                        string position = row["Occupation_Name"] as string ?? row["Occupation_Description"] as string;
                        if ( position != null )
                        {
                            person.Attributes.Add( "Position", positionAttribute );
                            person.AttributeValues.Add( "Position", new List<AttributeValue>() );
                            person.AttributeValues["Position"].Add( new AttributeValue()
                            {
                                AttributeId = positionAttribute.Id,
                                Value = position,
                                Order = 0
                            } );
                        }

                        string school = row["School_Name"] as string;
                        if ( school != null )
                        {
                            person.Attributes.Add( "School", schoolAttribute );
                            person.AttributeValues.Add( "School", new List<AttributeValue>() );
                            person.AttributeValues["School"].Add( new AttributeValue()
                            {
                                AttributeId = schoolAttribute.Id,
                                Value = school,
                                Order = 0
                            } );
                        }

                        DateTime? membershipDate = row["Status_Date"] as DateTime?;
                        if ( membershipDate != null )
                        {
                            person.CreatedDateTime = membershipDate;
                            person.Attributes.Add( "MembershipDate", membershipDateAttribute );
                            person.AttributeValues.Add( "MembershipDate", new List<AttributeValue>() );
                            person.AttributeValues["MembershipDate"].Add( new AttributeValue()
                            {
                                AttributeId = membershipDateAttribute.Id,
                                Value = membershipDate.Value.ToString( "MM/dd/yyyy" ),
                                Order = 0
                            } );
                        }

                        DateTime? firstVisit = row["First_Record"] as DateTime?;
                        if ( firstVisit != null )
                        {
                            person.CreatedDateTime = firstVisit;
                            // will always pick firstVisit if membershipDate is null
                            firstVisit = firstVisit > membershipDate ? membershipDate : firstVisit;
                            person.Attributes.Add( "FirstVisit", firstVisitAttribute );
                            person.AttributeValues.Add( "FirstVisit", new List<AttributeValue>() );
                            person.AttributeValues["FirstVisit"].Add( new AttributeValue()
                            {
                                AttributeId = firstVisitAttribute.Id,
                                Value = firstVisit.Value.ToString( "MM/dd/yyyy" ),
                                Order = 0
                            } );
                        }

                        // Other Attributes to create:
                        // former name
                        // bar_code
                        // member_env_code
                        // denomination_name

                        var groupMember = new GroupMember();
                        groupMember.Person = person;
                        groupMember.GroupRoleId = groupRoleId;
                        groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                        familyGroup.Members.Add( groupMember );
                    }
                }

                if ( familyGroup.Members.Any() )
                {
                    familyGroup.Name = familyGroup.Members.FirstOrDefault().Person.LastName + " Family";
                    familyGroup.GroupTypeId = familyGroupTypeId;

                    string primaryHouseholdCampus = householdCampusList.GroupBy( c => c ).OrderByDescending( c => c.Count() )
                        .Select( c => c.Key ).FirstOrDefault();
                    if ( primaryHouseholdCampus != null )
                    {
                        familyGroup.CampusId = CampusList.Where( c => c.Name.StartsWith( primaryHouseholdCampus ) || c.ShortCode == primaryHouseholdCampus )
                            .Select( c => (int?)c.Id ).FirstOrDefault();
                    }

                    familyList.Add( familyGroup );
                    completed++;
                    if ( completed % percentage < 1 )
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress( percentComplete, string.Format( "{0:N0} people imported ({1}% complete).", completed, percentComplete ) );
                    }
                    else if ( completed % ReportingNumber < 1 )
                    {
                        RockTransactionScope.WrapTransaction( () =>
                        {
                            var groupService = new GroupService();
                            var personService = new PersonService();
                            var attributeValueService = new AttributeValueService();
                            groupService.RockContext.Groups.AddRange( familyList );
                            groupService.RockContext.SaveChanges();

                            foreach ( var newFamilyGroup in familyList )
                            {
                                foreach ( var groupMember in newFamilyGroup.Members )
                                {
                                    var person = groupMember.Person;
                                    foreach ( var attributeCache in person.Attributes.Select( a => a.Value ) )
                                    {
                                        var newValue = person.AttributeValues[attributeCache.Key].FirstOrDefault();
                                        if ( newValue != null )
                                        {
                                            newValue.EntityId = person.Id;
                                            attributeValueService.RockContext.AttributeValues.Add( newValue );
                                        }
                                    }

                                    if ( !person.Aliases.Any( a => a.AliasPersonId == person.Id ) )
                                    {
                                        person.Aliases.Add( new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid } );
                                    }

                                    if ( groupMember.GroupRoleId != childRoleId )
                                    {
                                        person.GivingGroupId = newFamilyGroup.Id;
                                    }
                                }
                            }

                            attributeValueService.RockContext.SaveChanges();
                            personService.RockContext.SaveChanges();
                        } );

                        familyList.Clear();
                        ReportPartialProgress();
                    }
                }
            }

            // Save any remaining families in the batch
            if ( familyList.Any() )
            {
                RockTransactionScope.WrapTransaction( () =>
                {
                    var groupService = new GroupService();
                    var personService = new PersonService();
                    var attributeValueService = new AttributeValueService();
                    groupService.RockContext.Groups.AddRange( familyList );
                    groupService.RockContext.SaveChanges();

                    foreach ( var newFamilyGroup in familyList )
                    {
                        foreach ( var groupMember in newFamilyGroup.Members )
                        {
                            var person = groupMember.Person;
                            foreach ( var attributeCache in person.Attributes.Select( a => a.Value ) )
                            {
                                var newValue = person.AttributeValues[attributeCache.Key].FirstOrDefault();
                                if ( newValue != null )
                                {
                                    newValue.EntityId = person.Id;
                                    attributeValueService.RockContext.AttributeValues.Add( newValue );
                                }
                            }

                            if ( !person.Aliases.Any( a => a.AliasPersonId == person.Id ) )
                            {
                                person.Aliases.Add( new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid } );
                            }

                            if ( groupMember.GroupRoleId != childRoleId )
                            {
                                person.GivingGroupId = newFamilyGroup.Id;
                            }
                        }
                    }

                    attributeValueService.RockContext.SaveChanges();
                    personService.RockContext.SaveChanges();
                } );
            }

            ReportProgress( 100, string.Format( "Finished person import: {0:N0} people imported.", completed ) );
        }
コード例 #53
0
        /// <summary>
        /// Binds the comments grid.
        /// </summary>
        private void BindCommentsGrid()
        {
            var rockContext = new RockContext();

            var noteTypeService = new NoteTypeService( rockContext );
            var noteType = noteTypeService.Get( (int)_prayerRequestEntityTypeId, "Prayer Comment" );
            // TODO log exception if noteType is null

            var noteService = new NoteService( rockContext );
            var prayerComments = noteService.GetByNoteTypeId( noteType.Id );

            SortProperty sortProperty = gPrayerComments.SortProperty;

            // TODO: filter out comments that do not belong to the configured "category" grouping.
            //if ( _blockInstanceGroupCategoryId != All.Id )
            //{
            //    prayerComments = prayerComments.Where( c => c.CategoryId == _blockInstanceGroupCategoryId );
            //}

            // Filter by Date Range
            if ( drpDateRange.LowerValue.HasValue )
            {
                DateTime startDate = drpDateRange.LowerValue.Value.Date;
                prayerComments = prayerComments.Where( a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value >= startDate );
            }

            if ( drpDateRange.UpperValue.HasValue )
            {
                // Add one day in order to include everything up to the end of the selected datetime.
                var endDate = drpDateRange.UpperValue.Value.AddDays( 1 );
                prayerComments = prayerComments.Where( a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value < endDate );
            }

            // Sort by the given property otherwise sort by the EnteredDate
            if ( sortProperty != null )
            {
                gPrayerComments.DataSource = prayerComments.Sort( sortProperty ).ToList();
            }
            else
            {
                gPrayerComments.DataSource = prayerComments.OrderBy( n => n.CreatedDateTime ).ToList();
            }

            gPrayerComments.DataBind();
        }
コード例 #54
0
ファイル: PrayerSession.ascx.cs プロジェクト: Ganon11/Rock
        /// <summary>
        /// Sets the type of the note.
        /// </summary>
        private void SetNoteType()
        {
            var entityTypeId = EntityTypeCache.Read( typeof( PrayerRequest ) ).Id;
            string noteTypeName = GetAttributeValue( "NoteType" );

            var rockContext = new RockContext();
            var service = new NoteTypeService( rockContext );
            var noteType = service.Get( entityTypeId, noteTypeName );
            NoteTypeId = noteType.Id;
        }
コード例 #55
0
ファイル: PrayerSession.ascx.cs プロジェクト: pkdevbox/Rock
        /// <summary>
        /// Gets the configured NoteType for the PrayerRequest entity.
        /// </summary>
        private void GetNoteType()
        {
            string noteTypeName = GetAttributeValue( "NoteType" );

            var _prayerRequestEntityTypeId = Rock.Web.Cache.EntityTypeCache.GetId( new PrayerRequest().GetType().FullName );
            var noteTypeService = new NoteTypeService();
            var noteType = noteTypeService.Get( (int)_prayerRequestEntityTypeId, noteTypeName );
            
            // all that work to get this... for use later.
            PrayerCommentNoteTypeId = noteType.Id;
        }
コード例 #56
0
        /// <summary>
        /// Handles the Click event of the btnConfirm 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 btnConfirm_Click( object sender, EventArgs e )
        {
            if ( Page.IsValid )
            {
                var rockContext = new RockContext();
                var personService = new PersonService( rockContext );
                var ids = Individuals.Select( i => i.PersonId ).ToList();

                #region Individual Details Updates

                int? newTitleId = ddlTitle.SelectedValueAsInt();
                int? newSuffixId = ddlSuffix.SelectedValueAsInt();
                int? newConnectionStatusId = ddlStatus.SelectedValueAsInt();
                int? newRecordStatusId = ddlRecordStatus.SelectedValueAsInt();
                int? newInactiveReasonId = ddlInactiveReason.SelectedValueAsInt();
                string newInactiveReasonNote = tbInactiveReasonNote.Text;
                Gender newGender = ddlGender.SelectedValue.ConvertToEnum<Gender>();
                int? newMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt();

                int? newGraduationYear = null;
                if ( ypGraduation.SelectedYear.HasValue )
                {
                    newGraduationYear = ypGraduation.SelectedYear.Value;
                }

                int? newCampusId = cpCampus.SelectedCampusId;

                bool? newEmailActive = null;
                if ( !string.IsNullOrWhiteSpace( ddlIsEmailActive.SelectedValue ) )
                {
                    newEmailActive = ddlIsEmailActive.SelectedValue == "Active";
                }

                EmailPreference? newEmailPreference = ddlEmailPreference.SelectedValue.ConvertToEnumOrNull<EmailPreference>();

                string newEmailNote = tbEmailNote.Text;

                int? newReviewReason = ddlReviewReason.SelectedValueAsInt();
                string newSystemNote = tbSystemNote.Text;
                string newReviewReasonNote = tbReviewReasonNote.Text;

                int inactiveStatusId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ).Id;

                var allChanges = new Dictionary<int, List<string>>();

                var people = personService.Queryable().Where( p => ids.Contains( p.Id ) ).ToList();
                foreach ( var person in people )
                {
                    var changes = new List<string>();
                    allChanges.Add( person.Id, changes );

                    if ( SelectedFields.Contains( ddlTitle.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Title", DefinedValueCache.GetName( person.TitleValueId ), DefinedValueCache.GetName( newTitleId ) );
                        person.TitleValueId = newTitleId;
                    }

                    if ( SelectedFields.Contains( ddlSuffix.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Suffix", DefinedValueCache.GetName( person.SuffixValueId ), DefinedValueCache.GetName( newSuffixId ) );
                        person.SuffixValueId = newSuffixId;
                    }

                    if ( SelectedFields.Contains( ddlStatus.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Connection Status", DefinedValueCache.GetName( person.ConnectionStatusValueId ), DefinedValueCache.GetName( newConnectionStatusId ) );
                        person.ConnectionStatusValueId = newConnectionStatusId;
                    }

                    if ( SelectedFields.Contains( ddlRecordStatus.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Record Status", DefinedValueCache.GetName( person.RecordStatusValueId ), DefinedValueCache.GetName( newRecordStatusId ) );
                        person.RecordStatusValueId = newRecordStatusId;

                        if ( newRecordStatusId.HasValue && newRecordStatusId.Value == inactiveStatusId )
                        {
                            History.EvaluateChange( changes, "Inactive Reason", DefinedValueCache.GetName( person.RecordStatusReasonValueId ), DefinedValueCache.GetName( newInactiveReasonId ) );
                            person.RecordStatusReasonValueId = newInactiveReasonId;

                            if ( !string.IsNullOrWhiteSpace( newInactiveReasonNote ) )
                            {
                                History.EvaluateChange( changes, "Inactive Reason Note", person.InactiveReasonNote, newInactiveReasonNote );
                                person.InactiveReasonNote = newInactiveReasonNote;
                            }
                        }
                    }

                    if ( SelectedFields.Contains( ddlGender.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Gender", person.Gender, newGender );
                        person.Gender = newGender;
                    }

                    if ( SelectedFields.Contains( ddlMaritalStatus.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Marital Status", DefinedValueCache.GetName( person.MaritalStatusValueId ), DefinedValueCache.GetName( newMaritalStatusId ) );
                        person.MaritalStatusValueId = newMaritalStatusId;
                    }

                    if ( SelectedFields.Contains( ddlGradePicker.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Graduation Year", person.GraduationYear, newGraduationYear );
                        person.GraduationYear = newGraduationYear;
                    }

                    if ( SelectedFields.Contains( ddlIsEmailActive.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Email Is Active", person.IsEmailActive ?? true, newEmailActive.Value );
                        person.IsEmailActive = newEmailActive;
                    }

                    if ( SelectedFields.Contains( ddlEmailPreference.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Email Preference", person.EmailPreference, newEmailPreference );
                        person.EmailPreference = newEmailPreference.Value;
                    }

                    if ( SelectedFields.Contains( tbEmailNote.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Email Note", person.EmailNote, newEmailNote );
                        person.EmailNote = newEmailNote;
                    }

                    if ( SelectedFields.Contains( tbSystemNote.ClientID ) )
                    {
                        History.EvaluateChange( changes, "System Note", person.SystemNote, newSystemNote );
                        person.SystemNote = newSystemNote;
                    }

                    if ( SelectedFields.Contains( ddlReviewReason.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Review Reason", DefinedValueCache.GetName( person.ReviewReasonValueId ), DefinedValueCache.GetName( newReviewReason ) );
                        person.ReviewReasonValueId = newReviewReason;
                    }

                    if ( SelectedFields.Contains( tbReviewReasonNote.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Review Reason Note", person.ReviewReasonNote, newReviewReasonNote );
                        person.ReviewReasonNote = newReviewReasonNote;
                    }
                }

                if ( SelectedFields.Contains( cpCampus.ClientID ) && cpCampus.SelectedCampusId.HasValue )
                {
                    int campusId = cpCampus.SelectedCampusId.Value;

                    Guid familyGuid = new Guid( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY );

                    var familyMembers = new GroupMemberService( rockContext ).Queryable()
                        .Where( m => ids.Contains( m.PersonId ) && m.Group.GroupType.Guid == familyGuid )
                        .Select( m => new { m.PersonId, m.GroupId } )
                        .Distinct()
                        .ToList();

                    var families = new GroupMemberService( rockContext ).Queryable()
                        .Where( m => ids.Contains( m.PersonId ) && m.Group.GroupType.Guid == familyGuid )
                        .Select( m => m.Group )
                        .Distinct()
                        .ToList();

                    foreach ( int personId in ids )
                    {
                        var familyIds = familyMembers.Where( m => m.PersonId == personId ).Select( m => m.GroupId ).ToList();
                        if ( familyIds.Count == 1 )
                        {
                            int familyId = familyIds.FirstOrDefault();
                            var family = families.Where( g => g.Id == familyId ).FirstOrDefault();
                            {
                                if ( family != null )
                                {
                                    family.CampusId = campusId;
                                }
                                familyMembers.RemoveAll( m => m.GroupId == familyId );
                            }
                        }
                    }

                    rockContext.SaveChanges();
                }

                // Update following
                if ( SelectedFields.Contains( ddlFollow.ClientID ) )
                {
                    var personAliasEntityType = EntityTypeCache.Read( "Rock.Model.PersonAlias" );
                    if ( personAliasEntityType != null )
                    {
                        int personAliasEntityTypeId = personAliasEntityType.Id;

                        bool follow = true;
                        if ( !string.IsNullOrWhiteSpace( ddlFollow.SelectedValue ) )
                        {
                            follow = ddlFollow.SelectedValue == "Add";
                        }

                        var personAliasService = new PersonAliasService( rockContext );
                        var followingService = new FollowingService( rockContext );
                        if ( follow )
                        {
                            var paQry = personAliasService.Queryable();

                            var alreadyFollowingIds = followingService.Queryable()
                                .Where( f =>
                                    f.EntityTypeId == personAliasEntityTypeId &&
                                    f.PersonAlias.Id == CurrentPersonAlias.Id )
                                .Join( paQry, f => f.EntityId, p => p.Id, ( f, p ) => new { PersonAlias = p } )
                                .Select( p => p.PersonAlias.PersonId )
                                .Distinct()
                                .ToList();

                            foreach ( int id in ids.Where( id => !alreadyFollowingIds.Contains( id ) ) )
                            {
                                var following = new Following
                                {
                                    EntityTypeId = personAliasEntityTypeId,
                                    EntityId = ( people.FirstOrDefault( p => p.Id == id ).PrimaryAliasId ) ?? 0,
                                    PersonAliasId = CurrentPersonAlias.Id
                                };
                                followingService.Add( following );
                            }
                        }
                        else
                        {
                            var paQry = personAliasService.Queryable()
                                .Where( p => ids.Contains( p.PersonId ) )
                                .Select( p => p.Id );

                            foreach ( var following in followingService.Queryable()
                                .Where( f =>
                                    f.EntityTypeId == personAliasEntityTypeId &&
                                    paQry.Contains( f.EntityId ) &&
                                    f.PersonAlias.Id == CurrentPersonAlias.Id ) )
                            {
                                followingService.Delete( following );
                            }
                        }
                    }
                }

                rockContext.SaveChanges();

                #endregion

                #region Attributes

                var selectedCategories = new List<CategoryCache>();
                foreach ( string categoryGuid in GetAttributeValue( "AttributeCategories" ).SplitDelimitedValues() )
                {
                    var category = CategoryCache.Read( categoryGuid.AsGuid(), rockContext );
                    if ( category != null )
                    {
                        selectedCategories.Add( category );
                    }
                }

                var attributes = new List<AttributeCache>();
                var attributeValues = new Dictionary<int, string>();

                int categoryIndex = 0;
                foreach ( var category in selectedCategories.OrderBy( c => c.Name ) )
                {
                    PanelWidget pw = null;
                    string controlId = "pwAttributes_" + category.Id.ToString();
                    if ( categoryIndex % 2 == 0 )
                    {
                        pw = phAttributesCol1.FindControl( controlId ) as PanelWidget;
                    }
                    else
                    {
                        pw = phAttributesCol2.FindControl( controlId ) as PanelWidget;
                    }
                    categoryIndex++;

                    if ( pw != null )
                    {
                        var orderedAttributeList = new AttributeService( rockContext ).GetByCategoryId( category.Id )
                            .OrderBy( a => a.Order ).ThenBy( a => a.Name );
                        foreach ( var attribute in orderedAttributeList )
                        {
                            if ( attribute.IsAuthorized( Authorization.EDIT, CurrentPerson ) )
                            {
                                var attributeCache = AttributeCache.Read( attribute.Id );

                                Control attributeControl = pw.FindControl( string.Format( "attribute_field_{0}", attribute.Id ) );

                                if ( attributeControl != null && SelectedFields.Contains( attributeControl.ClientID ) )
                                {
                                    string newValue = attributeCache.FieldType.Field.GetEditValue( attributeControl, attributeCache.QualifierValues );
                                    attributes.Add( attributeCache );
                                    attributeValues.Add( attributeCache.Id, newValue );
                                }
                            }
                        }
                    }
                }

                if ( attributes.Any() )
                {
                    foreach ( var person in people )
                    {
                        person.LoadAttributes();
                        foreach ( var attribute in attributes )
                        {
                            string originalValue = person.GetAttributeValue( attribute.Key );
                            string newValue = attributeValues[attribute.Id];
                            if ( ( originalValue ?? string.Empty ).Trim() != ( newValue ?? string.Empty ).Trim() )
                            {
                                Rock.Attribute.Helper.SaveAttributeValue( person, attribute, newValue, rockContext );

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

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

                                History.EvaluateChange( allChanges[person.Id], attribute.Name, formattedOriginalValue, formattedNewValue );
                            }
                        }
                    }
                }

                // Create the history records
                foreach ( var changes in allChanges )
                {
                    if ( changes.Value.Any() )
                    {
                        HistoryService.AddChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                            changes.Key, changes.Value );
                    }
                }
                rockContext.SaveChanges();

                #endregion

                #region Add Note

                if ( !string.IsNullOrWhiteSpace( tbNote.Text ) && CurrentPerson != null )
                {
                    string text = tbNote.Text;
                    bool isAlert = cbIsAlert.Checked;
                    bool isPrivate = cbIsPrivate.Checked;

                    var noteTypeService = new NoteTypeService( rockContext );
                    var noteType = noteTypeService.Get( Rock.SystemGuid.NoteType.PERSON_TIMELINE.AsGuid() );
                    if ( noteType != null )
                    {
                        var notes = new List<Note>();
                        var noteService = new NoteService( rockContext );

                        foreach ( int id in ids )
                        {
                            var note = new Note();
                            note.IsSystem = false;
                            note.EntityId = id;
                            note.Caption = isPrivate ? "You - Personal Note" : string.Empty;
                            note.Text = tbNote.Text;
                            note.IsAlert = cbIsAlert.Checked;
                            note.NoteType = noteType;
                            notes.Add( note );
                            noteService.Add( note );
                        }

                        rockContext.WrapTransaction( () =>
                        {
                            rockContext.SaveChanges();
                            foreach ( var note in notes )
                            {
                                note.AllowPerson( Authorization.EDIT, CurrentPerson, rockContext );
                                if ( isPrivate )
                                {
                                    note.MakePrivate( Authorization.VIEW, CurrentPerson, rockContext );
                                }
                            }
                        } );

                    }
                }

                #endregion

                #region Group

                int? groupId = gpGroup.SelectedValue.AsIntegerOrNull();
                if ( groupId.HasValue )
                {
                    var group = new GroupService( rockContext ).Get( groupId.Value );
                    if ( group != null )
                    {
                        var groupMemberService = new GroupMemberService( rockContext );

                        var existingMembers = groupMemberService.Queryable( "Group" )
                            .Where( m =>
                                m.GroupId == group.Id &&
                                ids.Contains( m.PersonId ) )
                            .ToList();

                        string action = ddlGroupAction.SelectedValue;
                        if ( action == "Remove" )
                        {
                            groupMemberService.DeleteRange( existingMembers );
                            rockContext.SaveChanges();
                        }
                        else
                        {
                            var roleId = ddlGroupRole.SelectedValueAsInt();
                            var status = ddlGroupMemberStatus.SelectedValueAsEnum<GroupMemberStatus>();

                            // Get the attribute values updated
                            var gm = new GroupMember();
                            gm.Group = group;
                            gm.GroupId = group.Id;
                            gm.LoadAttributes( rockContext );
                            var selectedGroupAttributes = new List<AttributeCache>();
                            var selectedGroupAttributeValues = new Dictionary<string, string>();
                            foreach ( var attributeCache in gm.Attributes.Select( a => a.Value ) )
                            {
                                Control attributeControl = phAttributes.FindControl( string.Format( "attribute_field_{0}", attributeCache.Id ) );
                                if ( attributeControl != null && ( action == "Add" || SelectedFields.Contains( attributeControl.ClientID ) ) )
                                {
                                    string newValue = attributeCache.FieldType.Field.GetEditValue( attributeControl, attributeCache.QualifierValues );
                                    selectedGroupAttributes.Add( attributeCache );
                                    selectedGroupAttributeValues.Add( attributeCache.Key, newValue );
                                }
                            }

                            if ( action == "Add" )
                            {
                                if ( roleId.HasValue )
                                {
                                    var newGroupMembers = new List<GroupMember>();

                                    var existingIds = existingMembers.Select( m => m.PersonId ).Distinct().ToList();
                                    foreach ( int id in ids.Where( id => !existingIds.Contains( id ) ) )
                                    {
                                        var groupMember = new GroupMember();
                                        groupMember.GroupId = group.Id;
                                        groupMember.GroupRoleId = roleId.Value;
                                        groupMember.GroupMemberStatus = status;
                                        groupMember.PersonId = id;
                                        groupMemberService.Add( groupMember );
                                        newGroupMembers.Add( groupMember );
                                    }

                                    rockContext.SaveChanges();

                                    if ( selectedGroupAttributes.Any() )
                                    {
                                        foreach ( var groupMember in newGroupMembers )
                                        {
                                            foreach ( var attribute in selectedGroupAttributes )
                                            {
                                                Rock.Attribute.Helper.SaveAttributeValue( groupMember, attribute, selectedGroupAttributeValues[attribute.Key], rockContext );
                                            }
                                        }
                                    }
                                }
                            }
                            else // Update
                            {
                                if ( SelectedFields.Contains( ddlGroupRole.ClientID ) && roleId.HasValue )
                                {
                                    foreach ( var member in existingMembers.Where( m => m.GroupRoleId != roleId.Value ) )
                                    {
                                        if ( !existingMembers.Where( m => m.PersonId == member.PersonId && m.GroupRoleId == roleId.Value ).Any() )
                                        {
                                            member.GroupRoleId = roleId.Value;
                                        }
                                    }
                                }

                                if ( SelectedFields.Contains( ddlGroupMemberStatus.ClientID ) )
                                {
                                    foreach ( var member in existingMembers )
                                    {
                                        member.GroupMemberStatus = status;
                                    }
                                }

                                rockContext.SaveChanges();

                                if ( selectedGroupAttributes.Any() )
                                {
                                    foreach ( var groupMember in existingMembers )
                                    {
                                        foreach ( var attribute in selectedGroupAttributes )
                                        {
                                            Rock.Attribute.Helper.SaveAttributeValue( groupMember, attribute, selectedGroupAttributeValues[attribute.Key], rockContext );
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                #endregion

                pnlEntry.Visible = false;
                pnlConfirm.Visible = false;

                nbResult.Text = string.Format( "{0} {1} succesfully updated.",
                    ids.Count().ToString( "N0" ), ( ids.Count() > 1 ? "people were" : "person was" ) ); ;
                pnlResult.Visible = true;
            }
        }
コード例 #57
0
        /// <summary>
        /// Gets the type of the note.
        /// </summary>
        private void GetNoteType()
        {
            string noteTypeName = GetAttributeValue( "NoteType" );

            var rockContext = new RockContext();
            var service = new NoteTypeService( rockContext );
            noteType = service.Get( contextEntity.TypeId, noteTypeName );
        }
コード例 #58
0
        /// <summary>
        /// Add a note on the given person's record.
        /// </summary>
        /// <param name="personId"></param>
        /// <param name="noteTypeName"></param>
        /// <param name="noteText"></param>
        /// <param name="noteDate">(optional) The date the note was created</param>
        /// <param name="byPersonGuid">(optional) The guid of the person who created the note</param>
        /// <param name="rockContext"></param>
        private void AddNote( int personId, string noteTypeName, string noteText, string noteDate, string byPersonGuid, string isPrivate, RockContext rockContext )
        {
            var service = new NoteTypeService( rockContext );
            var noteType = service.Get( _personEntityTypeId, noteTypeName );

            // Find the person's alias
            int? createdByPersonAliasId = null;
            if ( byPersonGuid != null )
            {
                createdByPersonAliasId = _personCache[byPersonGuid.AsGuid()].PrimaryAliasId;
            }

            var noteService = new NoteService( rockContext );
            var note = new Note()
            {
                IsSystem = false,
                NoteTypeId = noteType.Id,
                EntityId = personId,
                Caption = string.Empty,
                CreatedByPersonAliasId = createdByPersonAliasId,
                Text = noteText,
                CreatedDateTime = string.IsNullOrWhiteSpace( noteDate ) ? RockDateTime.Now : DateTime.Parse( noteDate, new CultureInfo( "en-US" ) )
            };

            noteService.Add( note );

            if ( isPrivate.AsBoolean() )
            {
                rockContext.SaveChanges( disablePrePostProcessing: true );
                note.MakePrivate( Rock.Security.Authorization.VIEW, _personCache[byPersonGuid.AsGuid()], rockContext );
            }
        }
コード例 #59
0
        /// <summary>
        /// Reactivates the specified scheduled transaction.
        /// </summary>
        /// <param name="scheduledTransaction">The scheduled transaction.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public bool Reactivate( FinancialScheduledTransaction scheduledTransaction, out string errorMessages )
        {
            if ( scheduledTransaction != null &&
                scheduledTransaction.FinancialGateway != null &&
                scheduledTransaction.FinancialGateway.IsActive )
            {
                if ( scheduledTransaction.FinancialGateway.Attributes == null )
                {
                    scheduledTransaction.FinancialGateway.LoadAttributes( (RockContext)this.Context );
                }

                var gateway = scheduledTransaction.FinancialGateway.GetGatewayComponent();
                if ( gateway != null )
                {
                    if ( gateway.ReactivateScheduledPayment( scheduledTransaction, out errorMessages ) )
                    {
                        var noteTypeService = new NoteTypeService( (RockContext)this.Context );
                        var noteType = noteTypeService.Get( Rock.SystemGuid.NoteType.SCHEDULED_TRANSACTION_NOTE.AsGuid() );
                        if ( noteType != null )
                        {
                            var noteService = new NoteService( (RockContext)this.Context );
                            var note = new Note();
                            note.NoteTypeId = noteType.Id;
                            note.EntityId = scheduledTransaction.Id;
                            note.Caption = "Reactivated Transaction";
                            noteService.Add( note );
                        }

                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            errorMessages = "Gateway is invalid or not active";
            return false;
        }
コード例 #60
0
        private void GetNoteType()
        {
            string noteTypeName = GetAttributeValue( "NoteType" );

            var service = new NoteTypeService();
            noteType = service.Get( contextEntity.TypeId, noteTypeName );

            // If a note type with the specified name does not exist for the context entity type, create one
            if ( noteType == null )
            {
                noteType = new NoteType();
                noteType.IsSystem = false;
                noteType.EntityTypeId = contextEntity.TypeId;
                noteType.EntityTypeQualifierColumn = string.Empty;
                noteType.EntityTypeQualifierValue = string.Empty;
                noteType.Name = noteTypeName;
                service.Add( noteType, CurrentPersonId );
                service.Save( noteType, CurrentPersonId );
            }
        }