/// <summary>
        /// Called during serialization to write an object of the specified type to the specified stream.
        /// </summary>
        /// <param name="type">The type of the object to write.</param>
        /// <param name="value">The object to write.</param>
        /// <param name="writeStream">The stream to write to.</param>
        /// <param name="effectiveEncoding">The encoding to use when writing.</param>
        public override void WriteToStream(Type type, object value, System.IO.Stream writeStream, Encoding effectiveEncoding)
        {
            // query should be filtered by now, so iterate thru items and load attributes before the response is serialized
            if (LoadAttributes)
            {
                if (value is IEnumerable <Rock.Attribute.IHasAttributes> )
                {
                    var rockContext = new Rock.Data.RockContext();

                    // if the REST call specified that Attributes should be loaded and we are returning a list of IHasAttributes..
                    foreach (var item in value as IEnumerable <Rock.Attribute.IHasAttributes> )
                    {
                        item.LoadAttributes(rockContext);
                    }
                }
                else if (value is Rock.Attribute.IHasAttributes)
                {
                    var rockContext = new Rock.Data.RockContext();

                    // if the REST call specified that Attributes should be loaded and we are returning a single IHasAttributes..
                    (value as Rock.Attribute.IHasAttributes).LoadAttributes(rockContext);
                }
            }

            base.WriteToStream(type, value, writeStream, effectiveEncoding);
        }
        /// <summary>
        /// Returns a new <see cref="Rock.Model.AttendanceCode"/>
        /// </summary>
        /// <param name="codeLength">A <see cref="System.Int32"/> representing the length of the (security) code.</param>
        /// <returns>A new <see cref="Rock.Model.AttendanceCode"/></returns>
        public static AttendanceCode GetNew(int codeLength = 3)
        {
            string code = string.Empty;

            var attendanceCode = new AttendanceCode();

            var rockContext = new Rock.Data.RockContext();
            var service = new AttendanceCodeService( rockContext );

            // Make sure only one instance at a time is checking for unique code
            lock (obj)
            {
                // Find a good unique code for today
                while ( code == string.Empty ||
                    noGood.Any( s => s == code ) ||
                    service.Get( RockDateTime.Today, code ).Any() )
                {
                    code = GenerateRandomCode( codeLength );
                }

                attendanceCode.IssueDateTime = RockDateTime.Now;
                attendanceCode.Code = code;
                service.Add( attendanceCode );
                rockContext.SaveChanges();
            }

            return attendanceCode;
        }
Example #3
0
        public IHttpActionResult UpdateDeviceRegistrationByGuid(Guid personalDeviceGuid, string registration, bool?notificationsEnabled = null)
        {
            using (var rockContext = new Rock.Data.RockContext())
            {
                var service = new PersonalDeviceService(rockContext);

                // MAC address
                var personalDevice = service.Get(personalDeviceGuid);
                if (personalDevice == null)
                {
                    return(NotFound());
                }

                personalDevice.DeviceRegistrationId = registration;

                if (notificationsEnabled.HasValue)
                {
                    personalDevice.NotificationsEnabled = notificationsEnabled.Value;
                }

                rockContext.SaveChanges();

                return(Ok());
            }
        }
Example #4
0
        /// <summary>
        /// Gets the payments that have been processed for any scheduled transactions
        /// </summary>
        /// <param name="financialGateway">The financial gateway.</param>
        /// <param name="startDate">The start date.</param>
        /// <param name="endDate">The end date.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        public override List <Payment> GetPayments(FinancialGateway financialGateway, DateTime startDate, DateTime endDate, out string errorMessage)
        {
            errorMessage = string.Empty;
            var fakePayments             = new List <Payment>();
            var randomNumberOfPayments   = new Random().Next(1, 1000);
            var rockContext              = new Rock.Data.RockContext();
            var scheduledTransactionList = new FinancialScheduledTransactionService(rockContext).Queryable().ToList();

            var transactionDateTime = startDate;

            for (int paymentNumber = 0; paymentNumber < randomNumberOfPayments; paymentNumber++)
            {
                var scheduledTransaction = scheduledTransactionList.OrderBy(a => a.Guid).FirstOrDefault();
                var fakePayment          = new Payment
                {
                    Amount = scheduledTransaction.TotalAmount,
                    TransactionDateTime = startDate,
                    CreditCardTypeValue = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.FINANCIAL_CREDIT_CARD_TYPE.AsGuid()).DefinedValues.OrderBy(a => Guid.NewGuid()).First(),
                    CurrencyTypeValue   = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD.AsGuid()),
                    TransactionCode     = Guid.NewGuid().ToString("N"),
                    GatewayScheduleId   = scheduledTransaction.GatewayScheduleId
                };

                fakePayments.Add(fakePayment);
            }


            return(fakePayments);
        }
Example #5
0
        /// <summary>
        /// Purges the exception log.
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private void PurgeExceptionLog(JobDataMap dataMap)
        {
            int?exceptionExpireDays = dataMap.GetString("DaysKeepExceptions").AsIntegerOrNull();

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

                // delete in chunks (see http://dba.stackexchange.com/questions/1750/methods-of-speeding-up-a-huge-delete-from-table-with-no-clauses)
                bool keepDeleting = true;
                while (keepDeleting)
                {
                    var dbTransaction = exceptionLogRockContext.Database.BeginTransaction();
                    try
                    {
                        int rowsDeleted = exceptionLogRockContext.Database.ExecuteSqlCommand(@"DELETE TOP (1000) FROM [ExceptionLog] WHERE [CreatedDateTime] < @createdDateTime", new SqlParameter("createdDateTime", exceptionExpireDate));
                        keepDeleting = rowsDeleted > 0;
                    }
                    finally
                    {
                        dbTransaction.Commit();
                    }
                }
            }
        }
        public Rock.Model.Workflow WorkflowEntry(int workflowTypeId)
        {
            var rockContext         = new Rock.Data.RockContext();
            var workflowTypeService = new WorkflowTypeService(rockContext);
            var workflowType        = workflowTypeService.Get(workflowTypeId);

            if (workflowType != null)
            {
                var workflow = Rock.Model.Workflow.Activate(workflowType, "Workflow From REST");

                // set workflow attributes from querystring
                foreach (var parm in Request.GetQueryStrings())
                {
                    workflow.SetAttributeValue(parm.Key, parm.Value);
                }

                // save -> run workflow
                List <string> workflowErrors;
                new Rock.Model.WorkflowService(rockContext).Process(workflow, out workflowErrors);

                var response = ControllerContext.Request.CreateResponse(HttpStatusCode.Created);
                return(workflow);
            }
            else
            {
                var response = ControllerContext.Request.CreateResponse(HttpStatusCode.NotFound);
            }

            return(null);
        }
Example #7
0
        /// <summary>
        /// Purges the audit log.
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private void PurgeAuditLog(JobDataMap dataMap)
        {
            // purge audit log
            int?auditExpireDays = dataMap.GetString("AuditLogExpirationDays").AsIntegerOrNull();

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

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

                auditLogRockContext.SaveChanges();
            }
        }
Example #8
0
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="entityIdProperty">The entity identifier property.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override System.Linq.Expressions.Expression GetExpression(Rock.Data.RockContext context, System.Linq.Expressions.MemberExpression entityIdProperty, string selection)
        {
            var attributeValueService           = new AttributeValueService(context);
            var roomReservationGroupAttGuid     = ZoomGuid.Attribute.ROOM_RESERVATION_GROUP_ATTRIBUTE.AsGuid();
            var reservationLocationEntityTypeId = new EntityTypeService(context).GetNoTracking(com.bemaservices.RoomManagement.SystemGuid.EntityType.RESERVATION_LOCATION.AsGuid()).Id;

            var resGroupAttValues = attributeValueService.Queryable()
                                    .Where(x => x.Attribute.Guid == roomReservationGroupAttGuid)
                                    .Select(x => new { EntityId = x.EntityId, Value = x.Value });

            var groupQuery = new GroupService(context).Queryable()
                             .Select(g => new { GuidString = g.Guid.ToString(), GroupName = g.Name + " (" + g.Id.ToString() + ")" });

            var reservationQuery = new ReservationService(context).Queryable()
                                   .Select(r => new { r.Id });

            var reservationlocationQuery = new ReservationLocationService(context).Queryable()
                                           .Select(rl => new { rl.Id, rl.ReservationId });

            var occurrenceService = new RoomOccurrenceService(context);

            var resultQuery = occurrenceService.Queryable("ReservationLocation")
                              .Select(ro => groupQuery.FirstOrDefault(g => resGroupAttValues.FirstOrDefault(v => reservationQuery.FirstOrDefault(r => reservationlocationQuery.FirstOrDefault(rl => ro.EntityTypeId == reservationLocationEntityTypeId && rl.Id == ro.EntityId).ReservationId == r.Id).Id == v.EntityId).Value.Contains(g.GuidString)).GroupName);

            return(SelectExpressionExtractor.Extract(resultQuery, entityIdProperty, "ro"));
        }
        /// <summary> 
        /// Job that updates the JobPulse setting with the current date/time.
        /// This will allow us to notify an admin if the jobs stop running.
        /// 
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void  Execute(IJobExecutionContext context)
        {
            // get the job map
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            int maxRecords = Int32.Parse( dataMap.GetString( "MaxRecordsPerRun" ) );
            int throttlePeriod = Int32.Parse( dataMap.GetString( "ThrottlePeriod" ) );
            int retryPeriod = Int32.Parse( dataMap.GetString( "RetryPeriod" ) );

            DateTime retryDate = DateTime.Now.Subtract(new TimeSpan(retryPeriod, 0, 0, 0));

            var rockContext = new Rock.Data.RockContext();
            LocationService locationService = new LocationService(rockContext);
            var addresses = locationService.Queryable()
                                .Where( l => (
                                    (l.IsGeoPointLocked == null || l.IsGeoPointLocked == false) // don't ever try locked address
                                    && (l.IsActive == true && l.Street1 != null && l.PostalCode != null) // or incomplete addresses
                                    && (
                                        (l.GeocodedDateTime == null && (l.GeocodeAttemptedDateTime == null || l.GeocodeAttemptedDateTime < retryDate)) // has not been attempted to be geocoded since retry date
                                        ||
                                        (l.StandardizedDateTime == null && (l.StandardizeAttemptedDateTime == null || l.StandardizeAttemptedDateTime < retryDate)) // has not been attempted to be standardize since retry date
                                    )
                                ))
                                .Take( maxRecords ).ToList();

            foreach ( var address in addresses )
            {
                locationService.Verify( address, false ); // currently not reverifying 
                rockContext.SaveChanges();
                System.Threading.Thread.Sleep( throttlePeriod );
            }

        }
        /// <summary>
        /// Job that updates the JobPulse setting with the current date/time.
        /// This will allow us to notify an admin if the jobs stop running.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void  Execute(IJobExecutionContext context)
        {
            // get the job map
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            int maxRecords     = Int32.Parse(dataMap.GetString("MaxRecordsPerRun"));
            int throttlePeriod = Int32.Parse(dataMap.GetString("ThrottlePeriod"));
            int retryPeriod    = Int32.Parse(dataMap.GetString("RetryPeriod"));

            DateTime retryDate = DateTime.Now.Subtract(new TimeSpan(retryPeriod, 0, 0, 0));

            var             rockContext     = new Rock.Data.RockContext();
            LocationService locationService = new LocationService(rockContext);
            var             addresses       = locationService.Queryable()
                                              .Where(l => (
                                                         (l.IsGeoPointLocked == null || l.IsGeoPointLocked == false) && // don't ever try locked address
                                                         (l.IsActive == true && l.Street1 != null && l.PostalCode != null) && // or incomplete addresses
                                                         (
                                                             (l.GeocodedDateTime == null && (l.GeocodeAttemptedDateTime == null || l.GeocodeAttemptedDateTime < retryDate))             // has not been attempted to be geocoded since retry date
                                                             ||
                                                             (l.StandardizedDateTime == null && (l.StandardizeAttemptedDateTime == null || l.StandardizeAttemptedDateTime < retryDate)) // has not been attempted to be standardize since retry date
                                                         )
                                                         ))
                                              .Take(maxRecords).ToList();

            foreach (var address in addresses)
            {
                locationService.Verify(address, false);   // currently not reverifying
                rockContext.SaveChanges();
                System.Threading.Thread.Sleep(throttlePeriod);
            }
        }
Example #11
0
        /// <summary>
        /// Cleanups the unconfirmed user logins that have not been confirmed in X hours
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private void CleanupUnconfirmedUserLogins(JobDataMap dataMap)
        {
            int?userExpireHours = dataMap.GetString("HoursKeepUnconfirmedAccounts").AsIntegerOrNull();

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

                // delete in chunks (see http://dba.stackexchange.com/questions/1750/methods-of-speeding-up-a-huge-delete-from-table-with-no-clauses)
                bool keepDeleting = true;
                while (keepDeleting)
                {
                    var dbTransaction = userLoginRockContext.Database.BeginTransaction();
                    try
                    {
                        int rowsDeleted = userLoginRockContext.Database.ExecuteSqlCommand(@"DELETE TOP (1000) FROM [UserLogin] WHERE [IsConfirmed] = 0 AND ([CreatedDateTime] is null OR [CreatedDateTime] < @createdDateTime )", new SqlParameter("createdDateTime", userAccountExpireDate));
                        keepDeleting = rowsDeleted > 0;
                    }
                    finally
                    {
                        dbTransaction.Commit();
                    }
                }
            }
        }
Example #12
0
        /// <summary>
        /// Called during serialization to write an object of the specified type to the specified stream.
        /// </summary>
        /// <param name="type">The type of the object to write.</param>
        /// <param name="value">The object to write.</param>
        /// <param name="writeStream">The stream to write to.</param>
        /// <param name="effectiveEncoding">The encoding to use when writing.</param>
        public override void WriteToStream(Type type, object value, System.IO.Stream writeStream, Encoding effectiveEncoding)
        {
            IEnumerable <Attribute.IHasAttributes> items = null;

            // query should be filtered by now, so iterate thru items and load attributes before the response is serialized
            if (LoadAttributes)
            {
                if (value is IEnumerable <Rock.Attribute.IHasAttributes> )
                {
                    // if the REST call specified that Attributes should be loaded and we are returning a list of IHasAttributes..
                    items = value as IEnumerable <Rock.Attribute.IHasAttributes>;
                }
                else if (value is Rock.Attribute.IHasAttributes)
                {
                    // if the REST call specified that Attributes should be loaded and we are returning a single IHasAttributes..
                    items = new List <Attribute.IHasAttributes>(new Attribute.IHasAttributes[] { value as Rock.Attribute.IHasAttributes });
                }

                if (items != null)
                {
                    var rockContext = new Rock.Data.RockContext();
                    foreach (var item in items)
                    {
                        Rock.Attribute.Helper.LoadAttributes(item, rockContext);
                    }

                    FilterAttributes(rockContext, items, this.Person);
                }
            }

            base.WriteToStream(type, value, writeStream, effectiveEncoding);
        }
Example #13
0
        public Rock.Model.Workflow WorkflowEntry( int workflowTypeId )
        {
            var rockContext = new Rock.Data.RockContext();
            var workflowTypeService = new WorkflowTypeService( rockContext );
            var workflowType = workflowTypeService.Get( workflowTypeId );

            if ( workflowType != null )
            {
                var workflow = Rock.Model.Workflow.Activate( workflowType, "Workflow From REST" );

                // set workflow attributes from querystring
                foreach(var parm in Request.GetQueryStrings()){
                    workflow.SetAttributeValue( parm.Key, parm.Value );
                }

                // save -> run workflow
                List<string> workflowErrors;
                new Rock.Model.WorkflowService( rockContext ).Process( workflow, out workflowErrors );

                var response = ControllerContext.Request.CreateResponse( HttpStatusCode.Created );
                return workflow;
            }
            else
            {
                var response = ControllerContext.Request.CreateResponse( HttpStatusCode.NotFound );
            }

            return null;
        }
Example #14
0
        /// <summary>
        /// Cleans up expired entity sets.
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private void CleanupExpiredEntitySets(JobDataMap dataMap)
        {
            var entitySetRockContext = new Rock.Data.RockContext();
            var currentDateTime      = RockDateTime.Now;
            var entitySetService     = new EntitySetService(entitySetRockContext);
            var qry = entitySetService.Queryable().Where(a => a.ExpireDateTime.HasValue && a.ExpireDateTime < currentDateTime);

            foreach (var entitySet in qry.ToList())
            {
                string deleteWarning;
                if (entitySetService.CanDelete(entitySet, out deleteWarning))
                {
                    // delete in chunks (see http://dba.stackexchange.com/questions/1750/methods-of-speeding-up-a-huge-delete-from-table-with-no-clauses)
                    bool keepDeleting = true;
                    while (keepDeleting)
                    {
                        var dbTransaction = entitySetRockContext.Database.BeginTransaction();
                        try
                        {
                            string sqlCommand = @"DELETE TOP (1000) FROM [EntitySetItem] WHERE [EntitySetId] = @entitySetId";

                            int rowsDeleted = entitySetRockContext.Database.ExecuteSqlCommand(sqlCommand, new SqlParameter("entitySetId", entitySet.Id));
                            keepDeleting = rowsDeleted > 0;
                        }
                        finally
                        {
                            dbTransaction.Commit();
                        }
                    }

                    entitySetService.Delete(entitySet);
                    entitySetRockContext.SaveChanges();
                }
            }
        }
        /// <summary>
        /// Generates a random alternate Id search value for use in a
        /// <see cref="Rock.Model.PersonSearchKey" />.  It is comprised of random alpha
        /// numeric characters in the form ccccccc-ccccccc (7 random characters, a dash,
        /// and 7 more random characters). Example "f5f3df2-40b8946".
        /// </summary>
        /// <param name="verifyUnique">if set to <c>true</c> the key will be verified as unique across all existing "Alternate Id" search values.</param>
        /// <returns>
        /// A random key string
        /// </returns>
        public static string GenerateRandomAlternateId(bool verifyUnique = true)
        {
            string key = string.Empty;

            if (verifyUnique)
            {
                lock ( _obj )
                {
                    using (var rockContext = new Rock.Data.RockContext())
                    {
                        int alternateValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_SEARCH_KEYS_ALTERNATE_ID.AsGuid()).Id;
                        var service          = new PersonSearchKeyService(rockContext);
                        do
                        {
                            key = GenerateRandomAlternateId();
                        } while (service.Queryable().AsNoTracking().Any(a => a.SearchTypeValueId == alternateValueId && a.SearchValue == key));
                    }
                }
            }
            else
            {
                key = GenerateRandomAlternateId();
            }

            return(key);
        }
Example #16
0
        private static KioskLocationAttendance Create(int id)
        {
            using (var rockContext = new Rock.Data.RockContext())
            {
                var location = new LocationService(rockContext).Get(id);
                if (location != null)
                {
                    var locationAttendance = new KioskLocationAttendance();
                    locationAttendance.LocationId   = location.Id;
                    locationAttendance.LocationName = location.Name;
                    locationAttendance.Groups       = new List <KioskGroupAttendance>();

                    var attendanceService = new AttendanceService(rockContext);
                    foreach (var attendance in attendanceService
                             .GetByDateAndLocation(RockDateTime.Today, location.Id)
                             .Where(a =>
                                    a.DidAttend.HasValue &&
                                    a.DidAttend.Value &&
                                    !a.EndDateTime.HasValue))
                    {
                        AddAttendanceRecord(locationAttendance, attendance);
                    }

                    return(locationAttendance);
                }
            }

            return(null);
        }
Example #17
0
        /// <summary>
        /// Updates the scheduled jobs.
        /// </summary>
        /// <param name="context">The context.</param>
        private void UpdateScheduledJobs( IJobExecutionContext context )
        {
            var scheduler = context.Scheduler;

            var rockContext = new Rock.Data.RockContext();
            ServiceJobService jobService = new ServiceJobService( rockContext );
            List<ServiceJob> activeJobList = jobService.GetActiveJobs().ToList();
            List<Quartz.JobKey> scheduledQuartzJobs = scheduler.GetJobKeys( GroupMatcher<JobKey>.GroupStartsWith( string.Empty ) ).ToList();

            // delete any jobs that are no longer exist (are are not set to active) in the database
            var quartsJobsToDelete = scheduledQuartzJobs.Where( a => !activeJobList.Any( j => j.Guid.Equals( a.Name.AsGuid() ) ) );
            foreach ( JobKey jobKey in quartsJobsToDelete )
            {
                scheduler.DeleteJob( jobKey );
            }

            // add any jobs that are not yet scheduled
            var newActiveJobs = activeJobList.Where( a => !scheduledQuartzJobs.Any( q => q.Name.AsGuid().Equals( a.Guid ) ) );
            foreach ( Rock.Model.ServiceJob job in newActiveJobs )
            {
                try
                {
                    IJobDetail jobDetail = jobService.BuildQuartzJob( job );
                    ITrigger jobTrigger = jobService.BuildQuartzTrigger( job );

                    scheduler.ScheduleJob( jobDetail, jobTrigger );
                }
                catch ( Exception ex )
                {
                    // create a friendly error message
                    string message = string.Format( "Error loading the job: {0}.  Ensure that the correct version of the job's assembly ({1}.dll) in the websites App_Code directory. \n\n\n\n{2}", job.Name, job.Assembly, ex.Message );
                    job.LastStatusMessage = message;
                    job.LastStatus = "Error Loading Job";
                }
            }

            rockContext.SaveChanges();

            // reload the jobs in case any where added/removed
            scheduledQuartzJobs = scheduler.GetJobKeys( GroupMatcher<JobKey>.GroupStartsWith( string.Empty ) ).ToList();

            // update schedule if the schedule has changed
            foreach ( var jobKey in scheduledQuartzJobs )
            {
                var jobCronTrigger = scheduler.GetTriggersOfJob( jobKey ).OfType<ICronTrigger>().FirstOrDefault();
                if ( jobCronTrigger != null )
                {
                    var activeJob = activeJobList.FirstOrDefault( a => a.Guid.Equals( jobKey.Name.AsGuid() ) );
                    if ( activeJob != null )
                    {
                        if ( activeJob.CronExpression != jobCronTrigger.CronExpressionString )
                        {
                            ITrigger newJobTrigger = jobService.BuildQuartzTrigger( activeJob );
                            scheduler.RescheduleJob( jobCronTrigger.Key, newJobTrigger );
                        }
                    }
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            this.RockPage.AddScriptLink(ResolveUrl("../Scripts/jquery.autocomplete.min.js"));
            this.RockPage.AddScriptLink(ResolveUrl("../Scripts/underscore.min.js"));
            this.RockPage.AddScriptLink(ResolveUrl("../Scripts/jstz.min.js"));
            this.RockPage.AddScriptLink(ResolveUrl("../Scripts/calendar.js"));
            this.RockPage.AddScriptLink(ResolveUrl("../Scripts/ServiceUEvents.js"));

            this.RockPage.AddCSSLink(ResolveUrl("../Styles/autocomplete-styles.css"));
            this.RockPage.AddCSSLink(ResolveUrl("../Styles/ServiceUEvents.css"));
            this.RockPage.AddCSSLink(ResolveUrl("../Styles/calendar.min.css"));
            var eventtitleroute = PageParameter("eventcalendarroute");

            GetCampus();

            if (!Page.IsPostBack)
            {
                //i'm filtering out those axd calls becuase they are shwoing up for some reson as a valid valud of eventcalendarroute.
                if (!string.IsNullOrEmpty(eventtitleroute) && eventtitleroute != "WebResource.axd" && eventtitleroute != "ScriptResource.axd")
                {
                    var rc = new Rock.Data.RockContext();
                    // int eventid = 0;
                    string eventId = string.Empty;
                    using ( rc )
                    {
                        eventId = rc.Database.SqlQuery <string>("exec newpointe_getEventIDbyUrl @url", new SqlParameter("url", eventtitleroute)).ToList <string>()[0];
                    }
                    if (string.IsNullOrEmpty(eventId))
                    {
                        SiteCache site = SiteCache.GetSiteByDomain(Request.Url.Host);

                        //site.RedirectToPageNotFoundPage();
                    }
                    else
                    {
                        hdnEventId.Value = eventId;
                    }
                }
                else if (!string.IsNullOrEmpty(eventtitleroute))
                {
                    //Response.Redirect( eventtitleroute );
                }

                CampusService campusService = new CampusService(new Rock.Data.RockContext());

                var qry = campusService.Queryable().Where(c => !c.Name.Contains("Central Services") && !c.Name.Contains("Online") && !c.Name.Contains("Future") && (c.IsActive ?? false)).Select(p => new { Name = p.Name.Replace("Campus", "").Trim(), ShortCode = p.ShortCode }).OrderBy(c => c.Name).ToList();

                rptCampuses.DataSource = qry;
                rptCampuses.DataBind();

                qry.Insert(0, new { Name = "ALL", ShortCode = "ALL" });
                ddlCampusDropdown.DataSource     = qry;
                ddlCampusDropdown.DataValueField = "ShortCode";
                ddlCampusDropdown.DataTextField  = "Name";
                ddlCampusDropdown.DataBind();
            }
        }
        /// <summary>
        /// Operations to be performed during the upgrade process.
        /// </summary>
        public override void Up()
        {
            AddColumn("dbo.Person", "MetaPersonicxLifestageClusterId", c => c.Int());
            AddColumn("dbo.Person", "MetaPersonicxLifestageGroupId", c => c.Int());
            AlterColumn("dbo.MetaPersonicxLifestageCluster", "Summary", c => c.String(maxLength: 1000));
            CreateIndex("dbo.Person", "MetaPersonicxLifestageClusterId");
            CreateIndex("dbo.Person", "MetaPersonicxLifestageGroupId");
            AddForeignKey("dbo.Person", "MetaPersonicxLifestageClusterId", "dbo.MetaPersonicxLifestageCluster", "Id");
            AddForeignKey("dbo.Person", "MetaPersonicxLifestageGroupId", "dbo.MetaPersonicxLifestageGroup", "Id");

            Sql("DELETE [MetaFirstNameGenderLookup]");
            ExecuteSqlInsert(
                "INSERT INTO [MetaFirstNameGenderLookup] ([FirstName],[MaleCount],[FemaleCount],[Country],[Language],[TotalCount],[FemalePercent],[MalePercent],[Guid])",
                MigrationSQL._201707311527250_FirstNameGender);

            // use BulkInsert for LastName since there are 150,000+ rowsa
            List <Rock.Model.MetaLastNameLookup> metaLastNameLookupsToInsert = new List <Model.MetaLastNameLookup>();
            var lastNameLines = MigrationSQL._201707311527250_LastName.Split(new[] { "\n" }, StringSplitOptions.None).ToList();

            foreach (var lastNameLine in lastNameLines)
            {
                var lastNameColValues = lastNameLine.Split(new[] { ',' }, StringSplitOptions.None).ToList();
                if (lastNameColValues.Count == 4)
                {
                    var metaLastNameLookup = new Rock.Model.MetaLastNameLookup();
                    metaLastNameLookup.LastName    = lastNameColValues[0].TrimStart(new[] { '\'' }).TrimEnd(new[] { '\'' });
                    metaLastNameLookup.Count       = lastNameColValues[1].AsInteger();
                    metaLastNameLookup.Rank        = lastNameColValues[2].AsInteger();
                    metaLastNameLookup.CountIn100k = lastNameColValues[3].AsDecimalOrNull();
                    metaLastNameLookup.Guid        = Guid.NewGuid();
                    metaLastNameLookupsToInsert.Add(metaLastNameLookup);
                }
            }

            using (var rockContext = new Rock.Data.RockContext())
            {
                rockContext.Database.ExecuteSqlCommand("DELETE [MetaLastNameLookup]");
                rockContext.Database.ExecuteSqlCommand("ALTER TABLE MetaLastNameLookup ALTER COLUMN LastName NVARCHAR(100)");
                rockContext.BulkInsert(metaLastNameLookupsToInsert);
            }

            Sql("DELETE [MetaNickNameLookup]");
            ExecuteSqlInsert(
                "INSERT INTO [MetaNickNameLookup] ([FirstName],[NickName],[Gender],[Count],[Guid])",
                MigrationSQL._201707311527250_NickName);

            Sql("DELETE [MetaPersonicxLifestageGroup]");
            ExecuteSqlInsert(
                "INSERT INTO [MetaPersonicxLifestageGroup] ([LifestyleGroupCode],[LifestyleGroupName],[Description],[Summary],[PercentUS],[LifeStage],[MaritalStatus],[HomeOwnership],[Children],[Income],[IncomeRank],[Urbanicity], [UrbanicityRank], [NetWorth], [NetworthRank],[DetailsUrl],[Guid])",
                MigrationSQL._201707311527250_PersonicxGroup);

            Sql("DELETE [MetaPersonicxLifestageCluster]");
            ExecuteSqlInsert(
                "INSERT INTO [MetaPersonicxLifestageCluster] ([LifestyleClusterCode],[LifestyleClusterName],[Description],[Summary],[PercentUS],[LifeStage],[MaritalStatus],[HomeOwnership],[Children],[Income],[IncomeRank],[Urbanicity], [UrbanicityRank], [NetWorth], [NetworthRank],[MetaPersonicxLifestyleGroupId],[DetailsUrl],[Guid])",
                MigrationSQL._201707311527250_PersonicxCluster);
        }
Example #20
0
        public virtual List <int> GetAlternateEntityIds(Rock.Data.RockContext rockContext)
        {
            var entitiesByType = GetAlternateEntityIdsByType(rockContext);

            if (entitiesByType != null && entitiesByType.Any())
            {
                return(entitiesByType[0]);
            }
            return(null);
        }
Example #21
0
        /// <summary>
        /// Gets the new.
        /// </summary>
        /// <param name="alphaNumericLength">Length of the alpha numeric.</param>
        /// <param name="alphaLength">Length of the alpha.</param>
        /// <param name="numericLength">Length of the numeric.</param>
        /// <param name="isRandomized">if set to <c>true</c> [is randomized].</param>
        /// <returns></returns>
        public static AttendanceCode GetNew(int alphaNumericLength, int alphaLength, int numericLength, bool isRandomized)
        {
            lock ( _obj )
            {
                using (var rockContext = new Rock.Data.RockContext())
                {
                    var service = new AttendanceCodeService(rockContext);

                    DateTime today = RockDateTime.Today;
                    if (_todaysCodes == null || !_today.HasValue || !_today.Value.Equals(today))
                    {
                        _today = today;
                        DateTime tomorrow = today.AddDays(1);
                        _todaysCodes = service.Queryable().AsNoTracking()
                                       .Where(c => c.IssueDateTime >= today && c.IssueDateTime < tomorrow)
                                       .Select(c => c.Code)
                                       .ToList();
                    }

                    // Find a good alphanumeric code prefix
                    string alphaNumericCode = string.Empty;
                    if (alphaNumericLength > 0 || alphaLength > 0)
                    {
                        alphaNumericCode =
                            (alphaNumericLength > 0 ? GenerateRandomCode(alphaNumericLength) : string.Empty) +
                            (alphaLength > 0 ? GenerateRandomAlphaCode(alphaLength) : string.Empty);
                        while (noGood.Any(s => alphaNumericCode.Contains(s)) || _todaysCodes.Contains(alphaNumericCode))
                        {
                            alphaNumericCode =
                                (alphaNumericLength > 0 ? GenerateRandomCode(alphaNumericLength) : string.Empty) +
                                (alphaLength > 0 ? GenerateRandomAlphaCode(alphaLength) : string.Empty);
                        }
                    }

                    string numericCode = string.Empty;
                    if (numericLength > 0)
                    {
                        int codeLen  = alphaNumericLength + alphaLength + numericLength;
                        var lastCode = _todaysCodes.Where(c => c.Length == codeLen).OrderBy(c => c.Substring(alphaNumericLength + alphaLength)).LastOrDefault();
                        numericCode = GetNextNumericCodeAsString(alphaNumericLength, alphaLength, numericLength, isRandomized, lastCode);
                    }

                    string code = alphaNumericCode + numericCode;
                    _todaysCodes.Add(code);

                    var attendanceCode = new AttendanceCode();
                    attendanceCode.IssueDateTime = RockDateTime.Now;
                    attendanceCode.Code          = code;
                    service.Add(attendanceCode);
                    rockContext.SaveChanges();

                    return(attendanceCode);
                }
            }
        }
Example #22
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").AsInteger();

            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();
            }
        }
Example #23
0
        /// <summary>
        /// Operations to be performed during the upgrade process.
        /// </summary>
        public override void Up()
        {
            Sql("DELETE [MetaFirstNameGenderLookup]");
            ExecuteSqlInsert(
                "INSERT INTO [MetaFirstNameGenderLookup] ([FirstName],[MaleCount],[FemaleCount],[Country],[Language],[TotalCount],[FemalePercent],[MalePercent],[Guid])",
                MigrationSQL._201707311527250_FirstNameGender);

            // use BulkInsert for LastName since there are 150,000+ rowsa
            List <Rock.Model.MetaLastNameLookup> metaLastNameLookupsToInsert = new List <Model.MetaLastNameLookup>();
            List <string> lastNameLines;

            using (var lastNameZip = new System.IO.Compression.GZipStream(new MemoryStream(MigrationSQL._201707311527250_LastName), System.IO.Compression.CompressionMode.Decompress, false))
            {
                var lastNameText = Encoding.ASCII.GetString(lastNameZip.ReadBytesToEnd());
                lastNameLines = lastNameText.Split(new[] { "\n" }, StringSplitOptions.None).ToList();
            }

            foreach (var lastNameLine in lastNameLines)
            {
                var lastNameColValues = lastNameLine.Split(new[] { ',' }, StringSplitOptions.None).ToList();
                if (lastNameColValues.Count == 4)
                {
                    var metaLastNameLookup = new Rock.Model.MetaLastNameLookup();
                    metaLastNameLookup.LastName    = lastNameColValues[0].TrimStart(new[] { '\'' }).TrimEnd(new[] { '\'' });
                    metaLastNameLookup.Count       = lastNameColValues[1].AsInteger();
                    metaLastNameLookup.Rank        = lastNameColValues[2].AsInteger();
                    metaLastNameLookup.CountIn100k = lastNameColValues[3].AsDecimalOrNull();
                    metaLastNameLookup.Guid        = Guid.NewGuid();
                    metaLastNameLookupsToInsert.Add(metaLastNameLookup);
                }
            }

            using (var rockContext = new Rock.Data.RockContext())
            {
                rockContext.Database.ExecuteSqlCommand("DELETE [MetaLastNameLookup]");
                rockContext.Database.ExecuteSqlCommand("ALTER TABLE MetaLastNameLookup ALTER COLUMN LastName NVARCHAR(100)");
                rockContext.BulkInsert(metaLastNameLookupsToInsert);
            }

            Sql("DELETE [MetaNickNameLookup]");
            ExecuteSqlInsert(
                "INSERT INTO [MetaNickNameLookup] ([FirstName],[NickName],[Gender],[Count],[Guid])",
                MigrationSQL._201707311527250_NickName);

            Sql("DELETE [MetaPersonicxLifestageGroup]");
            ExecuteSqlInsert(
                "INSERT INTO [MetaPersonicxLifestageGroup] ([LifestyleGroupCode],[LifestyleGroupName],[Description],[Summary],[PercentUS],[LifeStage],[MaritalStatus],[HomeOwnership],[Children],[Income],[IncomeRank],[Urbanicity], [UrbanicityRank], [NetWorth], [NetworthRank],[DetailsUrl],[Guid])",
                MigrationSQL._201707311527250_PersonicxGroup);

            Sql("DELETE [MetaPersonicxLifestageCluster]");
            ExecuteSqlInsert(
                "INSERT INTO [MetaPersonicxLifestageCluster] ([LifestyleClusterCode],[LifestyleClusterName],[Description],[Summary],[PercentUS],[LifeStage],[MaritalStatus],[HomeOwnership],[Children],[Income],[IncomeRank],[Urbanicity], [UrbanicityRank], [NetWorth], [NetworthRank],[MetaPersonicxLifestyleGroupId],[DetailsUrl],[Guid])",
                MigrationSQL._201707311527250_PersonicxCluster);
        }
Example #24
0
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="entityIdProperty">The entity identifier property.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override System.Linq.Expressions.Expression GetExpression(Rock.Data.RockContext context, System.Linq.Expressions.MemberExpression entityIdProperty, string selection)
        {
            var occurrenceQuery = new RoomOccurrenceService(context).Queryable("Schedule");

            IQueryable <string> scheduleQuery;

            scheduleQuery = occurrenceQuery.Select(ro => ro.Schedule.Name);

            var exp = SelectExpressionExtractor.Extract(scheduleQuery, entityIdProperty, "ro");

            return(exp);
        }
Example #25
0
        private static KioskLocationAttendance Create(int id)
        {
            using (var rockContext = new Rock.Data.RockContext())
            {
                var location = NamedLocationCache.Get(id);
                if (location == null)
                {
                    return(null);
                }

                var locationAttendance = new KioskLocationAttendance();
                locationAttendance.LocationId   = location.Id;
                locationAttendance.LocationName = location.Name;
                locationAttendance.Groups       = new List <KioskGroupAttendance>();

                var attendanceService = new AttendanceService(rockContext);

                var todayDate = RockDateTime.Today.Date;

                var attendanceList = attendanceService.Queryable()
                                     .Where(a =>
                                            a.Occurrence.OccurrenceDate == todayDate &&
                                            a.Occurrence.LocationId == location.Id &&
                                            a.Occurrence.GroupId.HasValue &&
                                            a.Occurrence.LocationId.HasValue &&
                                            a.Occurrence.ScheduleId.HasValue &&
                                            a.PersonAliasId.HasValue &&
                                            a.DidAttend.HasValue &&
                                            a.DidAttend.Value &&
                                            !a.EndDateTime.HasValue)
                                     .Select(a => new AttendanceInfo
                {
                    EndDateTime   = a.EndDateTime,
                    StartDateTime = a.StartDateTime,
                    CampusId      = a.CampusId,
                    GroupId       = a.Occurrence.GroupId,
                    GroupName     = a.Occurrence.Group.Name,
                    Schedule      = a.Occurrence.Schedule,
                    PersonId      = a.PersonAlias.PersonId
                })
                                     .AsNoTracking()
                                     .ToList();

                foreach (var attendance in attendanceList)
                {
                    AddAttendanceRecord(locationAttendance, attendance);
                }

                return(locationAttendance);
            }
        }
Example #26
0
        /// <summary>
        /// Get Staff members by Ministry Area
        /// </summary>
        /// <param name="ministryAID">The Ministry Attribute ID.</param>
        /// <param name="positionAID">The position Attribute ID.</param>
        /// <param name="ministryID">The ministry DefinedType ID.</param>
        /// <returns></returns>
        public DataTable GetStaffMembersDTByMinistryID(int ministryAID, int positionAID, Guid?ministryID)
        {
            Rock.Data.RockContext context = new Rock.Data.RockContext();
            AttributeValueService attributeValueService = new AttributeValueService(context);
            AttributeService      attributeService      = new AttributeService(context);

            Rock.Model.Attribute ministryAttribute = attributeService.Get(ministryAID);
            Rock.Model.Attribute positionAttribute = attributeService.Get(positionAID);

            var matchingAttributes = attributeValueService.GetByAttributeId(ministryAttribute.Id).Where(av => av.Value == ministryID.ToString());

            DataTable results = new DataTable();

            results.Columns.Add("PersonAliasId");
            results.Columns.Add("Name");
            results.Columns.Add("Ministry Area");
            results.Columns.Add("Position");
            foreach (AttributeValue attributeValue in matchingAttributes)
            {
                PersonService personService = new PersonService(context);

                Person person = personService.Get(attributeValue.EntityId.Value);
                person.LoadAttributes();
                if (person.RecordStatusValue.Value != "Inactive")
                {
                    DataRow dr = results.NewRow();
                    dr["PersonAliasId"] = person.PrimaryAliasId;
                    dr["Name"]          = person.FullName;
                    if (person.AttributeValues[ministryAttribute.Key] != null)
                    {
                        dr["Ministry Area"] = person.AttributeValues[ministryAttribute.Key].Value;
                    }
                    else
                    {
                        dr["Ministry Area"] = "N/A";
                    }
                    if (person.AttributeValues[positionAttribute.Key] != null)
                    {
                        dr["Position"] = person.AttributeValues[positionAttribute.Key].Value;
                    }
                    else
                    {
                        dr["Position"] = "N/A";
                    }
                    results.Rows.Add(dr);
                }
            }
            return(results);
        }
Example #27
0
        public override IQueryable <Person> Get()
        {
            string queryString     = Request.RequestUri.Query;
            string includeDeceased = System.Web.HttpUtility.ParseQueryString(queryString).Get("IncludeDeceased");

            if (includeDeceased.AsBoolean(false))
            {
                var rockContext = new Rock.Data.RockContext();
                return(new PersonService(rockContext).Queryable(true));
            }
            else
            {
                return(base.Get());
            }
        }
        public override IQueryable<GroupMember> Get()
        {
            var queryString = Request.RequestUri.Query;
            var includeDeceased = System.Web.HttpUtility.ParseQueryString( queryString ).Get( "IncludeDeceased" );

            if ( includeDeceased.AsBoolean( false ) )
            {
                var rockContext = new Rock.Data.RockContext();
                return new GroupMemberService( rockContext ).Queryable( true );
            }
            else
            {
                return base.Get();
            }
        }
Example #29
0
        /// <summary>
        /// Cleanups the temporary binary files.
        /// </summary>
        private void CleanupTemporaryBinaryFiles()
        {
            var binaryFileRockContext = new Rock.Data.RockContext();
            // clean out any temporary binary files
            BinaryFileService binaryFileService = new BinaryFileService(binaryFileRockContext);

            foreach (var binaryFile in binaryFileService.Queryable().Where(bf => bf.IsTemporary == true).ToList())
            {
                if (binaryFile.ModifiedDateTime < RockDateTime.Now.AddDays(-1))
                {
                    binaryFileService.Delete(binaryFile);
                    binaryFileRockContext.SaveChanges();
                }
            }
        }
Example #30
0
        /// <summary>
        /// Operations to be performed during the upgrade process.
        /// </summary>
        public override void Up()
        {
            AddColumn("dbo.FinancialAccount", "ImageBinaryFileId", c => c.Int());
            AddColumn("dbo.FinancialAccount", "Url", c => c.String());
            CreateIndex("dbo.FinancialAccount", "ImageBinaryFileId");
            AddForeignKey("dbo.FinancialAccount", "ImageBinaryFileId", "dbo.BinaryFile", "Id");

            // update TransactionCode to be the CheckNumber for transactions that are a result of scanning checks from the Rock Check Scanner app
            try
            {
                var rockContext = new Rock.Data.RockContext();
                var financialTransactionService = new Rock.Model.FinancialTransactionService( rockContext );
                Guid currencyTypeCheckGuid = Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CHECK.AsGuid();
                var currencyTypeCheckId = Rock.Web.Cache.DefinedValueCache.Read( currencyTypeCheckGuid ).Id;
                var tran = rockContext.Database.BeginTransaction();
                try
                {
                    foreach ( var financialTransaction in financialTransactionService.Queryable().Where( a =>
                        ( a.CheckMicrEncrypted != null && a.CheckMicrEncrypted != string.Empty )
                        && ( a.TransactionCode == null || a.TransactionCode == string.Empty ) )
                        //&& a.CurrencyTypeValueId == currencyTypeCheckId )
                        .Select( a => new { a.Id, a.CheckMicrEncrypted } ).ToList() )
                    {
                        string checkMicrDecrypted = Rock.Security.Encryption.DecryptString( financialTransaction.CheckMicrEncrypted ) ?? string.Empty;
                        var parts = checkMicrDecrypted.Split( '_' );
                        if ( parts.Length == 3 )
                        {
                            string transactionCode = parts[2];

                            string sql = string.Format(
                                "update [FinancialTransaction] set [TransactionCode] = '{0}' where [Id] = {1}"
                                , transactionCode
                                , financialTransaction.Id );
                            rockContext.Database.ExecuteSqlCommand( sql );
                        }
                    }
                }
                finally
                {
                    tran.Commit();
                }
            }
            catch
            {
                // ignore if transaction TransactionCode can't be updated
            }
        }
Example #31
0
        /// <summary>
        /// Handles the ItemDataBound event of the rSelection control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RepeaterItemEventArgs"/> instance containing the event data.</param>
        protected void rSelection_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item == null)
            {
                return;
            }

            CheckInFamily checkInFamily = e.Item.DataItem as CheckInFamily;

            if (checkInFamily == null)
            {
                return;
            }

            Panel pnlSelectFamilyPostback = e.Item.FindControl("pnlSelectFamilyPostback") as Panel;

            pnlSelectFamilyPostback.Attributes["data-target"]       = Page.ClientScript.GetPostBackEventReference(rSelection, checkInFamily.Group.Id.ToString());
            pnlSelectFamilyPostback.Attributes["data-loading-text"] = "Loading...";
            Literal lSelectFamilyButtonHtml = e.Item.FindControl("lSelectFamilyButtonHtml") as Literal;

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, null, new Rock.Lava.CommonMergeFieldsOptions {
                GetLegacyGlobalMergeFields = false
            });

            mergeFields.Add("Family", checkInFamily);
            mergeFields.Add("Kiosk", CurrentCheckInState.Kiosk);
            mergeFields.Add("RegistrationModeEnabled", CurrentCheckInState.Kiosk.RegistrationModeEnabled);

            // prepare a query with a new context in case the Lava wants to access Members of this family, and so that lazy loading will work
            using (var rockContext = new Rock.Data.RockContext())
            {
                var familyMembersQuery = new GroupMemberService(rockContext).Queryable().Include(a => a.Person).Include(a => a.GroupRole)
                                         .AsNoTracking()
                                         .Where(a => a.GroupId == checkInFamily.Group.Id)
                                         .OrderBy(m => m.GroupRole.Order)
                                         .ThenBy(m => m.Person.BirthYear)
                                         .ThenBy(m => m.Person.BirthMonth)
                                         .ThenBy(m => m.Person.BirthDay)
                                         .ThenBy(m => m.Person.Gender);

                var familySelectLavaTemplate = CurrentCheckInState.CheckInType.FamilySelectLavaTemplate;

                mergeFields.Add("FamilyMembers", familyMembersQuery);

                lSelectFamilyButtonHtml.Text = familySelectLavaTemplate.ResolveMergeFields(mergeFields);
            }
        }
        /// <summary>
        /// Operations to be performed during the upgrade process.
        /// </summary>
        public override void Up()
        {
            AddColumn("dbo.FinancialAccount", "ImageBinaryFileId", c => c.Int());
            AddColumn("dbo.FinancialAccount", "Url", c => c.String());
            CreateIndex("dbo.FinancialAccount", "ImageBinaryFileId");
            AddForeignKey("dbo.FinancialAccount", "ImageBinaryFileId", "dbo.BinaryFile", "Id");

            // update TransactionCode to be the CheckNumber for transactions that are a result of scanning checks from the Rock Check Scanner app
            try
            {
                var  rockContext = new Rock.Data.RockContext();
                var  financialTransactionService = new Rock.Model.FinancialTransactionService(rockContext);
                Guid currencyTypeCheckGuid       = Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CHECK.AsGuid();
                var  currencyTypeCheckId         = Rock.Web.Cache.DefinedValueCache.Read(currencyTypeCheckGuid).Id;
                var  tran = rockContext.Database.BeginTransaction();
                try
                {
                    foreach (var financialTransaction in financialTransactionService.Queryable().Where(a =>
                                                                                                       (a.CheckMicrEncrypted != null && a.CheckMicrEncrypted != string.Empty) &&
                                                                                                       (a.TransactionCode == null || a.TransactionCode == string.Empty))
                             //&& a.CurrencyTypeValueId == currencyTypeCheckId )
                             .Select(a => new { a.Id, a.CheckMicrEncrypted }).ToList())
                    {
                        string checkMicrDecrypted = Rock.Security.Encryption.DecryptString(financialTransaction.CheckMicrEncrypted) ?? string.Empty;
                        var    parts = checkMicrDecrypted.Split('_');
                        if (parts.Length == 3)
                        {
                            string transactionCode = parts[2];

                            string sql = string.Format(
                                "update [FinancialTransaction] set [TransactionCode] = '{0}' where [Id] = {1}"
                                , transactionCode
                                , financialTransaction.Id);
                            rockContext.Database.ExecuteSqlCommand(sql);
                        }
                    }
                }
                finally
                {
                    tran.Commit();
                }
            }
            catch
            {
                // ignore if transaction TransactionCode can't be updated
            }
        }
        /// <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)
        {
            var entityTypeCache = EntityTypeCache.Get(TypeId);

            // Get the registration
            var registration = this.Registration;

            if (registration == null && this.RegistrationId > 0)
            {
                registration = new RegistrationService(rockContext)
                               .Queryable().AsNoTracking()
                               .FirstOrDefault(r => r.Id == this.RegistrationId);
            }

            if (entityTypeCache == null || registration == null)
            {
                return(null);
            }

            // Get the instance
            var registrationInstance = registration.RegistrationInstance;

            if (registrationInstance == null && registration.RegistrationInstanceId > 0)
            {
                registrationInstance = new RegistrationInstanceService(rockContext)
                                       .Queryable().AsNoTracking()
                                       .FirstOrDefault(r => r.Id == registration.RegistrationInstanceId);
            }

            if (registrationInstance == null)
            {
                return(null);
            }

            // Get all attributes there were defined for instance's template.
            var attributes = new List <AttributeCache>();

            foreach (var entityTypeAttribute in AttributeCache.GetByEntityType(entityTypeCache.Id)
                     .Where(e =>
                            e.EntityTypeQualifierColumn == "RegistrationTemplateId" &&
                            e.EntityTypeQualifierValue.AsInteger() == registrationInstance.RegistrationTemplateId))
            {
                attributes.Add(entityTypeAttribute);
            }

            return(attributes);
        }
Example #34
0
        /// <summary>
        /// Validates the recipient.
        /// </summary>
        /// <param name="recipient">The recipient.</param>
        /// <param name="isBulkCommunication">if set to <c>true</c> [is bulk communication].</param>
        /// <returns></returns>
        public virtual bool ValidRecipient(CommunicationRecipient recipient, bool isBulkCommunication)
        {
            bool valid = true;

            var person = recipient?.PersonAlias?.Person;

            if (person != null)
            {
                if (person.IsDeceased)
                {
                    recipient.Status     = CommunicationRecipientStatus.Failed;
                    recipient.StatusNote = "Person is deceased";
                    valid = false;
                }

                else if (recipient.Communication.ListGroupId.HasValue)
                {
                    // if this communication is being sent to a list, make sure the recipient is still an active member of the list
                    GroupMemberStatus?groupMemberStatus = null;
                    using (var rockContext = new Rock.Data.RockContext())
                    {
                        groupMemberStatus = new GroupMemberService(rockContext).Queryable()
                                            .Where(a => a.PersonId == person.Id && a.GroupId == recipient.Communication.ListGroupId)
                                            .Select(a => a.GroupMemberStatus).FirstOrDefault();
                    }

                    if (groupMemberStatus != null)
                    {
                        if (groupMemberStatus == GroupMemberStatus.Inactive)
                        {
                            recipient.Status     = CommunicationRecipientStatus.Failed;
                            recipient.StatusNote = "Person is not active member of communication list: " + recipient.Communication.ListGroup.Name;
                            valid = false;
                        }
                    }
                    else
                    {
                        recipient.Status     = CommunicationRecipientStatus.Failed;
                        recipient.StatusNote = "Person is not member of communication list: " + recipient.Communication.ListGroup.Name;
                        valid = false;
                    }
                }
            }

            return(valid);
        }
Example #35
0
        /// <summary>
        /// Gets the payments that have been processed for any scheduled transactions
        /// </summary>
        /// <param name="financialGateway">The financial gateway.</param>
        /// <param name="startDate">The start date.</param>
        /// <param name="endDate">The end date.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        public override List <Payment> GetPayments(FinancialGateway financialGateway, DateTime startDate, DateTime endDate, out string errorMessage)
        {
            errorMessage = string.Empty;
            if (!this.GetAttributeValue(financialGateway, AttributeKey.GenerateFakeGetPayments).AsBoolean())
            {
                return(new List <Payment>());
            }

            var fakePayments             = new List <Payment>();
            var randomNumberOfPayments   = new Random().Next(1, 1000);
            var rockContext              = new Rock.Data.RockContext();
            var scheduledTransactionList = new FinancialScheduledTransactionService(rockContext).Queryable().Where(a => a.FinancialGatewayId == financialGateway.Id).ToList();

            if (!scheduledTransactionList.Any())
            {
                return(fakePayments);
            }

            var transactionDateTime = startDate;

            for (int paymentNumber = 0; paymentNumber < randomNumberOfPayments; paymentNumber++)
            {
                // get a random scheduled Transaction (if any)
                var scheduledTransaction = scheduledTransactionList.OrderBy(a => a.Guid).FirstOrDefault();
                if (scheduledTransaction == null)
                {
                    return(new List <Payment>());
                }

                var fakePayment = new Payment
                {
                    Amount = scheduledTransaction.TotalAmount,
                    TransactionDateTime     = startDate,
                    CreditCardTypeValue     = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.FINANCIAL_CREDIT_CARD_TYPE.AsGuid()).DefinedValues.OrderBy(a => Guid.NewGuid()).First(),
                    CurrencyTypeValue       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD.AsGuid()),
                    TransactionCode         = Guid.NewGuid().ToString("N"),
                    GatewayScheduleId       = scheduledTransaction.GatewayScheduleId,
                    GatewayPersonIdentifier = scheduledTransaction?.FinancialPaymentDetail?.GatewayPersonIdentifier
                };

                fakePayments.Add(fakePayment);
            }


            return(fakePayments);
        }
Example #36
0
        /// <summary>
        /// Updates the attributes.
        /// </summary>
        public void UpdateAttributes()
        {
            var entityType = EntityTypeCache.Get <Rock.Model.WorkflowActionType>(false);

            if (entityType != null)
            {
                foreach (var component in this.Components)
                {
                    using (var rockContext = new Rock.Data.RockContext())
                    {
                        var actionComponent = component.Value.Value;
                        var type            = actionComponent.GetType();
                        Rock.Attribute.Helper.UpdateAttributes(type, entityType.Id, "EntityTypeId", EntityTypeCache.GetId(type.FullName).ToString(), rockContext);
                    }
                }
            }
        }
Example #37
0
        /// <summary> 
        /// Job that updates the JobPulse setting with the current date/time.
        /// This will allow us to notify an admin if the jobs stop running.
        /// 
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            // get the job map
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            int maxRecords = Int32.Parse( dataMap.GetString( "MaxRecordsPerRun" ) );
            int throttlePeriod = Int32.Parse( dataMap.GetString( "ThrottlePeriod" ) );
            int retryPeriod = Int32.Parse( dataMap.GetString( "RetryPeriod" ) );

            DateTime retryDate = DateTime.Now.Subtract(new TimeSpan(retryPeriod, 0, 0, 0));

            var rockContext = new Rock.Data.RockContext();
            LocationService locationService = new LocationService(rockContext);
            var addresses = locationService.Queryable()
                .Where( l =>
                    (
                        ( l.IsGeoPointLocked == null || l.IsGeoPointLocked == false ) &&// don't ever try locked address
                        l.IsActive == true &&
                        l.Street1 != null &&
                        l.Street1 != "" &&
                        l.City != null &&
                        l.City != "" &&
                        (
                            ( l.GeocodedDateTime == null && ( l.GeocodeAttemptedDateTime == null || l.GeocodeAttemptedDateTime < retryDate ) ) || // has not been attempted to be geocoded since retry date
                            ( l.StandardizedDateTime == null && ( l.StandardizeAttemptedDateTime == null || l.StandardizeAttemptedDateTime < retryDate ) ) // has not been attempted to be standardize since retry date
                        )
                    ) )
                .Take( maxRecords ).ToList();

            int attempts = 0;
            int successes = 0;
            foreach ( var address in addresses )
            {
                attempts++;
                if ( locationService.Verify( address, true ) )
                {
                    successes++;
                }
                rockContext.SaveChanges();
                System.Threading.Thread.Sleep( throttlePeriod );
            }

            context.Result = string.Format( "{0:N0} address verifications attempted; {1:N0} successfully verified", attempts, successes );
        }
Example #38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DefinedValueFieldAttribute" /> class.
 /// </summary>
 /// <param name="workflowTypeGuid">The group type GUID.</param>
 /// <param name="name">The name.</param>
 /// <param name="description">The description.</param>
 /// <param name="required">if set to <c>true</c> [required].</param>
 /// <param name="defaultValue">The default value.</param>
 /// <param name="category">The category.</param>
 /// <param name="order">The order.</param>
 /// <param name="key">The key.</param>
 public WorkflowFieldAttribute( string workflowTypeGuid = "", string name = "", string description = "", bool required = true, string defaultValue = "", string category = "", int order = 0, string key = null )
     : base(name, description, required, defaultValue, category, order, key, typeof( Rock.Field.Types.WorkflowFieldType ).FullName)
 {
     if ( !string.IsNullOrWhiteSpace( workflowTypeGuid ) )
     {
         Guid guid = Guid.Empty;
         if ( Guid.TryParse( workflowTypeGuid, out guid ) )
         {
             using ( var rockContext = new Rock.Data.RockContext() )
             {
                 var workflowType = new Rock.Model.WorkflowTypeService( rockContext ).Get( guid );
                 if ( workflowType != null )
                 {
                     var configValue = new Field.ConfigurationValue( workflowType.Id.ToString() );
                     FieldConfigurationValues.Add( "workflowtype", configValue );
                 }
             }
         }
     }
 }
        /// <summary>
        /// Returns a new <see cref="Rock.Model.AttendanceCode"/>
        /// </summary>
        /// <param name="codeLength">A <see cref="System.Int32"/> representing the length of the (security) code.</param>
        /// <returns>A new <see cref="Rock.Model.AttendanceCode"/></returns>
        public static AttendanceCode GetNew( int codeLength = 3 )
        {
            lock ( _obj )
            {
                using ( var rockContext = new Rock.Data.RockContext() )
                {
                    var service = new AttendanceCodeService( rockContext );

                    DateTime today = RockDateTime.Today;
                    if ( _todaysCodes == null || !_today.HasValue || !_today.Value.Equals( today ) )
                    {
                        _today = today;
                        DateTime tomorrow = today.AddDays( 1 );
                        _todaysCodes = service.Queryable().AsNoTracking()
                            .Where( c => c.IssueDateTime >= today && c.IssueDateTime < tomorrow )
                            .Select( c => c.Code )
                            .ToList();
                    }

                    // Find a good unique code for today
                    string code = GenerateRandomCode( codeLength );
                    while ( noGood.Any( s => s == code ) || _todaysCodes.Any( c => c == code ) )
                    {
                        code = GenerateRandomCode( codeLength );
                    }
                    _todaysCodes.Add( code );

                    var attendanceCode = new AttendanceCode();
                    attendanceCode.IssueDateTime = RockDateTime.Now;
                    attendanceCode.Code = code;
                    service.Add( attendanceCode );
                    rockContext.SaveChanges();

                    return attendanceCode;
                }
            }
        }
        /// <summary>
        /// The commands to run to migrate plugin to the specific version
        /// </summary>
        public override void Up()
        {
            var rockContext = new Rock.Data.RockContext();
            var existingRestPerson = new PersonService( rockContext ).Get( new Guid( restPersonGuid ) );
            var existingRestUser = new UserLoginService( rockContext ).Get( new Guid( restUserGuid ) );

            if ( existingRestPerson == null )
            {
                Sql( string.Format( @"
                INSERT INTO [dbo].[Person] (
                    [IsSystem]
                   ,[RecordTypeValueId]
                   ,[RecordStatusValueId]
                   ,[IsDeceased]
                   ,[LastName]
                   ,[Gender]
                   ,[Guid]
                   ,[EmailPreference]
                   ,[IsEmailActive]
                ) VALUES (
                    0
                   ,241
                   ,3
                   ,0
                   ,'Apollos'
                   ,0
                   ,'{0}'
                   ,0
                   ,0)", restPersonGuid ) );

                Sql( string.Format( @"
                INSERT INTO [dbo].[PersonAlias] (
                    [PersonId]
                   ,[AliasPersonId]
                   ,[AliasPersonGuid]
                   ,[Guid]
                ) VALUES (
                    (SELECT [Id] FROM [dbo].[Person] WHERE [Guid] = '{0}')
                   ,(SELECT [Id] FROM [dbo].[Person] WHERE [Guid] = '{0}')
                   ,'{0}'
                   ,'{1}')", restPersonGuid, restPersonAliasGuid ) );
            }

            if ( existingRestUser == null )
            {
                Sql( string.Format( @"
                INSERT INTO [dbo].[UserLogin] (
                    [UserName]
                   ,[IsConfirmed]
                   ,[ApiKey]
                   ,[PersonId]
                   ,[Guid]
                   ,[EntityTypeId]
                ) VALUES (
                    NEWID()
                   ,1
                   ,NEWID()
                   ,(SELECT [Id] FROM [dbo].[Person] WHERE [Guid] = '{0}')
                   ,'{1}'
                   ,27)", restPersonGuid, restUserGuid ) );
            }

            RockMigrationHelper.UpdateEntityType( "cc.newspring.Apollos.Workflow.Action.APISync", apiSyncGuid, false, true );
            RockMigrationHelper.UpdateEntityType( "cc.newspring.Apollos.Security.Authentication.Apollos", apollosAuthGuid, false, true );

            RockMigrationHelper.UpdateWorkflowActionEntityAttribute( apiSyncGuid, "1EDAFDED-DFE6-4334-B019-6EECBA89E05A", "Active", "Active", "Should Service be used?", 0, @"False", activeAttributeGuid ); // Active
            RockMigrationHelper.UpdateWorkflowActionEntityAttribute( apiSyncGuid, "7525C4CB-EE6B-41D4-9B64-A08048D5A5C0", "Action", "Action", "The workflow that this action is under is triggered by what type of event", 0, @"", actionAttributeGuid ); // Action
            RockMigrationHelper.UpdateWorkflowActionEntityAttribute( apiSyncGuid, "9C204CD0-1233-41C5-818A-C5DA439445AA", "Sync URL", "SyncURL", "The specific URL endpoint this related entity type should synchronize with", 0, @"", syncUrlAttributeGuid ); // Sync URL
            RockMigrationHelper.UpdateWorkflowActionEntityAttribute( apiSyncGuid, "9C204CD0-1233-41C5-818A-C5DA439445AA", "Token Name", "TokenName", "The key by which the token should be identified in the header of HTTP requests", 0, @"", tokenNameAttributeGuid ); // Token Name
            RockMigrationHelper.UpdateWorkflowActionEntityAttribute( apiSyncGuid, "9C204CD0-1233-41C5-818A-C5DA439445AA", "Token Value", "TokenValue", "The value of the token to authenticate with the URL endpoint", 0, @"", tokenValueAttributeGuid ); // Token Value
            RockMigrationHelper.UpdateWorkflowActionEntityAttribute( apiSyncGuid, "E4EAB7B2-0B76-429B-AFE4-AD86D7428C70", "Rest User", "RestUser", "The associated REST user that handles sync from the third party", 0, @"", restUserAttributeGuid ); // Rest User
            RockMigrationHelper.UpdateWorkflowActionEntityAttribute( apiSyncGuid, "A75DFC58-7A1B-4799-BF31-451B2BBE38FF", "Order", "Order", "The order that this service should be used (priority)", 0, @"", orderAttributeGuid ); // Order

            RockMigrationHelper.UpdateCategory( "C9F3C4A5-1526-474D-803F-D6C7A45CBBAE", "API Sync To Apollos", "fa fa-connectdevelop", "", categoryGuid, 0 );

            var entityName = "UserLogin";
            SetupWorkflow( entityName, userDeleteTypeGuid, userSaveTypeGuid, userDeleteActivityGuid, userSaveActivityGuid, userDeleteActionGuid, userSaveActionGuid );
            var qualifierValue = string.Format( "(SELECT Id FROM EntityType WHERE Guid = '{0}')", apollosAuthGuid );
            CreateTriggers( entityName, "EntityTypeId", qualifierValue, userSaveTypeGuid, userDeleteTypeGuid );

            entityName = "Person";
            SetupWorkflow( entityName, personDeleteTypeGuid, personSaveTypeGuid, personDeleteActivityGuid, personSaveActivityGuid, personDeleteActionGuid, personSaveActionGuid );
            CreateTriggers( entityName, string.Empty, "''", personSaveTypeGuid, personDeleteTypeGuid );

            entityName = "FinancialTransaction";
            SetupWorkflow( entityName, transactionDeleteTypeGuid, transactionSaveTypeGuid, transactionDeleteActivityGuid, transactionSaveActivityGuid, transactionDeleteActionGuid, transactionSaveActionGuid );
            CreateTriggers( entityName, string.Empty, "''", transactionSaveTypeGuid, transactionDeleteTypeGuid );

            entityName = "FinancialTransactionDetail";
            SetupWorkflow( entityName, transactionDetailDeleteTypeGuid, transactionDetailSaveTypeGuid, transactionDetailDeleteActivityGuid, transactionDetailSaveActivityGuid, transactionDetailDeleteActionGuid, transactionDetailSaveActionGuid );
            CreateTriggers( entityName, string.Empty, "''", transactionDetailSaveTypeGuid, transactionDetailDeleteTypeGuid );

            entityName = "FinancialAccount";
            SetupWorkflow( entityName, accountDeleteTypeGuid, accountSaveTypeGuid, accountDeleteActivityGuid, accountSaveActivityGuid, accountDeleteActionGuid, accountSaveActionGuid );
            CreateTriggers( entityName, string.Empty, "''", accountSaveTypeGuid, accountDeleteTypeGuid );

            entityName = "FinancialScheduledTransaction";
            SetupWorkflow( entityName, scheduledDeleteTypeGuid, scheduledSaveTypeGuid, scheduledDeleteActivityGuid, scheduledSaveActivityGuid, scheduledDeleteActionGuid, scheduledSaveActionGuid );
            CreateTriggers( entityName, string.Empty, "''", scheduledSaveTypeGuid, scheduledDeleteTypeGuid );

            entityName = "FinancialScheduledTransactionDetail";
            SetupWorkflow( entityName, scheduledDetailDeleteTypeGuid, scheduledDetailSaveTypeGuid, scheduledDetailDeleteActivityGuid, scheduledDetailSaveActivityGuid, scheduledDetailDeleteActionGuid, scheduledDetailSaveActionGuid );
            CreateTriggers( entityName, string.Empty, "''", scheduledDetailSaveTypeGuid, scheduledDetailDeleteTypeGuid );
        }
        public PersonSearchResult GetPopupHtml( int personId )
        {
            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 )
            {
                var appPath = System.Web.VirtualPathUtility.ToAbsolute( "~" );
                html.AppendFormat( "<header>{0} <h3>{1}<small>{2}</small></h3></header>",
                    Person.GetPhotoImageTag( person.PhotoId, person.Gender, 65, 65 ),
                    person.FullName,
                    person.ConnectionStatusValue != null ? person.ConnectionStatusValue.Name : string.Empty );

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

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

                if ( !string.IsNullOrWhiteSpace( person.Email ) )
                {
                    html.AppendFormat( "<br/><strong>Email</strong> <a href='mailto:{0}'>{0}</a>", person.Email );
                }

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

                // TODO: Should also show area: <br /><strong>Area</strong> WestwingS

                result.PickerItemDetailsHtml = html.ToString();
            }

            return result;
        }
Example #42
0
        /// <summary>
        /// Cleans up expired entity sets.
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private int CleanupExpiredEntitySets( JobDataMap dataMap )
        {
            var entitySetRockContext = new Rock.Data.RockContext();
            var currentDateTime = RockDateTime.Now;
            var entitySetService = new EntitySetService( entitySetRockContext );
            var qry = entitySetService.Queryable().Where( a => a.ExpireDateTime.HasValue && a.ExpireDateTime < currentDateTime );
            int totalRowsDeleted = 0;

            foreach ( var entitySet in qry.ToList() )
            {
                string deleteWarning;
                if ( entitySetService.CanDelete( entitySet, out deleteWarning ) )
                {
                    // delete in chunks (see http://dba.stackexchange.com/questions/1750/methods-of-speeding-up-a-huge-delete-from-table-with-no-clauses)
                    bool keepDeleting = true;
                    while ( keepDeleting )
                    {
                        var dbTransaction = entitySetRockContext.Database.BeginTransaction();
                        try
                        {
                            string sqlCommand = @"DELETE TOP (1000) FROM [EntitySetItem] WHERE [EntitySetId] = @entitySetId";

                            int rowsDeleted = entitySetRockContext.Database.ExecuteSqlCommand( sqlCommand, new SqlParameter( "entitySetId", entitySet.Id ) );
                            keepDeleting = rowsDeleted > 0;
                            totalRowsDeleted += rowsDeleted;
                        }
                        finally
                        {
                            dbTransaction.Commit();
                        }
                    }

                    entitySetService.Delete( entitySet );
                    entitySetRockContext.SaveChanges();
                }
            }

            return totalRowsDeleted;
        }
Example #43
0
        /// <summary>
        /// Cleans up PagesViews for sites that have a Page View retention period
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private int CleanupPageViews( JobDataMap dataMap )
        {
            var pageViewRockContext = new Rock.Data.RockContext();
            var currentDateTime = RockDateTime.Now;
            var siteService = new SiteService( pageViewRockContext );
            var siteQry = siteService.Queryable().Where( a => a.PageViewRetentionPeriodDays.HasValue );
            int totalRowsDeleted = 0;
            //

            foreach ( var site in siteQry.ToList() )
            {
                var retentionCutoffDateTime = currentDateTime.AddDays( -site.PageViewRetentionPeriodDays.Value );
                if ( retentionCutoffDateTime < System.Data.SqlTypes.SqlDateTime.MinValue.Value )
                {
                    retentionCutoffDateTime = System.Data.SqlTypes.SqlDateTime.MinValue.Value;
                }

                // delete in chunks (see http://dba.stackexchange.com/questions/1750/methods-of-speeding-up-a-huge-delete-from-table-with-no-clauses)
                bool keepDeleting = true;
                while ( keepDeleting )
                {
                    var dbTransaction = pageViewRockContext.Database.BeginTransaction();
                    try
                    {
                        string sqlCommand = @"DELETE TOP (1000) FROM [PageView] WHERE [SiteId] = @siteId AND DateTimeViewed < @retentionCutoffDateTime";

                        int rowsDeleted = pageViewRockContext.Database.ExecuteSqlCommand( sqlCommand, new SqlParameter( "siteId", site.Id ), new SqlParameter( "retentionCutoffDateTime", retentionCutoffDateTime ) );
                        keepDeleting = rowsDeleted > 0;
                        totalRowsDeleted += rowsDeleted;
                    }
                    finally
                    {
                        dbTransaction.Commit();
                    }
                }
            }

            return totalRowsDeleted;
        }
Example #44
0
        /// <summary> 
        /// Job that executes routine Rock cleanup tasks
        /// 
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute( IJobExecutionContext context )
        {
            var rockContext = new Rock.Data.RockContext();

            // get the job map
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            // delete accounts that have not been confirmed in X hours
            int? userExpireHours = dataMap.GetString( "HoursKeepUnconfirmedAccounts" ).AsIntegerOrNull();
            if ( userExpireHours.HasValue )
            {
                DateTime userAccountExpireDate = RockDateTime.Now.Add( new TimeSpan( userExpireHours.Value * -1, 0, 0 ) );

                var userLoginService = new UserLoginService(rockContext);

                foreach ( var user in userLoginService.Queryable().Where( u => u.IsConfirmed == false && ( u.CreatedDateTime ?? DateTime.MinValue ) < userAccountExpireDate ).ToList() )
                {
                    userLoginService.Delete( user );
                }

                rockContext.SaveChanges();
            }

            // purge exception log
            int? exceptionExpireDays = dataMap.GetString( "DaysKeepExceptions" ).AsIntegerOrNull();
            if ( exceptionExpireDays.HasValue )
            {
                DateTime exceptionExpireDate = RockDateTime.Now.Add( new TimeSpan( exceptionExpireDays.Value * -1, 0, 0, 0 ) );

                ExceptionLogService exceptionLogService = new ExceptionLogService( rockContext );

                foreach ( var exception in exceptionLogService.Queryable().Where( e => e.CreatedDateTime.HasValue && e.CreatedDateTime < exceptionExpireDate ).ToList() )
                {
                    exceptionLogService.Delete( exception );
                }

                rockContext.SaveChanges();
            }

            // purge audit log
            int? auditExpireDays = dataMap.GetString( "AuditLogExpirationDays" ).AsIntegerOrNull();
            if ( auditExpireDays.HasValue )
            {
                DateTime auditExpireDate = RockDateTime.Now.Add( new TimeSpan( auditExpireDays.Value * -1, 0, 0, 0 ) );
                AuditService auditService = new AuditService(rockContext);
                foreach ( var audit in auditService.Queryable().Where( a => a.DateTime < auditExpireDate ).ToList() )
                {
                    auditService.Delete( audit );
                }

                rockContext.SaveChanges();
            }

            // clean the cached file directory

            // get the attributes
            string cacheDirectoryPath = dataMap.GetString( "BaseCacheDirectory" );
            int? cacheExpirationDays = dataMap.GetString( "DaysKeepCachedFiles" ).AsIntegerOrNull();
            if ( cacheExpirationDays.HasValue )
            {
                DateTime cacheExpirationDate = RockDateTime.Now.Add( new TimeSpan( cacheExpirationDays.Value * -1, 0, 0, 0 ) );

                // if job is being run by the IIS scheduler and path is not null
                if ( context.Scheduler.SchedulerName == "RockSchedulerIIS" && !string.IsNullOrEmpty( cacheDirectoryPath ) )
                {
                    // get the physical path of the cache directory
                    cacheDirectoryPath = System.Web.Hosting.HostingEnvironment.MapPath( cacheDirectoryPath );
                }

                // if directory is not blank and cache expiration date not in the future
                if ( !string.IsNullOrEmpty( cacheDirectoryPath ) && cacheExpirationDate <= RockDateTime.Now )
                {
                    // Clean cache directory
                    CleanCacheDirectory( cacheDirectoryPath, cacheExpirationDate );
                }
            }

            // clean out any temporary binary files
            BinaryFileService binaryFileService = new BinaryFileService(rockContext);
            foreach ( var binaryFile in binaryFileService.Queryable().Where( bf => bf.IsTemporary == true ).ToList() )
            {
                if ( binaryFile.ModifiedDateTime < RockDateTime.Now.AddDays( -1 ) )
                {
                    binaryFileService.Delete( binaryFile );
                }
            }
            rockContext.SaveChanges();

            // Add any missing person aliases
            PersonService personService = new PersonService(rockContext);
            foreach ( var person in personService.Queryable( "Aliases" )
                .Where( p => !p.Aliases.Any() )
                .Take( 300 ) )
            {
                person.Aliases.Add( new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid } );
            }

            rockContext.SaveChanges();

            // Add any missing metaphones
            int namesToProcess = dataMap.GetString( "MaxMetaphoneNames" ).AsInteger();
            if ( namesToProcess > 0 )
            {
                var firstNameQry = personService.Queryable().Select( p => p.FirstName );
                var nickNameQry = personService.Queryable().Select( p => p.NickName );
                var lastNameQry = personService.Queryable().Select( p => p.LastName );
                var nameQry = firstNameQry.Union( nickNameQry.Union( lastNameQry ) );

                var metaphones = rockContext.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 );
                }

                rockContext.SaveChanges();
            }
        }
Example #45
0
        /// <summary>
        /// Cleans up temporary registrations.
        /// </summary>
        private int CleanUpTemporaryRegistrations()
        {
            var registrationRockContext = new Rock.Data.RockContext();
            int totalRowsDeleted = 0;
            // clean out any temporary registrations
            RegistrationService registrationService = new RegistrationService( registrationRockContext );
            foreach ( var registration in registrationService.Queryable().Where( bf => bf.IsTemporary == true ).ToList() )
            {
                if ( registration.ModifiedDateTime < RockDateTime.Now.AddHours( -1 ) )
                {
                    string errorMessage;
                    if ( registrationService.CanDelete( registration, out errorMessage ) )
                    {
                        registrationService.Delete( registration );
                        registrationRockContext.SaveChanges();
                        totalRowsDeleted++;
                    }
                }
            }

            return totalRowsDeleted;
        }
        /// <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 )
        {
            // 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.
                var rockContext = new Rock.Data.RockContext();
                var exceptionLogService = new ExceptionLogService( rockContext );
                exceptionLogService.Add( exceptionLog );
                rockContext.SaveChanges();

                // Recurse if inner exception is found
                if ( exceptionLog.HasInnerException.GetValueOrDefault( false ) )
                {
                    LogExceptions( ex.InnerException, exceptionLog, false );
                }

                if (ex is AggregateException)
                {
                    // if an AggregateException occurs, log the exceptions individually
                    var aggregateException = ( ex as AggregateException );
                    foreach ( var innerException in aggregateException.InnerExceptions )
                    {
                        LogExceptions( innerException, exceptionLog, false );
                    }
                }
            }
            catch ( Exception )
            {
                // If logging the exception fails, write the exceptions to a file
                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}\"\r\n", when, ex.GetType(), ex.Message ) );
                        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
                }
            }
        }
Example #47
0
        /// <summary>
        /// Execute method to write transaction to the database.
        /// </summary>
        public void Execute()
        {
            // store the view to the database if the viewer is NOT the target (don't track looking at your own record)
            if ( ViewerPersonAliasId != TargetPersonAliasId )
            {

                var pvRecord = new PersonViewed();
                pvRecord.TargetPersonAliasId = TargetPersonAliasId;
                pvRecord.ViewerPersonAliasId = ViewerPersonAliasId;
                pvRecord.ViewDateTime = DateTimeViewed;
                pvRecord.IpAddress = IPAddress;
                pvRecord.Source = Source;

                var rockContext = new Rock.Data.RockContext();
                var pvService = new PersonViewedService( rockContext );
                pvService.Add( pvRecord );
                rockContext.SaveChanges();
            }
        }
Example #48
0
        /// <summary>
        /// Handles the Start event of the Application 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 Application_Start( object sender, EventArgs e )
        {
            if ( System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment )
            {
                System.Diagnostics.Debug.WriteLine( string.Format( "Application_Start: {0}", DateTime.Now.ToString("hh:mm:ss.FFF" ) ));
            }

            // Check if database should be auto-migrated for the core and plugins
            bool autoMigrate = true;
            if ( !Boolean.TryParse( ConfigurationManager.AppSettings["AutoMigrateDatabase"], out autoMigrate ) )
            {
                autoMigrate = true;
            }

            if ( autoMigrate )
            {
                try
                {

                    Database.SetInitializer( new MigrateDatabaseToLatestVersion<Rock.Data.RockContext, Rock.Migrations.Configuration>() );

                    // explictly check if the database exists, and force create it if doesn't exist
                    Rock.Data.RockContext rockContext = new Rock.Data.RockContext();
                    if ( !rockContext.Database.Exists() )
                    {
                        rockContext.Database.Initialize( true );
                    }
                    else
                    {
                        var migrator = new System.Data.Entity.Migrations.DbMigrator( new Rock.Migrations.Configuration() );
                        migrator.Update();
                    }

                    // Migrate any plugins that have pending migrations
                    List<Type> configurationTypeList = Rock.Reflection.FindTypes( typeof( System.Data.Entity.Migrations.DbMigrationsConfiguration ) ).Select( a => a.Value ).ToList();

                    foreach ( var configType in configurationTypeList )
                    {
                        if ( configType != typeof( Rock.Migrations.Configuration ) )
                        {
                            var config = Activator.CreateInstance( configType ) as System.Data.Entity.Migrations.DbMigrationsConfiguration;
                            System.Data.Entity.Migrations.DbMigrator pluginMigrator = Activator.CreateInstance( typeof( System.Data.Entity.Migrations.DbMigrator ), config ) as System.Data.Entity.Migrations.DbMigrator;
                            pluginMigrator.Update();
                        }
                    }

                }
                catch ( Exception ex )
                {
                    // if migrations fail, log error and attempt to continue
                    LogError( ex, null );
                }

            }
            else
            {
                // default Initializer is CreateDatabaseIfNotExists, but we don't want that to happen if automigrate is false, so set it to NULL so that nothing happens
                Database.SetInitializer<Rock.Data.RockContext>( null );
            }

            if ( System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment )
            {
                new AttributeService().Get( 0 );
                System.Diagnostics.Debug.WriteLine( string.Format( "ConnectToDatabase - Connected: {0}", DateTime.Now.ToString( "hh:mm:ss.FFF" ) ) );
            }

            // Preload the commonly used objects
            LoadCacheObjects();
            if ( System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment )
            {
                System.Diagnostics.Debug.WriteLine( string.Format( "LoadCacheObjects - Done: {0}", DateTime.Now.ToString( "hh:mm:ss.FFF" ) ) );
            }

            // setup and launch the jobs infrastructure if running under IIS
            bool runJobsInContext = Convert.ToBoolean( ConfigurationManager.AppSettings["RunJobsInIISContext"] );
            if ( runJobsInContext )
            {

                ISchedulerFactory sf;

                // create scheduler
                sf = new StdSchedulerFactory();
                sched = sf.GetScheduler();

                // get list of active jobs
                ServiceJobService jobService = new ServiceJobService();
                foreach ( ServiceJob job in jobService.GetActiveJobs().ToList() )
                {
                    try
                    {
                        IJobDetail jobDetail = jobService.BuildQuartzJob( job );
                        ITrigger jobTrigger = jobService.BuildQuartzTrigger( job );

                        sched.ScheduleJob( jobDetail, jobTrigger );
                    }
                    catch ( Exception ex )
                    {
                        // create a friendly error message
                        string message = string.Format( "Error loading the job: {0}.  Ensure that the correct version of the job's assembly ({1}.dll) in the websites App_Code directory. \n\n\n\n{2}", job.Name, job.Assembly, ex.Message );
                        job.LastStatusMessage = message;
                        job.LastStatus = "Error Loading Job";

                        jobService.Save( job, null );
                    }
                }

                // set up the listener to report back from jobs as they complete
                sched.ListenerManager.AddJobListener( new RockJobListener(), EverythingMatcher<JobKey>.AllJobs() );

                // start the scheduler
                sched.Start();
            }

            // add call back to keep IIS process awake at night and to provide a timer for the queued transactions
            AddCallBack();

            RegisterFilters( GlobalConfiguration.Configuration.Filters );

            RegisterRoutes( RouteTable.Routes );

            Rock.Security.Authorization.Load();

            AddEventHandlers();

            new EntityTypeService().RegisterEntityTypes( Server.MapPath( "~" ) );
            new FieldTypeService().RegisterFieldTypes( Server.MapPath( "~" ) );

            BundleConfig.RegisterBundles( BundleTable.Bundles );
        }
        public IQueryable<PersonSearchResult> Search( string name, bool includeHtml )
        {
            int count = 20;
            bool reversed;
            bool allowFirstNameOnly = false;

            var searchComponent = Rock.Search.SearchContainer.GetComponent( typeof( Rock.Search.Person.Name ) );
            if ( searchComponent != null )
            {
                allowFirstNameOnly = searchComponent.GetAttributeValue( "FirstNameSearch" ).AsBoolean();
            }

            var rockContext = new Rock.Data.RockContext();
            IOrderedQueryable<Person> sortedPersonQry = new PersonService( rockContext )
                .GetByFullNameOrdered( name, true, false, allowFirstNameOnly, out reversed );

            var topQry = sortedPersonQry.Take( count );
            List<Person> sortedPersonList = topQry.ToList();

            var appPath = System.Web.VirtualPathUtility.ToAbsolute( "~" );
            string itemDetailFormat = @"
<div class='picker-select-item-details clearfix' style='display: none;'>
	{0}
	<div class='contents'>
        {1}
	</div>
</div>
";
            Guid activeRecord = new Guid( SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE );

            // figure out Family, Address, Spouse
            GroupMemberService groupMemberService = new GroupMemberService( rockContext );

            List<PersonSearchResult> searchResult = new List<PersonSearchResult>();
            foreach ( var person in sortedPersonList )
            {
                PersonSearchResult personSearchResult = new PersonSearchResult();
                personSearchResult.Name = reversed ? person.FullNameReversed : person.FullName;
                personSearchResult.ImageHtmlTag = Person.GetPhotoImageTag( person.PhotoId, person.Gender, 50, 50 );
                personSearchResult.Age = person.Age.HasValue ? person.Age.Value : -1;
                personSearchResult.ConnectionStatus = person.ConnectionStatusValueId.HasValue ? DefinedValueCache.Read( person.ConnectionStatusValueId.Value ).Name : string.Empty;
                personSearchResult.Gender = person.Gender.ConvertToString();
                personSearchResult.Email = person.Email;

                if ( person.RecordStatusValueId.HasValue )
                {
                    var recordStatus = DefinedValueCache.Read( person.RecordStatusValueId.Value );
                    personSearchResult.RecordStatus = recordStatus.Name;
                    personSearchResult.IsActive = recordStatus.Guid.Equals( activeRecord );
                }
                else
                {
                    personSearchResult.RecordStatus = string.Empty;
                    personSearchResult.IsActive = false;
                }

                personSearchResult.Id = person.Id;

                string imageHtml = string.Format(
                    "<div class='person-image' style='background-image:url({0}&width=65);background-size:cover;background-position:50%'></div>",
                    Person.GetPhotoUrl( person.PhotoId, person.Gender ) );

                string personInfo = string.Empty;

                Guid adultGuid = new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT );

                Guid familyGuid = new Guid( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY );
                var familyGroupMember = groupMemberService.Queryable()
                    .Where( a => a.PersonId == person.Id )
                    .Where( a => a.Group.GroupType.Guid.Equals( familyGuid ) )
                    .Select( s => new
                    {
                        s.GroupRole,
                        GroupLocation = s.Group.GroupLocations.Select( a => a.Location ).FirstOrDefault()
                    } ).FirstOrDefault();

                if ( familyGroupMember != null )
                {
                    personInfo += familyGroupMember.GroupRole.Name;
                    if ( person.Age != null )
                    {
                        personInfo += " <em>(" + person.Age.ToString() + " yrs old)</em>";
                    }

                    if ( familyGroupMember.GroupRole.Guid.Equals( adultGuid ) )
                    {
                        var spouse = person.GetSpouse();
                        if ( spouse != null )
                        {
                            personInfo += "<p><strong>Spouse:</strong> " + spouse.FullName + "</p>";
                            personSearchResult.SpouseName = spouse.FullName;
                        }
                    }
                }
                else
                {
                    if ( person.Age != null )
                    {
                        personInfo += person.Age.ToString() + " yrs old";
                    }
                }

                if ( familyGroupMember != null )
                {
                    var location = familyGroupMember.GroupLocation;

                    if ( location != null )
                    {
                        string streetInfo;
                        if ( !string.IsNullOrWhiteSpace( location.Street1 ) )
                        {
                            streetInfo = location.Street1 + " " + location.Street2;
                        }
                        else
                        {
                            streetInfo = location.Street2;
                        }

                        string addressHtml = string.Format( "<h5>Address</h5>{0} <br />{1}, {2}, {3}", streetInfo, location.City, location.State, location.Zip );
                        personSearchResult.Address = location.ToString();
                        personInfo += addressHtml;
                    }

                    if ( includeHtml )
                    {
                        personSearchResult.PickerItemDetailsHtml = string.Format( itemDetailFormat, imageHtml, personInfo );
                    }
                }

                searchResult.Add( personSearchResult );
            }

            return searchResult.AsQueryable();
        }
        /// <summary>
        /// Called during serialization to write an object of the specified type to the specified stream.
        /// </summary>
        /// <param name="type">The type of the object to write.</param>
        /// <param name="value">The object to write.</param>
        /// <param name="writeStream">The stream to write to.</param>
        /// <param name="effectiveEncoding">The encoding to use when writing.</param>
        public override void WriteToStream( Type type, object value, System.IO.Stream writeStream, Encoding effectiveEncoding )
        {
            IEnumerable<Attribute.IHasAttributes> items = null;

            // query should be filtered by now, so iterate thru items and load attributes before the response is serialized
            if ( LoadAttributes )
            {
                if ( value is IEnumerable<Rock.Attribute.IHasAttributes> )
                {
                    // if the REST call specified that Attributes should be loaded and we are returning a list of IHasAttributes..
                    items = value as IEnumerable<Rock.Attribute.IHasAttributes>;
                }
                else if ( value is Rock.Attribute.IHasAttributes )
                {
                    // if the REST call specified that Attributes should be loaded and we are returning a single IHasAttributes..
                    items = new List<Attribute.IHasAttributes>( new Attribute.IHasAttributes[] { value as Rock.Attribute.IHasAttributes } );
                }

                if ( items != null )
                {
                    var rockContext = new Rock.Data.RockContext();
                    foreach ( var item in items )
                    {
                        Rock.Attribute.Helper.LoadAttributes( item, rockContext );
                    }

                    FilterAttributes( rockContext, items, this.Person );
                }
            }

            base.WriteToStream( type, value, writeStream, effectiveEncoding );
        }
Example #51
0
 /// <summary>
 /// Cleanups the temporary binary files.
 /// </summary>
 private void CleanupTemporaryBinaryFiles()
 {
     var binaryFileRockContext = new Rock.Data.RockContext();
     // clean out any temporary binary files
     BinaryFileService binaryFileService = new BinaryFileService( binaryFileRockContext );
     foreach ( var binaryFile in binaryFileService.Queryable().Where( bf => bf.IsTemporary == true ).ToList() )
     {
         if ( binaryFile.ModifiedDateTime < RockDateTime.Now.AddDays( -1 ) )
         {
             binaryFileService.Delete( binaryFile );
             binaryFileRockContext.SaveChanges();
         }
     }
 }
Example #52
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 );
            foreach ( var person in personService.Queryable( "Aliases" )
                .Where( p => !p.Aliases.Any() )
                .Take( 300 ) )
            {
                person.Aliases.Add( new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid } );
            }

            personRockContext.SaveChanges();

            // Add any missing metaphones
            int namesToProcess = dataMap.GetString( "MaxMetaphoneNames" ).AsInteger();
            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();
            }
        }
Example #53
0
        /// <summary>
        /// Sets the chart style.
        /// </summary>
        /// <param name="chartStyleDefinedValueGuid">The chart style defined value unique identifier.</param>
        public void SetChartStyle( Guid? chartStyleDefinedValueGuid )
        {
            ChartStyle chartStyle = null;
            if ( chartStyleDefinedValueGuid.HasValue )
            {
                var rockContext = new Rock.Data.RockContext();
                var definedValue = new DefinedValueService( rockContext ).Get( chartStyleDefinedValueGuid.Value );
                if ( definedValue != null )
                {
                    definedValue.LoadAttributes( rockContext );
                    chartStyle = ChartStyle.CreateFromJson( definedValue.Value, definedValue.GetAttributeValue( "ChartStyle" ) );
                }
            }

            SetChartStyle( chartStyle ?? new ChartStyle() );
        }
Example #54
0
        /// <summary>
        /// Reads the specified id.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public static KioskLocationAttendance Read( int id )
        {
            string cacheKey = KioskLocationAttendance.CacheKey( id );

            ObjectCache cache = MemoryCache.Default;
            KioskLocationAttendance locationAttendance = cache[cacheKey] as KioskLocationAttendance;

            if ( locationAttendance != null )
            {
                return locationAttendance;
            }
            else
            {
                var rockContext = new Rock.Data.RockContext();
                var location = new LocationService(rockContext).Get( id );
                if ( location != null )
                {
                    locationAttendance = new KioskLocationAttendance();
                    locationAttendance.LocationId = location.Id;
                    locationAttendance.LocationName = location.Name;
                    locationAttendance.Groups = new List<KioskGroupAttendance>();

                    var attendanceService = new AttendanceService(rockContext);
                    foreach ( var attendance in attendanceService.GetByDateAndLocation( RockDateTime.Today, location.Id ) )
                    {
                        AddAttendanceRecord( locationAttendance, attendance );
                    }

                    var cachePolicy = new CacheItemPolicy();
                    cachePolicy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds( 60 );
                    cache.Set( cacheKey, locationAttendance, cachePolicy );

                    return locationAttendance;
                }
            }

            return null;
        }
Example #55
0
        /// <summary>
        /// Purges the audit log.
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private void PurgeAuditLog( JobDataMap dataMap )
        {
            // purge audit log
            int? auditExpireDays = dataMap.GetString( "AuditLogExpirationDays" ).AsIntegerOrNull();
            if ( auditExpireDays.HasValue )
            {
                var auditLogRockContext = new Rock.Data.RockContext();
                DateTime auditExpireDate = RockDateTime.Now.Add( new TimeSpan( auditExpireDays.Value * -1, 0, 0, 0 ) );

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

                auditLogRockContext.SaveChanges();
            }
        }
Example #56
0
        /// <summary>
        /// Updates the scheduled jobs.
        /// </summary>
        /// <param name="context">The context.</param>
        private void UpdateScheduledJobs( IJobExecutionContext context )
        {
            var scheduler = context.Scheduler;
            int jobsDeleted = 0;
            int jobsScheduleUpdated = 0;

            var rockContext = new Rock.Data.RockContext();
            ServiceJobService jobService = new ServiceJobService( rockContext );
            List<ServiceJob> activeJobList = jobService.GetActiveJobs().ToList();
            List<Quartz.JobKey> scheduledQuartzJobs = scheduler.GetJobKeys( GroupMatcher<JobKey>.GroupStartsWith( string.Empty ) ).ToList();

            // delete any jobs that are no longer exist (are are not set to active) in the database
            var quartsJobsToDelete = scheduledQuartzJobs.Where( a => !activeJobList.Any( j => j.Guid.Equals( a.Name.AsGuid() ) ) );
            foreach ( JobKey jobKey in quartsJobsToDelete )
            {
                scheduler.DeleteJob( jobKey );
                jobsDeleted++;
            }

            // add any jobs that are not yet scheduled
            var newActiveJobs = activeJobList.Where( a => !scheduledQuartzJobs.Any( q => q.Name.AsGuid().Equals( a.Guid ) ) );
            foreach ( Rock.Model.ServiceJob job in newActiveJobs )
            {
                const string errorSchedulingStatus = "Error scheduling Job";
                try
                {
                    IJobDetail jobDetail = jobService.BuildQuartzJob( job );
                    ITrigger jobTrigger = jobService.BuildQuartzTrigger( job );

                    scheduler.ScheduleJob( jobDetail, jobTrigger );
                    jobsScheduleUpdated++;

                    if ( job.LastStatus == errorSchedulingStatus )
                    {
                        job.LastStatusMessage = string.Empty;
                        job.LastStatus = string.Empty;
                        rockContext.SaveChanges();
                    }
                }
                catch ( Exception ex )
                {
                    ExceptionLogService.LogException( ex, null );

                    // create a friendly error message
                    string message = string.Format( "Error scheduling the job: {0}.\n\n{2}", job.Name, job.Assembly, ex.Message );
                    job.LastStatusMessage = message;
                    job.LastStatus = errorSchedulingStatus;
                }
            }

            rockContext.SaveChanges();

            // reload the jobs in case any where added/removed
            scheduledQuartzJobs = scheduler.GetJobKeys( GroupMatcher<JobKey>.GroupStartsWith( string.Empty ) ).ToList();

            // update schedule if the schedule has changed
            foreach ( var jobKey in scheduledQuartzJobs )
            {
                var jobCronTrigger = scheduler.GetTriggersOfJob( jobKey ).OfType<ICronTrigger>().FirstOrDefault();
                if ( jobCronTrigger != null )
                {
                    var activeJob = activeJobList.FirstOrDefault( a => a.Guid.Equals( jobKey.Name.AsGuid() ) );
                    if ( activeJob != null )
                    {
                        bool rescheduleJob = false;

                        // fix up the schedule if it has changed
                        if ( activeJob.CronExpression != jobCronTrigger.CronExpressionString )
                        {
                            rescheduleJob = true;
                        }

                        // update the job detail if it has changed
                        var scheduledJobDetail = scheduler.GetJobDetail( jobKey );
                        var jobDetail = jobService.BuildQuartzJob( activeJob );

                        if ( scheduledJobDetail != null && jobDetail != null )
                        {
                            if ( scheduledJobDetail.JobType != jobDetail.JobType )
                            {
                                rescheduleJob = true;
                            }

                            if ( scheduledJobDetail.JobDataMap.ToJson() != jobDetail.JobDataMap.ToJson() )
                            {
                                rescheduleJob = true;
                            }
                        }

                        if ( rescheduleJob )
                        {
                            const string errorReschedulingStatus = "Error re-scheduling Job";
                            try
                            {
                                ITrigger newJobTrigger = jobService.BuildQuartzTrigger( activeJob );
                                bool deletedSuccessfully = scheduler.DeleteJob( jobKey );
                                scheduler.ScheduleJob( jobDetail, newJobTrigger );
                                jobsScheduleUpdated++;

                                if ( activeJob.LastStatus == errorReschedulingStatus )
                                {
                                    activeJob.LastStatusMessage = string.Empty;
                                    activeJob.LastStatus = string.Empty;
                                    rockContext.SaveChanges();
                                }
                            }
                            catch ( Exception ex )
                            {
                                ExceptionLogService.LogException( ex, null );

                                // create a friendly error message
                                string message = string.Format( "Error re-scheduling the job: {0}.\n\n{2}", activeJob.Name, activeJob.Assembly, ex.Message );
                                activeJob.LastStatusMessage = message;
                                activeJob.LastStatus = errorReschedulingStatus;
                            }
                        }
                    }
                }
            }

            context.Result = string.Empty;

            if ( jobsDeleted > 0 )
            {
                context.Result += string.Format( "Deleted {0} job schedule(s)", jobsDeleted );
            }

            if ( jobsScheduleUpdated > 0 )
            {
                context.Result += ( string.IsNullOrEmpty( context.Result as string ) ? "" : " and " ) + string.Format( "Updated {0} schedule(s)", jobsScheduleUpdated );
            }
        }
Example #57
0
        /// <summary>
        /// Purges the exception log.
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private void PurgeExceptionLog( JobDataMap dataMap )
        {
            int? exceptionExpireDays = dataMap.GetString( "DaysKeepExceptions" ).AsIntegerOrNull();
            if ( exceptionExpireDays.HasValue )
            {
                var exceptionLogRockContext = new Rock.Data.RockContext();
                DateTime exceptionExpireDate = RockDateTime.Now.Add( new TimeSpan( exceptionExpireDays.Value * -1, 0, 0, 0 ) );

                // delete in chunks (see http://dba.stackexchange.com/questions/1750/methods-of-speeding-up-a-huge-delete-from-table-with-no-clauses)
                bool keepDeleting = true;
                while ( keepDeleting )
                {
                    var dbTransaction = exceptionLogRockContext.Database.BeginTransaction();
                    try
                    {
                        int rowsDeleted = exceptionLogRockContext.Database.ExecuteSqlCommand( @"DELETE TOP (1000) FROM [ExceptionLog] WHERE [CreatedDateTime] < @createdDateTime", new SqlParameter( "createdDateTime", exceptionExpireDate ) );
                        keepDeleting = rowsDeleted > 0;
                    }
                    finally
                    {
                        dbTransaction.Commit();
                    }
                }
            }
        }
Example #58
0
        /// <summary>
        /// Cleanups the unconfirmed user logins that have not been confirmed in X hours
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private void CleanupUnconfirmedUserLogins( JobDataMap dataMap )
        {
            int? userExpireHours = dataMap.GetString( "HoursKeepUnconfirmedAccounts" ).AsIntegerOrNull();
            if ( userExpireHours.HasValue )
            {
                var userLoginRockContext = new Rock.Data.RockContext();
                DateTime userAccountExpireDate = RockDateTime.Now.Add( new TimeSpan( userExpireHours.Value * -1, 0, 0 ) );

                // delete in chunks (see http://dba.stackexchange.com/questions/1750/methods-of-speeding-up-a-huge-delete-from-table-with-no-clauses)
                bool keepDeleting = true;
                while ( keepDeleting )
                {
                    var dbTransaction = userLoginRockContext.Database.BeginTransaction();
                    try
                    {
                        int rowsDeleted = userLoginRockContext.Database.ExecuteSqlCommand( @"DELETE TOP (1000) FROM [UserLogin] WHERE [IsConfirmed] = 0 AND ([CreatedDateTime] is null OR [CreatedDateTime] < @createdDateTime )", new SqlParameter( "createdDateTime", userAccountExpireDate ) );
                        keepDeleting = rowsDeleted > 0;
                    }
                    finally
                    {
                        dbTransaction.Commit();
                    }
                }
            }
        }
 public IQueryable<Person> GetByPhoneNumber( string number )
 {
     var rockContext = new Rock.Data.RockContext();
     return new PersonService( rockContext ).GetByPhonePartial( number, true );
 }
 public IQueryable<Person> GetByEmail( string email )
 {
     var rockContext = new Rock.Data.RockContext();
     return new PersonService( rockContext ).GetByEmail( email, true );
 }