/// <summary>
        /// Sets the edit value from IEntity.Id value
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id">The identifier.</param>
        public void SetEditValueFromEntityId(System.Web.UI.Control control, Dictionary <string, ConfigurationValue> configurationValues, int?id)
        {
            var    item      = new InteractionChannelService(new RockContext()).Get(id ?? 0);
            string guidValue = item != null?item.Guid.ToString() : string.Empty;

            SetEditValue(control, configurationValues, guidValue);
        }
Beispiel #2
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);
            }
        }
        /// <summary>
        /// Gets the edit value as the IEntity.Id
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <returns></returns>
        public int?GetEditValueAsEntityId(System.Web.UI.Control control, Dictionary <string, ConfigurationValue> configurationValues)
        {
            Guid guid = GetEditValue(control, configurationValues).AsGuid();
            var  item = new InteractionChannelService(new RockContext()).Get(guid);

            return(item != null ? item.Id : ( int? )null);
        }
        /// <summary>
        /// Shows the details.
        /// </summary>
        private void ShowEdit()
        {
            pnlView.Visible        = false;
            pnlEdit.Visible        = true;
            pdAuditDetails.Visible = false;

            // Hide the page list block
            this.HideSecondaryBlocks(true);

            var applicationId = PageParameter(PageParameterKey.SiteId).AsInteger();

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

            if (site != null)
            {
                hlblInactive.Visible = !site?.IsActive ?? true;
                lBlockTitle.Text     = site.Name;

                tbApplicationName.Text = site.Name;
                tbDescription.Text     = site.Description;

                cbIsActive.Checked = site.IsActive;

                var additionalSettings = JsonConvert.DeserializeObject <AppleTvApplicationSettings>(site.AdditionalSettings);

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

                cbEnablePageViews.Checked = site.EnablePageViews;

                // Login Page
                if (site.LoginPageRoute != null)
                {
                    ppLoginPage.SetValue(site.LoginPageRoute);
                }
                else
                {
                    ppLoginPage.SetValue(site.LoginPage);
                }

                // Set the API key
                var apiKeyLogin = new UserLoginService(rockContext).Get(additionalSettings.ApiKeyId ?? 0);
                txtApiKey.Text = apiKeyLogin != null ? apiKeyLogin.ApiKey : GenerateApiKey();

                // Get page view retention
                int channelMediumWebsiteValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id;
                var retentionDuration           = new InteractionChannelService(new RockContext()).Queryable()
                                                  .Where(c => c.ChannelTypeMediumValueId == channelMediumWebsiteValueId && c.ChannelEntityId == site.Id)
                                                  .Select(c => c.RetentionDuration)
                                                  .FirstOrDefault();

                if (retentionDuration.HasValue)
                {
                    nbPageViewRetentionPeriodDays.Text = retentionDuration.Value.ToString();
                }

                nbPageViewRetentionPeriodDays.Visible = site.EnablePageViews;
            }
        }
        /// <summary>
        /// Gets the selection.
        /// </summary>
        /// <param name="controls">The controls.</param>
        /// <returns></returns>
        public override string GetSelection(System.Web.UI.Control[] controls)
        {
            var ddlInteractionChannel   = (controls[0] as RockDropDownList);
            var ddlInteractionComponent = (controls[1] as RockDropDownList);
            var tbOperation             = (controls[2] as RockTextBox);
            var rblSelectionMode        = (controls[3] as RockRadioButtonList);

            int  interactionChannelId   = ddlInteractionChannel.SelectedValueAsId() ?? 0;
            var  rockContext            = new RockContext();
            var  interactionChannel     = new InteractionChannelService(rockContext).Get(interactionChannelId);
            Guid?interactionChannelGuid = null;

            if (interactionChannel != null)
            {
                interactionChannelGuid = interactionChannel.Guid;
            }

            int  interactionComponentId   = ddlInteractionComponent.SelectedValueAsId() ?? 0;
            var  interactionComponent     = new InteractionComponentService(rockContext).Get(interactionComponentId);
            Guid?interactionComponentGuid = null;

            if (interactionComponent != null)
            {
                interactionComponentGuid = interactionComponent.Guid;
            }

            return($"{interactionChannelGuid.ToString()}|{interactionComponentGuid}|{tbOperation.Text}|{rblSelectionMode.SelectedValue}");
        }
Beispiel #6
0
        /// <summary>
        /// Gets the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="controls">The controls.</param>
        /// <returns></returns>
        public override string GetSelection(Type entityType, Control[] controls)
        {
            var ddlInteractionChannel   = (controls[0] as RockDropDownList);
            var ddlInteractionComponent = (controls[1] as RockDropDownList);
            var tbOperation             = (controls[2] as RockTextBox);
            var slidingDateRangePicker  = (controls[3] as SlidingDateRangePicker);


            int  interactionChannelId   = ddlInteractionChannel.SelectedValueAsId() ?? 0;
            var  rockContext            = new RockContext();
            var  interactionChannel     = new InteractionChannelService(rockContext).Get(interactionChannelId);
            Guid?interactionChannelGuid = null;

            if (interactionChannel != null)
            {
                interactionChannelGuid = interactionChannel.Guid;
            }

            int  interactionComponentId   = ddlInteractionComponent.SelectedValueAsId() ?? 0;
            var  interactionComponent     = new InteractionComponentService(rockContext).Get(interactionComponentId);
            Guid?interactionComponentGuid = null;

            if (interactionComponent != null)
            {
                interactionComponentGuid = interactionComponent.Guid;
            }

            // convert pipe to comma delimited
            var delimitedValues = slidingDateRangePicker.DelimitedValues.Replace("|", ",");

            return($"{interactionChannelGuid.ToString()}|{interactionComponentGuid}|{tbOperation.Text}|{delimitedValues}");
        }
Beispiel #7
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);
            }
        }
Beispiel #8
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);
        }
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="serviceInstance">The service instance.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection)
        {
            string[] selectionValues = selection.Split('|');
            var      rockContext     = ( RockContext )serviceInstance.Context;

            if (selectionValues.Length >= 2)
            {
                var communicationId         = selectionValues[0].AsInteger();
                var communicationStatusType = selectionValues[1].ConvertToEnum <CommunicationStatusType>();
                var communicationRecipients = new CommunicationRecipientService(rockContext).GetByCommunicationId(communicationId);

                var interactionChannelCommunication = new InteractionChannelService(rockContext).Get(Rock.SystemGuid.InteractionChannel.COMMUNICATION.AsGuid());
                var interactionQuery = new InteractionService(rockContext).Queryable()
                                       .Where(a => a.InteractionComponent.ChannelId == interactionChannelCommunication.Id &&
                                              a.InteractionComponent.EntityId.Value == communicationId);
                CommunicationRecipientStatus[] sentStatus = new CommunicationRecipientStatus[] { CommunicationRecipientStatus.Opened, CommunicationRecipientStatus.Delivered };

                switch (communicationStatusType)
                {
                case CommunicationStatusType.Open:
                {
                    interactionQuery        = interactionQuery.Where(a => a.Operation == "Opened");
                    communicationRecipients = communicationRecipients.Where(a => sentStatus.Contains(a.Status) && interactionQuery.Any(b => b.EntityId == a.Id));
                }
                break;

                case CommunicationStatusType.Clicked:
                {
                    interactionQuery        = interactionQuery.Where(a => a.Operation == "Click");
                    communicationRecipients = communicationRecipients.Where(a => sentStatus.Contains(a.Status) && interactionQuery.Any(b => b.EntityId == a.Id));
                }
                break;

                case CommunicationStatusType.Unopened:
                {
                    interactionQuery        = interactionQuery.Where(a => a.Operation == "Click" || a.Operation == "Opened");
                    communicationRecipients = communicationRecipients.Where(a => sentStatus.Contains(a.Status) && !interactionQuery.Any(b => b.EntityId == a.Id));
                }
                break;

                case CommunicationStatusType.Failed:
                default:
                {
                    CommunicationRecipientStatus[] failedStatus = new CommunicationRecipientStatus[] { CommunicationRecipientStatus.Failed };
                    communicationRecipients = communicationRecipients.Where(a => failedStatus.Contains(a.Status));
                }
                break;
                }

                var qry = new PersonService(( RockContext )serviceInstance.Context).Queryable()
                          .Where(p => communicationRecipients.Any(x => x.PersonAlias.PersonId == p.Id));

                return(FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p"));
            }

            return(null);
        }
Beispiel #10
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
            });
        }
Beispiel #11
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);
        }
Beispiel #12
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());
        }
Beispiel #13
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);
        }
        /// <summary>
        /// Shows the list.
        /// </summary>
        public void ShowList()
        {
            int pageSize = GetAttributeValue("PageSize").AsInteger();

            int skipCount = pageNumber * pageSize;

            using (var rockContext = new RockContext())
            {
                var interactionChannel = new InteractionChannelService(rockContext).Get(_channelId.Value);
                if (interactionChannel != null)
                {
                    var interactionComponentQry = new InteractionComponentService(rockContext)
                                                  .Queryable().AsNoTracking()
                                                  .Where(a =>
                                                         a.ChannelId == _channelId.Value)
                                                  .OrderByDescending(a => a.ModifiedDateTime)
                                                  .Skip(skipCount)
                                                  .Take(pageSize + 1);

                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                    mergeFields.Add("ComponentDetailPage", LinkedPageRoute("ComponentDetailPage"));
                    mergeFields.Add("InteractionDetailPage", LinkedPageRoute("InteractionDetailPage"));
                    mergeFields.Add("InteractionChannel", interactionChannel);
                    mergeFields.Add("InteractionComponents", interactionComponentQry.ToList().Take(pageSize));

                    // set next button
                    if (interactionComponentQry.Count() > pageSize)
                    {
                        Dictionary <string, string> queryStringNext = new Dictionary <string, string>();
                        queryStringNext.Add("ChannelId", _channelId.ToString());
                        queryStringNext.Add("Page", (pageNumber + 1).ToString());

                        var pageReferenceNext = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringNext);
                        mergeFields.Add("NextPageNavigateUrl", pageReferenceNext.BuildUrl());
                    }

                    // set prev button
                    if (pageNumber != 0)
                    {
                        Dictionary <string, string> queryStringPrev = new Dictionary <string, string>();
                        queryStringPrev.Add("ChannelId", _channelId.ToString());
                        queryStringPrev.Add("Page", (pageNumber - 1).ToString());

                        var pageReferencePrev = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringPrev);
                        mergeFields.Add("PreviousPageNavigateUrl", pageReferencePrev.BuildUrl());
                    }

                    lContent.Text = interactionChannel.ComponentListTemplate.IsNotNullOrWhitespace() ?
                                    interactionChannel.ComponentListTemplate.ResolveMergeFields(mergeFields) :
                                    GetAttributeValue("DefaultTemplate").ResolveMergeFields(mergeFields);
                }
            }
        }
        /// <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 });
        }
        /// <summary>
        /// Shows the list.
        /// </summary>
        public void ShowList()
        {
            using (var rockContext = new RockContext())
            {
                var channelQry = new InteractionChannelService(rockContext)
                                 .Queryable().AsNoTracking();

                var channelMediumValueId = gfFilter.GetUserPreference(MEDIUM_TYPE_FILTER).AsIntegerOrNull();
                if (channelMediumValueId.HasValue)
                {
                    channelQry = channelQry.Where(a => a.ChannelTypeMediumValueId == channelMediumValueId.Value);
                }

                // Parse the default template so that it does not need to be parsed multiple times
                var defaultTemplate = Template.Parse(GetAttributeValue("DefaultTemplate"));
                var options         = new Rock.Lava.CommonMergeFieldsOptions();
                options.GetPageContext             = false;
                options.GetLegacyGlobalMergeFields = false;

                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, options);
                mergeFields.Add("ComponentListPage", LinkedPageRoute("ComponentListPage"));
                mergeFields.Add("SessionListPage", LinkedPageRoute("SessionListPage"));

                var channelItems = new List <ChannelItem>();
                foreach (var channel in channelQry)
                {
                    if (!channel.IsAuthorized(Authorization.VIEW, CurrentPerson))
                    {
                        continue;
                    }

                    var channelMergeFields = new Dictionary <string, object>(mergeFields);
                    channelMergeFields.Add("InteractionChannel", channel);

                    string html = channel.ChannelListTemplate.IsNotNullOrWhitespace() ?
                                  channel.ChannelListTemplate.ResolveMergeFields(channelMergeFields) :
                                  defaultTemplate.Render(Hash.FromDictionary(channelMergeFields));

                    channelItems.Add(new ChannelItem
                    {
                        Id          = channel.Id,
                        ChannelHtml = html
                    });
                }

                rptChannel.DataSource = channelItems;
                rptChannel.DataBind();
            }
        }
Beispiel #17
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);
        }
        /// <summary>
        /// Returns the field's current value(s)
        /// </summary>
        /// <param name="parentControl">The parent control.</param>
        /// <param name="value">Information about the value</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param>
        /// <returns></returns>
        public override string FormatValue(Control parentControl, string value, Dictionary <string, ConfigurationValue> configurationValues, bool condensed)
        {
            string formattedValue = string.Empty;

            Guid?guid = value.AsGuidOrNull();

            if (guid.HasValue)
            {
                var interactionChannel = new InteractionChannelService(new RockContext()).Get(guid.Value);
                if (interactionChannel != null)
                {
                    formattedValue = interactionChannel.Name;
                }
            }

            return(base.FormatValue(parentControl, formattedValue, configurationValues, condensed));
        }
Beispiel #19
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);
        }
Beispiel #20
0
        /// <summary>
        /// Formats the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override string FormatSelection(Type entityType, string selection)
        {
            string result = "Interactions";

            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 2)
            {
                var rockContext        = new RockContext();
                var interactionChannel = new InteractionChannelService(rockContext).Get(selectionValues[0].AsGuid());

                if (interactionChannel != null)
                {
                    result = string.Format("In Interaction Channel: {0}", interactionChannel.Name);

                    var interactionComponentGuid = selectionValues[1].AsGuidOrNull();
                    if (interactionComponentGuid.HasValue)
                    {
                        var interactionComponent = new InteractionComponentService(rockContext).Get(interactionComponentGuid.Value);
                        if (interactionComponent != null)
                        {
                            result += string.Format(", in Interaction Component: {0}", interactionComponent.Name);
                        }
                    }

                    var operation = selectionValues[2];
                    if (!string.IsNullOrEmpty(operation))
                    {
                        result += string.Format(", with operation: {0}", operation);
                    }

                    if (!string.IsNullOrEmpty(selectionValues[3]))
                    {
                        SlidingDateRangePicker fakeSlidingDateRangePicker = new SlidingDateRangePicker();
                        var formattedDelimitedValues = SlidingDateRangePicker.FormatDelimitedValues(selectionValues[3].Replace(',', '|'));
                        if (!string.IsNullOrEmpty(formattedDelimitedValues))
                        {
                            result += string.Format(", date range: {0}", formattedDelimitedValues);
                        }
                    }
                }
            }

            return(result);
        }
        /// <summary>
        /// Creates the control(s) necessary for prompting user for a new value
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id"></param>
        /// <returns>
        /// The control
        /// </returns>
        public override Control EditControl(Dictionary <string, ConfigurationValue> configurationValues, string id)
        {
            var editControl = new RockDropDownList {
                ID = id
            };

            editControl.Items.Add(new ListItem());

            var interactionChannels = new InteractionChannelService(new RockContext()).Queryable().OrderBy(d => d.Name);

            if (interactionChannels.Any())
            {
                foreach (var interactionChannel in interactionChannels)
                {
                    editControl.Items.Add(new ListItem(interactionChannel.Name, interactionChannel.Guid.ToString().ToUpper()));
                }

                return(editControl);
            }

            return(null);
        }
Beispiel #22
0
        /// <summary>
        /// Sets the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="controls">The controls.</param>
        /// <param name="selection">The selection.</param>
        public override void SetSelection(Type entityType, Control[] controls, string selection)
        {
            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 1)
            {
                Guid interactionChannelGuid = selectionValues[0].AsGuid();
                var  rockContext            = new RockContext();
                var  interactionChannel     = new InteractionChannelService(rockContext).Get(interactionChannelGuid);
                var  ddlInteractionChannel  = (controls[0] as RockDropDownList);
                ddlInteractionChannel.SetValue(interactionChannel != null ? interactionChannel.Id : ( int? )null);

                ddlInteractionChannel_SelectedIndexChanged(ddlInteractionChannel, new EventArgs());

                if (selectionValues.Length >= 2)
                {
                    var interactionComponentGuid = selectionValues[1].AsGuidOrNull();
                    if (interactionComponentGuid.HasValue)
                    {
                        RockDropDownList ddlInteractionComponent = (controls[1] as RockDropDownList);
                        var interactionComponent = new InteractionComponentService(rockContext).Get(interactionComponentGuid.Value);
                        ddlInteractionComponent.SetValue(interactionComponent != null ? interactionComponent.Id : ( int? )null);
                    }
                }

                RockTextBox tbOperation = controls[2] as RockTextBox;
                if (selectionValues.Length >= 3)
                {
                    tbOperation.Text = selectionValues[2];
                }

                SlidingDateRangePicker slidingDateRangePicker = controls[3] as SlidingDateRangePicker;
                if (selectionValues.Length >= 4)
                {
                    slidingDateRangePicker.DelimitedValues = selectionValues[3].Replace(',', '|');
                }
            }
        }
        /// <summary>
        /// Sets the selection.
        /// </summary>
        /// <param name="controls">The controls.</param>
        /// <param name="selection">The selection.</param>
        public override void SetSelection(System.Web.UI.Control[] controls, string selection)
        {
            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 1)
            {
                Guid interactionChannelGuid = selectionValues[0].AsGuid();
                var  rockContext            = new RockContext();
                var  interactionChannel     = new InteractionChannelService(rockContext).Get(interactionChannelGuid);
                var  ddlInteractionChannel  = (controls[0] as RockDropDownList);
                ddlInteractionChannel.SetValue(interactionChannel != null ? interactionChannel.Id : ( int? )null);

                ddlInteractionChannel_SelectedIndexChanged(ddlInteractionChannel, new EventArgs());

                if (selectionValues.Length >= 2)
                {
                    var interactionComponentGuid = selectionValues[1].AsGuidOrNull();
                    if (interactionComponentGuid.HasValue)
                    {
                        RockDropDownList ddlInteractionComponent = (controls[1] as RockDropDownList);
                        var interactionComponent = new InteractionComponentService(rockContext).Get(interactionComponentGuid.Value);
                        ddlInteractionComponent.SetValue(interactionComponent != null ? interactionComponent.Id : ( int? )null);
                    }
                }

                RockTextBox tbOperation = controls[2] as RockTextBox;
                if (selectionValues.Length >= 3)
                {
                    tbOperation.Text = selectionValues[2];
                }

                RockRadioButtonList rblSelectionMode = controls[3] as RockRadioButtonList;
                if (selectionValues.Length >= 4)
                {
                    rblSelectionMode.SetValue(selectionValues[3]);
                }
            }
        }
Beispiel #24
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);
            }
        }
Beispiel #25
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());
        }
Beispiel #26
0
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="site">The site.</param>
        private void ShowEditDetails(Rock.Model.Site site)
        {
            if (site.Id == 0)
            {
                nbDefaultPageNotice.Visible = true;
                lReadOnlyTitle.Text         = ActionTitle.Add(Rock.Model.Site.FriendlyTypeName).FormatAsHtmlTitle();
            }
            else
            {
                nbDefaultPageNotice.Visible = false;
                lReadOnlyTitle.Text         = site.Name.FormatAsHtmlTitle();
            }

            SetEditMode(true);

            LoadDropDowns();

            tbSiteName.ReadOnly = site.IsSystem;
            tbSiteName.Text     = site.Name;

            tbDescription.ReadOnly = site.IsSystem;
            tbDescription.Text     = site.Description;

            ddlTheme.Enabled = !site.IsSystem;
            ddlTheme.SetValue(site.Theme);

            imgSiteIcon.BinaryFileId = site.FavIconBinaryFileId;
            imgSiteLogo.BinaryFileId = site.SiteLogoBinaryFileId;

            if (site.DefaultPageRoute != null)
            {
                ppDefaultPage.SetValue(site.DefaultPageRoute);
            }
            else
            {
                ppDefaultPage.SetValue(site.DefaultPage);
            }

            if (site.LoginPageRoute != null)
            {
                ppLoginPage.SetValue(site.LoginPageRoute);
            }
            else
            {
                ppLoginPage.SetValue(site.LoginPage);
            }

            if (site.ChangePasswordPageRoute != null)
            {
                ppChangePasswordPage.SetValue(site.ChangePasswordPageRoute);
            }
            else
            {
                ppChangePasswordPage.SetValue(site.ChangePasswordPage);
            }

            if (site.CommunicationPageRoute != null)
            {
                ppCommunicationPage.SetValue(site.CommunicationPageRoute);
            }
            else
            {
                ppCommunicationPage.SetValue(site.CommunicationPage);
            }

            if (site.RegistrationPageRoute != null)
            {
                ppRegistrationPage.SetValue(site.RegistrationPageRoute);
            }
            else
            {
                ppRegistrationPage.SetValue(site.RegistrationPage);
            }

            if (site.PageNotFoundPageRoute != null)
            {
                ppPageNotFoundPage.SetValue(site.PageNotFoundPageRoute);
            }
            else
            {
                ppPageNotFoundPage.SetValue(site.PageNotFoundPage);
            }

            tbErrorPage.Text = site.ErrorPage;

            tbSiteDomains.Text            = string.Join("\n", site.SiteDomains.OrderBy(d => d.Order).Select(d => d.Domain).ToArray());
            tbGoogleAnalytics.Text        = site.GoogleAnalyticsCode;
            cbRequireEncryption.Checked   = site.RequiresEncryption;
            cbEnableForShortening.Checked = site.EnabledForShortening;

            cbEnableMobileRedirect.Checked = site.EnableMobileRedirect;
            ppMobilePage.SetValue(site.MobilePage);
            tbExternalURL.Text         = site.ExternalUrl;
            tbAllowedFrameDomains.Text = site.AllowedFrameDomains;
            cbRedirectTablets.Checked  = site.RedirectTablets;
            cbEnablePageViews.Checked  = site.EnablePageViews;

            int channelMediumWebsiteValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id;
            var interactionChannelForSite   = new InteractionChannelService(new RockContext()).Queryable()
                                              .Where(a => a.ChannelTypeMediumValueId == channelMediumWebsiteValueId && a.ChannelEntityId == site.Id).FirstOrDefault();

            if (interactionChannelForSite != null)
            {
                nbPageViewRetentionPeriodDays.Text = interactionChannelForSite.RetentionDuration.ToString();
            }

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

            // disable the indexing features if indexing on site is disabled
            var siteEntityType = EntityTypeCache.Get("Rock.Model.Site");

            if (siteEntityType != null && !siteEntityType.IsIndexingEnabled)
            {
                cbEnableIndexing.Visible        = false;
                tbIndexStartingLocation.Visible = false;
            }

            var attributeService     = new AttributeService(new RockContext());
            var siteIdQualifierValue = site.Id.ToString();

            PageAttributesState = attributeService.GetByEntityTypeId(new Page().TypeId, true).AsQueryable()
                                  .Where(a =>
                                         a.EntityTypeQualifierColumn.Equals("SiteId", StringComparison.OrdinalIgnoreCase) &&
                                         a.EntityTypeQualifierValue.Equals(siteIdQualifierValue))
                                  .OrderBy(a => a.Order)
                                  .ThenBy(a => a.Name)
                                  .ToList();
            BindPageAttributesGrid();

            SetControlsVisiblity();
        }
Beispiel #27
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);
            }
        }
Beispiel #28
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();
                        }
                    }
                }
            }
        }
        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;
        }
Beispiel #30
0
        /// <summary>
        /// Shows the list.
        /// </summary>
        public void ShowList()
        {
            var rockContext = new RockContext();

            int sessionCount = GetAttributeValue( "SessionCount" ).AsInteger();

            int skipCount = pageNumber * sessionCount;

            var person = new PersonService( rockContext ).GetByUrlEncodedKey( PageParameter( "Person" ) );

            if ( person != null )
            {
                lPersonName.Text = person.FullName;

                InteractionService interactionService = new InteractionService( rockContext );

                var pageViews = interactionService.Queryable();

                var sessionInfo = interactionService.Queryable()
                    .Where( s => s.PersonAlias.PersonId == person.Id );

                if ( startDate != DateTime.MinValue )
                {
                    sessionInfo = sessionInfo.Where( s => s.InteractionDateTime > drpDateFilter.LowerValue );
                }

                if ( endDate != DateTime.MaxValue )
                {
                    sessionInfo = sessionInfo.Where( s => s.InteractionDateTime < drpDateFilter.UpperValue );
                }

                if ( siteId != -1 )
                {
                    var site = SiteCache.Read( siteId );

                    string siteName = string.Empty;
                    if (site != null )
                    {
                        siteName = site.Name;
                    }
                    // lookup the interactionDeviceType, and create it if it doesn't exist
                    int channelMediumValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid() ).Id;

                    var interactionChannelId = new InteractionChannelService( rockContext ).Queryable()
                                                        .Where( a => a.ChannelTypeMediumValueId == channelMediumValueId && a.ChannelEntityId == siteId )
                                                        .Select( a => a.Id)
                                                        .FirstOrDefault();

                    sessionInfo = sessionInfo.Where( p => p.InteractionComponent.ChannelId == interactionChannelId );
                }

                var pageviewInfo = sessionInfo.GroupBy( s => new
                                {
                                    s.InteractionSession,
                                    s.InteractionComponent.Channel,
                                } )
                                .Select( s => new WebSession
                                {
                                    PageViewSession = s.Key.InteractionSession,
                                    StartDateTime = s.Min( x => x.InteractionDateTime ),
                                    EndDateTime = s.Max( x => x.InteractionDateTime ),
                                    SiteId = siteId,
                                    Site = s.Key.Channel.Name,
                                    PageViews = pageViews.Where( p => p.InteractionSessionId == s.Key.InteractionSession.Id && p.InteractionComponent.ChannelId == s.Key.Channel.Id ).OrderBy(p => p.InteractionDateTime).ToList()
                                } );

                pageviewInfo = pageviewInfo.OrderByDescending( p => p.StartDateTime )
                                .Skip( skipCount )
                                .Take( sessionCount + 1 );

                rptSessions.DataSource = pageviewInfo.ToList().Take( sessionCount );
                rptSessions.DataBind();

                // set next button
                if ( pageviewInfo.Count() > sessionCount )
                {
                    hlNext.Visible = hlNext.Enabled = true;
                    Dictionary<string, string> queryStringNext = new Dictionary<string, string>();
                    queryStringNext.Add( "Page", ( pageNumber + 1 ).ToString() );
                    queryStringNext.Add( "Person", person.UrlEncodedKey );
                    if ( siteId != -1 )
                    {
                        queryStringNext.Add( "SiteId", siteId.ToString() );
                    }

                    if ( startDate != DateTime.MinValue )
                    {
                        queryStringNext.Add( "StartDate", startDate.ToShortDateString() );
                    }

                    if ( endDate != DateTime.MaxValue )
                    {
                        queryStringNext.Add( "EndDate", endDate.ToShortDateString() );
                    }

                    var pageReferenceNext = new Rock.Web.PageReference( CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringNext );
                    hlNext.NavigateUrl = pageReferenceNext.BuildUrl();
                }
                else
                {
                    hlNext.Visible = hlNext.Enabled = false;
                }

                // set prev button
                if ( pageNumber == 0 )
                {
                    hlPrev.Visible = hlPrev.Enabled = false;
                }
                else
                {
                    hlPrev.Visible = hlPrev.Enabled = true;
                    Dictionary<string, string> queryStringPrev = new Dictionary<string, string>();
                    queryStringPrev.Add( "Page", ( pageNumber - 1 ).ToString() );
                    queryStringPrev.Add( "Person", person.UrlEncodedKey );
                    if ( siteId != -1 )
                    {
                        queryStringPrev.Add( "SiteId", siteId.ToString() );
                    }

                    if ( startDate != DateTime.MinValue )
                    {
                        queryStringPrev.Add( "StartDate", startDate.ToShortDateString() );
                    }

                    if ( endDate != DateTime.MaxValue )
                    {
                        queryStringPrev.Add( "EndDate", endDate.ToShortDateString() );
                    }

                    var pageReferencePrev = new Rock.Web.PageReference( CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringPrev );
                    hlPrev.NavigateUrl = pageReferencePrev.BuildUrl();
                }
            }
            else
            {
                lMessages.Text = "<div class='alert alert-warning'>No person provided to show results for.</div>";
            }
        }
        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();
                    }
                }
            }
        }
Beispiel #32
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();
                        }
                    }
                }
            }
        }
Beispiel #33
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();
                }
            }
        }