示例#1
0
        public int GetLastVisitOnSite(int personId, int siteId)
        {
            int channelMediumValueId = DefinedValueCache.Get(SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id;

            InteractionChannelService interactionChannelService = new InteractionChannelService((Rock.Data.RockContext)Service.Context);
            var interactionChannel = interactionChannelService.Queryable()
                                     .Where(a => a.ChannelTypeMediumValueId == channelMediumValueId && a.ChannelEntityId == siteId)
                                     .FirstOrDefault();

            if (interactionChannel == null)
            {
                return(-1);
            }
            Interaction mostRecentPageView = new InteractionService((Rock.Data.RockContext)Service.Context).Queryable()
                                             .Where(a => a.PersonAlias.PersonId == personId && a.InteractionComponent.InteractionChannelId == interactionChannel.Id)
                                             .OrderByDescending(p => p.InteractionDateTime)
                                             .FirstOrDefault();

            if (mostRecentPageView != null)
            {
                TimeSpan duration = RockDateTime.Now - mostRecentPageView.InteractionDateTime;
                return(duration.Days);
            }

            return(-1);
        }
示例#2
0
        /// <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>
        public static void LoadDropDownItems(IInteractionChannelPicker picker, bool includeEmptyOption)
        {
            var selectedItems = picker.Items.Cast <ListItem>()
                                .Where(i => i.Selected)
                                .Select(i => i.Value)
                                .AsIntegerList();

            picker.Items.Clear();

            if (includeEmptyOption)
            {
                // add Empty option first
                picker.Items.Add(new ListItem());
            }

            var rockContext = new RockContext();
            var interactionChannelService = new InteractionChannelService(rockContext);
            var channels = interactionChannelService.Queryable().AsNoTracking()
                           .Include("ChannelTypeMediumValue")
                           .Where(ic => ic.IsActive)
                           .OrderBy(ic => ic.Name)
                           .ToList();

            foreach (var channel in channels)
            {
                var li = new ListItem($"{channel.Name} ({(channel.ChannelTypeMediumValue != null ? channel.ChannelTypeMediumValue.Value : string.Empty )})", channel.Id.ToString());
                li.Selected = selectedItems.Contains(channel.Id);
                picker.Items.Add(li);
            }
        }
示例#3
0
        /// <summary>
        /// Gets the channel identifier by ForeignKey, and creates it if it doesn't exist.
        /// If foreignKey is blank, this will throw a <seealso cref="ArgumentNullException" />
        /// </summary>
        /// <param name="foreignKey">The foreign key.</param>
        /// <param name="channelName">Name of the channel.</param>
        /// <param name="channelTypeMediumValueId">The channel type medium value identifier.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">ForeignKey must be specified when using GetChannelIdByForeignKey</exception>
        /// <exception cref="ArgumentNullException">ForeignKey must be specified when using GetChannelIdByForeignKey</exception>
        public static int GetCreateChannelIdByForeignKey(string foreignKey, string channelName, int?channelTypeMediumValueId)
        {
            if (foreignKey.IsNullOrWhiteSpace())
            {
                throw new ArgumentNullException("ForeignKey must be specified when using GetChannelIdByForeignKey");
            }

            if (_interactionChannelIdLookupFromForeignKey.TryGetValue(foreignKey, out int channelId))
            {
                return(channelId);
            }

            using (var rockContext = new RockContext())
            {
                var interactionChannelService = new InteractionChannelService(rockContext);
                var interactionChannel        = interactionChannelService.Queryable()
                                                .Where(a => a.ForeignKey == foreignKey).FirstOrDefault();

                if (interactionChannel == null)
                {
                    interactionChannel            = new InteractionChannel();
                    interactionChannel.Name       = channelName;
                    interactionChannel.ForeignKey = foreignKey;
                    interactionChannel.ChannelTypeMediumValueId = channelTypeMediumValueId;
                    interactionChannelService.Add(interactionChannel);
                    rockContext.SaveChanges();
                }

                var interactionChannelId = Get(interactionChannel).Id;
                _interactionChannelIdLookupFromForeignKey.AddOrUpdate(foreignKey, interactionChannelId, (k, v) => interactionChannelId);

                return(interactionChannelId);
            }
        }
示例#4
0
        /// <summary>
        /// Creates the child controls.
        /// </summary>
        /// <returns></returns>
        public override Control[] CreateChildControls(Type entityType, FilterField filterControl)
        {
            var ddlInteractionChannel = new RockDropDownList();

            ddlInteractionChannel.ID                    = filterControl.ID + "_ddlInteractionChannel";
            ddlInteractionChannel.Label                 = "Interaction Channel";
            ddlInteractionChannel.CssClass              = "js-interaction-channel";
            ddlInteractionChannel.Required              = true;
            ddlInteractionChannel.AutoPostBack          = true;
            ddlInteractionChannel.EnhanceForLongLists   = true;
            ddlInteractionChannel.SelectedIndexChanged += ddlInteractionChannel_SelectedIndexChanged;
            filterControl.Controls.Add(ddlInteractionChannel);

            var interactionChannelService = new InteractionChannelService(new RockContext());
            var interactionChannels       = interactionChannelService.Queryable().OrderBy(a => a.Name).Select(a => new
            {
                a.Id,
                a.Name
            }).ToList();

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

            int?selectedInteractionChannelId = filterControl.Page.Request.Params[ddlInteractionChannel.UniqueID].AsIntegerOrNull();

            ddlInteractionChannel.SetValue(selectedInteractionChannelId);

            var ddlInteractionComponent = new RockDropDownList();

            ddlInteractionComponent.ID                  = filterControl.ID + "_ddlInteractionComponent";
            ddlInteractionComponent.Label               = "Interaction Component";
            ddlInteractionComponent.CssClass            = "js-interaction-component";
            ddlInteractionComponent.EnhanceForLongLists = true;
            filterControl.Controls.Add(ddlInteractionComponent);

            PopulateInteractionComponent(selectedInteractionChannelId, ddlInteractionComponent);

            RockTextBox tbOperation = new RockTextBox();

            tbOperation.Label    = "Operation";
            tbOperation.ID       = filterControl.ID + "_tbOperation";
            tbOperation.CssClass = "js-tbOperation";
            filterControl.Controls.Add(tbOperation);

            SlidingDateRangePicker slidingDateRangePicker = new SlidingDateRangePicker();

            slidingDateRangePicker.ID = filterControl.ID + "_slidingDateRangePicker";
            slidingDateRangePicker.AddCssClass("js-sliding-date-range");
            slidingDateRangePicker.Label = "Date Range";
            slidingDateRangePicker.Help  = "The date range of the interactions";
            filterControl.Controls.Add(slidingDateRangePicker);

            return(new Control[4] {
                ddlInteractionChannel, ddlInteractionComponent, tbOperation, slidingDateRangePicker
            });
        }
示例#5
0
        private static int LoadByGuid2(Guid guid, RockContext rockContext)
        {
            var interactionChannelService = new InteractionChannelService(rockContext);

            return(interactionChannelService
                   .Queryable().AsNoTracking()
                   .Where(c => c.Guid.Equals(guid))
                   .Select(c => c.Id)
                   .FirstOrDefault());
        }
        /// <summary>
        /// Creates the child controls.
        /// </summary>
        /// <param name="parentControl"></param>
        /// <returns></returns>
        public override System.Web.UI.Control[] CreateChildControls(System.Web.UI.Control parentControl)
        {
            RockDropDownList ddlInteractionChannel = new RockDropDownList();

            ddlInteractionChannel.ID                    = parentControl.ID + "_ddlInteractionChannel";
            ddlInteractionChannel.Label                 = "Interaction Channel";
            ddlInteractionChannel.Required              = true;
            ddlInteractionChannel.AutoPostBack          = true;
            ddlInteractionChannel.SelectedIndexChanged += ddlInteractionChannel_SelectedIndexChanged;
            parentControl.Controls.Add(ddlInteractionChannel);

            var interactionChannelService = new InteractionChannelService(new RockContext());
            var noteTypes = interactionChannelService.Queryable().OrderBy(a => a.Name).Select(a => new
            {
                a.Id,
                a.Name
            }).ToList();

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

            int?selectedInteractionChannelId = parentControl.Page.Request.Params[ddlInteractionChannel.UniqueID].AsIntegerOrNull();

            ddlInteractionChannel.SetValue(selectedInteractionChannelId);


            RockDropDownList ddlInteractionComponent = new RockDropDownList();

            ddlInteractionComponent.ID    = parentControl.ID + "_ddlInteractionComponent";
            ddlInteractionComponent.Label = "Interaction Component";
            ddlInteractionComponent.EnhanceForLongLists = true;
            parentControl.Controls.Add(ddlInteractionComponent);

            PopulateInteractionComponent(selectedInteractionChannelId, ddlInteractionComponent);
            RockTextBox tbOperation = new RockTextBox();

            tbOperation.Label = "Operation";
            tbOperation.ID    = parentControl.ID + "_tbOperation";
            parentControl.Controls.Add(tbOperation);


            RockRadioButtonList rblSelectionMode = new RockRadioButtonList();

            rblSelectionMode.ID    = parentControl.ID + "rblSelectionMode";
            rblSelectionMode.Label = "Selection Mode";
            rblSelectionMode.BindToEnum <FirstLastInteraction>();
            rblSelectionMode.SetValue(FirstLastInteraction.First.ConvertToInt());
            parentControl.Controls.Add(rblSelectionMode);

            return(new System.Web.UI.Control[] { ddlInteractionChannel, ddlInteractionComponent, tbOperation, rblSelectionMode });
        }
示例#7
0
        private static InteractionChannelCache LoadById2(int id, RockContext rockContext)
        {
            var interactionChannelService = new InteractionChannelService(rockContext);
            var interactionChannelModel   = interactionChannelService
                                            .Queryable()
                                            .Where(t => t.Id == id)
                                            .FirstOrDefault();

            if (interactionChannelModel != null)
            {
                return(new InteractionChannelCache(interactionChannelModel));
            }

            return(null);
        }
示例#8
0
        /// <summary>
        /// Cleans up Interactions for Interaction Channels that have a retention period
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        private int CleanupInteractions(JobDataMap dataMap)
        {
            int?batchAmount               = dataMap.GetString("BatchCleanupAmount").AsIntegerOrNull() ?? 1000;
            var interactionRockContext    = new Rock.Data.RockContext();
            var currentDateTime           = RockDateTime.Now;
            var interactionChannelService = new InteractionChannelService(interactionRockContext);
            var interactionChannelQry     = interactionChannelService.Queryable().Where(a => a.RetentionDuration.HasValue);
            int totalRowsDeleted          = 0;

            foreach (var interactionChannel in interactionChannelQry.ToList())
            {
                var retentionCutoffDateTime = currentDateTime.AddDays(-interactionChannel.RetentionDuration.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 = interactionRockContext.Database.BeginTransaction();
                    try
                    {
                        string sqlCommand  = @"
DELETE TOP (@batchAmount)
FROM ia
FROM [Interaction] ia
INNER JOIN [InteractionComponent] ic ON ia.InteractionComponentId = ic.Id
WHERE ic.ChannelId = @channelId
	AND ia.InteractionDateTime < @retentionCutoffDateTime
";
                        int    rowsDeleted = interactionRockContext.Database.ExecuteSqlCommand(sqlCommand, new SqlParameter("batchAmount", batchAmount), new SqlParameter("channelId", interactionChannel.Id), new SqlParameter("retentionCutoffDateTime", retentionCutoffDateTime));
                        keepDeleting      = rowsDeleted > 0;
                        totalRowsDeleted += rowsDeleted;
                    }
                    finally
                    {
                        dbTransaction.Commit();
                    }
                }
            }

            return(totalRowsDeleted);
        }
示例#9
0
        /// <summary>
        /// Gets the channel identifier by type identifier and entity identifier, and creates it if it doesn't exist.
        /// </summary>
        /// <param name="channelTypeMediumValueId">The channel type medium value identifier.</param>
        /// <param name="channelEntityId">The channel entity identifier.</param>
        /// <param name="channelName">Name of the channel. This value will only be used if a new record is created.</param>
        /// <param name="componentEntityTypeId">The component entity type identifier. This value will only be used if a new record is created.</param>
        /// <param name="interactionEntityTypeId">The interaction entity type identifier. This value will only be used if a new record is created.</param>
        /// <returns></returns>
        public static int GetChannelIdByTypeIdAndEntityId(int?channelTypeMediumValueId, int?channelEntityId, string channelName, int?componentEntityTypeId, int?interactionEntityTypeId)
        {
            var lookupKey = $"{channelTypeMediumValueId}|{channelEntityId}";

            if (_interactionChannelLookupFromChannelIdByEntityId.TryGetValue(lookupKey, out int channelId))
            {
                return(channelId);
            }

            using (var rockContext = new RockContext())
            {
                var interactionChannelService = new InteractionChannelService(rockContext);
                var interactionChannel        = interactionChannelService.Queryable()
                                                .Where(a =>
                                                       a.ChannelTypeMediumValueId == channelTypeMediumValueId &&
                                                       a.ChannelEntityId == channelEntityId)
                                                .FirstOrDefault();

                if (interactionChannel == null)
                {
                    interactionChannel      = new InteractionChannel();
                    interactionChannel.Name = channelName;
                    interactionChannel.ChannelTypeMediumValueId = channelTypeMediumValueId;
                    interactionChannel.ChannelEntityId          = channelEntityId;
                    interactionChannel.ComponentEntityTypeId    = componentEntityTypeId;
                    interactionChannel.InteractionEntityTypeId  = interactionEntityTypeId;
                    interactionChannelService.Add(interactionChannel);
                    rockContext.SaveChanges();
                }

                var interactionChannelId = Get(interactionChannel).Id;
                _interactionChannelLookupFromChannelIdByEntityId.AddOrUpdate(lookupKey, interactionChannelId, (k, v) => interactionChannelId);

                return(interactionChannelId);
            }
        }
示例#10
0
        public IHttpActionResult PostInteractions([FromBody] List <MobileInteractionSession> sessions, Guid?personalDeviceGuid = null)
        {
            var person    = GetPerson();
            var ipAddress = System.Web.HttpContext.Current?.Request?.UserHostAddress;

            using (var rockContext = new Data.RockContext())
            {
                var interactionChannelService   = new InteractionChannelService(rockContext);
                var interactionComponentService = new InteractionComponentService(rockContext);
                var interactionSessionService   = new InteractionSessionService(rockContext);
                var interactionService          = new InteractionService(rockContext);
                var userLoginService            = new UserLoginService(rockContext);
                var channelMediumTypeValue      = DefinedValueCache.Get(SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE);
                var pageEntityTypeId            = EntityTypeCache.Get(typeof(Model.Page)).Id;

                //
                // Check to see if we have a site and the API key is valid.
                //
                if (MobileHelper.GetCurrentApplicationSite() == null)
                {
                    return(StatusCode(System.Net.HttpStatusCode.Forbidden));
                }

                //
                // Get the personal device identifier if they provided it's unique identifier.
                //
                int?personalDeviceId = null;
                if (personalDeviceGuid.HasValue)
                {
                    personalDeviceId = new PersonalDeviceService(rockContext).GetId(personalDeviceGuid.Value);
                }

                rockContext.WrapTransaction(() =>
                {
                    foreach (var mobileSession in sessions)
                    {
                        var interactionGuids         = mobileSession.Interactions.Select(i => i.Guid).ToList();
                        var existingInteractionGuids = interactionService.Queryable()
                                                       .Where(i => interactionGuids.Contains(i.Guid))
                                                       .Select(i => i.Guid)
                                                       .ToList();

                        //
                        // Loop through all interactions that don't already exist and add each one.
                        //
                        foreach (var mobileInteraction in mobileSession.Interactions.Where(i => !existingInteractionGuids.Contains(i.Guid)))
                        {
                            int?interactionComponentId = null;

                            //
                            // Lookup the interaction channel, and create it if it doesn't exist
                            //
                            if (mobileInteraction.AppId.HasValue && mobileInteraction.PageGuid.HasValue)
                            {
                                var site = SiteCache.Get(mobileInteraction.AppId.Value);
                                var page = PageCache.Get(mobileInteraction.PageGuid.Value);

                                if (site == null || page == null)
                                {
                                    continue;
                                }

                                //
                                // Try to find an existing interaction channel.
                                //
                                var interactionChannelId = interactionChannelService.Queryable()
                                                           .Where(a =>
                                                                  a.ChannelTypeMediumValueId == channelMediumTypeValue.Id &&
                                                                  a.ChannelEntityId == site.Id)
                                                           .Select(a => ( int? )a.Id)
                                                           .FirstOrDefault();

                                //
                                // If not found, create one.
                                //
                                if (!interactionChannelId.HasValue)
                                {
                                    var interactionChannel = new InteractionChannel
                                    {
                                        Name = site.Name,
                                        ChannelTypeMediumValueId = channelMediumTypeValue.Id,
                                        ChannelEntityId          = site.Id,
                                        ComponentEntityTypeId    = pageEntityTypeId
                                    };

                                    interactionChannelService.Add(interactionChannel);
                                    rockContext.SaveChanges();

                                    interactionChannelId = interactionChannel.Id;
                                }

                                //
                                // Get an existing or create a new component.
                                //
                                var interactionComponent = interactionComponentService.GetComponentByChannelIdAndEntityId(interactionChannelId.Value, page.Id, page.InternalName);
                                rockContext.SaveChanges();

                                interactionComponentId = interactionComponent.Id;
                            }
                            else if (mobileInteraction.ChannelId.HasValue)
                            {
                                var interactionChannelId = mobileInteraction.ChannelId;

                                if (mobileInteraction.ComponentId.HasValue)
                                {
                                    interactionComponentId = mobileInteraction.ComponentId.Value;
                                }
                                else if (mobileInteraction.ComponentName.IsNotNullOrWhiteSpace())
                                {
                                    //
                                    // Get an existing or create a new component.
                                    //
                                    var interactionComponent = interactionComponentService.GetComponentByComponentName(interactionChannelId.Value, mobileInteraction.ComponentName);
                                    rockContext.SaveChanges();

                                    interactionComponentId = interactionComponent.Id;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                continue;
                            }

                            //
                            // Add the interaction
                            //
                            if (interactionComponentId.HasValue)
                            {
                                var interaction = interactionService.CreateInteraction(interactionComponentId.Value,
                                                                                       mobileInteraction.EntityId,
                                                                                       mobileInteraction.Operation,
                                                                                       mobileInteraction.Summary,
                                                                                       mobileInteraction.Data,
                                                                                       person?.PrimaryAliasId,
                                                                                       mobileInteraction.DateTime,
                                                                                       mobileSession.Application,
                                                                                       mobileSession.OperatingSystem,
                                                                                       mobileSession.ClientType,
                                                                                       null,
                                                                                       ipAddress,
                                                                                       mobileSession.Guid);

                                interaction.Guid             = mobileInteraction.Guid;
                                interaction.PersonalDeviceId = personalDeviceId;
                                interactionService.Add(interaction);
                                rockContext.SaveChanges();
                            }
                        }
                    }
                });
            }

            return(Ok());
        }
示例#11
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            Site site;

            if (Page.IsValid)
            {
                var               rockContext       = new RockContext();
                PageService       pageService       = new PageService(rockContext);
                SiteService       siteService       = new SiteService(rockContext);
                SiteDomainService siteDomainService = new SiteDomainService(rockContext);
                bool              newSite           = false;

                int siteId = hfSiteId.Value.AsInteger();

                if (siteId == 0)
                {
                    newSite = true;
                    site    = new Rock.Model.Site();
                    siteService.Add(site);
                }
                else
                {
                    site = siteService.Get(siteId);
                }

                site.Name                      = tbSiteName.Text;
                site.Description               = tbDescription.Text;
                site.Theme                     = ddlTheme.Text;
                site.DefaultPageId             = ppDefaultPage.PageId;
                site.DefaultPageRouteId        = ppDefaultPage.PageRouteId;
                site.LoginPageId               = ppLoginPage.PageId;
                site.LoginPageRouteId          = ppLoginPage.PageRouteId;
                site.ChangePasswordPageId      = ppChangePasswordPage.PageId;
                site.ChangePasswordPageRouteId = ppChangePasswordPage.PageRouteId;
                site.CommunicationPageId       = ppCommunicationPage.PageId;
                site.CommunicationPageRouteId  = ppCommunicationPage.PageRouteId;
                site.RegistrationPageId        = ppRegistrationPage.PageId;
                site.RegistrationPageRouteId   = ppRegistrationPage.PageRouteId;
                site.PageNotFoundPageId        = ppPageNotFoundPage.PageId;
                site.PageNotFoundPageRouteId   = ppPageNotFoundPage.PageRouteId;
                site.ErrorPage                 = tbErrorPage.Text;
                site.GoogleAnalyticsCode       = tbGoogleAnalytics.Text;
                site.RequiresEncryption        = cbRequireEncryption.Checked;
                site.EnabledForShortening      = cbEnableForShortening.Checked;
                site.EnableMobileRedirect      = cbEnableMobileRedirect.Checked;
                site.MobilePageId              = ppMobilePage.PageId;
                site.ExternalUrl               = tbExternalURL.Text;
                site.AllowedFrameDomains       = tbAllowedFrameDomains.Text;
                site.RedirectTablets           = cbRedirectTablets.Checked;
                site.EnablePageViews           = cbEnablePageViews.Checked;

                site.AllowIndexing         = cbAllowIndexing.Checked;
                site.IsIndexEnabled        = cbEnableIndexing.Checked;
                site.IndexStartingLocation = tbIndexStartingLocation.Text;

                site.PageHeaderContent = cePageHeaderContent.Text;

                int?existingIconId = null;
                if (site.FavIconBinaryFileId != imgSiteIcon.BinaryFileId)
                {
                    existingIconId           = site.FavIconBinaryFileId;
                    site.FavIconBinaryFileId = imgSiteIcon.BinaryFileId;
                }

                int?existingLogoId = null;
                if (site.SiteLogoBinaryFileId != imgSiteLogo.BinaryFileId)
                {
                    existingLogoId            = site.SiteLogoBinaryFileId;
                    site.SiteLogoBinaryFileId = imgSiteLogo.BinaryFileId;
                }

                var currentDomains = tbSiteDomains.Text.SplitDelimitedValues().ToList <string>();
                site.SiteDomains = site.SiteDomains ?? new List <SiteDomain>();

                // Remove any deleted domains
                foreach (var domain in site.SiteDomains.Where(w => !currentDomains.Contains(w.Domain)).ToList())
                {
                    site.SiteDomains.Remove(domain);
                    siteDomainService.Delete(domain);
                }

                int order = 0;
                foreach (string domain in currentDomains)
                {
                    SiteDomain sd = site.SiteDomains.Where(d => d.Domain == domain).FirstOrDefault();
                    if (sd == null)
                    {
                        sd        = new SiteDomain();
                        sd.Domain = domain;
                        sd.Guid   = Guid.NewGuid();
                        site.SiteDomains.Add(sd);
                    }
                    sd.Order = order++;
                }

                if (!site.DefaultPageId.HasValue && !newSite)
                {
                    ppDefaultPage.ShowErrorMessage("Default Page is required.");
                    return;
                }

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

                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();

                    SaveAttributes(new Page().TypeId, "SiteId", site.Id.ToString(), PageAttributesState, rockContext);

                    if (existingIconId.HasValue)
                    {
                        BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                        var binaryFile = binaryFileService.Get(existingIconId.Value);
                        if (binaryFile != null)
                        {
                            // marked the old images as IsTemporary so they will get cleaned up later
                            binaryFile.IsTemporary = true;
                            rockContext.SaveChanges();
                        }
                    }

                    if (existingLogoId.HasValue)
                    {
                        BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                        var binaryFile = binaryFileService.Get(existingLogoId.Value);
                        if (binaryFile != null)
                        {
                            // marked the old images as IsTemporary so they will get cleaned up later
                            binaryFile.IsTemporary = true;
                            rockContext.SaveChanges();
                        }
                    }

                    if (newSite)
                    {
                        Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.EDIT);
                        Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.ADMINISTRATE);
                        Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.APPROVE);
                    }
                });

                // add/update for the InteractionChannel for this site and set the RetentionPeriod
                var interactionChannelService   = new InteractionChannelService(rockContext);
                int channelMediumWebsiteValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id;
                var interactionChannelForSite   = interactionChannelService.Queryable()
                                                  .Where(a => a.ChannelTypeMediumValueId == channelMediumWebsiteValueId && a.ChannelEntityId == site.Id).FirstOrDefault();

                if (interactionChannelForSite == null)
                {
                    interactionChannelForSite = new InteractionChannel();
                    interactionChannelForSite.ChannelTypeMediumValueId = channelMediumWebsiteValueId;
                    interactionChannelForSite.ChannelEntityId          = site.Id;
                    interactionChannelService.Add(interactionChannelForSite);
                }

                interactionChannelForSite.Name = site.Name;
                interactionChannelForSite.RetentionDuration     = nbPageViewRetentionPeriodDays.Text.AsIntegerOrNull();
                interactionChannelForSite.ComponentEntityTypeId = EntityTypeCache.Get <Rock.Model.Page>().Id;

                rockContext.SaveChanges();


                // Create the default page is this is a new site
                if (!site.DefaultPageId.HasValue && newSite)
                {
                    var siteCache = SiteCache.Get(site.Id);

                    // Create the layouts for the site, and find the first one
                    LayoutService.RegisterLayouts(Request.MapPath("~"), siteCache);

                    var    layoutService = new LayoutService(rockContext);
                    var    layouts       = layoutService.GetBySiteId(siteCache.Id);
                    Layout layout        = layouts.FirstOrDefault(l => l.FileName.Equals("FullWidth", StringComparison.OrdinalIgnoreCase));
                    if (layout == null)
                    {
                        layout = layouts.FirstOrDefault();
                    }

                    if (layout != null)
                    {
                        var page = new Page();
                        page.LayoutId              = layout.Id;
                        page.PageTitle             = siteCache.Name + " Home Page";
                        page.InternalName          = page.PageTitle;
                        page.BrowserTitle          = page.PageTitle;
                        page.EnableViewState       = true;
                        page.IncludeAdminFooter    = true;
                        page.MenuDisplayChildPages = true;

                        var lastPage = pageService.GetByParentPageId(null).OrderByDescending(b => b.Order).FirstOrDefault();

                        page.Order = lastPage != null ? lastPage.Order + 1 : 0;
                        pageService.Add(page);

                        rockContext.SaveChanges();

                        site = siteService.Get(siteCache.Id);
                        site.DefaultPageId = page.Id;

                        rockContext.SaveChanges();
                    }
                }

                var qryParams = new Dictionary <string, string>();
                qryParams["siteId"] = site.Id.ToString();

                NavigateToPage(RockPage.Guid, qryParams);
            }
        }
示例#12
0
        /// <summary>
        /// Execute method to write transaction to the database.
        /// </summary>
        public void Execute()
        {
            if (PageShortLinkId.HasValue)
            {
                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 = InteractionDeviceType.GetClientType(userAgent);

                    // don't log visits from crawlers
                    if (clientType != "Crawler")
                    {
                        // lookup the interaction channel, and create it if it doesn't exist
                        int channelMediumTypeValueId = DefinedValueCache.Get(SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_URLSHORTENER.AsGuid()).Id;
                        InteractionChannelService interactionChannelService = new InteractionChannelService(rockContext);
                        var interactionChannel = interactionChannelService.Queryable()
                                                 .Where(a => a.ChannelTypeMediumValueId == channelMediumTypeValueId)
                                                 .FirstOrDefault();
                        if (interactionChannel == null)
                        {
                            interactionChannel      = new InteractionChannel();
                            interactionChannel.Name = "Short Links";
                            interactionChannel.ChannelTypeMediumValueId = channelMediumTypeValueId;
                            interactionChannel.ComponentEntityTypeId    = EntityTypeCache.Get <Rock.Model.PageShortLink>().Id;;
                            interactionChannel.Guid = SystemGuid.InteractionChannel.SHORT_LINKS.AsGuid();
                            interactionChannelService.Add(interactionChannel);
                            rockContext.SaveChanges();
                        }

                        // check that the page exists as a component
                        var interactionComponent = new InteractionComponentService(rockContext).GetComponentByEntityId(interactionChannel.Id, PageShortLinkId.Value, Token);
                        if (Url.IsNotNullOrWhiteSpace())
                        {
                            if (interactionComponent.ComponentSummary != Url)
                            {
                                interactionComponent.ComponentSummary = Url;
                            }

                            var urlDataJson = new { Url = Url }.ToJson();
                            if (interactionComponent.ComponentData != urlDataJson)
                            {
                                interactionComponent.ComponentData = urlDataJson;
                            }
                        }

                        rockContext.SaveChanges();

                        // Add the interaction
                        if (interactionComponent != null)
                        {
                            int?personAliasId = null;
                            if (UserName.IsNotNullOrWhiteSpace())
                            {
                                var currentUser = new UserLoginService(rockContext).GetByUserName(UserName);
                                personAliasId = currentUser?.Person?.PrimaryAlias?.Id;
                            }

                            ClientInfo client        = uaParser.Parse(userAgent);
                            var        clientOs      = client.OS.ToString();
                            var        clientBrowser = client.UserAgent.ToString();

                            new InteractionService(rockContext).AddInteraction(interactionComponent.Id, null, "View", Url, personAliasId, DateViewed,
                                                                               clientBrowser, clientOs, clientType, userAgent, IPAddress, this.SessionId?.AsGuidOrNull());
                            rockContext.SaveChanges();
                        }
                    }
                }
            }
        }
示例#13
0
        /// <summary>
        /// Execute method to write transaction to the database.
        /// </summary>
        public void Execute()
        {
            if (!PageId.HasValue)
            {
                return;
            }

            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 = InteractionDeviceType.GetClientType(userAgent);

            // don't log visits from crawlers
            if (clientType == "Crawler")
            {
                return;
            }

            using (var rockContext = new RockContext())
            {
                // lookup the interaction channel, and create it if it doesn't exist
                int channelMediumTypeValueId  = DefinedValueCache.Get(SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id;
                var interactionChannelService = new InteractionChannelService(rockContext);
                var interactionChannelId      = interactionChannelService.Queryable()
                                                .Where(a =>
                                                       a.ChannelTypeMediumValueId == channelMediumTypeValueId &&
                                                       a.ChannelEntityId == this.SiteId)
                                                .Select(a => ( int? )a.Id)
                                                .FirstOrDefault();
                if (interactionChannelId == null)
                {
                    var interactionChannel = new InteractionChannel();
                    interactionChannel.Name = SiteCache.Get(SiteId ?? 1).Name;
                    interactionChannel.ChannelTypeMediumValueId = channelMediumTypeValueId;
                    interactionChannel.ChannelEntityId          = this.SiteId;
                    interactionChannel.ComponentEntityTypeId    = EntityTypeCache.Get <Rock.Model.Page>().Id;
                    interactionChannelService.Add(interactionChannel);
                    rockContext.SaveChanges();
                    interactionChannelId = interactionChannel.Id;
                }

                // check that the page exists as a component
                var interactionComponent = new InteractionComponentService(rockContext).GetComponentByEntityId(interactionChannelId.Value, PageId.Value, PageTitle);
                if (interactionComponent.Id == 0)
                {
                    rockContext.SaveChanges();
                }

                // Add the interaction
                if (interactionComponent != null)
                {
                    var title = string.Empty;
                    if (BrowserTitle.IsNotNullOrWhiteSpace())
                    {
                        title = BrowserTitle;
                    }
                    else
                    {
                        title = PageTitle;
                    }

                    // remove site name from browser title
                    if (title.Contains("|"))
                    {
                        title = title.Substring(0, title.LastIndexOf('|')).Trim();
                    }

                    var interactionService = new InteractionService(rockContext);
                    var interaction        = interactionService.CreateInteraction(interactionComponent.Id, this.UserAgent, this.Url, this.IPAddress, this.SessionId.AsGuidOrNull());

                    interaction.EntityId            = null;
                    interaction.Operation           = "View";
                    interaction.InteractionSummary  = title;
                    interaction.InteractionData     = Url;
                    interaction.PersonAliasId       = PersonAliasId;
                    interaction.InteractionDateTime = DateViewed;
                    interactionService.Add(interaction);

                    rockContext.SaveChanges();
                }
            }
        }
        public void Execute()
        {
            if (PageId.HasValue || !string.IsNullOrWhiteSpace(ComponentName))
            {
                using (var rockContext = new RockContext())
                {
                    int channelMediumTypeValueId  = DefinedValueCache.Get(AvalancheUtilities.AppMediumValue.AsGuid()).Id;
                    var interactionChannelService = new InteractionChannelService(rockContext);
                    var interactionService        = new InteractionService(rockContext);
                    var interactionChannel        = interactionChannelService.Queryable()
                                                    .Where(a =>
                                                           a.ChannelTypeMediumValueId == channelMediumTypeValueId &&
                                                           a.ChannelEntityId == this.SiteId)
                                                    .FirstOrDefault();
                    if (interactionChannel == null)
                    {
                        interactionChannel      = new InteractionChannel();
                        interactionChannel.Name = SiteCache.Get(SiteId ?? 1).Name;
                        interactionChannel.ChannelTypeMediumValueId = channelMediumTypeValueId;
                        interactionChannel.ChannelEntityId          = this.SiteId;
                        interactionChannel.ComponentEntityTypeId    = EntityTypeCache.Get <Rock.Model.Page>().Id;
                        interactionChannelService.Add(interactionChannel);
                        rockContext.SaveChanges();
                    }

                    InteractionComponent interactionComponent = null;
                    var interactionComponentService           = new InteractionComponentService(rockContext);

                    if (PageId.HasValue)
                    {
                        interactionComponent = interactionComponentService.GetComponentByEntityId(interactionChannel.Id, PageId.Value, PageTitle);
                    }
                    else
                    {
                        interactionComponent = interactionComponentService.GetComponentByComponentName(interactionChannel.Id, ComponentName);
                    }
                    rockContext.SaveChanges();

                    // Add the interaction
                    if (interactionComponent != null)
                    {
                        var deviceId = Regex.Match(UserAgent, "(?<=-).+(?=\\))").Value.Trim();
                        if (deviceId.Length > 20)
                        {
                            deviceId = deviceId.Substring(0, 20);
                        }
                        var deviceApplication = Regex.Match(UserAgent, "^[\\S]{0,}").Value.Trim() + " " + deviceId;
                        var clientOs          = Regex.Match(UserAgent, "(?<=;).+(?=-)").Value.Trim();
                        var clientType        = Regex.Match(UserAgent, "(?<=\\().+(?=;)").Value.Trim();

                        var deviceType = interactionService.GetInteractionDeviceType(deviceApplication, clientOs, clientType, UserAgent);
                        var interactionSessionService = new InteractionSessionService(rockContext);
                        var interactionSession        = interactionSessionService.Queryable().Where(s => s.IpAddress == IPAddress && s.DeviceTypeId == deviceType.Id).FirstOrDefault();

                        if (interactionSession == null)
                        {
                            interactionSession = new InteractionSession()
                            {
                                DeviceTypeId = deviceType.Id,
                                IpAddress    = TrimString(IPAddress, 25)
                            };
                            interactionSessionService.Add(interactionSession);
                            rockContext.SaveChanges();
                        }

                        Operation          = TrimString(Operation, 25);
                        InteractionSummary = TrimString(InteractionSummary, 500);
                        clientType         = TrimString(clientType, 25);
                        deviceApplication  = TrimString(deviceApplication, 100);
                        clientOs           = TrimString(clientOs, 100);

                        var interaction = new InteractionService(rockContext).AddInteraction(interactionComponent.Id, null, Operation, InteractionData, PersonAliasId, DateViewed,
                                                                                             deviceApplication, clientOs, clientType, UserAgent, IPAddress, interactionSession.Guid);

                        interaction.InteractionSummary = InteractionSummary;

                        PersonalDevice personalDevice = AvalancheUtilities.GetPersonalDevice(deviceId, PersonAliasId, rockContext);
                        if (personalDevice != null)
                        {
                            interaction.PersonalDeviceId = personalDevice.Id;
                        }

                        rockContext.SaveChanges();
                    }
                }
            }
        }
示例#15
0
        /// <summary>
        /// Execute method to write transaction to the database.
        /// </summary>
        public void Execute()
        {
            if (!this._logInteraction || InteractionSummary.IsNullOrWhiteSpace())
            {
                return;
            }

            if (!this.LogCrawlers)
            {
                // get user agent info
                var clientType = InteractionDeviceType.GetClientType(_userAgent);
                // don't log visits from crawlers
                if (clientType == "Crawler")
                {
                    return;
                }
            }

            var rockContext = new RockContext();

            // lookup the interaction channel, and create it if it doesn't exist
            var interactionChannelService = new InteractionChannelService(rockContext);
            var interactionChannelId      = interactionChannelService.Queryable()
                                            .Where(a =>
                                                   a.ChannelTypeMediumValueId == _channelMediumTypeValue.Id &&
                                                   a.ChannelEntityId == _channelEntityId)
                                            .Select(a => ( int? )a.Id)
                                            .FirstOrDefault();

            if (interactionChannelId == null)
            {
                var interactionChannel = new InteractionChannel();
                interactionChannel.Name = _channelName;
                interactionChannel.ChannelTypeMediumValueId = _channelMediumTypeValue.Id;
                interactionChannel.ChannelEntityId          = _channelEntityId;
                interactionChannel.ComponentEntityTypeId    = _componentEntityTypeId;
                interactionChannelService.Add(interactionChannel);
                rockContext.SaveChanges();
                interactionChannelId = interactionChannel.Id;
            }

            // check that the contentChannelItem exists as a component
            var interactionComponent = new InteractionComponentService(rockContext).GetComponentByEntityId(interactionChannelId.Value, _componentEntityId, _componentName);

            rockContext.SaveChanges();

            // Add the interaction
            if (interactionComponent != null)
            {
                var interactionService = new InteractionService(rockContext);
                var interaction        = interactionService.CreateInteraction(interactionComponent.Id, _userAgent, _url, _ipAddress, _browserSessionId);

                interaction.EntityId            = null;
                interaction.Operation           = "View";
                interaction.InteractionSummary  = InteractionSummary;
                interaction.InteractionData     = _url;
                interaction.PersonAliasId       = CurrentPersonAliasId;
                interaction.InteractionDateTime = RockDateTime.Now;
                interactionService.Add(interaction);
                rockContext.SaveChanges();
            }
        }
示例#16
0
        public int GetLastVisitOnSite( int personId, int siteId )
        {
            int channelMediumValueId = DefinedValueCache.Read( SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid() ).Id;

            InteractionChannelService interactionChannelService = new InteractionChannelService( ( Rock.Data.RockContext ) Service.Context );
            var interactionChannel = interactionChannelService.Queryable()
                                                .Where( a => a.ChannelTypeMediumValueId == channelMediumValueId && a.ChannelEntityId == siteId )
                                                .FirstOrDefault();

            if ( interactionChannel == null )
            {
                return -1;
            }
            Interaction mostRecentPageView = new InteractionService( ( Rock.Data.RockContext ) Service.Context ).Queryable()
                                                .Where( a => a.PersonAlias.PersonId == personId && a.InteractionComponent.ChannelId == interactionChannel.Id )
                                                .OrderByDescending( p => p.InteractionDateTime )
                                                .FirstOrDefault();

            if ( mostRecentPageView != null )
            {
                TimeSpan duration = RockDateTime.Now - mostRecentPageView.InteractionDateTime;
                return duration.Days;
            }

            return -1;
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            var applicationId = PageParameter(PageParameterKey.SiteId).AsInteger();

            var rockContext = new RockContext();
            var siteService = new SiteService(rockContext);
            var site        = siteService.Get(applicationId);

            var additionalSettings = new AppleTvApplicationSettings();
            var isNewSite          = false;

            // Site is new so create one
            if (site == null)
            {
                site = new Site();
                siteService.Add(site);
                isNewSite = true;
            }
            else
            {
                additionalSettings = JsonConvert.DeserializeObject <AppleTvApplicationSettings>(site.AdditionalSettings);
            }

            site.Name        = tbApplicationName.Text;
            site.Description = tbDescription.Text;
            site.IsActive    = cbIsActive.Checked;
            site.SiteType    = SiteType.Tv;

            additionalSettings.ApplicationScript = ceApplicationJavaScript.Text;
            additionalSettings.ApplicationStyles = ceApplicationStyles.Text;
            additionalSettings.TvApplicationType = TvApplicationType.AppleTv;

            // Login page
            site.LoginPageId      = ppLoginPage.PageId;
            site.LoginPageRouteId = ppLoginPage.PageRouteId;

            // Create/Modify API Key
            additionalSettings.ApiKeyId = SaveApiKey(additionalSettings.ApiKeyId, txtApiKey.Text, string.Format("tv_application_{0}", site.Id), rockContext);
            site.AdditionalSettings     = additionalSettings.ToJson();

            rockContext.SaveChanges();

            // Create interaction channel for this site
            var interactionChannelService   = new InteractionChannelService(rockContext);
            int channelMediumWebsiteValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id;
            var interactionChannelForSite   = interactionChannelService.Queryable()
                                              .Where(a => a.ChannelTypeMediumValueId == channelMediumWebsiteValueId && a.ChannelEntityId == site.Id).FirstOrDefault();

            if (interactionChannelForSite == null)
            {
                interactionChannelForSite = new InteractionChannel();
                interactionChannelForSite.ChannelTypeMediumValueId = channelMediumWebsiteValueId;
                interactionChannelForSite.ChannelEntityId          = site.Id;
                interactionChannelService.Add(interactionChannelForSite);
            }

            interactionChannelForSite.Name = site.Name;
            interactionChannelForSite.RetentionDuration     = nbPageViewRetentionPeriodDays.Text.AsIntegerOrNull();
            interactionChannelForSite.ComponentEntityTypeId = EntityTypeCache.Get <Rock.Model.Page>().Id;

            rockContext.SaveChanges();

            // If this is a new site then we also need to add a layout record and a 'default page'
            if (isNewSite)
            {
                var layoutService = new LayoutService(rockContext);

                var layout = new Layout
                {
                    Name        = "Homepage",
                    FileName    = "Homepage.xaml",
                    Description = string.Empty,
                    SiteId      = site.Id
                };

                layoutService.Add(layout);
                rockContext.SaveChanges();

                var pageService = new PageService(rockContext);
                var page        = new Rock.Model.Page {
                    InternalName     = "Start Screen",
                    BrowserTitle     = "Start Screen",
                    PageTitle        = "Start Screen",
                    DisplayInNavWhen = DisplayInNavWhen.WhenAllowed,
                    Description      = string.Empty,
                    LayoutId         = layout.Id,
                    Order            = 0
                };

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

                site.DefaultPageId = page.Id;
                rockContext.SaveChanges();
            }

            // If the save was successful, reload the page using the new record Id.
            var qryParams = new Dictionary <string, string>();

            qryParams[PageParameterKey.SiteId] = site.Id.ToString();

            NavigateToPage(RockPage.Guid, qryParams);
        }
示例#18
0
        /// <summary>
        /// Execute method to write transaction to the database.
        /// </summary>
        public void Execute()
        {
            if (PageId.HasValue)
            {
                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 = InteractionDeviceType.GetClientType(userAgent);

                    // don't log visits from crawlers
                    if (clientType != "Crawler")
                    {
                        // lookup the interaction channel, and create it if it doesn't exist
                        int channelMediumTypeValueId  = DefinedValueCache.Read(SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id;
                        var interactionChannelService = new InteractionChannelService(rockContext);
                        var interactionChannel        = interactionChannelService.Queryable()
                                                        .Where(a =>
                                                               a.ChannelTypeMediumValueId == channelMediumTypeValueId &&
                                                               a.ChannelEntityId == this.SiteId)
                                                        .FirstOrDefault();
                        if (interactionChannel == null)
                        {
                            interactionChannel      = new InteractionChannel();
                            interactionChannel.Name = SiteCache.Read(SiteId ?? 1).Name;
                            interactionChannel.ChannelTypeMediumValueId = channelMediumTypeValueId;
                            interactionChannel.ChannelEntityId          = this.SiteId;
                            interactionChannel.ComponentEntityTypeId    = EntityTypeCache.Read <Rock.Model.Page>().Id;
                            interactionChannelService.Add(interactionChannel);
                            rockContext.SaveChanges();
                        }

                        // check that the page exists as a component
                        var interactionComponent = new InteractionComponentService(rockContext).GetComponentByEntityId(interactionChannel.Id, PageId.Value, PageTitle);
                        rockContext.SaveChanges();

                        // Add the interaction
                        if (interactionComponent != null)
                        {
                            ClientInfo client        = uaParser.Parse(userAgent);
                            var        clientOs      = client.OS.ToString();
                            var        clientBrowser = client.UserAgent.ToString();

                            var interaction = new InteractionService(rockContext).AddInteraction(interactionComponent.Id, null, "View", Url, PersonAliasId, DateViewed,
                                                                                                 clientBrowser, clientOs, clientType, userAgent, IPAddress, this.SessionId?.AsGuidOrNull());

                            if (Url.IsNotNullOrWhitespace() && Url.IndexOf("utm_", StringComparison.OrdinalIgnoreCase) >= 0)
                            {
                                var urlParams = HttpUtility.ParseQueryString(Url);
                                interaction.Source   = urlParams.Get("utm_source").Truncate(25);
                                interaction.Medium   = urlParams.Get("utm_medium").Truncate(25);
                                interaction.Campaign = urlParams.Get("utm_campaign").Truncate(50);
                                interaction.Content  = urlParams.Get("utm_content").Truncate(50);
                            }

                            rockContext.SaveChanges();
                        }
                    }
                }
            }
        }
示例#19
0
        /// <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();
                }
            }
        }