/// <summary> /// Gets the interaction component ids. /// </summary> /// <returns></returns> private List <int> GetInteractionComponentIds() { if (_interactionComponentIds == null) { var pageCache = GetPageCache(); if (pageCache == null) { return(null); } var rockContext = new RockContext(); var interactionComponentService = new InteractionComponentService(rockContext); var channelMediumTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE).Id; _interactionComponentIds = interactionComponentService.Queryable() .AsNoTracking() .Where(ic => ic.InteractionChannel.ChannelTypeMediumValueId == channelMediumTypeValueId) .Where(ic => ic.EntityId == pageCache.Id) .Select(ic => ic.Id) .ToList(); } return(_interactionComponentIds); }
/// <summary> /// Loads the drop down items. /// </summary> /// <param name="picker">The picker.</param> /// <param name="includeEmptyOption">if set to <c>true</c> [include empty option].</param> internal static void LoadDropDownItems(IInteractionComponentPicker picker, bool includeEmptyOption) { var selectedItems = picker.Items.Cast <ListItem>() .Where(i => i.Selected) .Select(i => i.Value) .AsIntegerList(); picker.Items.Clear(); if (!picker.InteractionChannelId.HasValue) { return; } if (includeEmptyOption) { // add Empty option first picker.Items.Add(new ListItem()); } var rockContext = new RockContext(); var interactionComponentService = new InteractionComponentService(rockContext); var components = interactionComponentService.Queryable().AsNoTracking() .Where(ic => ic.InteractionChannelId == picker.InteractionChannelId.Value) .OrderBy(ic => ic.Name) .ToList(); foreach (var component in components) { var li = new ListItem(component.Name, component.Id.ToString()); li.Selected = selectedItems.Contains(component.Id); picker.Items.Add(li); } }
private static int LoadByGuid2(Guid guid, RockContext rockContext) { var interactionComponentService = new InteractionComponentService(rockContext); return(interactionComponentService .Queryable().AsNoTracking() .Where(c => c.Guid.Equals(guid)) .Select(c => c.Id) .FirstOrDefault()); }
/// <summary> /// Populates the group roles. /// </summary> /// <param name="interactionChannelId">The interaction channel identifier.</param> /// <param name="ddlInteractionComponent">The Interaction Component.</param> private void PopulateInteractionComponent(int?interactionChannelId, RockDropDownList ddlInteractionComponent) { if (interactionChannelId.HasValue) { var interactionComponentService = new InteractionComponentService(new RockContext()); var interactionComponents = interactionComponentService.Queryable() .Where(a => a.ChannelId == (interactionChannelId ?? 0)) .OrderBy(a => a.Name). Select(a => new { a.Id, a.Name }).ToList(); ddlInteractionComponent.Items.Clear(); ddlInteractionComponent.Items.Add(new ListItem()); ddlInteractionComponent.Items.AddRange(interactionComponents.Select(a => new ListItem(a.Name, a.Id.ToString())).ToArray()); ddlInteractionComponent.Visible = interactionComponents.Count > 0; } else { ddlInteractionComponent.Visible = false; } }
/// <summary> /// Gets the component identifier by foreign key and ChannelId, and creates it if it doesn't exist. /// If foreignKey is blank, this will throw a <seealso cref="ArgumentNullException" /> /// If creating a new InteractionComponent with this, componentName must be specified /// </summary> /// <param name="foreignKey">The foreign key.</param> /// <param name="interactionChannelId">The interaction channel identifier.</param> /// <param name="componentName">Name of the component.</param> /// <returns></returns> /// <exception cref="ArgumentNullException">ForeignKey must be specified when using GetComponentIdByForeignKey</exception> public static int GetComponentIdByForeignKeyAndChannelId(string foreignKey, int interactionChannelId, string componentName) { if (foreignKey.IsNullOrWhiteSpace()) { throw new ArgumentNullException("ForeignKey must be specified when using GetComponentIdByForeignKey"); } var lookupKey = $"{foreignKey}|interactionChannelId:{interactionChannelId}"; if (_interactionComponentIdLookupFromForeignKey.TryGetValue(lookupKey, out int channelId)) { return(channelId); } using (var rockContext = new RockContext()) { var interactionComponentService = new InteractionComponentService(rockContext); var interactionComponent = interactionComponentService.Queryable() .Where(a => a.ForeignKey == foreignKey && a.InteractionChannelId == interactionChannelId).FirstOrDefault(); if (interactionComponent == null) { interactionComponent = new InteractionComponent(); interactionComponent.Name = componentName; interactionComponent.ForeignKey = foreignKey; interactionComponent.InteractionChannelId = interactionChannelId; interactionComponentService.Add(interactionComponent); rockContext.SaveChanges(); } var interactionComponentId = Get(interactionComponent).Id; _interactionComponentIdLookupFromForeignKey.AddOrUpdate(lookupKey, interactionComponentId, (k, v) => interactionComponentId); return(interactionComponentId); } }
public void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; var rockContext = new RockContext(); InteractionChannelService channelService = new InteractionChannelService(rockContext); InteractionComponentService componentService = new InteractionComponentService(rockContext); InteractionService interactionService = new InteractionService(rockContext); ScheduleService scheduleService = new ScheduleService(rockContext); LocationService locationService = new LocationService(rockContext); AttendanceService attendanceService = new AttendanceService(rockContext); GroupService groupService = new GroupService(rockContext); // Load the channel InteractionChannelCache channel = InteractionChannelCache.Read(dataMap.GetString("InteractionChannel").AsGuid()); // Setup int campusLocationTypeId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.LOCATION_TYPE_CAMPUS).Id; var groupType = GroupTypeCache.Read(dataMap.GetString("GroupType").AsGuid()); var groups = groupService.GetByGroupTypeId(groupType.Id); string operation = !string.IsNullOrWhiteSpace(dataMap.GetString("Operation")) ? dataMap.GetString("Operation") : null; // Fetch the job so we can get the last run date/time int jobId = Convert.ToInt16(context.JobDetail.Description); var jobService = new ServiceJobService(rockContext); var job = jobService.Get(jobId); DateTime lastRun = job?.LastSuccessfulRunDateTime ?? DateTime.MinValue; var componentCampusMapping = dataMap.GetString("ComponentCampusMapping").AsDictionaryOrNull(); foreach (var componentName in componentCampusMapping.Keys) { var component = componentService.Queryable().Where(cs => cs.Name.ToLower() == componentName.ToLower() && cs.ChannelId == channel.Id).FirstOrDefault(); CampusCache campus = CampusCache.All().Where(c => c.Name == componentCampusMapping[componentName]).FirstOrDefault(); if (campus != null && component != null) { Group group = groups.Where(g => g.IsActive == true && g.CampusId == campus.Id).FirstOrDefault(); if (group?.GroupLocations != null) { foreach (var gl in group?.GroupLocations) { Location location = gl.Location; foreach (Schedule schedule in gl.Schedules) { var occurrences = schedule.GetOccurrences(DateTime.MinValue, DateTime.Now); foreach (var occurrence in occurrences) { DateTime startDate = occurrence.Period.StartTime.Value; DateTime endDate = occurrence.Period.EndTime.Value; var peopleAttended = interactionService.Queryable().Where( i => i.InteractionComponentId == component.Id && i.InteractionDateTime <= endDate && i.InteractionEndDateTime >= startDate && i.PersonAliasId != null && (i.CreatedDateTime > lastRun || i.PersonalDevice.ModifiedDateTime > lastRun || i.PersonalDevice.CreatedDateTime > lastRun) && (operation == null || i.Operation == operation) ).Select(i => i.PersonAliasId).Distinct(); int newAttendance = 0; foreach (int personAliasId in peopleAttended) { // Make sure we don't already have an attendance Record if (!attendanceService.Queryable().Any(a => DbFunctions.TruncateTime(a.StartDateTime) == occurrence.Period.StartTime.Value.Date && a.ScheduleId == schedule.Id && a.PersonAliasId == personAliasId && a.GroupId == group.Id && a.LocationId == location.Id && a.DidAttend == true)) { Attendance attendance = new Attendance() { PersonAliasId = personAliasId, CampusId = campus.Id, GroupId = group.Id, LocationId = location.Id, ScheduleId = schedule.Id, StartDateTime = occurrence.Period.StartTime.Value, EndDateTime = occurrence.Period?.EndTime?.Value, DidAttend = true }; attendanceService.Add(attendance); newAttendance++; } } if (newAttendance > 0) { rockContext.SaveChanges(); context.Result += string.Format("{0} people attended {1} on {2} (Component {3}).\n", newAttendance, campus.Name, occurrence.Period.StartTime.Value.ToString("MM/dd/yyyy h:mm tt"), component.Name); } } } } } } } }
public HttpResponseMessage Post(List <MACPresence> presenceList) { using (var rockContext = new RockContext()) { var interactionChannel = new InteractionChannelService(rockContext).Get(Rock.SystemGuid.InteractionChannel.WIFI_PRESENCE.AsGuid()); if (interactionChannel != null) { var interactionComponentIds = new Dictionary <string, int>(); var personalDeviceService = new PersonalDeviceService(rockContext); var interactionService = new InteractionService(rockContext); var interactionComponentService = new InteractionComponentService(rockContext); // Can't set to local time here as it won't compute DST correctly later. var epochTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); foreach (var macPresence in presenceList.Where(l => l.Mac != null && l.Mac != "")) { var device = personalDeviceService.GetByMACAddress(macPresence.Mac); if (device == null) { device = new PersonalDevice(); device.MACAddress = macPresence.Mac; personalDeviceService.Add(device); rockContext.SaveChanges(); } if (macPresence.Presence != null && macPresence.Presence.Any()) { foreach (var presence in macPresence.Presence) { // Calc data needed for new and existing data DateTime interactionStart = epochTime.AddSeconds(presence.Arrive).ToLocalTime(); DateTime interactionEnd = epochTime.AddSeconds(presence.Depart).ToLocalTime(); TimeSpan ts = interactionEnd.Subtract(interactionStart); string duration = (ts.TotalMinutes >= 60 ? $"{ts:%h} hours and " : "") + $"{ts:%m} minutes"; Interaction interaction = interactionService.Queryable().Where(i => i.ForeignKey != null && i.ForeignKey == presence.SessionId).FirstOrDefault(); if (interaction == null) { if (!interactionComponentIds.ContainsKey(presence.Space)) { var component = interactionComponentService .Queryable().AsNoTracking() .Where(c => c.InteractionChannelId == interactionChannel.Id && c.Name == presence.Space) .FirstOrDefault(); if (component == null) { component = new InteractionComponent(); interactionComponentService.Add(component); component.InteractionChannelId = interactionChannel.Id; component.Name = presence.Space; rockContext.SaveChanges(); } interactionComponentIds.Add(presence.Space, component.Id); } interaction = new Interaction(); interaction.InteractionDateTime = interactionStart; interaction.InteractionEndDateTime = interactionEnd; interaction.Operation = "Present"; interaction.InteractionSummary = $"Arrived at {presence.Space} on {interactionStart.ToShortDateTimeString()}. Stayed for {duration}."; interaction.InteractionComponentId = interactionComponentIds[presence.Space]; interaction.InteractionData = presence.ToJson(); interaction.PersonalDeviceId = device.Id; interaction.PersonAliasId = device.PersonAliasId; interaction.ForeignKey = presence.SessionId; interactionService.Add(interaction); } else { // Update the existing interaction interaction.InteractionEndDateTime = interactionEnd; interaction.InteractionSummary = $"Arrived at {presence.Space} on {interactionStart.ToShortDateTimeString()}. Stayed for {duration}."; interaction.InteractionData = presence.ToJson(); } rockContext.SaveChanges(); } } } var response = ControllerContext.Request.CreateResponse(HttpStatusCode.Created); return(response); } else { var response = ControllerContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "A WiFi Presense Interaction Channel Was Not Found!"); throw new HttpResponseException(response); } } }
public void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; var rockContext = new RockContext(); InteractionChannelService channelService = new InteractionChannelService(rockContext); InteractionComponentService componentService = new InteractionComponentService(rockContext); InteractionService interactionService = new InteractionService(rockContext); ScheduleService scheduleService = new ScheduleService(rockContext); LocationService locationService = new LocationService(rockContext); AttendanceService attendanceService = new AttendanceService(rockContext); AttendanceOccurrenceService attendanceOccurrenceService = new AttendanceOccurrenceService(rockContext); GroupService groupService = new GroupService(rockContext); // Load the channel InteractionChannelCache channel = InteractionChannelCache.Get(dataMap.GetString("InteractionChannel").AsGuid()); // Setup int campusLocationTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.LOCATION_TYPE_CAMPUS).Id; var groupType = GroupTypeCache.Get(dataMap.GetString("GroupType").AsGuid()); var groupLocations = groupService.GetByGroupTypeId(groupType.Id).Where(g => g.IsActive == true).SelectMany(g => g.GroupLocations).ToList(); string operation = !string.IsNullOrWhiteSpace(dataMap.GetString("Operation")) ? dataMap.GetString("Operation") : null; // Fetch the job so we can get the last run date/time int jobId = Convert.ToInt16(context.JobDetail.Description); var jobService = new ServiceJobService(rockContext); var job = jobService.Get(jobId); DateTime lastRun = job?.LastSuccessfulRunDateTime ?? DateTime.MinValue; var componentCampusMapping = dataMap.GetString("ComponentCampusMapping").AsDictionaryOrNull(); DateRange dateRange = Rock.Web.UI.Controls.SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(dataMap.GetString("DateRange") ?? "-1||"); // Flip the component campus mapping around and translate to ids Dictionary <int, List <int> > campusComponentIds = new Dictionary <int, List <int> >(); foreach (CampusCache campus in CampusCache.All()) { var componentNames = componentCampusMapping.Where(ccm => ccm.Value == campus.Name).Select(c => c.Key.ToLower()); campusComponentIds[campus.Id] = componentService.Queryable().Where(cs => componentNames.Contains(cs.Name.ToLower()) && cs.ChannelId == channel.Id).Select(c => c.Id).ToList(); } foreach (GroupLocation gl in groupLocations) { if (gl.Group.CampusId.HasValue) { Location location = gl.Location; List <int> componentIds = campusComponentIds[gl.Group.CampusId.Value]; foreach (Schedule schedule in gl.Schedules) { var occurrences = schedule.GetOccurrences(dateRange.Start.Value, dateRange.End.Value); foreach (var occurrence in occurrences) { DateTime startDate = occurrence.Period.StartTime.Value; DateTime endDate = occurrence.Period.EndTime.Value; var peopleAttended = interactionService.Queryable().Where( i => componentIds.Contains(i.InteractionComponentId) && i.InteractionDateTime <= endDate && i.InteractionEndDateTime >= startDate && i.PersonAliasId != null && (i.CreatedDateTime > lastRun || i.PersonalDevice.ModifiedDateTime > lastRun || i.PersonalDevice.CreatedDateTime > lastRun) && (operation == null || i.Operation == operation) ).Select(i => i.PersonAliasId).Distinct(); int newAttendance = 0; var occurrenceModel = attendanceOccurrenceService.Get(occurrence.Period.StartTime.Value.Date, gl.GroupId, location.Id, schedule.Id); // Make sure we don't already have an attendance Record var existingAttendees = attendanceOccurrenceService.Queryable().Where(ao => DbFunctions.TruncateTime(ao.OccurrenceDate) == occurrence.Period.StartTime.Value.Date && ao.ScheduleId == schedule.Id && ao.GroupId == gl.GroupId && ao.LocationId == location.Id).SelectMany(a => a.Attendees).Where(a => a.DidAttend == true).Select(a => a.PersonAliasId); foreach (int personAliasId in peopleAttended.Except(existingAttendees)) { // Check to see if an occurrence exists already if (occurrenceModel == null) { var attendance = attendanceService.AddOrUpdate(personAliasId, occurrence.Period.StartTime.Value, gl.GroupId, location.Id, schedule.Id, gl.Group.CampusId); attendance.EndDateTime = occurrence.Period?.EndTime?.Value; attendance.DidAttend = true; attendance.CampusId = gl.Group.CampusId; occurrenceModel = attendance.Occurrence; } else { Attendance attendance = new Attendance(); attendance.PersonAliasId = personAliasId; attendance.OccurrenceId = occurrenceModel.Id; attendance.StartDateTime = occurrence.Period.StartTime.Value; attendance.EndDateTime = occurrence.Period?.EndTime?.Value; attendance.DidAttend = true; attendance.CampusId = gl.Group.CampusId; attendanceService.Add(attendance); } newAttendance++; } if (newAttendance > 0) { rockContext.SaveChanges(); context.Result += string.Format("{0} people attended {1} on {2}.\n", newAttendance, gl.Group.Campus.Name, occurrence.Period.StartTime.Value.ToString("MM/dd/yyyy h:mm tt")); } } } } } }
/// <summary> /// Execute method to write transaction to the database. /// </summary> public void Execute() { using ( var rockContext = new RockContext() ) { var userAgent = (this.UserAgent ?? string.Empty).Trim(); if ( userAgent.Length > 450 ) { userAgent = userAgent.Substring( 0, 450 ); // trim super long useragents to fit in pageViewUserAgent.UserAgent } // get user agent info var clientType = PageViewUserAgent.GetClientType( userAgent ); // don't log visits from crawlers if ( clientType != "Crawler" ) { InteractionChannelService interactionChannelService = new InteractionChannelService( rockContext ); InteractionComponentService interactionComponentService = new InteractionComponentService( rockContext ); InteractionDeviceTypeService interactionDeviceTypeService = new InteractionDeviceTypeService( rockContext ); InteractionSessionService interactionSessionService = new InteractionSessionService( rockContext ); InteractionService interactionService = new InteractionService( rockContext ); ClientInfo client = uaParser.Parse( userAgent ); var clientOs = client.OS.ToString(); var clientBrowser = client.UserAgent.ToString(); // lookup the interactionDeviceType, and create it if it doesn't exist var interactionDeviceType = interactionDeviceTypeService.Queryable().Where( a => a.Application == clientBrowser && a.OperatingSystem == clientOs && a.ClientType == clientType ).FirstOrDefault(); if ( interactionDeviceType == null ) { interactionDeviceType = new InteractionDeviceType(); interactionDeviceType.DeviceTypeData = userAgent; interactionDeviceType.ClientType = clientType; interactionDeviceType.OperatingSystem = clientOs; interactionDeviceType.Application = clientBrowser; interactionDeviceType.Name = string.Format( "{0} - {1}", clientOs, clientBrowser ); interactionDeviceTypeService.Add( interactionDeviceType ); rockContext.SaveChanges(); } // lookup interactionSession, and create it if it doesn't exist Guid sessionId = this.SessionId.AsGuid(); int? interactionSessionId = interactionSessionService.Queryable() .Where( a => a.DeviceTypeId == interactionDeviceType.Id && a.Guid == sessionId ) .Select( a => (int?)a.Id ) .FirstOrDefault(); if ( !interactionSessionId.HasValue ) { var interactionSession = new InteractionSession(); interactionSession.DeviceTypeId = interactionDeviceType.Id; interactionSession.IpAddress = this.IPAddress; interactionSession.Guid = sessionId; interactionSessionService.Add( interactionSession ); rockContext.SaveChanges(); interactionSessionId = interactionSession.Id; } int componentEntityTypeId = EntityTypeCache.Read<Rock.Model.Page>().Id; string siteName = SiteCache.Read( SiteId ?? 1 ).Name; // lookup the interaction channel, and create it if it doesn't exist int channelMediumTypeValueId = DefinedValueCache.Read( SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid() ).Id; // check that the site exists as a channel var interactionChannel = interactionChannelService.Queryable() .Where( a => a.ChannelTypeMediumValueId == channelMediumTypeValueId && a.ChannelEntityId == this.SiteId ) .FirstOrDefault(); if ( interactionChannel == null ) { interactionChannel = new InteractionChannel(); interactionChannel.Name = siteName; interactionChannel.ChannelTypeMediumValueId = channelMediumTypeValueId; interactionChannel.ChannelEntityId = this.SiteId; interactionChannel.ComponentEntityTypeId = componentEntityTypeId; interactionChannelService.Add( interactionChannel ); rockContext.SaveChanges(); } // check that the page exists as a component var interactionComponent = interactionComponentService.Queryable() .Where( a => a.EntityId == PageId && a.ChannelId == interactionChannel.Id ) .FirstOrDefault(); if ( interactionComponent == null ) { interactionComponent = new InteractionComponent(); interactionComponent.Name = PageTitle; interactionComponent.EntityId = PageId; interactionComponent.ChannelId = interactionChannel.Id; interactionComponentService.Add( interactionComponent ); rockContext.SaveChanges(); } // add the interaction Interaction interaction = new Interaction(); interactionService.Add( interaction ); // obfuscate rock magic token Regex rgx = new Regex( @"rckipid=([^&]*)" ); string cleanUrl = rgx.Replace( this.Url, "rckipid=XXXXXXXXXXXXXXXXXXXXXXXXXXXX" ); interaction.InteractionData = cleanUrl; interaction.Operation = "View"; interaction.PersonAliasId = this.PersonAliasId; interaction.InteractionDateTime = this.DateViewed; interaction.InteractionSessionId = interactionSessionId; interaction.InteractionComponentId = interactionComponent.Id; rockContext.SaveChanges(); } } }