/// <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)
        {
            if (!Page.IsValid)
            {
                return;
            }

            var rockContext         = new RockContext();
            var mediaAccount        = GetMediaAccount(rockContext);
            var mediaAccountService = new MediaAccountService(rockContext);
            var isNew = mediaAccount == null;

            if (isNew)
            {
                mediaAccount = new MediaAccount();
                mediaAccountService.Add(mediaAccount);
            }

            mediaAccount.Name     = tbName.Text;
            mediaAccount.IsActive = cbActive.Checked;
            mediaAccount.ComponentEntityTypeId = cpMediaAccountComponent.SelectedEntityTypeId ?? 0;
            rockContext.SaveChanges();

            mediaAccount.LoadAttributes(rockContext);
            avcComponentAttributes.GetEditValues(mediaAccount);
            mediaAccount.SaveAttributeValues(rockContext);
            rockContext.SaveChanges();

            var pageReference = RockPage.PageReference;

            pageReference.Parameters.AddOrReplace(PageParameterKey.MediaAccountId, mediaAccount.Id.ToString());
            Response.Redirect(pageReference.BuildUrl(), false);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext         = new RockContext();
            var mediaAccountService = new MediaAccountService(rockContext);

            // Use AsNoTracking() since these records won't be modified, and therefore don't need to be tracked by the EF change tracker
            var qry = mediaAccountService.Queryable().AsNoTracking();

            // name filter
            string nameFilter = gfAccounts.GetUserPreference(UserPreferenceKey.Name);

            if (!string.IsNullOrEmpty(nameFilter))
            {
                qry = qry.Where(account => account.Name.Contains(nameFilter));
            }

            Guid?accountTypeGuid = gfAccounts.GetUserPreference(UserPreferenceKey.AccountType).AsGuidOrNull();

            if (accountTypeGuid.HasValue)
            {
                qry = qry.Where(l => l.ComponentEntityType.Guid.Equals(accountTypeGuid.Value));
            }

            bool showInactiveAccounts = gfAccounts.GetUserPreference(UserPreferenceKey.IncludeInactive).AsBoolean();

            if (!showInactiveAccounts)
            {
                qry = qry.Where(s => s.IsActive == true);
            }

            var selectQry = qry
                            .Select(a => new
            {
                a.Id,
                a.Name,
                Type = a.ComponentEntityType,
                a.LastRefreshDateTime,
                Folders = a.MediaFolders.Count,
                Videos  = a.MediaFolders.SelectMany(b => b.MediaElements).Count()
            });

            var sortProperty = gAccountList.SortProperty;

            if (gAccountList.AllowSorting && sortProperty != null)
            {
                qry = qry.Sort(sortProperty);
            }
            else
            {
                qry = qry.OrderBy(a => a.Name);
            }

            gAccountList.EntityTypeId = EntityTypeCache.GetId <MediaAccount>();
            gAccountList.DataSource   = selectQry.ToList();
            gAccountList.DataBind();
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="mediaFolder">The media folder.</param>
        private void ShowEditDetails(MediaFolder mediaFolder)
        {
            if (mediaFolder.Id == 0)
            {
                lActionTitle.Text = ActionTitle.Add(MediaFolder.FriendlyTypeName).FormatAsHtmlTitle();
            }
            else
            {
                lActionTitle.Text = mediaFolder.Name.FormatAsHtmlTitle();
            }

            SetEditMode(true);

            tbName.Text        = mediaFolder.Name;
            tbDescription.Text = mediaFolder.Description;
            wtpWorkflowType.SetValue(mediaFolder.WorkflowTypeId);

            swEnableContentChannelSync.Checked = mediaFolder.IsContentChannelSyncEnabled;
            swEnableContentChannelSync_CheckedChanged(null, null);
            if (mediaFolder.IsContentChannelSyncEnabled)
            {
                if (mediaFolder.ContentChannel != null)
                {
                    ddlContentChannel.SetValue(mediaFolder.ContentChannel.Guid);
                }

                ddlContentChannel_SelectedIndexChanged(null, null);
                rrbContentChannelItemStatus.SetValue(mediaFolder.ContentChannelItemStatus.ConvertToInt().ToString());
                if (mediaFolder.ContentChannelAttributeId.HasValue)
                {
                    ddlChannelAttribute.SetValue(mediaFolder.ContentChannelAttributeId.Value);
                }
            }

            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if (!IsUserAuthorized(Authorization.EDIT))
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(MediaFolder.FriendlyTypeName);
            }

            var mediaAccount          = new MediaAccountService(new RockContext()).Get(mediaFolder.MediaAccountId);
            var mediaAccountComponent = GetMediaAccountComponent(mediaAccount);

            if (mediaAccountComponent != null)
            {
                readOnly = !mediaAccountComponent.AllowsManualEntry;
            }

            tbName.ReadOnly        = readOnly;
            tbDescription.ReadOnly = readOnly;
        }
        /// <summary>
        /// Handles the Click event of the btnSyncWithProvider 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 btnSyncWithProvider_Click(object sender, EventArgs e)
        {
            var mediaAccountId = hfMediaAccountId.ValueAsInt();

            Task.Run(async() =>
            {
                await MediaAccountService.SyncMediaInAccountAsync(mediaAccountId);
                await MediaAccountService.SyncAnalyticsInAccountAsync(mediaAccountId);
            });

            mdSyncMessage.Show("Synchronization with provider started and will continue in the background.", ModalAlertType.Information);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Get the actual media account model for deleting or editing
        /// </summary>
        /// <returns></returns>
        private MediaAccount GetMediaAccount(RockContext rockContext = null)
        {
            rockContext = rockContext ?? new RockContext();
            var mediaAccountService = new MediaAccountService(rockContext);

            var mediaAccountId = PageParameter(PageParameterKey.MediaAccountId).AsIntegerOrNull();

            if (!mediaAccountId.HasValue)
            {
                return(null);
            }

            return(mediaAccountService.Queryable().FirstOrDefault(a => a.Id == mediaAccountId.Value));
        }
 /// <summary>
 /// Handles the Click event of the btnCancel 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 btnCancel_Click(object sender, EventArgs e)
 {
     if (hfMediaAccountId.Value.Equals("0"))
     {
         // Cancelling on Add
         Dictionary <string, string> qryString = new Dictionary <string, string>();
         qryString[PageParameterKey.MediaAccountId] = hfMediaAccountId.Value;
         NavigateToParentPage(qryString);
     }
     else
     {
         // Cancelling on Edit
         var mediaAccount = new MediaAccountService(new RockContext()).Get(int.Parse(hfMediaAccountId.Value));
         ShowReadonlyDetails(mediaAccount);
     }
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Processes one account and return the result of the operation.
        /// </summary>
        /// <param name="mediaAccount">The media account.</param>
        /// <param name="limitFullSync"><c>true</c> if a full-sync should only be performed once per day.</param>
        /// <returns>The result of the operation.</returns>
        private async Task <OperationResult> ProcessOneAccount(MediaAccount mediaAccount, bool limitFullSync)
        {
            var sw     = System.Diagnostics.Stopwatch.StartNew();
            var errors = new List <string>();

            if (mediaAccount.GetMediaAccountComponent() == null)
            {
                return(new OperationResult($"Skipped account {mediaAccount.Name}.", new[] { $"{mediaAccount.Name}: Media Account component was not found." }));
            }

            // Determine if this is a full sync or a partial refresh.
            var currentDateTime = RockDateTime.Now;
            var lastFullSync    = mediaAccount.LastRefreshDateTime;
            var haveSyncedToday = lastFullSync.HasValue && lastFullSync.Value.Date == currentDateTime.Date;
            var refreshOnly     = limitFullSync && haveSyncedToday;

            if (refreshOnly)
            {
                // Quick refresh media and folders only.
                var result = await MediaAccountService.RefreshMediaInAccountAsync(mediaAccount.Id);

                errors.AddRange(result.Errors);
            }
            else
            {
                // First sync all the media and folders.
                var result = await MediaAccountService.SyncMediaInAccountAsync(mediaAccount.Id);

                errors.AddRange(result.Errors);

                // Next sync all the analytics.
                result = await MediaAccountService.SyncAnalyticsInAccountAsync(mediaAccount.Id);

                errors.AddRange(result.Errors);
            }

            sw.Stop();
            var seconds = ( int )sw.Elapsed.TotalSeconds;

            var message = $"{( refreshOnly ? "Refreshed" : "Synchronized" )} account {mediaAccount.Name} in {seconds}s.";

            // Since we will be aggregating errors include the
            // account name if there were any errors.
            return(new OperationResult(message, errors.Select(a => $"{mediaAccount.Name}: {a}")));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Synchronizes the folders and media in all active accounts.
        /// </summary>
        /// <param name="limitFullSync"><c>true</c> if a full-sync should only be performed once per day.</param>
        /// <returns>A <see cref="SyncOperationResult"/> object with the result of the operation.</returns>
        private async Task <OperationResult> ProcessAllAccounts(bool limitFullSync)
        {
            using (var rockContext = new RockContext())
            {
                var tasks         = new List <Task <OperationResult> >();
                var mediaAccounts = new MediaAccountService(rockContext).Queryable()
                                    .AsNoTracking()
                                    .Where(a => a.IsActive)
                                    .ToList();

                if (mediaAccounts.Count == 0)
                {
                    return(new OperationResult("No active accounts to process.", new string[0]));
                }

                // Start a SyncMedia task for each active account.
                foreach (var mediaAccount in mediaAccounts)
                {
                    var task = Task.Run(async() =>
                    {
                        try
                        {
                            return(await ProcessOneAccount(mediaAccount, limitFullSync));
                        }
                        catch (Exception ex)
                        {
                            ExceptionLogService.LogException(ex);
                            return(new OperationResult($"Failed to sync account.", new[] { $"{mediaAccount.Name}: {ex.Message}" }));
                        }
                    });

                    tasks.Add(task);
                }

                // Wait for all operational tasks to complete and then
                // aggregate the results.
                var results = await Task.WhenAll(tasks);

                var message = string.Join(Environment.NewLine, results.Select(a => a.Message));

                return(new OperationResult(message, results.SelectMany(a => a.Errors)));
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Handles the DeleteClick event of the gAccountList control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs"/> instance containing the event data.</param>
        protected void gAccountList_DeleteClick(object sender, Rock.Web.UI.Controls.RowEventArgs e)
        {
            var rockContext         = new RockContext();
            var mediaAccountService = new MediaAccountService(rockContext);
            var mediaAccount        = mediaAccountService.Get(e.RowKeyId);

            if (mediaAccount != null)
            {
                string errorMessage;
                if (!mediaAccountService.CanDelete(mediaAccount, out errorMessage))
                {
                    mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                    return;
                }

                mediaAccountService.Delete(mediaAccount);
                rockContext.SaveChanges();
            }

            BindGrid();
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Handles the Click event of the btnDelete 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 btnDelete_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();

            var service      = new MediaAccountService(rockContext);
            var mediaAccount = service.Get(int.Parse(hfMediaAccountId.Value));

            if (mediaAccount == null)
            {
                return;
            }

            service.Delete(mediaAccount);

            rockContext.SaveChanges();

            // reload page
            var qryParams = new Dictionary <string, string>();

            NavigateToParentPage(qryParams);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="mediaFolderId">The media folder identifier.</param>
        /// <param name="mediaAccountId">The media account identifier.</param>
        private void ShowDetail(int mediaFolderId, int?mediaAccountId)
        {
            var         rockContext        = new RockContext();
            var         mediaFolderService = new MediaFolderService(rockContext);
            MediaFolder mediaFolder        = null;

            if (!mediaAccountId.Equals(0))
            {
                mediaFolder = mediaFolderService.Get(mediaFolderId);
            }

            if (mediaFolder == null)
            {
                MediaAccount mediaAccount = null;
                if (mediaAccountId.HasValue)
                {
                    mediaAccount = new MediaAccountService(rockContext).Get(mediaAccountId.Value);
                }

                if (mediaAccount != null)
                {
                    mediaFolder = new MediaFolder {
                        Id = 0, MediaAccountId = mediaAccount.Id
                    };
                }
                else
                {
                    pnlView.Visible = false;
                    return;
                }
            }

            hfId.SetValue(mediaFolder.Id);
            hfMediaAccountId.SetValue(mediaFolder.MediaAccountId);
            pnlView.Visible = true;

            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if (!IsUserAuthorized(Authorization.EDIT))
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(MediaFolder.FriendlyTypeName);
            }

            if (readOnly)
            {
                btnEdit.Visible = false;
                btnSyncContentChannelItems.Visible = false;

                ShowReadonlyDetails(mediaFolder);
            }
            else
            {
                btnEdit.Visible = true;

                if (mediaFolder.Id > 0)
                {
                    btnSyncContentChannelItems.Visible = !(mediaFolder.MediaAccount.GetMediaAccountComponent()?.AllowsManualEntry ?? true);
                    ShowReadonlyDetails(mediaFolder);
                }
                else
                {
                    btnSyncContentChannelItems.Visible = false;
                    ShowEditDetails(mediaFolder);
                }
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Handles the Click event of the btnEdit 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 btnEdit_Click(object sender, EventArgs e)
        {
            var mediaAccount = new MediaAccountService(new RockContext()).Get(hfMediaAccountId.Value.AsInteger());

            ShowEditDetails(mediaAccount);
        }