Example #1
0
        /// <summary>
        /// Gets the channel.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="identifier">The identifier.</param>
        /// <returns></returns>
        private InteractionChannelCache GetChannel(RockContext rockContext, string identifier)
        {
            if (identifier.IsNotNullOrWhiteSpace())
            {
                // Find by Id
                int?id = identifier.AsIntegerOrNull();
                if (id.HasValue)
                {
                    var channel = InteractionChannelCache.Get(id.Value);
                    if (channel != null)
                    {
                        return(channel);
                    }
                }

                // Find by Guid
                Guid?guid = identifier.AsGuidOrNull();
                if (guid.HasValue)
                {
                    var channel = InteractionChannelCache.Get(guid.Value);
                    if (channel != null)
                    {
                        return(channel);
                    }
                }

                if (!id.HasValue && !guid.HasValue)
                {
                    // Find by Name
                    int?interactionChannelId = new InteractionChannelService(rockContext)
                                               .Queryable()
                                               .AsNoTracking()
                                               .Where(c => c.Name == identifier)
                                               .Select(c => c.Id)
                                               .Cast <int?>()
                                               .FirstOrDefault();

                    if (interactionChannelId != null)
                    {
                        return(InteractionChannelCache.Get(interactionChannelId.Value));
                    }

                    // If still no match, and we have a name, create a new channel
                    using (var newRockContext = new RockContext())
                    {
                        InteractionChannel interactionChannel = new InteractionChannel();
                        interactionChannel.Name = identifier;
                        new InteractionChannelService(newRockContext).Add(interactionChannel);
                        newRockContext.SaveChanges();
                        return(InteractionChannelCache.Get(interactionChannel.Id));
                    }
                }
            }

            return(null);
        }
Example #2
0
        /// <summary>
        /// Returns breadcrumbs specific to the block that should be added to navigation
        /// based on the current page reference.  This function is called during the page's
        /// oninit to load any initial breadcrumbs.
        /// </summary>
        /// <param name="pageReference">The <see cref="T:Rock.Web.PageReference" />.</param>
        /// <returns>
        /// A <see cref="T:System.Collections.Generic.List`1" /> of block related <see cref="T:Rock.Web.UI.BreadCrumb">BreadCrumbs</see>.
        /// </returns>
        public override List <BreadCrumb> GetBreadCrumbs(PageReference pageReference)
        {
            _rockContext    = new RockContext();
            _channelService = new InteractionChannelService(_rockContext);
            _channel        = _channelService.Get(PageParameter("ChannelId").AsInteger());

            var breadCrumbs = new List <BreadCrumb>();

            breadCrumbs.Add(new BreadCrumb(_channel != null ? _channel.Name : "Channel", pageReference));
            return(breadCrumbs);
        }
Example #3
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();
                        }
                    }
                }
            }
        }
        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();
                    }
                }
            }
        }
Example #5
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());
        }
Example #6
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);
            }
        }
Example #7
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();
                        }
                    }
                }
            }
        }
Example #8
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();
                }
            }
        }
Example #9
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();
                }
            }
        }
Example #10
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();
            }
        }
        /// <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);
        }