Entity Framework Context
Inheritance: DbContext
        /// <summary>
        /// Executes the specified workflow action.
        /// </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? personAliasGuid = GetAttributeValue( action, "Person" ).AsGuidOrNull();
            if ( personAliasGuid.HasValue )
            {
                var personAlias = new PersonAliasService( rockContext ).Queryable( "Person" )
                    .Where( a => a.Guid.Equals( personAliasGuid.Value ) )
                    .FirstOrDefault();

                if (personAlias != null)
                {
                    action.Activity.AssignedPersonAlias = personAlias;
                    action.Activity.AssignedPersonAliasId = personAlias.Id;
                    action.Activity.AssignedGroup = null;
                    action.Activity.AssignedGroupId = null;
                    action.AddLogEntry( string.Format( "Assigned activity to '{0}' ({1})",  personAlias.Person.FullName, personAlias.Person.Id ) );
                    return true;
                }

            }

            return false;
        }
        /// <summary>
        /// Executes this instance.
        /// </summary>
        public void Execute()
        {
            using ( var rockContext = new RockContext() )
            {
                var gateway = new FinancialGatewayService( rockContext ).Get( GatewayId );
                if ( gateway != null )
                {
                    var gatewayComponent = gateway.GetGatewayComponent();
                    if ( gatewayComponent != null )
                    {
                        var scheduledTxnService = new FinancialScheduledTransactionService( rockContext );

                        foreach( var txnId in ScheduledTransactionIds )
                        {
                            var scheduledTxn = scheduledTxnService.Get( txnId );
                            if ( scheduledTxn != null )
                            {
                                string statusMsgs = string.Empty;
                                gatewayComponent.GetScheduledPaymentStatus( scheduledTxn, out statusMsgs );
                                rockContext.SaveChanges();
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Returns the field's current value(s)
        /// </summary>
        /// <param name="parentControl">The parent control.</param>
        /// <param name="value">Information about the value</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param>
        /// <returns></returns>
        public override string FormatValue( Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed )
        {
            string formattedValue = string.Empty;

            string[] parts = ( value ?? string.Empty ).Split( '|' );
            Guid? groupTypeGuid = parts[0].AsGuidOrNull();
            Guid? groupGuid = parts[1].AsGuidOrNull();
            var rockContext = new RockContext();
            if ( groupGuid.HasValue )
            {
                var group = new GroupService( rockContext ).Get( groupGuid.Value );
                if ( group != null )
                {
                    formattedValue = "Group: " + group.Name;
                }
            }
            else if ( groupTypeGuid.HasValue )
            {
                var groupType = new GroupTypeService( rockContext ).Get( groupTypeGuid.Value );
                if ( groupType != null )
                {
                    formattedValue = "Group type: " + groupType.Name;
                }
            }

            return base.FormatValue( parentControl, formattedValue, null, condensed );
        }
Beispiel #4
0
        /// <summary>
        /// Gets the HTML preview.
        /// </summary>
        /// <param name="communication">The communication.</param>
        /// <param name="person">The person.</param>
        /// <returns></returns>
        public override string GetHtmlPreview( Model.Communication communication, Person person )
        {
            var rockContext = new RockContext();

            // Requery the Communication object
            communication = new CommunicationService( rockContext ).Get( communication.Id );

            var globalAttributes = Rock.Web.Cache.GlobalAttributesCache.Read();
            var mergeValues = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields( null );

            if ( person != null )
            {
                mergeValues.Add( "Person", person );

                var recipient = communication.Recipients.Where( r => r.PersonId == person.Id ).FirstOrDefault();
                if ( recipient != null )
                {
                    // Add any additional merge fields created through a report
                    foreach ( var mergeField in recipient.AdditionalMergeValues )
                    {
                        if ( !mergeValues.ContainsKey( mergeField.Key ) )
                        {
                            mergeValues.Add( mergeField.Key, mergeField.Value );
                        }
                    }
                }
            }

            string message = communication.GetChannelDataValue( "Message" );
            return message.ResolveMergeFields( mergeValues );
        }
        /// <summary>
        /// Returns breadcrumbs specific to the block that should be added to navigation
        /// based on the current page reference.  This function is called during the page's
        /// oninit to load any initial breadcrumbs
        /// </summary>
        /// <param name="pageReference">The page reference.</param>
        /// <returns></returns>
        public override List<BreadCrumb> GetBreadCrumbs( PageReference pageReference )
        {
            var rockContext = new RockContext();
            var breadCrumbs = new List<BreadCrumb>();

            ConnectionRequest connectionRequest = null;

            int? requestId = PageParameter( "ConnectionRequestId" ).AsIntegerOrNull();
            if ( requestId.HasValue && requestId.Value > 0 )
            {
                connectionRequest = new ConnectionRequestService( rockContext ).Get( requestId.Value );
            }

            if ( connectionRequest != null )
            {
                breadCrumbs.Add( new BreadCrumb( connectionRequest.PersonAlias.Person.FullName, pageReference ) );
            }
            else
            {
                var connectionOpportunity = new ConnectionOpportunityService( rockContext ).Get( PageParameter( "ConnectionOpportunityId" ).AsInteger() );
                if ( connectionOpportunity != null )
                {
                    breadCrumbs.Add( new BreadCrumb( String.Format( "New {0} Connection Request", connectionOpportunity.Name ), pageReference ) );
                }
                else
                {
                    breadCrumbs.Add( new BreadCrumb( "New Connection Request", pageReference ) );
                }
            }

            return breadCrumbs;
        }
Beispiel #6
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute( RockContext rockContext, Model.WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            var checkInState = GetCheckInState( entity, out errorMessages );
            if ( checkInState != null )
            {
                foreach ( var family in checkInState.CheckIn.Families.ToList() )
                {
                    foreach ( var person in family.People.ToList() )
                    {
                        if ( person.GroupTypes.Count == 0 )
                        {
                            family.People.Remove( person );
                        }
                        else if ( person.GroupTypes.All( t => t.ExcludedByFilter ) )
                        {
                            person.ExcludedByFilter = true;
                        }
                    }
                }

                return true;
            }

            return false;
        }
Beispiel #7
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 #8
0
        /// <summary>
        /// Loads the drop down items.
        /// </summary>
        private void LoadDropDownItems()
        {
            this.Items.Clear();

            if ( _entityTypeId.HasValue )
            {
                // add Empty option first
                this.Items.Add( new ListItem() );

                using ( var rockContext = new RockContext() )
                {
                    var allEntityFilters = new DataViewFilterService( rockContext )
                        .Queryable().AsNoTracking()
                        .Where( f => f.EntityTypeId == _entityTypeId )
                        .ToList();

                    foreach ( var dataView in new DataViewService( rockContext )
                        .GetByEntityTypeId( _entityTypeId.Value )
                        .Include( "EntityType" )
                        .Include( "Category" )
                        .Include( "DataViewFilter" )
                        .AsNoTracking() )
                    {
                        var currentPerson = HttpContext.Current.Items["CurrentPerson"] as Person;
                        if ( dataView.IsAuthorized( Authorization.VIEW, currentPerson ) &&
                            dataView.DataViewFilter.IsAuthorized( Authorization.VIEW, currentPerson, allEntityFilters ) )
                        {
                            this.Items.Add( new ListItem( dataView.Name, dataView.Id.ToString() ) );
                        }
                    }
                }
            }
        }
Beispiel #9
0
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        public void LoadDropDowns()
        {
            // get accounts that are both allowed by the BlockSettings and also in the personal AccountList setting
            var rockContext = new RockContext();
            var accountGuidList = GetAttributeValue( "Accounts" ).SplitDelimitedValues().Select( a => a.AsGuid() );

            string keyPrefix = string.Format( "transaction-matching-{0}-", this.BlockId );
            var personalAccountGuidList = ( this.GetUserPreference( keyPrefix + "account-list" ) ?? string.Empty ).SplitDelimitedValues().Select( a => a.AsGuid() ).ToList();

            var accountQry = new FinancialAccountService( rockContext ).Queryable();

            // no accounts specified means "all"
            if ( accountGuidList.Any() )
            {
                accountQry = accountQry.Where( a => accountGuidList.Contains( a.Guid ) );
            }

            // no personal accounts specified means "all(that are allowed in block settings)"
            if ( personalAccountGuidList.Any() )
            {
                accountQry = accountQry.Where( a => personalAccountGuidList.Contains( a.Guid ) );
            }

            rptAccounts.DataSource = accountQry.OrderBy( a => a.Order ).ThenBy( a => a.Name ).ToList();
            rptAccounts.DataBind();
        }
Beispiel #10
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute( RockContext rockContext, Model.WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            var checkInState = GetCheckInState( entity, out errorMessages );
            if ( checkInState != null )
            {
                foreach ( var family in checkInState.CheckIn.GetFamilies( true ) )
                {
                    foreach ( var person in family.People )
                    {
                        foreach ( var kioskGroupType in checkInState.Kiosk.ActiveGroupTypes( checkInState.ConfiguredGroupTypes ) )
                        {
                            if ( kioskGroupType.KioskGroups.SelectMany( g => g.KioskLocations ).Any( l => l.IsCheckInActive && l.IsActiveAndNotFull ) )
                            {
                                if ( !person.GroupTypes.Any( g => g.GroupType.Id == kioskGroupType.GroupType.Id ) )
                                {
                                    var checkinGroupType = new CheckInGroupType();
                                    checkinGroupType.GroupType = kioskGroupType.GroupType;
                                    person.GroupTypes.Add( checkinGroupType );
                                }
                            }
                        }
                    }
                }

                return true;
            }

            return false;
        }
        /// <summary>
        /// Execute method to write transaction to the database.
        /// </summary>
        public void Execute()
        {
            if ( Trigger != null )
            {
                var rockContext = new RockContext();
                var workflowTypeService = new WorkflowTypeService( rockContext );
                var workflowType = workflowTypeService.Get( Trigger.WorkflowTypeId );

                if ( workflowType != null )
                {
                    var workflow = Rock.Model.Workflow.Activate( workflowType, Trigger.WorkflowName );

                    List<string> workflowErrors;
                    if ( workflow.Process( rockContext, Entity, out workflowErrors ) )
                    {
                        if ( workflow.IsPersisted || workflowType.IsPersisted )
                        {
                            var workflowService = new Rock.Model.WorkflowService( rockContext );
                            workflowService.Add( workflow );

                            rockContext.WrapTransaction( () =>
                            {
                                rockContext.SaveChanges();
                                workflow.SaveAttributeValues( rockContext );
                                foreach ( var activity in workflow.Activities )
                                {
                                    activity.SaveAttributeValues( rockContext );
                                }
                            } );
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Handles the Delete event of the gBinaryFile 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 gBinaryFile_Delete( object sender, RowEventArgs e )
        {
            var rockContext = new RockContext();
            BinaryFileService binaryFileService = new BinaryFileService( rockContext );
            BinaryFile binaryFile = binaryFileService.Get( e.RowKeyId );

            if ( binaryFile != null )
            {
                string errorMessage;
                if ( !binaryFileService.CanDelete( binaryFile, out errorMessage ) )
                {
                    mdGridWarning.Show( errorMessage, ModalAlertType.Information );
                    return;
                }

                Guid guid = binaryFile.Guid;
                bool clearDeviceCache = binaryFile.BinaryFileType.Guid.Equals( Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL.AsGuid() );

                binaryFileService.Delete( binaryFile );
                rockContext.SaveChanges();

                if ( clearDeviceCache )
                {
                    Rock.CheckIn.KioskDevice.FlushAll();
                    Rock.CheckIn.KioskLabel.Flush( guid );
                }
            }

            BindGrid();
        }
Beispiel #13
0
        /// <summary>
        /// Notifies the admins.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <param name="message">The message.</param>
        /// <param name="appRoot">The application root.</param>
        /// <param name="themeRoot">The theme root.</param>
        /// <param name="createCommunicationHistory">if set to <c>true</c> [create communication history].</param>
        /// <exception cref="System.Exception">Error sending System Email: Could not read Email Medium Entity Type</exception>
        public static void NotifyAdmins( string subject, string message, string appRoot = "", string themeRoot = "", bool createCommunicationHistory = true  )
        {
            try
            {
                List<string> recipients = null;

                Guid adminGroup = Rock.SystemGuid.Group.GROUP_ADMINISTRATORS.AsGuid();
                using ( var rockContext = new RockContext() )
                {
                    recipients = new GroupMemberService( rockContext ).Queryable()
                        .Where( m =>
                            m.Group.Guid.Equals( adminGroup ) &&
                            m.GroupMemberStatus == GroupMemberStatus.Active &&
                            m.Person.Email != null &&
                            m.Person.Email != "" )
                        .Select( m => m.Person.Email )
                        .ToList();
                }

                Email.Send(GlobalAttributesCache.Value("OrganizationEmail"), subject, recipients, message, appRoot, themeRoot, null, createCommunicationHistory );
            }
            catch ( Exception ex )
            {
                ExceptionLogService.LogException( ex, HttpContext.Current );
            }
        }
Beispiel #14
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();
        }
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        private void LoadDropDowns()
        {
            ddlEntityType.Items.Clear();
            var rockContext = new RockContext();
            new EntityTypeService( rockContext ).GetEntityListItems().ForEach( l => ddlEntityType.Items.Add( l ) );

            ddlWorkflowType.Items.Clear();
            ddlWorkflowType.Items.Add( new ListItem( string.Empty, string.Empty));

            foreach ( var workflowType in new WorkflowTypeService( rockContext ).Queryable().OrderBy( w => w.Name ) )
            {
                if ( workflowType.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
                {
                    ddlWorkflowType.Items.Add( new ListItem( workflowType.Name, workflowType.Id.ToString() ) );
                }
            }

            rblTriggerType.Items.Clear();
            Type type = typeof(WorkflowTriggerType);
            foreach ( var value in Enum.GetValues( type ) )
            {
                rblTriggerType.Items.Add( new ListItem( Enum.GetName( type, value ).SplitCase().Replace( " ", "-" ), Convert.ToInt32( value ).ToString() ) );
            }
            
        }
Beispiel #16
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;
                }

                groupType.ParentGroupTypes.Clear();
                groupType.ChildGroupTypes.Clear();

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

                GroupTypeCache.Flush( groupTypeId );
            }

            BindGrid();
        }
        /// <summary>
        /// Gets a list of all <see cref="Rock.Model.FieldType">FieldTypes</see> (all items that implement the <see cref="Rock.Field.IFieldType"/> interface) and registers the 
        /// <see cref="Rock.Model.FieldType">FieldTypes</see> that have not been previously registered.
        /// </summary>
        /// <param name="physWebAppPath">A <see cref="System.String"/> representing the physical path of the web application.</param>
        public static void RegisterFieldTypes( string physWebAppPath )
        {
            var fieldTypes = new Dictionary<string, EntityType>();

            var rockContext = new RockContext();
            var fieldTypeService = new FieldTypeService( rockContext );

            var existingFieldTypes = fieldTypeService.Queryable().ToList();

            foreach ( var type in Rock.Reflection.FindTypes( typeof( Rock.Field.IFieldType ) ) )
            {
                string assemblyName = type.Value.Assembly.GetName().Name;
                string className = type.Value.FullName;

                if ( !existingFieldTypes.Where( f =>
                    f.Assembly == assemblyName &&
                    f.Class == className ).Any() )
                {
                    string fieldTypeName = type.Value.Name.SplitCase();
                    if (fieldTypeName.EndsWith(" Field Type"))
                    {
                        fieldTypeName = fieldTypeName.Substring( 0, fieldTypeName.Length - 11 );
                    }
                    var fieldType = new FieldType();
                    fieldType.Name = fieldTypeName;
                    fieldType.Assembly = assemblyName;
                    fieldType.Class = className;
                    fieldType.IsSystem = false;
                    fieldTypeService.Add( fieldType );
                }
            }

            rockContext.SaveChanges();
        }
Beispiel #18
0
 /// <summary>
 /// Starts logging all EF SQL Calls to the Debug Output Window as T-SQL Blocks
 /// </summary>
 /// <param name="rockContext">The rock context to limit the output to.  Leave blank to show output for all rockContexts.</param>
 public static void SQLLoggingStart( RockContext rockContext = null )
 {
     _callCounts = 0;
     SQLLoggingStop();
     _debugLoggingDbCommandInterceptor.RockContext = rockContext;
     DbInterception.Add( _debugLoggingDbCommandInterceptor );
 }
        /// <summary>
        /// Launch the workflow
        /// </summary>
        protected void LaunchTheWorkflow(string workflowName)
        {
            Guid workflowTypeGuid = Guid.NewGuid();
            if ( Guid.TryParse( workflowName, out workflowTypeGuid ) )
            {
                var rockContext = new RockContext();
                var workflowTypeService = new WorkflowTypeService(rockContext);
                var workflowType = workflowTypeService.Get( workflowTypeGuid );
                if ( workflowType != null )
                {
                    var workflow = Rock.Model.Workflow.Activate( workflowType, workflowName );

                    List<string> workflowErrors;
                    if ( workflow.Process( rockContext, out workflowErrors ) )
                    {
                        if ( workflow.IsPersisted || workflowType.IsPersisted )
                        {
                            var workflowService = new Rock.Model.WorkflowService(rockContext);
                            workflowService.Add( workflow );

                            rockContext.WrapTransaction( () =>
                            {
                                rockContext.SaveChanges();
                                workflow.SaveAttributeValues( rockContext );
                                foreach ( var activity in workflow.Activities )
                                {
                                    activity.SaveAttributeValues( rockContext );
                                }
                            } );
                        }
                    }
                }
            }     
        }
Beispiel #20
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            Guid guid = GetAttributeValue( action, "Attribute" ).AsGuid();
            if ( !guid.IsEmpty() )
            {
                var attribute = AttributeCache.Read( guid, rockContext );
                if ( attribute != null )
                {
                    string value = GetAttributeValue( action, "Value" );

                    value = value.ResolveMergeFields( GetMergeFields( action ) );

                    if ( attribute.EntityTypeId == new Rock.Model.Workflow().TypeId )
                    {
                        action.Activity.Workflow.SetAttributeValue( attribute.Key, value );
                        action.AddLogEntry( string.Format( "Set '{0}' attribute to '{1}'.", attribute.Name, value ) );
                    }
                    else if ( attribute.EntityTypeId == new Rock.Model.WorkflowActivity().TypeId )
                    {
                        action.Activity.SetAttributeValue( attribute.Key, value );
                        action.AddLogEntry( string.Format( "Set '{0}' attribute to '{1}'.", attribute.Name, value ) );
                    }
                }
            }

            return true;
        }
Beispiel #21
0
 /// <summary>
 /// Executes the specified workflow.
 /// </summary>
 /// <param name="rockContext">The rock context.</param>
 /// <param name="action">The action.</param>
 /// <param name="entity">The entity.</param>
 /// <param name="errorMessages">The error messages.</param>
 /// <returns></returns>
 public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
 {
     errorMessages = new List<string>();
     string message = GetAttributeValue( action, "Message" ).ResolveMergeFields( GetMergeFields( action ) );
     errorMessages.Add( message );
     return false;
 }
        /// <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();
        }
        /// <summary>
        /// Execute method to write transaction to the database.
        /// </summary>
        public void Execute()
        {
            using ( var rockContext = new RockContext() )
            {
                var docTypeService = new SignatureDocumentTemplateService( rockContext );
                var docService = new SignatureDocumentService( rockContext );

                var document = docService.Get( SignatureDocumentId );
                if ( document != null )
                {
                    var status = document.Status;
                    int? binaryFileId = document.BinaryFileId;
                    string folderPath = System.Web.Hosting.HostingEnvironment.MapPath( "~/App_Data/Cache/SignNow" );
                    var updateErrorMessages = new List<string>();

                    if ( docTypeService.UpdateDocumentStatus( document, folderPath, out updateErrorMessages ) )
                    {
                        if ( status != document.Status || !binaryFileId.Equals( document.BinaryFileId ) )
                        {
                            rockContext.SaveChanges();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Binds the package grid.
        /// </summary>
        public void BindPackageGrid()
        {
            using ( var rockContext = new RockContext() )
            {
                var definedValues = new DefinedValueService( rockContext )
                    .GetByDefinedTypeGuid( Rock.SystemGuid.DefinedType.PROTECT_MY_MINISTRY_PACKAGES.AsGuid() )
                    .ToList();

                foreach( var definedValue in definedValues )
                {
                    definedValue.LoadAttributes( rockContext );
                }

                gDefinedValues.DataSource = definedValues.Select( v => new
                {
                    v.Id,
                    v.Value,
                    v.Description,
                    PackageName = v.GetAttributeValue( "PMMPackageName" ),
                    DefaultCounty = v.GetAttributeValue( "DefaultCounty" ),
                    SendAddressCounty = v.GetAttributeValue( "SendHomeCounty" ).AsBoolean(),
                    DefaultState = v.GetAttributeValue( "DefaultState" ),
                    SendAddressState = v.GetAttributeValue( "SendHomeState" ).AsBoolean(),
                    MVRJurisdication = v.GetAttributeValue("MVRJurisdiction"),
                    SendAddressStateMVR = v.GetAttributeValue( "SendHomeStateMVR" ).AsBoolean()
                } )
                .ToList();
                gDefinedValues.DataBind();
            }
        }
        /// <summary>
        /// Binds the group members grid.
        /// </summary>
        protected void BindLayoutBlocksGrid()
        {
            pnlBlocks.Visible = false;

            int layoutId = PageParameter( "layoutId" ).AsInteger();
            if ( layoutId == 0 )
            {
                pnlContent.Visible = false;
                return;
            }

            var rockContext = new RockContext();
            var layout = LayoutCache.Read( layoutId, rockContext );
            if (layout == null)
            {
                pnlContent.Visible = false;
                return;
            }

            hfLayoutId.SetValue( layoutId );

            pnlBlocks.Visible = true;

            BlockService blockService = new BlockService( new RockContext() );

            gLayoutBlocks.DataSource = blockService.GetByLayout( layoutId ).ToList();
            gLayoutBlocks.DataBind();
        }
        /// <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;
        }
        public HttpResponseMessage CreatePersonAndFamily( [FromBody]PersonParameters personParameters )
        {
            var rockContext = new RockContext();
            var response = new HttpResponseMessage( HttpStatusCode.Created );

            try
            {
                rockContext.WrapTransaction( () =>
                {
                    var person = CreatePerson(personParameters, null, rockContext, false);
                    response.Content = new StringContent( person.Id.ToString() );
                } );
            }
            catch ( HttpResponseException exception )
            {
                return exception.Response;
            }
            catch ( Exception exception )
            {
                var errorResponse = new HttpResponseMessage( HttpStatusCode.InternalServerError );
                errorResponse.Content = new StringContent( exception.Message );
                return errorResponse;
            }

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

            if ( action.Activity.Workflow.InitiatorPersonAliasId.HasValue )
            {
                var personAlias = new PersonAliasService( rockContext ).Get( action.Activity.Workflow.InitiatorPersonAliasId.Value );
                if ( personAlias != null )
                {
                    // Get the attribute to set
                    Guid guid = GetAttributeValue( action, "PersonAttribute" ).AsGuid();
                    if ( !guid.IsEmpty() )
                    {
                        var personAttribute = AttributeCache.Read( guid, rockContext );
                        if ( personAttribute != null )
                        {
                            // If this is a person type attribute
                            if ( personAttribute.FieldTypeId == FieldTypeCache.Read( SystemGuid.FieldType.PERSON.AsGuid(), rockContext ).Id )
                            {
                                SetWorkflowAttributeValue( action, guid, personAlias.Guid.ToString() );
                            }
                            else if ( personAttribute.FieldTypeId == FieldTypeCache.Read( SystemGuid.FieldType.TEXT.AsGuid(), rockContext ).Id )
                            {
                                SetWorkflowAttributeValue( action, guid, personAlias.Person.FullName );
                            }
                        }
                    }
                }
            }

            return true;
        }
Beispiel #29
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            BlockType blockType;
            var rockContext = new RockContext();
            BlockTypeService blockTypeService = new BlockTypeService( rockContext );

            int blockTypeId = int.Parse( hfBlockTypeId.Value );

            if ( blockTypeId == 0 )
            {
                blockType = new BlockType();
                blockTypeService.Add( blockType );
            }
            else
            {
                BlockTypeCache.Flush( blockTypeId );
                blockType = blockTypeService.Get( blockTypeId );
            }

            blockType.Name = tbName.Text;
            blockType.Path = tbPath.Text;
            blockType.Description = tbDescription.Text;

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

            rockContext.SaveChanges();

            NavigateToParentPage();
        }
Beispiel #30
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();
        }
Beispiel #31
0
    private void ProcessSendGridEvent(SendGridEvent sendGridEvent, Rock.Data.RockContext rockContext)
    {
        Guid?actionGuid = null;
        Guid?communicationRecipientGuid = null;

        if (!string.IsNullOrWhiteSpace(sendGridEvent.WorkflowActionGuid))
        {
            actionGuid = sendGridEvent.WorkflowActionGuid.AsGuidOrNull();
        }

        if (!string.IsNullOrWhiteSpace(sendGridEvent.CommunicationRecipientGuid))
        {
            communicationRecipientGuid = sendGridEvent.CommunicationRecipientGuid.AsGuidOrNull();
        }

        if (actionGuid != null)
        {
            ProcessForWorkflow(actionGuid, rockContext, sendGridEvent);
        }

        if (communicationRecipientGuid != null)
        {
            ProcessForRecipient(communicationRecipientGuid, rockContext, sendGridEvent);
        }
    }
Beispiel #32
0
    private void ProcessSendGridEventListAsync(List <SendGridEvent> sendGridEvents)
    {
        var rockContext = new Rock.Data.RockContext();

        foreach (var sendGridEvent in sendGridEvents)
        {
            ProcessSendGridEvent(sendGridEvent, rockContext);
        }
    }
Beispiel #33
0
    private void ProcessForWorkflow(Guid?actionGuid, Rock.Data.RockContext rockContext, SendGridEvent payload)
    {
        RockLogger.Log.Debug(RockLogDomains.Communications, "ProcessForWorkflow {@payload}", payload);

        string status = string.Empty;

        switch (payload.EventType)
        {
        case "unsubscribe":
        case "delivered":
            status = SendEmailWithEvents.SENT_STATUS;
            break;

        case "click":
            status = SendEmailWithEvents.CLICKED_STATUS;
            break;

        case "open":
            status = SendEmailWithEvents.OPENED_STATUS;
            break;

        case "failed":
        case "dropped":
        case "blocked":
        case "bounce":
        case "bounced":
            status = SendEmailWithEvents.FAILED_STATUS;
            string message = payload.ServerResponse.IsNotNullOrWhiteSpace() ? payload.ServerResponse : payload.EventTypeReason;

            Rock.Communication.Email.ProcessBounce(
                payload.Email,
                Rock.Communication.BounceType.HardBounce,
                message,
                RockDateTime.ConvertLocalDateTimeToRockDateTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(payload.Timestamp).ToLocalTime()));
            break;
        }

        if (actionGuid != null && !string.IsNullOrWhiteSpace(status))
        {
            SendEmailWithEvents.UpdateEmailStatus(actionGuid.Value, status, payload.EventType, rockContext, true);
        }
    }
    /// <summary>
    /// Processes for workflow.
    /// </summary>
    /// <param name="eventType">Type of the event.</param>
    /// <param name="actionGuid">The action unique identifier.</param>
    /// <param name="rockContext">The rock context.</param>
    private void ProcessForWorkflow(Guid?actionGuid, Rock.Data.RockContext rockContext)
    {
        string status = string.Empty;

        switch (mailgunRequestPayload.EventType)
        {
        case "complained":
        case "unsubscribed":
        case "delivered":
            status = SendEmailWithEvents.SENT_STATUS;
            break;

        case "clicked":
            status = SendEmailWithEvents.CLICKED_STATUS;
            break;

        case "opened":
            status = SendEmailWithEvents.OPENED_STATUS;
            break;

        case "failed":
        case "dropped":
        case "suppress-bounce":
        case "bounced":
            status = SendEmailWithEvents.FAILED_STATUS;
            string message = mailgunRequestPayload.Notification.IsNotNullOrWhiteSpace() ? mailgunRequestPayload.Notification : mailgunRequestPayload.Description;

            Rock.Communication.Email.ProcessBounce(
                mailgunRequestPayload.Recipient,
                Rock.Communication.BounceType.HardBounce,
                message,
                RockDateTime.ConvertLocalDateTimeToRockDateTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(mailgunRequestPayload.TimeStamp).ToLocalTime()));
            break;
        }

        if (actionGuid != null && !string.IsNullOrWhiteSpace(status))
        {
            SendEmailWithEvents.UpdateEmailStatus(actionGuid.Value, status, mailgunRequestPayload.EventType, rockContext, true);
        }
    }
Beispiel #35
0
    /// <summary>
    /// Processes for workflow.
    /// </summary>
    /// <param name="eventType">Type of the event.</param>
    /// <param name="actionGuid">The action unique identifier.</param>
    /// <param name="rockContext">The rock context.</param>
    private void ProcessForWorkflow(string eventType, Guid?actionGuid, Rock.Data.RockContext rockContext)
    {
        string status = string.Empty;

        switch (eventType)
        {
        case "complained":
        case "unsubscribed":
        case "delivered":
            status = SendEmailWithEvents.SENT_STATUS;
            break;

        case "clicked":
            status = SendEmailWithEvents.CLICKED_STATUS;
            break;

        case "opened":
            status = SendEmailWithEvents.OPENED_STATUS;
            break;

        case "dropped":
        case "suppress-bounce":
        case "bounced":
            status = SendEmailWithEvents.FAILED_STATUS;
            int secs = request.Form["timestamp"].AsInteger();
            Rock.Communication.Email.ProcessBounce(
                request.Form["recipient"],
                Rock.Communication.BounceType.HardBounce,
                request.Form["notification"],
                RockDateTime.ConvertLocalDateTimeToRockDateTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(secs).ToLocalTime()));
            break;
        }

        if (actionGuid != null && !string.IsNullOrWhiteSpace(status))
        {
            SendEmailWithEvents.UpdateEmailStatus(actionGuid.Value, status, eventType, rockContext, true);
        }
    }
Beispiel #36
0
    private void ProcessRequest()
    {
        var rockContext = new Rock.Data.RockContext();

        // We need to get the transport type now that there are two
        var emailMediumEntity = EntityTypeCache.Get("Rock.Communication.Medium.Email");

        var emailMediumAttribute = new AttributeService(rockContext)
                                   .Queryable()
                                   .Where(a => a.EntityTypeId == emailMediumEntity.Id && a.Key == "TransportContainer")
                                   .FirstOrDefault();

        var emailMediumAttributeValue = new AttributeValueService(rockContext)
                                        .Queryable()
                                        .Where(v => v.AttributeId == emailMediumAttribute.Id)
                                        .FirstOrDefault();

        string apiKey = string.Empty;

        var mailgunEntity = EntityTypeCache.Get(emailMediumAttributeValue.Value.AsGuid(), rockContext);

        if (mailgunEntity != null)
        {
            apiKey = new AttributeValueService(rockContext)
                     .Queryable()
                     .AsNoTracking()
                     .Where(v => v.Attribute.EntityTypeId == mailgunEntity.Id && v.Attribute.Key == "APIKey")
                     .Select(v => v.Value)
                     .FirstOrDefault();
        }

        if (!Rock.Mailgun.MailgunUtilities.AuthenticateMailgunRequest(mailgunRequestPayload.TimeStamp, mailgunRequestPayload.Token, mailgunRequestPayload.Signature, apiKey))
        {
            response.Write("Invalid request signature.");
            response.StatusCode = 406;
            return;
        }

        Guid?actionGuid = null;
        Guid?communicationRecipientGuid = null;

        if (!string.IsNullOrWhiteSpace(mailgunRequestPayload.WorkflowActionGuid))
        {
            actionGuid = mailgunRequestPayload.WorkflowActionGuid.Split(',')[0].AsGuidOrNull();
        }

        if (!string.IsNullOrWhiteSpace(mailgunRequestPayload.CommunicationRecipientGuid))
        {
            communicationRecipientGuid = mailgunRequestPayload.CommunicationRecipientGuid.Split(',')[0].AsGuidOrNull();
        }

        if (!string.IsNullOrWhiteSpace(mailgunRequestPayload.XMailgunVariables))
        {
            // for http sent email, mailgun puts the info as URL encoded JSON into the form key "X-Mailgun-Variables"
            string mailgunVariables = HttpContext.Current.Server.UrlDecode(mailgunRequestPayload.XMailgunVariables);
            if (mailgunVariables.IsNotNullOrWhiteSpace())
            {
                var mailgunVarDictionary = JsonConvert.DeserializeObject <Dictionary <string, string> >(mailgunVariables);

                if (actionGuid == null && mailgunVarDictionary.ContainsKey("workflow_action_guid"))
                {
                    actionGuid = mailgunVarDictionary["workflow_action_guid"].AsGuidOrNull();
                }

                if (communicationRecipientGuid == null && mailgunVarDictionary.ContainsKey("communication_recipient_guid"))
                {
                    communicationRecipientGuid = mailgunVarDictionary["communication_recipient_guid"].AsGuidOrNull();
                }
            }
        }

        if (actionGuid != null)
        {
            ProcessForWorkflow(actionGuid, rockContext);
        }

        if (communicationRecipientGuid != null)
        {
            ProcessForReceipent(communicationRecipientGuid, rockContext);
        }

        response.Write(string.Format("Successfully processed '{0}' message", mailgunRequestPayload.EventType));
        response.StatusCode = ( int )System.Net.HttpStatusCode.OK;
    }
Beispiel #37
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 #38
0
        public override bool Execute(Rock.Data.RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();
            var castedModel = entity as IModel;

            if (castedModel != null)
            {
                var restUserGuid = GetAttributeValue(action, "RestUser").AsType <Guid?>();

                if (castedModel.ModifiedByPersonAliasId.HasValue)
                {
                    var modifier = new PersonAliasService(new RockContext()).Get(castedModel.ModifiedByPersonAliasId.Value);

                    if (modifier.Guid == restUserGuid)
                    {
                        // If the modifier is Apollos, don't send the data to Apollos (bounceback sync)
                        return(true);
                    }
                }
                else if (castedModel.CreatedByPersonAliasId.HasValue)
                {
                    var modifier = new PersonAliasService(new RockContext()).Get(castedModel.CreatedByPersonAliasId.Value);

                    if (modifier.Guid == restUserGuid)
                    {
                        return(true);
                    }
                }
            }

            var castedEntity = entity as IEntity;
            var isSave       = GetAttributeValue(action, "Action") == "Save";
            var url          = GetAttributeValue(action, "SyncURL");
            var tokenName    = GetAttributeValue(action, "TokenName");
            var tokenValue   = GetAttributeValue(action, "TokenValue");
            var lastSlash    = "/";

            if (string.IsNullOrWhiteSpace(url))
            {
                return(true);
            }

            if (url.EndsWith(lastSlash))
            {
                lastSlash = string.Empty;
            }

            var request = new RestRequest(isSave ? Method.POST : Method.DELETE);

            request.RequestFormat = DataFormat.Json;
            request.AddHeader(tokenName, tokenValue);

            var fullUrl = string.Format("{0}{1}{2}", url, lastSlash, castedEntity.Id);
            var client  = new RestClient(fullUrl);

            if (isSave)
            {
                request.JsonSerializer = new NewtonsoftJsonSerializer(request.JsonSerializer);

                if (!(entity is UserLogin))
                {
                    request.AddJsonBody(entity);
                }
                else
                {
                    // Do this so the password hash is synced
                    var apollosUser = new ApollosUserLogin((UserLogin)entity);
                    request.AddJsonBody(apollosUser);
                }
            }

            var response = client.Execute(request);

            return(true);
        }
Beispiel #39
0
 /// <summary>
 /// Allows the security role.
 /// </summary>
 /// <param name="action">The action.</param>
 /// <param name="group">The group.</param>
 /// <param name="rockContext">The rock context.</param>
 public virtual void AllowSecurityRole(string action, Group group, RockContext rockContext = null)
 {
     Security.Authorization.AllowSecurityRole(this, action, group, rockContext);
 }
Beispiel #40
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
                });
            }
        }
        public Person GetCurrentPerson()
        {
            var rockContext = new Rock.Data.RockContext();

            return(new PersonService(rockContext).Get(GetPerson().Id));
        }
        public IQueryable <Person> GetByPhoneNumber(string number)
        {
            var rockContext = new Rock.Data.RockContext();

            return(new PersonService(rockContext).GetByPhonePartial(number, true).Include(a => a.Aliases));
        }
Beispiel #43
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 #44
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 #45
0
        /// <summary>
        /// Gets the next pending.
        /// </summary>
        /// <param name="communicationId">The communication identifier.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        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 #46
0
        public static IEnumerable <Person> GetByMatch(this PersonService personService, String firstName, String lastName, DateTime?birthDate, String email = null, String phone = null, String street1 = null, String postalCode = null, bool createNameless = false)
        {
            using (Rock.Data.RockContext context = new Rock.Data.RockContext())
            {
                //FirstName LastName and (DOB or email or phone or street address) are required. If not return an empty list.
                if (firstName.IsNullOrWhiteSpace() || lastName.IsNullOrWhiteSpace() ||
                    (!birthDate.HasValue &&
                     email.IsNullOrWhiteSpace() &&
                     phone.IsNullOrWhiteSpace() &&
                     street1.IsNullOrWhiteSpace()))
                {
                    if (createNameless && (email.IsNotNullOrWhiteSpace() || phone.IsNotNullOrWhiteSpace()))
                    {
                        return(new List <Person> {
                            GetOrCreateNamelessPerson(email, phone, personService)
                        });
                    }
                    else
                    {
                        return(new List <Person>());
                    }
                }

                LocationService       locationService       = new LocationService(context);
                AttributeValueService attributeValueService = new AttributeValueService(context);
                List <AttributeValue> attributeValues       = attributeValueService.GetByAttributeId(AttributeCache.Get(GOES_BY_ATTRIBUTE.AsGuid()).Id).ToList();
                var diminutiveName = DefinedTypeCache.Get(DIMINUTIVE_NAMES.AsGuid());

                firstName = firstName ?? string.Empty;
                lastName  = lastName ?? string.Empty;
                email     = email.ToLower() ?? string.Empty;
                phone     = PhoneNumber.CleanNumber(phone ?? string.Empty);
                List <Person> matchingPersons = new List <Person>();

                // Do a quick check to see if we get a match right up front
                List <Person> persons = new List <Person>();
                if (birthDate.HasValue || !string.IsNullOrEmpty(email))
                {
                    var fastQuery = personService.Queryable(false, false).Where(p => (p.FirstName.ToLower() == firstName.ToLower() || p.NickName.ToLower() == firstName.ToLower()) && p.LastName == lastName);
                    if (birthDate.HasValue)
                    {
                        fastQuery = fastQuery.Where(p => p.BirthDate == birthDate);
                    }
                    if (!String.IsNullOrEmpty(email))
                    {
                        fastQuery = fastQuery.Where(p => p.Email.ToLower() == email);
                    }
                    persons = fastQuery.ToList();

                    // We have an exact match.  Just be done.
                    if (persons.Count == 1)
                    {
                        return(persons);
                    }
                }

                // Go ahead and do this more leniant search if we get this far
                persons = personService.Queryable(false, false)
                          .Where(p =>
                                 p.LastName == lastName &&
                                 (!birthDate.HasValue || p.BirthDate == null || (birthDate.HasValue && p.BirthDate.Value == birthDate.Value)))
                          .ToList();

                // Set a placeholder for the location so we only geocode it 1 time
                Location location = null;

                foreach (Person person in persons)
                {
                    // Check to see if the phone exists anywhere in the family
                    Boolean phoneExists = !string.IsNullOrWhiteSpace(phone) && person.GetFamilies().Where(f => f.Members.Where(m => m.Person.PhoneNumbers.Where(pn => pn.Number == phone).Any()).Any()).Any();

                    // Check to see if the email exists anywhere in the family
                    Boolean emailExists = !string.IsNullOrWhiteSpace(email) && person.GetFamilies().Where(f => f.Members.Where(m => m.Person.Email == email).Any()).Any();

                    Boolean addressMatches = false;
                    // Check the address if it was passed
                    if (!string.IsNullOrEmpty(street1) && !string.IsNullOrEmpty(postalCode))
                    {
                        if (person.GetHomeLocation() != null)
                        {
                            if (person.GetHomeLocation().Street1 == street1)
                            {
                                addressMatches = true;
                            }
                            // If it doesn't match, we need to geocode it and check it again
                            if (location == null && !string.IsNullOrEmpty(street1) && !string.IsNullOrEmpty(postalCode))
                            {
                                location            = new Location();
                                location.Street1    = street1;
                                location.PostalCode = postalCode;
                                locationService.Verify(location, true);
                            }
                            if (location != null && !addressMatches && person.GetHomeLocation().Street1 == location.Street1)
                            {
                                addressMatches = true;
                            }
                        }
                    }

                    // At least phone, email, or address have to match
                    if (phoneExists || emailExists || addressMatches)
                    {
                        matchingPersons.Add(person);
                    }
                }

                List <Person> firstNameMatchingPersons = new List <Person>();

                // Now narrow down the list by looking for the first name (or diminutive name)
                foreach (Person matchingPerson in matchingPersons)
                {
                    if (firstName != null && ((matchingPerson.FirstName != null && matchingPerson.FirstName.ToLower() != firstName.ToLower()) || (matchingPerson.NickName != null && matchingPerson.NickName.ToLower() != firstName.ToLower())))
                    {
                        foreach (DefinedValueCache dv in diminutiveName.DefinedValues)
                        {
                            AttributeValue av       = attributeValues.Where(av2 => av2.EntityId == dv.Id).FirstOrDefault();
                            List <string>  nameList = new List <string>();
                            nameList = av.Value.Split('|').ToList();
                            nameList.Add(dv.Value);
                            if (nameList.Contains(firstName.ToLower()) &&
                                (nameList.Contains(matchingPerson.FirstName.ToLower()) || nameList.Contains(matchingPerson.NickName.ToLower())))
                            {
                                firstNameMatchingPersons.Add(matchingPerson);
                                break;
                            }
                        }
                    }
                    else
                    {
                        firstNameMatchingPersons.Add(matchingPerson);
                    }
                }

                return(firstNameMatchingPersons);
            }
        }
Beispiel #47
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="fromPhone">From 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, DefinedValueCache fromPhone, string responseCode, Rock.Data.RockContext rockContext)
        {
            // add communication for reply
            var communication = new Rock.Model.Communication();

            communication.Name = string.Format("From: {0}", fromPersonName);
            communication.CommunicationType   = CommunicationType.SMS;
            communication.SenderPersonAliasId = fromPersonAliasId;
            communication.IsBulkCommunication = false;
            communication.Status                = CommunicationStatus.Approved;
            communication.SMSMessage            = message;
            communication.SMSFromDefinedValueId = fromPhone.Id;

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

            recipient.Status             = CommunicationRecipientStatus.Pending;
            recipient.PersonAliasId      = toPersonAliasId;
            recipient.ResponseCode       = responseCode;
            recipient.MediumEntityTypeId = EntityTypeCache.Read("Rock.Communication.Medium.Sms").Id;
            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);
        }
Beispiel #48
0
 /// <summary>
 /// Get a list of all inherited Attributes that should be applied to this entity.
 /// </summary>
 /// <returns>A list of all inherited AttributeCache objects.</returns>
 public override List <AttributeCache> GetInheritedAttributes(Rock.Data.RockContext rockContext)
 {
     return(GetInheritedAttributesForQualifier(rockContext, TypeId, "Id"));
 }
Beispiel #49
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());
        }
        public PersonSearchResult GetPopupHtml(int personId, bool emailAsLink)
        {
            var result = new PersonSearchResult();

            result.Id = personId;
            result.PickerItemDetailsHtml = "No Details Available";

            var html = new StringBuilder();

            // Create new service (need ProxyServiceEnabled)
            var rockContext = new Rock.Data.RockContext();
            var person      = new PersonService(rockContext).Queryable("ConnectionStatusValue, PhoneNumbers")
                              .Where(p => p.Id == personId)
                              .FirstOrDefault();

            if (person != null)
            {
                Guid?recordTypeValueGuid = null;
                if (person.RecordTypeValueId.HasValue)
                {
                    recordTypeValueGuid = DefinedValueCache.Get(person.RecordTypeValueId.Value).Guid;
                }

                var appPath = System.Web.VirtualPathUtility.ToAbsolute("~");
                html.AppendFormat(
                    "<header>{0} <h3>{1}<small>{2}</small></h3></header>",
                    Person.GetPersonPhotoImageTag(person, 65, 65),
                    person.FullName,
                    person.ConnectionStatusValue != null ? person.ConnectionStatusValue.Value : string.Empty);

                html.Append("<div class='body'>");

                var spouse = person.GetSpouse(rockContext);
                if (spouse != null)
                {
                    html.AppendFormat(
                        "<div><strong>Spouse</strong> {0}</div>",
                        spouse.LastName == person.LastName ? spouse.FirstName : spouse.FullName);
                }

                int?age = person.Age;
                if (age.HasValue)
                {
                    html.AppendFormat("<div><strong>Age</strong> {0}</div>", age);
                }

                if (!string.IsNullOrWhiteSpace(person.Email))
                {
                    if (emailAsLink)
                    {
                        html.AppendFormat("<div style='text-overflow: ellipsis; white-space: nowrap; overflow:hidden; width: 245px;'><strong>Email</strong> {0}</div>", person.GetEmailTag(VirtualPathUtility.ToAbsolute("~/")));
                    }
                    else
                    {
                        html.AppendFormat("<div style='text-overflow: ellipsis; white-space: nowrap; overflow:hidden; width: 245px;'><strong>Email</strong> {0}</div>", person.Email);
                    }
                }

                foreach (var phoneNumber in person.PhoneNumbers.Where(n => n.IsUnlisted == false && n.NumberTypeValueId.HasValue).OrderBy(n => n.NumberTypeValue.Order))
                {
                    html.AppendFormat("<div><strong>{0}</strong> {1}</div>", phoneNumber.NumberTypeValue.Value, phoneNumber.ToString());
                }

                html.Append("</div>");

                result.PickerItemDetailsHtml = html.ToString();
            }

            return(result);
        }
Beispiel #51
0
    /// <summary>
    /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler" /> interface.
    /// </summary>
    /// <param name="context">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
    public void ProcessRequest(HttpContext context)
    {
        request              = context.Request;
        response             = context.Response;
        response.ContentType = "text/plain";

        if (request.HttpMethod != "POST")
        {
            response.Write("Invalid request type.");
            response.StatusCode = 406;
            return;
        }

        int    timestamp = request.Form["timestamp"].AsInteger();
        string token     = request.Form["token"];
        string signature = request.Form["signature"];
        string apiKey    = string.Empty;

        using (var rockContext = new Rock.Data.RockContext())
        {
            // We need to get the transport type now that there are two
            var emailMediumEntity = EntityTypeCache.Get("Rock.Communication.Medium.Email");

            var emailMediumAttribute = new AttributeService(rockContext)
                                       .Queryable()
                                       .Where(a => a.EntityTypeId == emailMediumEntity.Id && a.Key == "TransportContainer")
                                       .FirstOrDefault();

            var emailMediumAttributeValue = new AttributeValueService(rockContext)
                                            .Queryable()
                                            .Where(v => v.AttributeId == emailMediumAttribute.Id)
                                            .FirstOrDefault();

            var mailgunEntity = EntityTypeCache.Get(emailMediumAttributeValue.Value.AsGuid(), rockContext);

            if (mailgunEntity != null)
            {
                apiKey = new AttributeValueService(rockContext)
                         .Queryable()
                         .AsNoTracking()
                         .Where(v => v.Attribute.EntityTypeId == mailgunEntity.Id && v.Attribute.Key == "APIKey")
                         .Select(v => v.Value)
                         .FirstOrDefault();
            }

            if (!Rock.Mailgun.MailgunUtilities.AuthenticateMailgunRequest(timestamp, token, signature, apiKey))
            {
                response.Write("Invalid request signature.");
                response.StatusCode = 406;
                return;
            }

            string eventType  = request.Form["event"];
            Guid?  actionGuid = null;
            Guid?  communicationRecipientGuid = null;

            if (!string.IsNullOrWhiteSpace(request.Form["workflow_action_guid"]))
            {
                actionGuid = request.Form["workflow_action_guid"].Split(',')[0].AsGuidOrNull();
            }

            if (!string.IsNullOrWhiteSpace(request.Form["communication_recipient_guid"]))
            {
                communicationRecipientGuid = request.Form["communication_recipient_guid"].Split(',')[0].AsGuidOrNull();
            }

            if (!string.IsNullOrWhiteSpace(request.Form["X-Mailgun-Variables"]))
            {
                // for http sent email, mailgun puts the info as URL encoded JSON into the form key "X-Mailgun-Variables"
                string mailgunVariables = HttpContext.Current.Server.UrlDecode(request.Form["X-Mailgun-Variables"]);
                if (mailgunVariables.IsNotNullOrWhiteSpace())
                {
                    var mailgunVarDictionary = JsonConvert.DeserializeObject <Dictionary <string, string> >(mailgunVariables);
                    actionGuid = mailgunVarDictionary.ContainsKey("workflow_action_guid") ? mailgunVarDictionary["workflow_action_guid"].AsGuidOrNull() : null;
                    communicationRecipientGuid = mailgunVarDictionary.ContainsKey("communication_recipient_guid") ? mailgunVarDictionary["communication_recipient_guid"].AsGuidOrNull() : null;
                }
            }

            if (actionGuid != null)
            {
                ProcessForWorkflow(eventType, actionGuid, rockContext);
            }

            if (communicationRecipientGuid != null)
            {
                ProcessForReceipent(eventType, communicationRecipientGuid, rockContext);
            }

            response.Write(string.Format("Successfully processed '{0}' message", eventType));
            response.StatusCode = 200;
        }
    }
        public IQueryable <Person> GetByEmail(string email)
        {
            var rockContext = new Rock.Data.RockContext();

            return(new PersonService(rockContext).GetByEmail(email, true).Include(a => a.Aliases));
        }
Beispiel #53
0
        /// <summary>
        /// Creates the communication to the recipient'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)
        {
            // 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 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);
        }
Beispiel #54
0
        /// <summary>
        /// Process inbound messages that are sent to a SMS number.
        /// </summary>
        /// <param name="toPhone">The phone number a message is sent to.</param>
        /// <param name="fromPhone">The phone number a message is sent from.</param>
        /// <param name="message">The message that was sent.</param>
        /// <param name="errorMessage">The error message.</param>
        public void ProcessResponse(string toPhone, string fromPhone, string message, out string errorMessage)
        {
            errorMessage = string.Empty;

            string transportPhone = string.Empty;

            using (Rock.Data.RockContext rockContext = new Rock.Data.RockContext())
            {
                Person toPerson = null;

                // get from person
                var fromPerson = new PersonService(rockContext).Queryable()
                                 .Where(p => p.PhoneNumbers.Any(n => (n.CountryCode + n.Number) == fromPhone.Replace("+", "")))
                                 .OrderBy(p => p.Id).FirstOrDefault();      // order by person id to get the oldest person to help with duplicate records of the response recipient

                // get recipient from defined value
                var definedType = DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.COMMUNICATION_SMS_FROM.AsGuid());
                if (definedType != null)
                {
                    if (definedType.DefinedValues != null && definedType.DefinedValues.Any())
                    {
                        var matchValue = definedType.DefinedValues.Where(v => v.Value == toPhone).OrderBy(v => v.Order).FirstOrDefault();
                        if (matchValue != null)
                        {
                            transportPhone = matchValue.Id.ToString();
                            var toPersonAliasGuid = matchValue.GetAttributeValue("ResponseRecipient").AsGuidOrNull();
                            if (toPersonAliasGuid.HasValue)
                            {
                                toPerson = new PersonAliasService(rockContext)
                                           .Queryable().Where(p => p.Guid.Equals(toPersonAliasGuid.Value))
                                           .Select(p => p.Person)
                                           .FirstOrDefault();
                            }
                        }
                    }
                }

                if (fromPerson != null && toPerson != null && fromPerson.PrimaryAliasId.HasValue && toPerson.PrimaryAliasId.HasValue)
                {
                    if (toPerson.Id == fromPerson.Id)   // message from the medium recipient
                    {
                        // look for response code in the message
                        Match match = Regex.Match(message, @"@\d{3}");
                        if (match.Success)
                        {
                            string responseCode = match.ToString();

                            var recipient = new CommunicationRecipientService(rockContext).Queryable("Communication")
                                            .Where(r => r.ResponseCode == responseCode)
                                            .OrderByDescending(r => r.CreatedDateTime).FirstOrDefault();

                            if (recipient != null && recipient.Communication.SenderPersonAliasId.HasValue)
                            {
                                CreateCommunication(fromPerson.PrimaryAliasId.Value, fromPerson.FullName, recipient.Communication.SenderPersonAliasId.Value, message.Replace(responseCode, ""), transportPhone, "", rockContext);
                            }
                            else // send a warning message back to the medium recipient
                            {
                                string warningMessage = string.Format("A conversation could not be found with the response token {0}.", responseCode);
                                CreateCommunication(fromPerson.PrimaryAliasId.Value, fromPerson.FullName, fromPerson.PrimaryAliasId.Value, warningMessage, transportPhone, "", rockContext);
                            }
                        }
                    }
                    else // response from someone other than the medium recipient
                    {
                        string messageId = GenerateResponseCode(rockContext);
                        message = string.Format("-{0}-\n{1}\n( {2} )", fromPerson.FullName, message, messageId);
                        CreateCommunication(fromPerson.PrimaryAliasId.Value, fromPerson.FullName, toPerson.PrimaryAliasId.Value, message, transportPhone, messageId, rockContext);
                    }
                }
                else
                {
                    var    globalAttributes = Rock.Web.Cache.GlobalAttributesCache.Read();
                    string organizationName = globalAttributes.GetValue("OrganizationName");

                    errorMessage = string.Format("Could not deliver message. This phone number is not registered in the {0} database.", organizationName);
                }
            }
        }
Beispiel #55
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);

            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();
        }
        /// <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 #57
0
        /// <summary>
        /// Creates a new communication.
        /// </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 to send.</param>
        /// <param name="plainMessage">The plain message.</param>
        /// <param name="rockSmsFromPhoneDv">From 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>
        /// <param name="errorMessage">The error message.</param>
        private void CreateCommunication(Person fromPerson, string messageKey, int?toPersonAliasId, string message, string plainMessage, DefinedValueCache rockSmsFromPhoneDv, string responseCode, Rock.Data.RockContext rockContext, out string errorMessage)
        {
            errorMessage = string.Empty;

            try
            {
                LaunchWorkflow(fromPerson?.PrimaryAliasId, messageKey, message, toPersonAliasId, rockSmsFromPhoneDv);
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
                // Log error and continue, don't stop because the workflow failed.
                ExceptionLogService.LogException(ex);
            }

            // See if this should go to a phone or to the DB. Default is to the phone so if for some reason we get a null here then just send it to the phone.
            var enableResponseRecipientForwarding = rockSmsFromPhoneDv.GetAttributeValue("EnableResponseRecipientForwarding").AsBooleanOrNull() ?? true;

            // NOTE: FromPerson should never be null

            if (enableResponseRecipientForwarding)
            {
                CreateCommunicationMobile(fromPerson, toPersonAliasId, message, rockSmsFromPhoneDv, responseCode, rockContext);
            }

            CreateCommunicationResponse(fromPerson, messageKey, toPersonAliasId, plainMessage, rockSmsFromPhoneDv, responseCode, rockContext);
        }
Beispiel #58
0
 /// <summary>
 /// If the action on the current entity is private, removes the auth rules that made it private.
 /// </summary>
 /// <param name="action">The action.</param>
 /// <param name="person">The person.</param>
 /// <param name="rockContext">The rock context.</param>
 public virtual void MakeUnPrivate(string action, Person person, RockContext rockContext = null)
 {
     Security.Authorization.MakeUnPrivate(this, action, person, rockContext);
 }
Beispiel #59
0
 /// <summary>
 /// Adds an 'Allow' rule for the current person as the first rule for the selected action
 /// </summary>
 /// <param name="action">The action.</param>
 /// <param name="person">The person.</param>
 /// <param name="rockContext">The rock context.</param>
 public virtual void AllowPerson(string action, Person person, RockContext rockContext = null)
 {
     Security.Authorization.AllowPerson(this, action, person, rockContext);
 }