Beispiel #1
0
        /// <summary>
        /// Saves the communication.
        /// </summary>
        /// <param name="newNumberList">The new number list.</param>
        /// <param name="updatedPersonList">The updated person list.</param>
        private static void SaveCommunication( List<PhoneNumber> newNumberList, List<Person> updatedPersonList )
        {
            var rockContext = new RockContext();
            rockContext.WrapTransaction( () =>
            {
                rockContext.Configuration.AutoDetectChangesEnabled = false;
                rockContext.PhoneNumbers.AddRange( newNumberList );
                rockContext.SaveChanges( DisableAudit );

                var newAttributeValues = new List<AttributeValue>();
                foreach ( var updatedPerson in updatedPersonList.Where( p => p.Attributes.Any() ) )
                {
                    foreach ( var attributeCache in updatedPerson.Attributes.Select( a => a.Value ) )
                    {
                        var newValue = updatedPerson.AttributeValues[attributeCache.Key];
                        if ( newValue != null )
                        {
                            newValue.EntityId = updatedPerson.Id;
                            newAttributeValues.Add( newValue );
                        }
                    }
                }

                rockContext.AttributeValues.AddRange( newAttributeValues );
                rockContext.SaveChanges( DisableAudit );
            } );
        }
Beispiel #2
0
        /// <summary>
        /// Creates the CommunicationResponse for Rock SMS Conversations
        /// </summary>
        /// <param name="fromPerson">From person.</param>
        /// <param name="messageKey">The message key.</param>
        /// <param name="toPersonAliasId">To person alias identifier.</param>
        /// <param name="message">The message.</param>
        /// <param name="rockSmsFromPhoneDv">From phone.</param>
        /// <param name="responseCode">The response code.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="attachments">The attachments.</param>
        /// <exception cref="System.Exception">Configuration Error. No SMS Transport Component is currently active.</exception>
        private void CreateCommunicationResponse(Person fromPerson, string messageKey, int?toPersonAliasId, string message, DefinedValueCache rockSmsFromPhoneDv, string responseCode, Rock.Data.RockContext rockContext, List <BinaryFile> attachments = null)
        {
            var smsMedium = EntityTypeCache.Get(SystemGuid.EntityType.COMMUNICATION_MEDIUM_SMS);

            if (this.Transport == null)
            {
                throw new Exception("Configuration Error. No SMS Transport Component is currently active.");
            }

            var smsTransport    = this.Transport.EntityType.Id;
            int?communicationId = null;

            if (fromPerson != null)
            {
                communicationId = GetCommunicationId(rockSmsFromPhoneDv, fromPerson.PrimaryAliasId.Value, 2);
            }

            var communicationResponse = new CommunicationResponse
            {
                MessageKey                   = messageKey,
                FromPersonAliasId            = fromPerson?.PrimaryAliasId,
                ToPersonAliasId              = toPersonAliasId,
                IsRead                       = false,
                RelatedSmsFromDefinedValueId = rockSmsFromPhoneDv.Id,
                RelatedCommunicationId       = communicationId,
                RelatedTransportEntityTypeId = smsTransport,
                RelatedMediumEntityTypeId    = smsMedium.Id,
                Response                     = message
            };

            var communicationResposeService = new CommunicationResponseService(rockContext);

            communicationResposeService.Add(communicationResponse);
            rockContext.SaveChanges();

            // Now that we have a communication response ID we can add the attachments
            if (attachments != null && attachments.Any())
            {
                foreach (var attachment in attachments)
                {
                    communicationResponse.Attachments.Add(
                        new CommunicationResponseAttachment
                    {
                        BinaryFileId            = attachment.Id,
                        CommunicationResponseId = communicationResponse.Id,
                        CommunicationType       = CommunicationType.SMS
                    }
                        );
                }

                rockContext.SaveChanges();
            }
        }
Beispiel #3
0
        /// <summary>
        /// Creates the communication to the recipient's mobile device with attachments.
        /// </summary>
        /// <param name="fromPerson">From person.</param>
        /// <param name="toPersonAliasId">To person alias identifier.</param>
        /// <param name="message">The message.</param>
        /// <param name="fromPhone">From phone.</param>
        /// <param name="responseCode">The response code.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="attachments">The attachments.</param>
        public static void CreateCommunicationMobile(Person fromPerson, int?toPersonAliasId, string message, DefinedValueCache fromPhone, string responseCode, Rock.Data.RockContext rockContext, List <BinaryFile> attachments)
        {
            // NOTE: fromPerson should never be null since a Nameless Person record should have been created if a regular person record wasn't found
            string communicationName = fromPerson != null?string.Format("From: {0}", fromPerson.FullName) : "From: unknown person";

            var communicationService = new CommunicationService(rockContext);

            var createSMSCommunicationArgs = new CommunicationService.CreateSMSCommunicationArgs
            {
                FromPerson            = fromPerson,
                ToPersonAliasId       = toPersonAliasId,
                Message               = message,
                FromPhone             = fromPhone,
                CommunicationName     = communicationName,
                ResponseCode          = responseCode,
                SystemCommunicationId = null,
            };

            Rock.Model.Communication communication = communicationService.CreateSMSCommunication(createSMSCommunicationArgs);

            rockContext.SaveChanges();

            // Now that we have a communication ID we can add the attachments
            if (attachments != null && attachments.Any())
            {
                foreach (var attachment in attachments)
                {
                    var communicationAttachment = new CommunicationAttachment
                    {
                        BinaryFileId      = attachment.Id,
                        CommunicationId   = communication.Id,
                        CommunicationType = CommunicationType.SMS
                    };

                    communication.AddAttachment(communicationAttachment, CommunicationType.SMS);
                }

                rockContext.SaveChanges();
            }

            // queue the sending
            var transaction = new ProcessSendCommunication.Message()
            {
                CommunicationId = communication.Id,
            };

            transaction.Send();
        }
Beispiel #4
0
        /// <summary>
        /// Handles the Delete event of the gCampuses 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 gCampuses_Delete( object sender, RowEventArgs e )
        {
            var rockContext = new RockContext();
            CampusService campusService = new CampusService( rockContext );
            Campus campus = campusService.Get( e.RowKeyId );
            if ( campus != null )
            {
                // Don't allow deleting the last campus
                if ( !campusService.Queryable().Where( c => c.Id != campus.Id ).Any() )
                {
                    mdGridWarning.Show( campus.Name + " is the only campus and cannot be deleted (Rock requires at least one campus).", ModalAlertType.Information );
                    return;
                }

                string errorMessage;
                if ( !campusService.CanDelete( campus, out errorMessage ) )
                {
                    mdGridWarning.Show( errorMessage, ModalAlertType.Information );
                    return;
                }

                CampusCache.Flush( campus.Id );

                campusService.Delete( campus );
                rockContext.SaveChanges();
            }

            BindGrid();
        }
Beispiel #5
0
        /// <summary>
        /// Does cleanup of Locations
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private void LocationCleanup(JobDataMap dataMap)
        {
            // Add any missing person aliases
            using (var rockContext = new Rock.Data.RockContext())
            {
                var definedType = DefinedTypeCache.Get(new Guid(SystemGuid.DefinedType.LOCATION_ADDRESS_STATE));
                var stateList   = definedType
                                  .DefinedValues
                                  .Where(v => v.ContainsKey("Country") && v["Country"] != null)
                                  .Select(v => new { State = v.Value, Country = v["Country"] }).ToLookup(v => v.State);

                LocationService locationService = new LocationService(rockContext);
                var             locations       = locationService
                                                  .Queryable()
                                                  .Where(l => (l.Country == null || l.Country == string.Empty) && l.State != null && l.State != string.Empty)
                                                  .ToList();

                foreach (var location in locations)
                {
                    if (stateList.Contains(location.State))
                    {
                        var state = stateList[location.State];
                        if (state.Count() == 1)
                        {
                            location.Country = state.First().Country.ToStringSafe();
                        }
                    }
                }

                rockContext.SaveChanges();
            }
        }
Beispiel #6
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            // get the configured timeout, or default to 60 minutes if it is blank
            _commandTimeout = dataMap.GetString("CommandTimeout").AsIntegerOrNull() ?? 3600;

            using (var rockContext = new RockContext())
            {
                // MP: Populate AnalyticsSourceDate (if it isn't already)
                if (!rockContext.AnalyticsSourceDates.AsQueryable().Any())
                {
                    var analyticsStartDate = new DateTime(RockDateTime.Today.AddYears(-150).Year, 1, 1);
                    var analyticsEndDate   = new DateTime(RockDateTime.Today.AddYears(101).Year, 1, 1).AddDays(-1);
                    Rock.Model.AnalyticsSourceDate.GenerateAnalyticsSourceDateData(1, false, analyticsStartDate, analyticsEndDate);
                }
            }

            // MP: Migrate any pre-v9 RegistrationTemplateFee.CostValue data to RegistrationTemplateFeeItems
            using (var rockContext = new Rock.Data.RockContext())
            {
                var registrationTemplateFeeService = new Rock.Model.RegistrationTemplateFeeService(rockContext);

                // disable Obsolete warning since we need to run this, but don't want anybody else to start using it
#pragma warning disable 612, 618
                registrationTemplateFeeService.MigrateFeeCostValueToFeeItems();
#pragma warning restore 612, 618
                rockContext.SaveChanges();
            }

            PopulateRegistrationRegistrantFee();

            DeleteJob(context.GetJobId());
        }
        /// <summary>
        /// Gets the specified <see cref="Rock.Model.EntityType"/> by the object type. If a match is not found, it can optionally create a new <see cref="Rock.Model.EntityType"/> for the object.
        /// </summary>
        /// <param name="type">The <see cref="System.Type"/> to search for.</param>
        /// <param name="createIfNotFound">A <see cref="System.Boolean"/> value that indicates if a new <see cref="Rock.Model.EntityType"/> should be created if a match is not found. This value
        /// will be <c>true</c> if a new <see cref="Rock.Model.EntityType"/> should be created if there is not a match; otherwise <c>false</c>/</param>
        /// <param name="personAlias">A <see cref="Rock.Model.PersonAlias"/> representing the alias of the <see cref="Rock.Model.Person"/> who is searching for and possibly creating a new EntityType.  This value can be
        /// null if the logged in person is not known (i.e. an anonymous user).</param>
        /// <returns>A <see cref="Rock.Model.EntityType"/> matching the provided type. If a match is not found and createIfNotFound is false this value will be null.</returns>
        public EntityType Get( Type type, bool createIfNotFound, PersonAlias personAlias )
        {
            var entityType = Get( type.FullName );
            if ( entityType != null )
            {
                return entityType;
            }

            if ( createIfNotFound )
            {
                // Create a new context so type can be saved independing of current context
                using ( var rockContext = new RockContext() )
                {
                    var EntityTypeService = new EntityTypeService( rockContext );
                    entityType = new EntityType();
                    entityType.Name = type.FullName;
                    entityType.FriendlyName = type.Name.SplitCase();
                    entityType.AssemblyName = type.AssemblyQualifiedName;
                    EntityTypeService.Add( entityType );
                    rockContext.SaveChanges();
                }

                // Read type using current context
                return this.Get( entityType.Id );
            }

            return null;
        }
Beispiel #8
0
        /// <summary>
        /// Copies the page.
        /// </summary>
        /// <param name="pageId">The page identifier.</param>
        /// <param name="currentPersonAliasId">The current person alias identifier.</param>
        public Guid? CopyPage( int pageId, int? currentPersonAliasId = null )
        {
            var rockContext = new RockContext();
            var pageService = new PageService( rockContext );
            Guid? newPageGuid = null;

            var page = pageService.Get( pageId );
            if ( page != null )
            {
                Dictionary<Guid, Guid> pageGuidDictionary = new Dictionary<Guid, Guid>();
                Dictionary<Guid, Guid> blockGuidDictionary = new Dictionary<Guid, Guid>();
                var newPage = GeneratePageCopy( page, pageGuidDictionary, blockGuidDictionary, currentPersonAliasId );

                pageService.Add( newPage );
                rockContext.SaveChanges();

                if ( newPage.ParentPageId.HasValue )
                {
                    PageCache.Flush( newPage.ParentPageId.Value );
                }
                newPageGuid= newPage.Guid;

                GenerateBlockAttributeValues( pageGuidDictionary, blockGuidDictionary, rockContext, currentPersonAliasId );
                GeneratePageBlockAuths( pageGuidDictionary, blockGuidDictionary, rockContext, currentPersonAliasId );
                CloneHtmlContent( blockGuidDictionary, rockContext, currentPersonAliasId );
            }

            return newPageGuid;
        }
Beispiel #9
0
        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        public static void SetValue(string key, string value)
        {
            var rockContext      = new Rock.Data.RockContext();
            var attributeService = new AttributeService(rockContext);
            var attribute        = attributeService.GetSystemSetting(key);

            if (attribute == null)
            {
                attribute             = new Rock.Model.Attribute();
                attribute.FieldTypeId = FieldTypeCache.Get(new Guid(SystemGuid.FieldType.TEXT)).Id;
                attribute.EntityTypeQualifierColumn = Rock.Model.Attribute.SYSTEM_SETTING_QUALIFIER;
                attribute.EntityTypeQualifierValue  = string.Empty;
                attribute.Key          = key;
                attribute.Name         = key.SplitCase();
                attribute.DefaultValue = value;
                attributeService.Add(attribute);
            }
            else
            {
                attribute.DefaultValue = value;
            }

            // NOTE: Service Layer will automatically update this Cache (see Attribute.cs UpdateCache)
            rockContext.SaveChanges();

            if (key == Rock.SystemKey.SystemSetting.START_DAY_OF_WEEK)
            {
                RockDateTime.FirstDayOfWeek = value.ConvertToEnumOrNull <DayOfWeek>() ?? RockDateTime.DefaultFirstDayOfWeek;
            }
        }
Beispiel #10
0
        /// <summary>
        /// Creates the CommunicationResponse for Rock SMS Conversations
        /// </summary>
        /// <param name="fromPerson">From person.</param>
        /// <param name="messageKey">The message key.</param>
        /// <param name="toPersonAliasId">To person alias identifier.</param>
        /// <param name="message">The message.</param>
        /// <param name="rockSmsFromPhoneDv">From phone.</param>
        /// <param name="responseCode">The response code.</param>
        /// <param name="rockContext">The rock context.</param>
        private void CreateCommunicationResponse(Person fromPerson, string messageKey, int?toPersonAliasId, string message, DefinedValueCache rockSmsFromPhoneDv, string responseCode, Rock.Data.RockContext rockContext)
        {
            var smsMedium       = EntityTypeCache.Get(SystemGuid.EntityType.COMMUNICATION_MEDIUM_SMS);
            var smsTransport    = this.Transport.EntityType.Id;
            int?communicationId = null;

            if (fromPerson != null)
            {
                communicationId = GetCommunicationId(rockSmsFromPhoneDv, fromPerson.PrimaryAliasId.Value, 2);
            }

            var communicationResponse = new CommunicationResponse
            {
                MessageKey                   = messageKey,
                FromPersonAliasId            = fromPerson?.PrimaryAliasId,
                ToPersonAliasId              = toPersonAliasId,
                IsRead                       = false,
                RelatedSmsFromDefinedValueId = rockSmsFromPhoneDv.Id,
                RelatedCommunicationId       = communicationId,
                RelatedTransportEntityTypeId = smsTransport,
                RelatedMediumEntityTypeId    = smsMedium.Id,
                Response                     = message
            };

            var communicationResposeService = new CommunicationResponseService(rockContext);

            communicationResposeService.Add(communicationResponse);
            rockContext.SaveChanges();
        }
Beispiel #11
0
        /// <summary>
        /// Handles the Delete event of the gCommunication control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs"/> instance containing the event data.</param>
        protected void gCommunication_Delete( object sender, Rock.Web.UI.Controls.RowEventArgs e )
        {
            var rockContext = new RockContext();
            var service = new CommunicationTemplateService( rockContext );
            var template = service.Get( e.RowKeyId );
            if ( template != null )
            {
                if ( !template.IsAuthorized( Authorization.EDIT, this.CurrentPerson ) )
                {
                    maGridWarning.Show( "You are not authorized to delete this template", ModalAlertType.Information );
                    return;
                }

                string errorMessage;
                if ( !service.CanDelete( template, out errorMessage ) )
                {
                    maGridWarning.Show( errorMessage, ModalAlertType.Information );
                    return;
                }

                service.Delete( template );

                rockContext.SaveChanges();
            }

            BindGrid();
        }
        public static Rock.Model.CommunicationRecipient GetNextPending(int communicationId, Rock.Data.RockContext rockContext)
        {
            CommunicationRecipient recipient = null;

            var delayTime = RockDateTime.Now.AddMinutes(-10);

            lock ( _obj )
            {
                recipient = new CommunicationRecipientService(rockContext).Queryable("Communication,PersonAlias.Person")
                            .Where(r =>
                                   r.CommunicationId == communicationId &&
                                   (r.PersonAlias.Person.IsDeceased == false) &&
                                   (r.Status == CommunicationRecipientStatus.Pending ||
                                    (r.Status == CommunicationRecipientStatus.Sending && r.ModifiedDateTime < delayTime)))
                            .FirstOrDefault();

                if (recipient != null)
                {
                    recipient.Status = CommunicationRecipientStatus.Sending;
                    rockContext.SaveChanges();
                }
            }

            return(recipient);
        }
Beispiel #13
0
        /// <summary>
        /// Handles the Delete event of the gGroupType 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 gGroupType_Delete( object sender, RowEventArgs e )
        {
            var rockContext = new RockContext();
            GroupTypeService groupTypeService = new GroupTypeService( rockContext );
            GroupType groupType = groupTypeService.Get( e.RowKeyId );

            if ( groupType != null )
            {
                int groupTypeId = groupType.Id;

                if ( !groupType.IsAuthorized( "Administrate", CurrentPerson ) )
                {
                    mdGridWarning.Show( "Sorry, you're not authorized to delete this group type.", ModalAlertType.Alert );
                    return;
                }

                string errorMessage;
                if ( !groupTypeService.CanDelete( groupType, out errorMessage ) )
                {
                    mdGridWarning.Show( errorMessage, ModalAlertType.Alert );
                    return;
                }

                groupTypeService.Delete( groupType );
                rockContext.SaveChanges();

                GroupTypeCache.Flush( groupTypeId );
            }

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

            var workflow = action.Activity.Workflow;
            workflow.IsPersisted = true;

            if ( GetAttributeValue( action, "PersistImmediately" ).AsBoolean( false ) )
            {
                var service = new WorkflowService( rockContext );
                if ( workflow.Id == 0 )
                {
                    service.Add( workflow );
                }

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

            action.AddLogEntry( "Updated workflow to be persisted!" );

            return true;
        }
        /// <summary>
        /// Gets the next pending.
        /// </summary>
        /// <param name="communicationId">The communication identifier.</param>
        /// <param name="mediumEntityId">The medium entity identifier.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        public static Rock.Model.CommunicationRecipient GetNextPending(int communicationId, int mediumEntityId, Rock.Data.RockContext rockContext)
        {
            CommunicationRecipient recipient = null;

            var delayTime = RockDateTime.Now.AddMinutes(-240);

            lock ( _obj )
            {
                recipient = new CommunicationRecipientService(rockContext).Queryable().Include(r => r.Communication).Include(r => r.PersonAlias.Person)
                            .Where(r =>
                                   r.CommunicationId == communicationId &&
                                   (r.Status == CommunicationRecipientStatus.Pending ||
                                    (r.Status == CommunicationRecipientStatus.Sending && r.ModifiedDateTime < delayTime)
                                   ) &&
                                   r.MediumEntityTypeId.HasValue &&
                                   r.MediumEntityTypeId.Value == mediumEntityId)
                            .FirstOrDefault();

                if (recipient != null)
                {
                    recipient.ModifiedDateTime = RockDateTime.Now;
                    recipient.Status           = CommunicationRecipientStatus.Sending;
                    rockContext.SaveChanges();
                }
            }

            return(recipient);
        }
Beispiel #16
0
        /// <summary>
        /// Creates a new communication.
        /// </summary>
        /// <param name="fromPersonAliasId">From person alias identifier.</param>
        /// <param name="fromPersonName">Name of from person.</param>
        /// <param name="toPersonAliasId">To person alias identifier.</param>
        /// <param name="message">The message to send.</param>
        /// <param name="transportPhone">The transport phone.</param>
        /// <param name="responseCode">The reponseCode to use for tracking the conversation.</param>
        /// <param name="rockContext">A context to use for database calls.</param>
        private void CreateCommunication(int fromPersonAliasId, string fromPersonName, int toPersonAliasId, string message, string transportPhone, string responseCode, Rock.Data.RockContext rockContext)
        {
            // add communication for reply
            var communication = new Rock.Model.Communication();

            communication.IsBulkCommunication = false;
            communication.Status = CommunicationStatus.Approved;
            communication.SenderPersonAliasId = fromPersonAliasId;
            communication.Subject             = string.Format("From: {0}", fromPersonName);

            communication.SetMediumDataValue("Message", message);
            communication.SetMediumDataValue("FromValue", transportPhone);

            communication.MediumEntityTypeId = EntityTypeCache.Read("Rock.Communication.Medium.Sms").Id;

            var recipient = new Rock.Model.CommunicationRecipient();

            recipient.Status        = CommunicationRecipientStatus.Pending;
            recipient.PersonAliasId = toPersonAliasId;
            recipient.ResponseCode  = responseCode;
            communication.Recipients.Add(recipient);

            var communicationService = new Rock.Model.CommunicationService(rockContext);

            communicationService.Add(communication);
            rockContext.SaveChanges();

            // queue the sending
            var transaction = new Rock.Transactions.SendCommunicationTransaction();

            transaction.CommunicationId = communication.Id;
            transaction.PersonAlias     = null;
            Rock.Transactions.RockQueue.TransactionQueue.Enqueue(transaction);
        }
        /// <summary>
        /// Handles the SaveClick event of the mdEdit 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 mdEdit_SaveClick( object sender, EventArgs e )
        {
            var rockContext = new RockContext();
            EntityTypeService entityTypeService = new EntityTypeService( rockContext );
            EntityType entityType = entityTypeService.Get( int.Parse( hfEntityTypeId.Value ) );

            if ( entityType == null )
            {
                entityType = new EntityType();
                entityType.IsEntity = true;
                entityType.IsSecured = true;
                entityTypeService.Add( entityType );
            }

            entityType.Name = tbName.Text;
            entityType.FriendlyName = tbFriendlyName.Text;
            entityType.IsCommon = cbCommon.Checked;

            rockContext.SaveChanges();

            EntityTypeCache.Flush( entityType.Id );

            hfEntityTypeId.Value = string.Empty;

            HideDialog();

            BindGrid();
        }
        protected void bbtnDelete_Click( object sender, EventArgs e )
        {
            BootstrapButton bbtnDelete = (BootstrapButton)sender;
            RepeaterItem riItem = (RepeaterItem)bbtnDelete.NamingContainer;

            HiddenField hfScheduledTransactionId = (HiddenField)riItem.FindControl( "hfScheduledTransactionId" );
            Literal content = (Literal)riItem.FindControl( "lLiquidContent" );
            Button btnEdit = (Button)riItem.FindControl( "btnEdit" );

            var rockContext = new Rock.Data.RockContext();
            FinancialScheduledTransactionService fstService = new FinancialScheduledTransactionService( rockContext );
            var currentTransaction = fstService.Get( Int32.Parse(hfScheduledTransactionId.Value) );

            string errorMessage = string.Empty;
            if ( fstService.Cancel( currentTransaction, out errorMessage ) )
            {
                rockContext.SaveChanges();
                content.Text = String.Format( "<div class='alert alert-success'>Your recurring {0} has been deleted.</div>", GetAttributeValue( "TransactionLabel" ).ToLower() );
            }
            else
            {
                content.Text = String.Format( "<div class='alert alert-danger'>An error occured while deleting your scheduled transation. Message: {0}</div>", errorMessage );
            }

            bbtnDelete.Visible = false;
            btnEdit.Visible = false;
        }
Beispiel #19
0
        protected void bbtnDelete_Click(object sender, EventArgs e)
        {
            BootstrapButton bbtnDelete = (BootstrapButton)sender;
            RepeaterItem    riItem     = (RepeaterItem)bbtnDelete.NamingContainer;

            HiddenField hfScheduledTransactionId = (HiddenField)riItem.FindControl("hfScheduledTransactionId");
            Literal     content = (Literal)riItem.FindControl("lLiquidContent");
            Button      btnEdit = (Button)riItem.FindControl("btnEdit");

            var rockContext = new Rock.Data.RockContext();
            FinancialScheduledTransactionService fstService = new FinancialScheduledTransactionService(rockContext);
            var currentTransaction = fstService.Get(Int32.Parse(hfScheduledTransactionId.Value));

            string errorMessage = string.Empty;

            if (fstService.Cancel(currentTransaction, out errorMessage))
            {
                rockContext.SaveChanges();
                content.Text = String.Format("<div class='alert alert-success'>Your recurring {0} has been deleted.</div>", GetAttributeValue("TransactionLabel").ToLower());
            }
            else
            {
                content.Text = String.Format("<div class='alert alert-danger'>An error occured while deleting your scheduled transation. Message: {0}</div>", errorMessage);
            }

            bbtnDelete.Visible = false;
            btnEdit.Visible    = false;
        }
Beispiel #20
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages)
        {
            errorMessages = new List<string>();

            EntityTypeCache cachedEntityType = EntityTypeCache.Read(GetAttributeValue(action, "EntityType").AsGuid());
            var propertyValues = GetAttributeValue(action, "EntityProperties").Replace(" ! ", " | ").ResolveMergeFields(GetMergeFields(action)).TrimEnd('|').Split('|').Select(p => p.Split('^')).Select(p => new { Name = p[0], Value = p[1] });

            if (cachedEntityType != null)
            {
                Type entityType = cachedEntityType.GetEntityType();
                IEntity newEntity = (IEntity)Activator.CreateInstance(entityType);

                foreach (var prop in propertyValues)
                {
                    PropertyInfo propInf = entityType.GetProperty(prop.Name, BindingFlags.Public | BindingFlags.Instance);
                    if (null != propInf && propInf.CanWrite)
                    {
                        if (!(GetAttributeValue(action, "EmptyValueHandling") == "IGNORE" && String.IsNullOrWhiteSpace(prop.Value)))
                        {
                            try
                            {
                                propInf.SetValue(newEntity, ObjectConverter.ConvertObject(prop.Value, propInf.PropertyType, GetAttributeValue(action, "EmptyValueHandling") == "NULL"), null);
                            }
                            catch (Exception ex) when (ex is InvalidCastException || ex is FormatException || ex is OverflowException)
                            {
                                errorMessages.Add("Invalid Property Value: " + prop.Name + ": " + ex.Message);
                            }
                        }
                    }
                    else
                    {
                        errorMessages.Add("Invalid Property: " + prop.Name);
                    }
                }

                rockContext.Set(entityType).Add(newEntity);
                rockContext.SaveChanges();

                // If request attribute was specified, requery the request and set the attribute's value
                Guid? entityAttributeGuid = GetAttributeValue(action, "EntityAttribute").AsGuidOrNull();
                if (entityAttributeGuid.HasValue)
                {
                    newEntity = (IEntity)rockContext.Set(entityType).Find(new object[] { newEntity.Id });
                    if (newEntity != null)
                    {
                        SetWorkflowAttributeValue(action, entityAttributeGuid.Value, newEntity.Guid.ToString());
                    }
                }

                return true;

            }
            else
            {
                errorMessages.Add("Invalid Entity Type");
            }
            return false;
        }
Beispiel #21
0
 /// <summary>
 /// Saves the bank accounts.
 /// </summary>
 /// <param name="newBankAccounts">The new bank accounts.</param>
 private static void SaveBankAccounts( List<FinancialPersonBankAccount> newBankAccounts )
 {
     using ( var rockContext = new RockContext() )
     {
         rockContext.Configuration.AutoDetectChangesEnabled = false;
         rockContext.FinancialPersonBankAccounts.AddRange( newBankAccounts );
         rockContext.SaveChanges( DisableAuditing );
     }
 }
Beispiel #22
0
 /// <summary>
 /// Saves the financial batches.
 /// </summary>
 /// <param name="newBatches">The new batches.</param>
 private static void SaveFinancialBatches( List<FinancialBatch> newBatches )
 {
     using ( var rockContext = new RockContext() )
     {
         rockContext.Configuration.AutoDetectChangesEnabled = false;
         rockContext.FinancialBatches.AddRange( newBatches );
         rockContext.SaveChanges( DisableAuditing );
     }
 }
Beispiel #23
0
 /// <summary>
 /// Saves the contributions.
 /// </summary>
 /// <param name="newTransactions">The new transactions.</param>
 private static void SaveContributions( List<FinancialTransaction> newTransactions )
 {
     using ( var rockContext = new RockContext() )
     {
         rockContext.Configuration.AutoDetectChangesEnabled = false;
         rockContext.FinancialTransactions.AddRange( newTransactions );
         rockContext.SaveChanges( DisableAuditing );
     }
 }
Beispiel #24
0
 /// <summary>
 /// Saves the family address.
 /// </summary>
 /// <param name="newGroupLocations">The new group locations.</param>
 private static void SaveFamilyAddress( List<GroupLocation> newGroupLocations )
 {
     var rockContext = new RockContext();
     rockContext.WrapTransaction( () =>
     {
         rockContext.Configuration.AutoDetectChangesEnabled = false;
         rockContext.GroupLocations.AddRange( newGroupLocations );
         rockContext.SaveChanges( DisableAuditing );
     } );
 }
Beispiel #25
0
 /// <summary>
 /// Saves the financial batches.
 /// </summary>
 /// <param name="newBatches">The new batches.</param>
 private static void SaveFinancialBatches( List<FinancialBatch> newBatches )
 {
     var rockContext = new RockContext();
     rockContext.WrapTransaction( () =>
     {
         rockContext.Configuration.AutoDetectChangesEnabled = false;
         rockContext.FinancialBatches.AddRange( newBatches );
         rockContext.SaveChanges( DisableAudit );
     } );
 }
Beispiel #26
0
 /// <summary>
 /// Saves the notes.
 /// </summary>
 /// <param name="noteList">The note list.</param>
 private static void SaveNotes( List<Note> noteList )
 {
     var rockContext = new RockContext();
     rockContext.WrapTransaction( () =>
     {
         rockContext.Configuration.AutoDetectChangesEnabled = false;
         rockContext.Notes.AddRange( noteList );
         rockContext.SaveChanges( DisableAudit );
     } );
 }
Beispiel #27
0
 /// <summary>
 /// Saves the attendance.
 /// </summary>
 /// <param name="attendance">The attendance.</param>
 private static void SaveAttendance( Rock.Model.Attendance attendance )
 {
     var rockContext = new RockContext();
     rockContext.WrapTransaction( () =>
     {
         rockContext.Configuration.AutoDetectChangesEnabled = false;
         rockContext.Attendances.Add( attendance );
         rockContext.SaveChanges( DisableAudit );
     } );
 }
        /// <summary>
        /// Handles the Click event of the bbtnDelete 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 bbtnDelete_Click(object sender, EventArgs e)
        {
            /* 2021-08-27 MDP
             *
             * We really don't want to actually delete a FinancialScheduledTransaction.
             * Just inactivate it, even if there aren't FinancialTransactions associated with it.
             * It is possible the the Gateway has processed a transaction on it that Rock doesn't know about yet.
             * If that happens, Rock won't be able to match a record for that downloaded transaction!
             * We also might want to match inactive or "deleted" schedules on the Gateway to a person in Rock,
             * so we'll need the ScheduledTransaction to do that.
             *
             * So, don't delete ScheduledTransactions.
             *
             */

            BootstrapButton bbtnDelete = ( BootstrapButton )sender;
            RepeaterItem    riItem     = ( RepeaterItem )bbtnDelete.NamingContainer;

            HiddenField hfScheduledTransactionId = ( HiddenField )riItem.FindControl("hfScheduledTransactionId");
            Literal     lLavaContent             = ( Literal )riItem.FindControl("lLavaContent");
            Button      btnEdit = ( Button )riItem.FindControl("btnEdit");

            using (var rockContext = new Rock.Data.RockContext())
            {
                FinancialScheduledTransactionService fstService = new FinancialScheduledTransactionService(rockContext);
                var currentTransaction = fstService.Get(hfScheduledTransactionId.Value.AsInteger());
                if (currentTransaction != null && currentTransaction.FinancialGateway != null)
                {
                    currentTransaction.FinancialGateway.LoadAttributes(rockContext);
                }

                string errorMessage = string.Empty;
                if (fstService.Cancel(currentTransaction, out errorMessage))
                {
                    try
                    {
                        fstService.GetStatus(currentTransaction, out errorMessage);
                    }
                    catch
                    {
                        // Ignore
                    }

                    rockContext.SaveChanges();
                    lLavaContent.Text = string.Format("<div class='alert alert-success'>Your scheduled {0} has been deleted.</div>", GetAttributeValue(AttributeKey.TransactionLabel).ToLower());
                }
                else
                {
                    lLavaContent.Text = string.Format("<div class='alert alert-danger'>An error occurred while deleting your scheduled transaction. Message: {0}</div>", errorMessage);
                }
            }

            bbtnDelete.Visible = false;
            btnEdit.Visible    = false;
        }
Beispiel #29
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages)
        {
            errorMessages = new List<string>();

            Guid workflowAttributeGuid = GetAttributeValue(action, "Entity").AsGuid();
            Guid entityGuid = action.GetWorklowAttributeValue(workflowAttributeGuid).AsGuid();

            if (!entityGuid.IsEmpty())
            {
                IEntity entityObject = null;
                EntityTypeCache cachedEntityType = EntityTypeCache.Read(GetAttributeValue(action, "EntityType").AsGuid());

                if (cachedEntityType != null)
                {
                    Type entityType = cachedEntityType.GetEntityType();
                    entityObject = rockContext.Set<IEntity>().AsQueryable().Where(e => e.Guid == entityGuid).FirstOrDefault();
                }
                else {
                    var field = AttributeCache.Read(workflowAttributeGuid).FieldType.Field;
                    entityObject = ((Rock.Field.IEntityFieldType)field).GetEntity(entityGuid.ToString(), rockContext);
                }

                var propertyValues = GetAttributeValue(action, "EntityProperties").Replace(" ! ", " | ").ResolveMergeFields(GetMergeFields(action)).TrimEnd('|').Split('|').Select(p => p.Split('^')).Select(p => new { Name = p[0], Value = p[1] });

                foreach (var prop in propertyValues)
                {
                    PropertyInfo propInf = entityObject.GetType().GetProperty(prop.Name, BindingFlags.Public | BindingFlags.Instance);
                    if (null != propInf && propInf.CanWrite)
                    {
                        if (!(GetAttributeValue(action, "EmptyValueHandling") == "IGNORE" && String.IsNullOrWhiteSpace(prop.Value)))
                        {
                            try
                            {
                                propInf.SetValue(entityObject, ObjectConverter.ConvertObject(prop.Value, propInf.PropertyType, GetAttributeValue(action, "EmptyValueHandling") == "NULL"), null);
                            }
                            catch (Exception ex) when (ex is InvalidCastException || ex is FormatException || ex is OverflowException)
                            {
                                errorMessages.Add("Invalid Property Value: " + prop.Name + ": " + ex.Message);
                            }
                        }
                    }
                    else
                    {
                        errorMessages.Add("Invalid Property: " + prop.Name);
                    }
                }

                rockContext.SaveChanges();
                return true;
            }
            else {
                errorMessages.Add("Invalid Entity Attribute");
            }
            return false;
        }
        /// <summary>
        /// Handles the Click event of the btnChange 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 btnChange_Click( object sender, EventArgs e )
        {
            RockContext rockContext = new RockContext();
            var userLoginService = new UserLoginService( rockContext );
            var userLogin = userLoginService.GetByUserName( tbUserName.Text );

            if ( userLogin != null )
            {
                if ( UserLoginService.IsPasswordValid( tbPassword.Text ) )
                {
                    var component = Rock.Security.AuthenticationContainer.GetComponent( userLogin.EntityType.Name );

                    if ( component.SupportsChangePassword )
                    {

                        string warningMessage;
                        if ( component.ChangePassword( userLogin, tbOldPassword.Text, tbPassword.Text, out warningMessage ) )
                        {
                            rockContext.SaveChanges();

                            lSuccess.Text = GetAttributeValue( "SuccessCaption" );
                            pnlEntry.Visible = false;
                            pnlSuccess.Visible = true;
                        }
                        else
                        {
                            if ( string.IsNullOrWhiteSpace( warningMessage ) )
                            {
                                DisplayErrorFromAttribute( "InvalidPasswordCaption" );
                            }
                            else
                            {
                                DisplayErrorText( warningMessage );
                            }
                        }
                    }
                    else
                    {
                        // shouldn't happen, but just in case
                        DisplayErrorFromAttribute( "ChangePasswordNotSupportedCaption" );
                        pnlChangePassword.Visible = false;
                    }
                }
                else
                {
                    InvalidPassword();
                }
            }
            else
            {
                DisplayErrorFromAttribute( "InvalidUserNameCaption" );
            }
        }
        /// <summary>
        /// Handles the Delete event of the gBusinessList control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs"/> instance containing the event data.</param>
        protected void gBusinessList_Delete( object sender, Rock.Web.UI.Controls.RowEventArgs e )
        {
            var rockContext = new RockContext();
            PersonService service = new PersonService( rockContext );
            Person business = service.Get( e.RowKeyId );
            if ( business != null )
            {
                business.RecordStatusValueId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ) ).Id;
                rockContext.SaveChanges();
            }

            BindGrid();
        }
        /// <summary>
        /// Handles the Delete event of the gEmailTemplates 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 gEmailTemplates_Delete( object sender, RowEventArgs e )
        {
            var rockContext = new RockContext();
            SystemEmailService emailTemplateService = new SystemEmailService( rockContext );
            SystemEmail emailTemplate = emailTemplateService.Get( (int)gEmailTemplates.DataKeys[e.RowIndex]["id"] );
            if ( emailTemplate != null )
            {
                emailTemplateService.Delete( emailTemplate );
                rockContext.SaveChanges();
            }

            BindGrid();
        }
        /// <summary>
        /// When implemented by a class, enables a server control to process an event raised when a form is posted to the server.
        /// </summary>
        /// <param name="eventArgument">A <see cref="T:System.String" /> that represents an optional event argument to be passed to the event handler.</param>
        public void RaisePostBackEvent( string eventArgument )
        {
            if ( eventArgument == "StatusUpdate" &&
                ddlAction != null &&
                ddlAction.SelectedValue != null &&
                !string.IsNullOrWhiteSpace( ddlAction.SelectedValue ) )
            {
                var batchesSelected = new List<int>();

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

                if ( batchesSelected.Any() )
                {
                    var newStatus = ddlAction.SelectedValue == "OPEN" ? BatchStatus.Open : BatchStatus.Closed;

                    var rockContext = new RockContext();
                    var batchService = new FinancialBatchService( rockContext );
                    var batchesToUpdate = batchService.Queryable()
                        .Where( b =>
                            batchesSelected.Contains( b.Id ) &&
                            b.Status != newStatus )
                        .ToList();

                    foreach ( var batch in batchesToUpdate )
                    {
                        batch.Status = newStatus;
                    }

                    rockContext.SaveChanges();

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

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

                ddlAction.SelectedIndex = 0;
                BindGrid();
            }
        }
Beispiel #34
0
        /// <summary>
        /// Execute method to write transaction to the database.
        /// </summary>
        public void Execute()
        {
            if ( Audits != null && Audits.Count > 0 )
            {
                var rockContext = new RockContext();
                var auditService = new AuditService( rockContext );

                foreach ( var audit in Audits.Where( a => a.Details.Any() ) )
                {
                    auditService.Add( audit );
                }

                rockContext.SaveChanges();
            }
        }
Beispiel #35
0
        /// <summary>
        /// Handles the Click event of the btnSaveRequestNote 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 btnSaveRequestNote_Click( object sender, EventArgs e )
        {
            int? setId = PageParameter( "Set" ).AsIntegerOrNull();
            if ( setId.HasValue )
            {
                var rockContext = new RockContext();
                var entitySet = new EntitySetService( rockContext ).Get( setId.Value );
                entitySet.Note = tbEntitySetNote.Text;
                rockContext.SaveChanges();

                nbNoteSavedSuccess.Visible = true;
                tbEntitySetNote.Visible = false;
                btnSaveRequestNote.Visible = false;
            }
        }
Beispiel #36
0
        /// <summary>
        /// Creates the communication to the recipent's mobile device.
        /// </summary>
        /// <param name="fromPerson">From person.</param>
        /// <param name="toPersonAliasId">To person alias identifier.</param>
        /// <param name="message">The message.</param>
        /// <param name="fromPhone">From phone.</param>
        /// <param name="responseCode">The response code.</param>
        /// <param name="rockContext">The rock context.</param>
        public static void CreateCommunicationMobile(Person fromPerson, int?toPersonAliasId, string message, DefinedValueCache fromPhone, string responseCode, Rock.Data.RockContext rockContext)
        {
            string communicationName = fromPerson != null?string.Format("From: {0}", fromPerson.FullName) : "From: unknown person";

            var communicationService = new CommunicationService(rockContext);
            var communication        = communicationService.CreateSMSCommunication(fromPerson, toPersonAliasId, message, fromPhone, responseCode, communicationName);

            rockContext.SaveChanges();

            // queue the sending
            var transaction = new Rock.Transactions.SendCommunicationTransaction();

            transaction.CommunicationId = communication.Id;
            transaction.PersonAlias     = null;
            Rock.Transactions.RockQueue.TransactionQueue.Enqueue(transaction);
        }
        protected void attendanceDelete_Click(object sender, RowEventArgs e)
        {
            RockContext editContext = new RockContext();
            AttendanceService editAttServe = new AttendanceService(editContext);

            var attendItem = editAttServe.Queryable().Where(x => x.Id == e.RowKeyId).FirstOrDefault();
            if (attendItem.IsAuthorized("Edit", CurrentPerson))
            {
                attendItem.DidAttend = !attendItem.DidAttend;
                attendItem.DidNotOccur = !attendItem.DidAttend;
                editContext.SaveChanges();
            }

            _rockContext = new RockContext();
            attendServ = new AttendanceService(_rockContext);
            doStuff();
        }
        /// <summary>
        /// Update the Disc Adaptive Score
        /// </summary>
        public void UpdateDiscAdaptiveScore()
        {
            //Adaptive D
            using (var rockContext = new Rock.Data.RockContext())
            {
                var attribute       = new AttributeService(rockContext).Get(new Guid("EDE5E199-37BE-424F-A788-5CDCC064157C"));
                var attributeValues = new AttributeValueService(rockContext).Queryable().Where(b => b.AttributeId == attribute.Id && b.Value != string.Empty);
                attributeValues.ToList().ForEach(a => {
                    a.Value = DiscService.GetAdaptiveScoreValue(DiscService.AttributeKeys.AdaptiveD, Convert.ToInt32(Math.Round(a.Value.AsDecimal() * 0.28m, 0))).ToString();
                });
                rockContext.SaveChanges();
            }

            //Adaptive S
            using (var rockContext = new Rock.Data.RockContext())
            {
                var attribute       = new AttributeService(rockContext).Get(new Guid("2512DAC6-BBC4-4D0E-A01D-E92F94C534BD"));
                var attributeValues = new AttributeValueService(rockContext).Queryable().Where(b => b.AttributeId == attribute.Id && b.Value != string.Empty);
                attributeValues.ToList().ForEach(a => {
                    a.Value = DiscService.GetAdaptiveScoreValue(DiscService.AttributeKeys.AdaptiveS, Convert.ToInt32(Math.Round(a.Value.AsDecimal() * 0.28m, 0))).ToString();
                });
                rockContext.SaveChanges();
            }

            //Adaptive I
            using (var rockContext = new Rock.Data.RockContext())
            {
                var attribute       = new AttributeService(rockContext).Get(new Guid("7F0A1794-0150-413B-9AE1-A6B0D6373DA6"));
                var attributeValues = new AttributeValueService(rockContext).Queryable().Where(b => b.AttributeId == attribute.Id && b.Value != string.Empty);
                attributeValues.ToList().ForEach(a => {
                    a.Value = DiscService.GetAdaptiveScoreValue(DiscService.AttributeKeys.AdaptiveI, Convert.ToInt32(Math.Round(a.Value.AsDecimal() * 0.28m, 0))).ToString();
                });
                rockContext.SaveChanges();
            }

            //Adaptive C
            using (var rockContext = new Rock.Data.RockContext())
            {
                var attribute       = new AttributeService(rockContext).Get(new Guid("4A2E1539-4ECC-40B9-9EBD-C0C84EC8DA36"));
                var attributeValues = new AttributeValueService(rockContext).Queryable().Where(b => b.AttributeId == attribute.Id && b.Value != string.Empty);
                attributeValues.ToList().ForEach(a => {
                    a.Value = DiscService.GetAdaptiveScoreValue(DiscService.AttributeKeys.AdaptiveC, Convert.ToInt32(Math.Round(a.Value.AsDecimal() * 0.28m, 0))).ToString();
                });
                rockContext.SaveChanges();
            }
        }
        /// <summary>
        /// Update the Disc Natural Score
        /// </summary>
        public void UpdateDiscNaturalScore()
        {
            //Natural D
            using (var rockContext = new Rock.Data.RockContext())
            {
                var attribute       = new AttributeService(rockContext).Get(new Guid("86670F7D-07BA-4ECE-9BB9-9D94B5FB5F26"));
                var attributeValues = new AttributeValueService(rockContext).Queryable().Where(b => b.AttributeId == attribute.Id && b.Value != string.Empty);
                attributeValues.ToList().ForEach(a => {
                    a.Value = DiscService.GetNaturalScoreValue(DiscService.AttributeKeys.NaturalD, Convert.ToInt32(Math.Round((27 - a.Value.AsDecimal() * 0.78m), 0))).ToString();
                });
                rockContext.SaveChanges();
            }

            //Natural S
            using (var rockContext = new Rock.Data.RockContext())
            {
                var attribute       = new AttributeService(rockContext).Get(new Guid("FA4341B4-28C7-409E-A101-548BB5759BE6"));
                var attributeValues = new AttributeValueService(rockContext).Queryable().Where(b => b.AttributeId == attribute.Id && b.Value != string.Empty);
                attributeValues.ToList().ForEach(a => {
                    a.Value = DiscService.GetNaturalScoreValue(DiscService.AttributeKeys.NaturalS, Convert.ToInt32(Math.Round((27 - a.Value.AsDecimal() * 0.78m), 0))).ToString();
                });
                rockContext.SaveChanges();
            }

            //Natural I
            using (var rockContext = new Rock.Data.RockContext())
            {
                var attribute       = new AttributeService(rockContext).Get(new Guid("3EFF4FEF-EE4C-40E2-8DBD-80F3276852DA"));
                var attributeValues = new AttributeValueService(rockContext).Queryable().Where(b => b.AttributeId == attribute.Id && b.Value != string.Empty);
                attributeValues.ToList().ForEach(a => {
                    a.Value = DiscService.GetNaturalScoreValue(DiscService.AttributeKeys.NaturalI, Convert.ToInt32(Math.Round((26 - a.Value.AsDecimal() * 0.78m), 0))).ToString();
                });
                rockContext.SaveChanges();
            }

            //Natural C
            using (var rockContext = new Rock.Data.RockContext())
            {
                var attribute       = new AttributeService(rockContext).Get(new Guid("3A10ECFB-8CAB-4CCA-8B29-298756CD3251"));
                var attributeValues = new AttributeValueService(rockContext).Queryable().Where(b => b.AttributeId == attribute.Id && b.Value != string.Empty);
                attributeValues.ToList().ForEach(a => {
                    a.Value = DiscService.GetNaturalScoreValue(DiscService.AttributeKeys.NaturalC, Convert.ToInt32(Math.Round((26 - a.Value.AsDecimal() * 0.78m), 0))).ToString();
                });
                rockContext.SaveChanges();
            }
        }
Beispiel #40
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;
            }
        }
Beispiel #41
0
        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        public static void SetValue(string key, string value)
        {
            var rockContext      = new Rock.Data.RockContext();
            var attributeService = new AttributeService(rockContext);
            var attribute        = attributeService.GetSystemSetting(key);

            bool isNew = false;

            if (attribute == null)
            {
                attribute             = new Rock.Model.Attribute();
                attribute.FieldTypeId = FieldTypeCache.Read(new Guid(SystemGuid.FieldType.TEXT)).Id;
                attribute.EntityTypeQualifierColumn = Rock.Model.Attribute.SYSTEM_SETTING_QUALIFIER;
                attribute.EntityTypeQualifierValue  = string.Empty;
                attribute.Key          = key;
                attribute.Name         = key.SplitCase();
                attribute.DefaultValue = value;
                attributeService.Add(attribute);
                isNew = true;
            }
            else
            {
                attribute.DefaultValue = value;
            }

            rockContext.SaveChanges();

            AttributeCache.Flush(attribute.Id);
            if (isNew)
            {
                AttributeCache.FlushEntityAttributes();
            }

            var settings       = SystemSettings.Read();
            var attributeCache = settings.Attributes.FirstOrDefault(a => a.Key.Equals(key, StringComparison.OrdinalIgnoreCase));

            if (attributeCache != null)
            {
                attributeCache.DefaultValue = value;
            }
            else
            {
                settings.Attributes.Add(AttributeCache.Read(attribute.Id));
            }
        }
        /// <summary>
        /// Execute method to write transaction to the database.
        /// </summary>
        public void Execute()
        {
            if ( Audits != null && Audits.Count > 0 )
            {
                var auditsToAdd = Audits.Where( a => a.Details.Any() );
                if ( auditsToAdd.Any() )
                {
                    using ( var rockContext = new RockContext() )
                    {
                        var auditService = new AuditService( rockContext );

                        auditService.AddRange( auditsToAdd );

                        rockContext.SaveChanges( true );
                    }
                }
            }
        }
        /// <summary>
        /// Handles the Delete event of the grdScheduledJobs 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 gScheduledJobs_Delete( object sender, RowEventArgs e )
        {
            var rockContext = new RockContext();
            var jobService = new ServiceJobService( rockContext );
            ServiceJob job = jobService.Get( e.RowKeyId );

            string errorMessage;
            if ( !jobService.CanDelete( job, out errorMessage ) )
            {
                mdGridWarning.Show( errorMessage, ModalAlertType.Information );
                return;
            }

            jobService.Delete( job );
            rockContext.SaveChanges();

            BindGrid();
        }
Beispiel #44
0
        /// <summary>
        /// Adds the account.
        /// </summary>
        /// <param name="lookupContext">The lookup context.</param>
        /// <param name="fundName">Name of the fund.</param>
        /// <param name="fundCampusId">The fund campus identifier.</param>
        /// <returns></returns>
        private static FinancialAccount AddAccount( RockContext lookupContext, string fundName, int? fundCampusId, int? parentAccountId )
        {
            lookupContext = lookupContext ?? new RockContext();

            var account = new FinancialAccount();
            account.Name = fundName;
            account.PublicName = fundName;
            account.IsTaxDeductible = true;
            account.IsActive = true;
            account.CampusId = fundCampusId;
            account.ParentAccountId = parentAccountId;
            account.CreatedByPersonAliasId = ImportPersonAlias.Id;

            lookupContext.FinancialAccounts.Add( account );
            lookupContext.SaveChanges( DisableAudit );

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

            Guid? workflowGuid = GetAttributeValue( action, "Workflow", true ).AsGuidOrNull();
            if ( workflowGuid.HasValue )
            {
                using ( var newRockContext = new RockContext() )
                {
                    var workflowService = new WorkflowService( newRockContext );
                    var workflow = workflowService.Get( workflowGuid.Value );
                    if ( workflow != null )
                    {
                        string status = GetAttributeValue( action, "Status" ).ResolveMergeFields( GetMergeFields( action ) );
                        workflow.Status = status;
                        workflow.AddLogEntry( string.Format( "Status set to '{0}' by another workflow: {1}", status, action.Activity.Workflow ) );
                        newRockContext.SaveChanges();

                        action.AddLogEntry( string.Format( "Set Status to '{0}' on another workflow: {1}", status, workflow ) );

                        bool processNow = GetAttributeValue( action, "ProcessNow" ).AsBoolean();
                        if ( processNow )
                        {
                            var processErrors = new List<string>();
                            if ( !workflowService.Process( workflow, out processErrors ) )
                            {
                                action.AddLogEntry( "Error(s) occurred processing target workflow: " + processErrors.AsDelimited( ", " ) );
                            }
                        }

                        return true;
                    }
                }

                action.AddLogEntry( "Could not find selected workflow." );
            }
            else
            {
                action.AddLogEntry( "Workflow attribute was not set." );
                return true;    // Continue processing in this case
            }

            return false;
        }
Beispiel #46
0
        /// <summary>
        /// Cleanups the temporary binary files.
        /// </summary>
        private void CleanupTemporaryBinaryFiles()
        {
            var binaryFileRockContext = new Rock.Data.RockContext();
            // clean out any temporary binary files
            BinaryFileService binaryFileService = new BinaryFileService(binaryFileRockContext);

            foreach (var binaryFile in binaryFileService.Queryable().Where(bf => bf.IsTemporary == true).ToList())
            {
                if (binaryFile.ModifiedDateTime < RockDateTime.Now.AddDays(-1))
                {
                    string errorMessage;
                    if (binaryFileService.CanDelete(binaryFile, out errorMessage))
                    {
                        binaryFileService.Delete(binaryFile);
                        binaryFileRockContext.SaveChanges();
                    }
                }
            }
        }
        /// <summary>
        /// Handles the Click event of the bbtnDelete 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 bbtnDelete_Click(object sender, EventArgs e)
        {
            BootstrapButton bbtnDelete = ( BootstrapButton )sender;
            RepeaterItem    riItem     = ( RepeaterItem )bbtnDelete.NamingContainer;

            HiddenField hfScheduledTransactionId = ( HiddenField )riItem.FindControl("hfScheduledTransactionId");
            Literal     content = ( Literal )riItem.FindControl("lLiquidContent");
            Button      btnEdit = ( Button )riItem.FindControl("btnEdit");

            using (var rockContext = new Rock.Data.RockContext())
            {
                FinancialScheduledTransactionService fstService = new FinancialScheduledTransactionService(rockContext);
                var currentTransaction = fstService.Get(hfScheduledTransactionId.Value.AsInteger());
                if (currentTransaction != null && currentTransaction.FinancialGateway != null)
                {
                    currentTransaction.FinancialGateway.LoadAttributes(rockContext);
                }

                string errorMessage = string.Empty;
                if (fstService.Cancel(currentTransaction, out errorMessage))
                {
                    try
                    {
                        fstService.GetStatus(currentTransaction, out errorMessage);
                    }
                    catch
                    {
                        // Ignore
                    }

                    rockContext.SaveChanges();
                    content.Text = string.Format("<div class='alert alert-success'>Your recurring {0} has been deleted.</div>", GetAttributeValue(AttributeKey.TransactionLabel).ToLower());
                }
                else
                {
                    content.Text = string.Format("<div class='alert alert-danger'>An error occurred while deleting your scheduled transaction. Message: {0}</div>", errorMessage);
                }
            }

            bbtnDelete.Visible = false;
            btnEdit.Visible    = false;
        }
Beispiel #48
0
        /// <summary>
        /// Cleans up temporary registrations.
        /// </summary>
        private int CleanUpTemporaryRegistrations()
        {
            var registrationRockContext = new Rock.Data.RockContext();
            int totalRowsDeleted        = 0;
            // clean out any temporary registrations
            RegistrationService registrationService = new RegistrationService(registrationRockContext);

            foreach (var registration in registrationService.Queryable().Where(bf => bf.IsTemporary == true).ToList())
            {
                if (registration.ModifiedDateTime < RockDateTime.Now.AddHours(-1))
                {
                    string errorMessage;
                    if (registrationService.CanDelete(registration, out errorMessage))
                    {
                        registrationService.Delete(registration);
                        registrationRockContext.SaveChanges();
                        totalRowsDeleted++;
                    }
                }
            }

            return(totalRowsDeleted);
        }
Beispiel #49
0
        /// <summary>
        /// Purges the audit log.
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private int PurgeAuditLog(JobDataMap dataMap)
        {
            // purge audit log
            int totalRowsDeleted = 0;
            int?batchAmount      = dataMap.GetString("BatchCleanupAmount").AsIntegerOrNull() ?? 1000;
            int?auditExpireDays  = dataMap.GetString("AuditLogExpirationDays").AsIntegerOrNull();

            if (auditExpireDays.HasValue)
            {
                var      auditLogRockContext = new Rock.Data.RockContext();
                DateTime auditExpireDate     = RockDateTime.Now.Add(new TimeSpan(auditExpireDays.Value * -1, 0, 0, 0));

                // delete in chunks (see http://dba.stackexchange.com/questions/1750/methods-of-speeding-up-a-huge-delete-from-table-with-no-clauses)
                bool keepDeleting = true;
                while (keepDeleting)
                {
                    var dbTransaction = auditLogRockContext.Database.BeginTransaction();
                    try
                    {
                        int rowsDeleted = auditLogRockContext.Database.ExecuteSqlCommand(@"DELETE TOP (@batchAmount) FROM [Audit] WHERE [DateTime] < @auditExpireDate",
                                                                                         new SqlParameter("batchAmount", batchAmount),
                                                                                         new SqlParameter("auditExpireDate", auditExpireDate)
                                                                                         );
                        keepDeleting      = rowsDeleted > 0;
                        totalRowsDeleted += rowsDeleted;
                    }
                    finally
                    {
                        dbTransaction.Commit();
                    }
                }

                auditLogRockContext.SaveChanges();
            }

            return(totalRowsDeleted);
        }
Beispiel #50
0
    /// <summary>
    /// Processes for recipient.
    /// </summary>
    /// <param name="eventType">Type of the event.</param>
    /// <param name="communicationRecipientGuid">The communication recipient unique identifier.</param>
    /// <param name="rockContext">The rock context.</param>
    private void ProcessForRecipient(Guid?communicationRecipientGuid, Rock.Data.RockContext rockContext, SendGridEvent payload)
    {
        RockLogger.Log.Debug(RockLogDomains.Communications, "ProcessForRecipient {@payload}", payload);

        if (!communicationRecipientGuid.HasValue)
        {
            return;
        }

        var communicationRecipient = new CommunicationRecipientService(rockContext).Get(communicationRecipientGuid.Value);

        if (communicationRecipient != null && communicationRecipient.Communication != null)
        {
            var communicationGuid    = Rock.SystemGuid.InteractionChannel.COMMUNICATION.AsGuid();
            var interactionComponent = new InteractionComponentService(rockContext)
                                       .GetComponentByEntityId(communicationGuid, communicationRecipient.CommunicationId, communicationRecipient.Communication.Subject);

            rockContext.SaveChanges();

            var      interactionService = new InteractionService(rockContext);
            DateTime timeStamp          = RockDateTime.ConvertLocalDateTimeToRockDateTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(payload.Timestamp).ToLocalTime());

            switch (payload.EventType)
            {
            case "processed":
                // Do nothing.
                break;

            case "dropped":
                communicationRecipient.Status     = CommunicationRecipientStatus.Failed;
                communicationRecipient.StatusNote = payload.EventTypeReason;

                if (payload.EventTypeReason == "Bounced Address")
                {
                    Rock.Communication.Email.ProcessBounce(
                        payload.Email,
                        Rock.Communication.BounceType.HardBounce,
                        payload.EventTypeReason,
                        timeStamp);
                }

                break;

            case "delivered":
                communicationRecipient.Status     = CommunicationRecipientStatus.Delivered;
                communicationRecipient.StatusNote = string.Format("Confirmed delivered by SendGrid at {0}", timeStamp.ToString());
                break;

            case "deferred":
                // TODO: handle deferred.
                break;

            case "bounce":
                communicationRecipient.Status     = CommunicationRecipientStatus.Failed;
                communicationRecipient.StatusNote = payload.EventTypeReason + payload.ServerResponse;

                Rock.Communication.Email.ProcessBounce(
                    payload.Email,
                    Rock.Communication.BounceType.HardBounce,
                    payload.EventTypeReason,
                    timeStamp);
                break;

            case "blocked":
                // TODO: handle blocked.
                break;

            case "open":
                communicationRecipient.Status         = CommunicationRecipientStatus.Opened;
                communicationRecipient.OpenedDateTime = timeStamp;
                communicationRecipient.OpenedClient   = string.Format(
                    "{0} {1} ({2})",
                    payload.ClientOs ?? "unknown",
                    payload.ClientBrowser ?? "unknown",
                    payload.ClientDeviceType ?? "unknown");

                if (interactionComponent != null)
                {
                    interactionService.AddInteraction(
                        interactionComponent.Id,
                        communicationRecipient.Id,
                        "Opened",
                        payload.SendGridEventId,
                        communicationRecipient.PersonAliasId,
                        timeStamp,
                        payload.ClientBrowser,
                        payload.ClientOs,
                        payload.ClientDeviceType,
                        payload.ClientDeviceBrand,
                        payload.IpAddress,
                        null);
                }

                break;

            case "click":
                if (interactionComponent != null)
                {
                    interactionService.AddInteraction(
                        interactionComponent.Id,
                        communicationRecipient.Id,
                        "Click",
                        payload.Url,
                        communicationRecipient.PersonAliasId,
                        timeStamp,
                        payload.ClientBrowser,
                        payload.ClientOs,
                        payload.ClientDeviceType,
                        payload.ClientDeviceBrand,
                        payload.IpAddress,
                        null);
                }

                break;

            case "spamreport":
            case "unsubscribe":
            case "group_unsubscribe":
            case "group_resubscribe":
                // Do nothing.
                break;
            }

            rockContext.SaveChanges();
        }
    }
Beispiel #51
0
        /// <summary>
        /// Does cleanup of Person Aliases and Metaphones
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private void PersonCleanup(JobDataMap dataMap)
        {
            // Add any missing person aliases
            using (var personRockContext = new Rock.Data.RockContext())
            {
                PersonService      personService      = new PersonService(personRockContext);
                PersonAliasService personAliasService = new PersonAliasService(personRockContext);
                var personAliasServiceQry             = personAliasService.Queryable();
                foreach (var person in personService.Queryable("Aliases")
                         .Where(p => !p.Aliases.Any() && !personAliasServiceQry.Any(pa => pa.AliasPersonId == p.Id))
                         .Take(300))
                {
                    person.Aliases.Add(new PersonAlias {
                        AliasPersonId = person.Id, AliasPersonGuid = person.Guid
                    });
                }

                personRockContext.SaveChanges();
            }

            AddMissingAlternateIds();

            using (var personRockContext = new Rock.Data.RockContext())
            {
                PersonService personService = new PersonService(personRockContext);
                // Add any missing metaphones
                int namesToProcess = dataMap.GetString("MaxMetaphoneNames").AsIntegerOrNull() ?? 500;
                if (namesToProcess > 0)
                {
                    var firstNameQry = personService.Queryable().Select(p => p.FirstName).Where(p => p != null);
                    var nickNameQry  = personService.Queryable().Select(p => p.NickName).Where(p => p != null);
                    var lastNameQry  = personService.Queryable().Select(p => p.LastName).Where(p => p != null);
                    var nameQry      = firstNameQry.Union(nickNameQry.Union(lastNameQry));

                    var metaphones    = personRockContext.Metaphones;
                    var existingNames = metaphones.Select(m => m.Name).Distinct();

                    // Get the names that have not yet been processed
                    var namesToUpdate = nameQry
                                        .Where(n => !existingNames.Contains(n))
                                        .Take(namesToProcess)
                                        .ToList();

                    foreach (string name in namesToUpdate)
                    {
                        string mp1 = string.Empty;
                        string mp2 = string.Empty;
                        Rock.Utility.DoubleMetaphone.doubleMetaphone(name, ref mp1, ref mp2);

                        var metaphone = new Metaphone();
                        metaphone.Name       = name;
                        metaphone.Metaphone1 = mp1;
                        metaphone.Metaphone2 = mp2;

                        metaphones.Add(metaphone);
                    }

                    personRockContext.SaveChanges(disablePrePostProcessing: true);
                }
            }

            // Ensures the PrimaryFamily is correct for all person records in the database
            using (var personRockContext = new Rock.Data.RockContext())
            {
                int primaryFamilyUpdates = PersonService.UpdatePrimaryFamilyAll(personRockContext);
            }

            // update any updated or incorrect age classifications on persons
            using (var personRockContext = new Rock.Data.RockContext())
            {
                int ageClassificationUpdates = PersonService.UpdatePersonAgeClassificationAll(personRockContext);
            }

            //// Add any missing Implied/Known relationship groups
            // Known Relationship Group
            AddMissingRelationshipGroups(GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS), Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid());

            // Implied Relationship Group
            AddMissingRelationshipGroups(GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_PEER_NETWORK), Rock.SystemGuid.GroupRole.GROUPROLE_PEER_NETWORK_OWNER.AsGuid());

            // Find family groups that have no members or that have only 'inactive' people (record status) and mark the groups inactive.
            using (var familyRockContext = new Rock.Data.RockContext())
            {
                int familyGroupTypeId           = GroupTypeCache.GetFamilyGroupType().Id;
                int recordStatusInactiveValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid()).Id;

                var activeFamilyWithNoActiveMembers = new GroupService(familyRockContext).Queryable()
                                                      .Where(a => a.GroupTypeId == familyGroupTypeId && a.IsActive == true)
                                                      .Where(a => !a.Members.Where(m => m.Person.RecordStatusValueId != recordStatusInactiveValueId).Any());

                var currentDateTime = RockDateTime.Now;

                familyRockContext.BulkUpdate(activeFamilyWithNoActiveMembers, x => new Rock.Model.Group
                {
                    IsActive = false
                });
            }
        }
Beispiel #52
0
        /// <summary>
        /// Recursively logs exception and any children.
        /// </summary>
        /// <param name="ex">The <see cref="System.Exception"/> to log.</param>
        /// <param name="log">The parent <see cref="Rock.Model.ExceptionLog"/> of the exception being logged. This value is nullable.</param>
        /// <param name="isParent">A <see cref="System.Boolean"/> flag indicating if this Exception is a parent exception. This value is
        ///     <c>true</c> if the exception that is being logged is a parent exception, otherwise <c>false</c>.
        /// </param>
        private static void LogExceptions(Exception ex, ExceptionLog log, bool isParent)
        {
            bool logToFile = AlwaysLogToFile;

            // First, attempt to log exception to the database.
            try
            {
                ExceptionLog exceptionLog;

                // If this is a recursive call and not the originating exception being logged,
                // attempt to clone the initial one, and populate it with Exception Type and Message
                // from the inner exception, while retaining the contextual information from where
                // the exception originated.
                if (!isParent)
                {
                    exceptionLog = log.Clone(false);

                    if (exceptionLog != null)
                    {
                        // Populate with inner exception type, message and update whether or not there is another inner exception.
                        exceptionLog.ExceptionType     = ex.GetType().ToString();
                        exceptionLog.Description       = ex.Message;
                        exceptionLog.Source            = ex.Source;
                        exceptionLog.StackTrace        = ex.StackTrace;
                        exceptionLog.HasInnerException = ex.InnerException != null;

                        // Ensure EF properly recognizes this as a new record.
                        exceptionLog.Id       = 0;
                        exceptionLog.Guid     = Guid.NewGuid();
                        exceptionLog.ParentId = log.Id;
                    }
                }
                else
                {
                    exceptionLog = log;
                }

                // The only reason this should happen is if the `log.Clone()` operation failed. Compiler sugar.
                if (exceptionLog == null)
                {
                    return;
                }

                // Write ExceptionLog record to database.
                using (var rockContext = new Rock.Data.RockContext())
                {
                    var exceptionLogService = new ExceptionLogService(rockContext);
                    exceptionLogService.Add(exceptionLog);

                    // make sure to call the regular SaveChanges so that CreatedBy,CreatedByDateTime, etc get set properly. If any of the post processing happens to also create an exception, we can just log to the exception file instead
                    rockContext.SaveChanges();
                }

                // Recurse if inner exception is found
                if (exceptionLog.HasInnerException.GetValueOrDefault(false))
                {
                    if (ex is AggregateException aggregateException)
                    {
                        foreach (var innerException in aggregateException.InnerExceptions)
                        {
                            LogExceptions(innerException, exceptionLog, false);
                        }
                    }
                    else
                    {
                        LogExceptions(ex.InnerException, exceptionLog, false);
                    }
                }
            }
            catch (Exception)
            {
                // If logging the exception fails, write the exceptions to a file
                logToFile = true;
            }

            if (logToFile)
            {
                try
                {
                    string directory = AppDomain.CurrentDomain.BaseDirectory;
                    directory = Path.Combine(directory, "App_Data", "Logs");

                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }

                    string filePath = Path.Combine(directory, "RockExceptions.csv");
                    string when     = RockDateTime.Now.ToString();
                    while (ex != null)
                    {
                        File.AppendAllText(filePath, string.Format("{0},{1},\"{2}\",\"{3}\"\r\n", when, ex.GetType(), ex.Message, ex.StackTrace));
                        ex = ex.InnerException;
                    }
                }
                catch
                {
                    // failed to write to database and also failed to write to log file, so there is nowhere to log this error
                }
            }
        }
Beispiel #53
0
    /// <summary>
    /// Processes for recipient.
    /// </summary>
    /// <param name="eventType">Type of the event.</param>
    /// <param name="communicationRecipientGuid">The communication recipient unique identifier.</param>
    /// <param name="rockContext">The rock context.</param>
    private void ProcessForReceipent(string eventType, Guid?communicationRecipientGuid, Rock.Data.RockContext rockContext)
    {
        if (!communicationRecipientGuid.HasValue)
        {
            return;
        }

        var communicationRecipient = new CommunicationRecipientService(rockContext).Get(communicationRecipientGuid.Value);

        if (communicationRecipient != null && communicationRecipient.Communication != null)
        {
            int      secs = request.Form["timestamp"].AsInteger();
            DateTime ts   = RockDateTime.ConvertLocalDateTimeToRockDateTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(secs).ToLocalTime());

            var communicationGuid = Rock.SystemGuid.InteractionChannel.COMMUNICATION.AsGuid();

            InteractionComponent interactionComponent = new InteractionComponentService(rockContext)
                                                        .GetComponentByEntityId(communicationGuid, communicationRecipient.CommunicationId, communicationRecipient.Communication.Subject);

            rockContext.SaveChanges();

            var interactionService = new InteractionService(rockContext);

            switch (eventType)
            {
            case "delivered":
                communicationRecipient.Status     = CommunicationRecipientStatus.Delivered;
                communicationRecipient.StatusNote = string.Format("Confirmed delivered by Mailgun at {0}", ts.ToString());
                break;

            case "opened":
                communicationRecipient.Status         = CommunicationRecipientStatus.Opened;
                communicationRecipient.OpenedDateTime = ts;
                communicationRecipient.OpenedClient   = string.Format(
                    "{0} {1} ({2})",
                    request.Form["client-os"] ?? "unknown",
                    request.Form["client-name"] ?? "unknown",
                    request.Form["device-type"] ?? "unknown");

                if (interactionComponent != null)
                {
                    interactionService.AddInteraction(
                        interactionComponent.Id,
                        communicationRecipient.Id,
                        "Opened",
                        string.Empty,
                        communicationRecipient.PersonAliasId,
                        ts,
                        request.Form["client-name"],
                        request.Form["client-os"],
                        request.Form["client-type"],
                        request.Form["device-type"],
                        request.Form["ip"],
                        null);
                }

                break;

            case "clicked":
                if (interactionComponent != null)
                {
                    interactionService.AddInteraction(
                        interactionComponent.Id,
                        communicationRecipient.Id,
                        "Click",
                        request.Form["url"],
                        communicationRecipient.PersonAliasId,
                        ts,
                        request.Form["client-name"],
                        request.Form["client-os"],
                        request.Form["client-type"],
                        request.Form["device-type"],
                        request.Form["ip"],
                        null);
                }

                break;

            case "complained":
                break;

            case "unsubscribed":
                break;

            case "dropped":
                communicationRecipient.Status     = CommunicationRecipientStatus.Failed;
                communicationRecipient.StatusNote = request.Form["description"];
                break;

            case "bounced":
                communicationRecipient.Status     = CommunicationRecipientStatus.Failed;
                communicationRecipient.StatusNote = request.Form["notification"];

                Rock.Communication.Email.ProcessBounce(
                    request.Form["recipient"],
                    Rock.Communication.BounceType.HardBounce,
                    request.Form["notification"],
                    ts);

                break;
            }

            rockContext.SaveChanges();
        }
    }
Beispiel #54
0
    /// <summary>
    /// Processes for recipient.
    /// </summary>
    /// <param name="eventType">Type of the event.</param>
    /// <param name="communicationRecipientGuid">The communication recipient unique identifier.</param>
    /// <param name="rockContext">The rock context.</param>
    private void ProcessForReceipent(Guid?communicationRecipientGuid, Rock.Data.RockContext rockContext)
    {
        if (!communicationRecipientGuid.HasValue)
        {
            return;
        }

        var communicationRecipient = new CommunicationRecipientService(rockContext).Get(communicationRecipientGuid.Value);

        if (communicationRecipient != null && communicationRecipient.Communication != null)
        {
            var communicationGuid    = Rock.SystemGuid.InteractionChannel.COMMUNICATION.AsGuid();
            var interactionComponent = new InteractionComponentService(rockContext)
                                       .GetComponentByEntityId(communicationGuid, communicationRecipient.CommunicationId, communicationRecipient.Communication.Subject);

            rockContext.SaveChanges();

            var      interactionService = new InteractionService(rockContext);
            DateTime timeStamp          = RockDateTime.ConvertLocalDateTimeToRockDateTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(mailgunRequestPayload.TimeStamp).ToLocalTime());

            switch (mailgunRequestPayload.EventType)
            {
            case "delivered":
                communicationRecipient.Status     = CommunicationRecipientStatus.Delivered;
                communicationRecipient.StatusNote = string.Format("Confirmed delivered by Mailgun at {0}", timeStamp.ToString());
                break;

            case "opened":
                communicationRecipient.Status         = CommunicationRecipientStatus.Opened;
                communicationRecipient.OpenedDateTime = timeStamp;
                communicationRecipient.OpenedClient   = string.Format(
                    "{0} {1} ({2})",
                    mailgunRequestPayload.ClientOs ?? "unknown",
                    mailgunRequestPayload.ClientName ?? "unknown",
                    mailgunRequestPayload.DeviceType ?? "unknown");

                if (interactionComponent != null)
                {
                    interactionService.AddInteraction(
                        interactionComponent.Id,
                        communicationRecipient.Id,
                        "Opened",
                        string.Empty,
                        communicationRecipient.PersonAliasId,
                        timeStamp,
                        mailgunRequestPayload.ClientName,
                        mailgunRequestPayload.ClientOs,
                        mailgunRequestPayload.ClientType,
                        mailgunRequestPayload.DeviceType,
                        mailgunRequestPayload.Ip,
                        null);
                }

                break;

            case "clicked":
                if (interactionComponent != null)
                {
                    interactionService.AddInteraction(
                        interactionComponent.Id,
                        communicationRecipient.Id,
                        "Click",
                        mailgunRequestPayload.Url,
                        communicationRecipient.PersonAliasId,
                        timeStamp,
                        mailgunRequestPayload.ClientName,
                        mailgunRequestPayload.ClientOs,
                        mailgunRequestPayload.ClientType,
                        mailgunRequestPayload.DeviceType,
                        mailgunRequestPayload.Ip,
                        null);
                }

                break;

            case "complained":
                break;

            case "unsubscribed":
                break;

            case "dropped":
                communicationRecipient.Status     = CommunicationRecipientStatus.Failed;
                communicationRecipient.StatusNote = mailgunRequestPayload.Description;
                break;

            case "bounced":
                communicationRecipient.Status     = CommunicationRecipientStatus.Failed;
                communicationRecipient.StatusNote = mailgunRequestPayload.Notification;

                Rock.Communication.Email.ProcessBounce(
                    mailgunRequestPayload.Recipient,
                    Rock.Communication.BounceType.HardBounce,
                    mailgunRequestPayload.Notification,
                    timeStamp);
                break;

            case "failed":
                // The new mailgun API bundles undeliverable mail into a failed event. The reason (e.g. bounced) is in a seperate property called reason.
                if (mailgunRequestPayload.EventTypeReason.IsNotNullOrWhiteSpace())
                {
                    switch (mailgunRequestPayload.EventTypeReason)
                    {
                    case "bounce":
                    case "suppress-bounce":
                        communicationRecipient.Status     = CommunicationRecipientStatus.Failed;
                        communicationRecipient.StatusNote = mailgunRequestPayload.Description;

                        Rock.Communication.Email.ProcessBounce(
                            mailgunRequestPayload.Recipient,
                            Rock.Communication.BounceType.HardBounce,
                            mailgunRequestPayload.Description,
                            timeStamp);
                        break;

                    default:
                        communicationRecipient.Status     = CommunicationRecipientStatus.Failed;
                        communicationRecipient.StatusNote = mailgunRequestPayload.Description;
                        break;
                    }
                }

                break;
            }

            rockContext.SaveChanges();
        }
    }
Beispiel #55
0
        /// <summary>
        /// Does cleanup of Person Aliases and Metaphones
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private void PersonCleanup(JobDataMap dataMap)
        {
            // Add any missing person aliases
            var                personRockContext     = new Rock.Data.RockContext();
            PersonService      personService         = new PersonService(personRockContext);
            PersonAliasService personAliasService    = new PersonAliasService(personRockContext);
            var                personAliasServiceQry = personAliasService.Queryable();

            foreach (var person in personService.Queryable("Aliases")
                     .Where(p => !p.Aliases.Any() && !personAliasServiceQry.Any(pa => pa.AliasPersonId == p.Id))
                     .Take(300))
            {
                person.Aliases.Add(new PersonAlias {
                    AliasPersonId = person.Id, AliasPersonGuid = person.Guid
                });
            }

            personRockContext.SaveChanges();

            // Add any missing metaphones
            int namesToProcess = dataMap.GetString("MaxMetaphoneNames").AsIntegerOrNull() ?? 500;

            if (namesToProcess > 0)
            {
                var firstNameQry = personService.Queryable().Select(p => p.FirstName).Where(p => p != null);
                var nickNameQry  = personService.Queryable().Select(p => p.NickName).Where(p => p != null);
                var lastNameQry  = personService.Queryable().Select(p => p.LastName).Where(p => p != null);
                var nameQry      = firstNameQry.Union(nickNameQry.Union(lastNameQry));

                var metaphones    = personRockContext.Metaphones;
                var existingNames = metaphones.Select(m => m.Name).Distinct();

                // Get the names that have not yet been processed
                var namesToUpdate = nameQry
                                    .Where(n => !existingNames.Contains(n))
                                    .Take(namesToProcess)
                                    .ToList();

                foreach (string name in namesToUpdate)
                {
                    string mp1 = string.Empty;
                    string mp2 = string.Empty;
                    Rock.Utility.DoubleMetaphone.doubleMetaphone(name, ref mp1, ref mp2);

                    var metaphone = new Metaphone();
                    metaphone.Name       = name;
                    metaphone.Metaphone1 = mp1;
                    metaphone.Metaphone2 = mp2;

                    metaphones.Add(metaphone);
                }

                personRockContext.SaveChanges();
            }

            //// Add any missing Implied/Known relationship groups
            // Known Relationship Group
            AddMissingRelationshipGroups(GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS), Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid());

            // Implied Relationship Group
            AddMissingRelationshipGroups(GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_IMPLIED_RELATIONSHIPS), Rock.SystemGuid.GroupRole.GROUPROLE_IMPLIED_RELATIONSHIPS_OWNER.AsGuid());
        }