public ActionResult AddCourseDialog(String learningAimRef)
        {
            UserContext.UserContextInfo uco = UserContext.GetUserContext();
            if (uco.ContextName != UserContext.UserContextName.Provider)
            {
                return(HttpNotFound());
            }

            Provider provider = db.Providers.Find(userContext.ItemId);

            if (provider == null)
            {
                return(HttpNotFound());
            }

            AddCourseModel model = new AddCourseModel();

            if (learningAimRef == null)
            {
                model.CourseHasLearningAimRef = 0; /* Used for Adding a new course - no default */
            }
            else if (learningAimRef == "")
            {
                model.CourseHasLearningAimRef = 1; /* No */
            }
            else
            {
                model.CourseHasLearningAimRef = 2; /* Yes */
                model.LearningAim             = db.LearningAims.Find(learningAimRef);
            }

            return(View(model));
        }
        /// <summary>
        ///     Populate an account search view model.
        /// </summary>
        /// <param name="model">
        ///     The model.
        /// </param>
        /// <param name="db">
        ///     The db.
        /// </param>
        /// <returns>
        ///     The <see cref="AddEditAccountViewModel" />.
        /// </returns>
        public static AccountSearchViewModel Populate(this AccountSearchViewModel model, ProviderPortalEntities db)
        {
            UserContext.UserContextInfo context = UserContext.GetUserContext();
            switch (context.ContextName)
            {
            case UserContext.UserContextName.Provider:

                model.CanAdd = Permission.HasPermission(false, true,
                                                        Permission.PermissionName.CanAddEditProviderUsers);
                break;

            case UserContext.UserContextName.Organisation:

                model.CanAdd = Permission.HasPermission(false, true,
                                                        Permission.PermissionName.CanAddEditOrganisationUsers);
                break;

            case UserContext.UserContextName.Administration:

                model.CanAdd = Permission.HasPermission(false, true,
                                                        Permission.PermissionName.CanAddEditAdminUsers);
                break;
            }

            model.CanEditSecureAccessUsers = Permission.HasPermission(false, true,
                                                                      Permission.PermissionName.CanEditSecureAccessUsers);
            return(model);
        }
        public static string GetCsvFileName(this BulkUploadViewModel model, UserContext.UserContextInfo userContext, ProviderPortalEntities db, Constants.BulkUpload_DataType dataType)
        {
            var providerOrOrganisationName = userContext.IsOrganisation()
                           ? db.Organisations.Where(o => o.OrganisationId.Equals(userContext.ItemId.Value)).Select(o => o.OrganisationName).FirstOrDefault()
                           : db.Providers.Where(p => p.ProviderId.Equals(userContext.ItemId.Value)).Select(p => p.ProviderName).FirstOrDefault();

            var dataTypeName = (dataType == Constants.BulkUpload_DataType.CourseData ? "Courses" : "Apprenticeships");

            return(string.Format("{0}_{1}.{2}", providerOrOrganisationName, dataTypeName, Constants.BulkDownloadFileExtension));
        }
        public static void Populate(this BulkUploadViewModel model, UserContext.UserContextInfo userContext, ProviderPortalEntities db, Constants.BulkUpload_DataType dataType)
        {
            var providers = LoadProviders(userContext, db, true, userContext.IsOrganisation());

            model.UserCntxName = userContext.ContextName;

            if (userContext.IsProvider())
            {
                model.ProviderViewModel = LoadProviderInformation(providers.FirstOrDefault(), dataType);
            }
            else if (userContext.IsOrganisation())
            {
                model.OrganisationViewModel = LoadOrganisationProviderInfo(providers, dataType);
            }
        }
        public List <Provider> LoadProviders(UserContext.UserContextInfo userContext, ProviderPortalEntities db, bool downloadableProvidersOnly = false)
        {
            var providers = new List <Provider>();

            switch (userContext.ContextName)
            {
            case UserContext.UserContextName.Provider:
            {
                var provider = db.Providers.Find(userContext.ItemId);

                if (provider != null)
                {
                    providers.Add(provider);
                }
                break;
            }

            case UserContext.UserContextName.Organisation:
            {
                var organisation = db.Organisations.FirstOrDefault(x => x.OrganisationId == userContext.ItemId);

                if (organisation != null)
                {
                    foreach (var organisationProvider in organisation.OrganisationProviders)
                    {
                        if (downloadableProvidersOnly)
                        {
                            if (organisationProvider.CanOrganisationEditProvider)
                            {
                                providers.Add(organisationProvider.Provider);
                            }
                        }
                        else
                        {
                            providers.Add(organisationProvider.Provider);
                        }
                    }
                }
                break;
            }
            }
            return(providers);
        }
        public static AddEditApprenticeshipViewModel Populate(this AddEditApprenticeshipViewModel model,
                                                              ProviderPortalEntities db)
        {
            // Create new apprenticeship
            if (model == null)
            {
                model = new AddEditApprenticeshipViewModel();
            }
            model.RecordStatusId = (int)Constants.RecordStatus.Pending;

            UserContext.UserContextInfo uc = UserContext.GetUserContext();
            if (uc.IsProvider())
            {
                Provider provider = db.Providers.Find(uc.ItemId);
                if (provider != null)
                {
                    model.DisplayNotPublishedBanner = !provider.ApprenticeshipContract;
                }
            }

            return(model);
        }
Ejemplo n.º 7
0
        public async Task <ActionResult> Delete(DeleteOrganisationViewModel model)
        {
            Organisation organisation = await db.Organisations.FindAsync(userContext.ItemId);

            if (organisation.OrganisationProviders.Any(x => x.IsAccepted && !x.IsRejected))
            {
                return(Delete());
            }

            organisation.RecordStatusId = (int)Constants.RecordStatus.Deleted;
            await db.SaveChangesAsync();

            // Reset the user's current context and find out what it is
            UserContext.UserContextInfo defaultContext = UserContext.InstantiateSession();
            if (defaultContext.ContextName != UserContext.UserContextName.Administration)
            {
                IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication;
                authenticationManager.SignOut();
                SessionManager.End();
            }
            ShowGenericSavedMessage();
            return(RedirectToAction("Index", "Home"));
        }
 public static void AddMetaData(this AddEditDeliveryLocationViewModel model,
                                ProviderPortalEntities db, UserContext.UserContextInfo userContext)
 {
     model.DeliveryModes = db.DeliveryModes.ToList();
     model.Locations     = db.Locations
                           .Where(x => x.ProviderId == userContext.ItemId.Value)
                           .Select(x => new SelectListItem
     {
         Text = x.LocationName,
         // ReSharper disable once SpecifyACultureInStringConversionExplicitly
         Value = x.LocationId.ToString()
     })
                           .ToList();
     model.SelectedDeliveryModes = model.SelectedDeliveryModes ?? new List <Int32>();
     if (String.IsNullOrEmpty(model.ApprenticeshipName))
     {
         var apprenticeship = db.Apprenticeships
                              .FirstOrDefault(x => x.ApprenticeshipId == model.ApprenticeshipId);
         model.ApprenticeshipName = apprenticeship != null
             ? apprenticeship.ApprenticeshipDetails()
             : String.Empty;
     }
 }
Ejemplo n.º 9
0
        public static ContentViewModel Populate(this ContentViewModel model, string path,
                                                UserContext.UserContextName contextName, int version, ProviderPortalEntities db,
                                                UserContext.UserContextInfo userContext)
        {
            model = model.PopulateInner(path, contextName, version, db, userContext);

            // Safely embed if required to prevent infinite recursion
            if (model.SafeEmbed && model.Status != ContentStatus.ExistingPage)
            {
                return(new ContentViewModel
                {
                    Status = ContentStatus.ExistingPage,
                    Content = new AddEditContentViewModel
                    {
                        Path = path,
                        Embed = true,
                        UserContext = userContext.ContextName
                    },
                    SafeEmbed = model.SafeEmbed
                });
            }

            return(model);
        }
Ejemplo n.º 10
0
        private static ContentViewModel PopulateInner(this ContentViewModel model, string path,
                                                      UserContext.UserContextName contextName, int version, ProviderPortalEntities db,
                                                      UserContext.UserContextInfo userContext)
        {
            bool canManageContent = Permission.HasPermission(false, true, Permission.PermissionName.CanManageContent);

            version     = canManageContent ? version : PublishedVersion;
            contextName = canManageContent && contextName != UserContext.UserContextName.None
                ? contextName
                : userContext.ContextName;

            if (String.IsNullOrWhiteSpace(path))
            {
                return(new ContentViewModel {
                    Content = null, Status = ContentStatus.NotFound
                });
            }

            var cachedVersion = version == PublishedVersion
                ? ContentCache.Get(path, contextName)
                : null;

            if (cachedVersion != null)
            {
                return(cachedVersion);
            }

            var query = db.Contents.Where(x =>
                                          x.Path.Equals(path, StringComparison.CurrentCultureIgnoreCase))
                        .AsQueryable();
            var content = version == PublishedVersion
                ? query.FirstOrDefault(x => x.RecordStatusId == (int)Constants.RecordStatus.Live && ((int)contextName & x.UserContext) != 0)
                : query.FirstOrDefault(x => x.Version == version);

            // No content exists for the current user context return an error
            if (content == null && !canManageContent)
            {
                return(new ContentViewModel
                {
                    Content = null,
                    Status = query.Any() && !HttpContext.Current.Request.IsAuthenticated
                        ? ContentStatus.AuthenticationRequired
                        : ContentStatus.NotFound,
                    SafeEmbed = model.SafeEmbed
                });
            }

            var otherAvailableContexts = UserContext.UserContextName.None;

            if (canManageContent)
            {
                // Work out what other contexts the content is available in
                var availableContexts = query
                                        .Where(x => x.RecordStatusId == (int)Constants.RecordStatus.Live)
                                        .Select(x => new { x.ContentId, x.UserContext }).ToList();
                foreach (var item in availableContexts)
                {
                    if (content == null || content.ContentId != item.ContentId)
                    {
                        otherAvailableContexts |= (UserContext.UserContextName)item.UserContext;
                    }
                }
                otherAvailableContexts ^= content == null
                    ? UserContext.UserContextName.None
                    : (UserContext.UserContextName)content.UserContext;

                // The page doesn't exist, offer to create a new one
                if (content == null)
                {
                    var defaultContent = db.Contents.FirstOrDefault(x => x.Path == "DefaultContent") ?? new Content();
                    return(new ContentViewModel
                    {
                        Content = new AddEditContentViewModel
                        {
                            Version = 1,
                            Path = path,
                            Title = defaultContent.Title,
                            Body = defaultContent.Body,
                            Scripts = defaultContent.Scripts,
                            Styles = defaultContent.Styles,
                            Summary = null,
                            UserContext = UserContext.UserContextName.All ^ otherAvailableContexts,
                            Embed = false,
                            RecordStatusId = (int)Constants.RecordStatus.Pending,
                            LanguageId = defaultContent.LanguageId,
                            ContextsInUse = otherAvailableContexts
                        },
                        Status = ContentStatus.NewPage,
                        SafeEmbed = model.SafeEmbed
                    });
                }
            }

            // Page exists and isn't new
            var result = new ContentViewModel
            {
                Content = new AddEditContentViewModel
                {
                    ContentId      = content.ContentId,
                    Version        = content.Version,
                    Path           = content.Path,
                    Title          = content.Title,
                    Body           = content.Body,
                    Scripts        = content.Scripts,
                    Styles         = content.Styles,
                    Summary        = null,
                    UserContext    = (UserContext.UserContextName)content.UserContext,
                    Embed          = content.Embed,
                    RecordStatusId = content.RecordStatusId,
                    LanguageId     = content.LanguageId,
                    ContextsInUse  = otherAvailableContexts
                },
                Status    = ContentStatus.ExistingPage,
                SafeEmbed = model.SafeEmbed
            };

            if (result.Content.ContentId != 0 && version == PublishedVersion)
            {
                ContentCache.Add(result);
            }
            return(result);
        }
Ejemplo n.º 11
0
        public static AddEditContentViewModel Populate(this AddEditContentViewModel model, string path,
                                                       UserContext.UserContextName contextName, int version, ProviderPortalEntities db, UserContext.UserContextInfo userContext)
        {
            var content = new ContentViewModel();

            model = content.Populate(path, contextName, version, db, userContext).Content;
            var availableContexts = GetAvailableContexts(path, db);

            model.ContextsInUse = UserContext.UserContextName.All ^ availableContexts;
            return(model);
        }
        public static void Populate(this List <BulkUploadHistoryViewModel> model, UserContext.UserContextInfo userContext, ProviderPortalEntities db, Constants.BulkUpload_DataType dataType)
        {
            try
            {
                //IQueryable<BulkUploadHistory> historyRecords;
                IQueryable <BulkUpload> historyRecords;

                if (userContext.IsOrganisation())
                {
                    //all providerswhich belongs to the organsiation
                    var providersToSearch = BulkUploadValidateExtension.GetPermittedBulkUploadProviders(db, userContext, dataType);

                    //get history of all the provider which belongs to organisation + organisation's respective upload

                    /*
                     * historyRecords =
                     *  db.BulkUploadHistories.Include("BulkUploadHistoryProviders.Provider")
                     *      .Where(
                     *          x =>
                     *          providersToSearch.Contains(x.UserProviderId.Value)
                     || x.UserOrganisationId == userContext.ItemId);
                     */

                    historyRecords =
                        db.BulkUploads
                        .Include("BulkUploadProviders.Provider")
                        .Where(x =>
                               (providersToSearch.Contains(x.UserProviderId.Value) || x.UserOrganisationId == userContext.ItemId)
                               &&
                               (x.FileContentType == null || x.FileContentType == (int)dataType));
                }
                else
                {
                    /*
                     * historyRecords =
                     *  db.BulkUploadHistories.Include("BulkUploadHistoryProviders.Provider")
                     *      .Where(
                     *          x =>
                     *          x.UserProviderId.HasValue && x.UserProviderId == userContext.ItemId
                     || x.BulkUploadHistoryProviders.Any(p => p.ProviderId == userContext.ItemId));
                     */

                    historyRecords =
                        db.BulkUploads
                        .Include("BulkUploadProviders.Provider")
                        .Where(x =>
                               (x.UserProviderId.HasValue && x.UserProviderId == userContext.ItemId || x.BulkUploadProviders.Any(p => p.ProviderId == userContext.ItemId))
                               &&
                               (x.FileContentType == null || x.FileContentType == (int)dataType));
                }

                foreach (var historyRecord in historyRecords.OrderByDescending(x => x.BulkUploadId))
                {
                    var currentStatus =
                        historyRecord.BulkUploadStatusHistories.OrderByDescending(x => x.CreatedDateTimeUtc)
                        .FirstOrDefault();
                    if (currentStatus == null)
                    {
                        continue;
                    }
                    var item = new BulkUploadHistoryViewModel
                    {
                        BulkUploadId                  = historyRecord.BulkUploadId,
                        FileName                      = historyRecord.FileName,
                        DownloadUrl                   = historyRecord.FilePath,
                        IsOrganisationUpload          = userContext.IsOrganisation(),
                        ProviderName                  = LoadProviderName(historyRecord),
                        IsAuthorisedToViewAndDownload = userContext.IsOrganisation()
                            ? historyRecord.UserOrganisationId == userContext.ItemId
                            : historyRecord.UserProviderId == userContext.ItemId,
                        UserName            = currentStatus.AspNetUser.Name,
                        UploadedDateTime    = currentStatus.CreatedDateTimeUtc.ToLocalTime(),
                        StatusDescription   = currentStatus.BulkUploadStatu.BulkUploadStatusText,
                        IsDownloadAvailable =
                            !string.IsNullOrEmpty(historyRecord.FilePath) && File.Exists(historyRecord.FilePath),
                        IsUploadSuccessful =
                            currentStatus.BulkUploadStatusId.Equals((int)Constants.BulkUploadStatus.Published),
                    };

                    if (historyRecord.FileContentType != null)
                    {
                        item.FileContentType = (Constants.FileContentType)Enum.Parse(typeof(Constants.FileContentType), historyRecord.FileContentType.ToString());
                    }

                    model.Add(item);
                }
            }
            catch (Exception ex)
            {
                AppGlobal.Log.WriteLog(string.Concat(ex.Message, "-", ex.StackTrace));
            }
        }
        private static List <Provider> LoadProviders(UserContext.UserContextInfo userContext, ProviderPortalEntities db,
                                                     bool downloadableProvidersOnly = false, bool eagerLoading = false)
        {
            var providers = new List <Provider>();

            switch (userContext.ContextName)
            {
            case UserContext.UserContextName.Provider:
            {
                var provider = eagerLoading
                        ? db.Providers
                               .Include("Venues.Address")
                               .Include("Courses.CourseInstances.CourseInstanceStartDates")
                               .First(x => x.ProviderId == userContext.ItemId)
                        : db.Providers.Find(userContext.ItemId);
                if (provider != null)
                {
                    providers.Add(provider);
                }
                break;
            }

            case UserContext.UserContextName.Organisation:
            {
                var organisation = db.Organisations.FirstOrDefault(x => x.OrganisationId == userContext.ItemId);

                if (organisation != null)
                {
                    var providerIds = organisation.OrganisationProviders.Where(
                        o =>
                        o.IsAccepted && !o.IsRejected &&
                        o.Provider.RecordStatusId == (int)Constants.RecordStatus.Live &&
                        (o.CanOrganisationEditProvider || !downloadableProvidersOnly))
                                      .Select(x => x.ProviderId).ToList();

                    //foreach (var item in providerIds)
                    //{
                    //    providers.Add(
                    //        eagerLoading
                    //            ? db.Providers
                    //                .Include("Venues.Address")
                    //                .Include("Courses.CourseInstances.CourseInstanceStartDates")
                    //                .First(x => x.ProviderId == item)
                    //            : db.Providers.Find(item)
                    //        );
                    //}

                    providers.AddRange(
                        providerIds.Select(
                            item =>
                            (Provider)
                            (eagerLoading
                                            ? db.Providers.Include("Venues.Address")
                             .Include("Courses.CourseInstances.CourseInstanceStartDates")
                             .First(x => x.ProviderId == item)
                                            : db.Providers.Find(item))));
                }
                break;
            }
            }
            return(providers);
        }
        public static byte[] TransformToCsv(this BulkUploadViewModel model, UserContext.UserContextInfo userContext, ProviderPortalEntities db, Constants.BulkUpload_DataType dataType)
        {
            var providers = LoadProviders(userContext, db, true, true);

            return(new EntityToCsvConvertor(providers, userContext, dataType).ToCsv());
        }
        public static ManageUsersViewModel Populate(this ManageUsersViewModel model, ProviderPortalEntities db,
                                                    UserContext.UserContextInfo context, bool deferredLoad)
        {
            model.CanAdd = false;
            model.CanEditSecureAccessUsers = Permission.HasPermission(false, true,
                                                                      Permission.PermissionName.CanEditSecureAccessUsers);
            model.DeferredLoad = deferredLoad;

            var noUkprn       = AppGlobal.Language.GetText("Manage_Users_NoUKPRN", "N/A");
            var noProviderOrg = AppGlobal.Language.GetText("Manage_Users_NoProviderOrOrganisation", "N/A");
            var noRole        = AppGlobal.Language.GetText("Manage_Users_NoRole", "N/A");

            IQueryable <AspNetUser> aspNetUsers = null;

            switch (context.ContextName)
            {
            case UserContext.UserContextName.Provider:

                model.CanAdd = Permission.HasPermission(false, true,
                                                        Permission.PermissionName.CanAddEditProviderUsers);
                if (!deferredLoad)
                {
                    aspNetUsers = db.Providers
                                  .Where(x => x.ProviderId == (int)context.ItemId)
                                  .SelectMany(x => x.AspNetUsers);
                }
                break;

            case UserContext.UserContextName.Organisation:

                model.CanAdd = Permission.HasPermission(false, true,
                                                        Permission.PermissionName.CanAddEditOrganisationUsers);
                if (!deferredLoad)
                {
                    aspNetUsers = db.Organisations
                                  .Where(x => x.OrganisationId == (int)context.ItemId)
                                  .SelectMany(x => x.AspNetUsers);
                }
                break;

            case UserContext.UserContextName.Administration:

                model.CanAdd = Permission.HasPermission(false, true,
                                                        Permission.PermissionName.CanAddEditAdminUsers);
                if (!deferredLoad)
                {
                    aspNetUsers = db.AspNetUsers;
                }
                break;

            default:

                model.Users  = new List <ManageUsersViewModelItem>();
                model.CanAdd = false;
                break;
            }

            if (aspNetUsers != null && model.Category != UserCategory.All)
            {
                switch (model.Category)
                {
                case UserCategory.Active:
                    // Live
                    // DfE Secure Access
                    aspNetUsers = aspNetUsers
                                  .Where(x =>
                                         !x.IsDeleted && (
                                             x.IsSecureAccessUser
                                             ||
                                             (x.EmailConfirmed && !x.PasswordResetRequired &&
                                              (!x.LockoutEnabled || (x.LockoutEnabled && x.LockoutEndDateUtc == null)))
                                             ));
                    break;

                case UserCategory.Deleted:
                    // Deleted
                    aspNetUsers = aspNetUsers.Where(x => x.IsDeleted);
                    break;

                case UserCategory.Pending:
                    // Email Confirmation Required
                    // Pasword Reset Required
                    // Account Locked
                    aspNetUsers = aspNetUsers
                                  .Where(x => !x.IsDeleted && !x.IsSecureAccessUser
                                         &&
                                         (!x.EmailConfirmed || x.PasswordResetRequired ||
                                          x.LockoutEnabled && x.LockoutEndDateUtc > DateTime.UtcNow)
                                         );
                    break;
                }
            }

            model.Users = aspNetUsers == null
                ? new List <ManageUsersViewModelItem>()
                : aspNetUsers
                          .Select(x => new ManageUsersViewModelItem
            {
                UserId = x.Id,
                Email  = x.Email,
                Status = x.IsDeleted
                        ? "Deleted"
                        : x.IsSecureAccessUser
                            ? "DfE Secure Access"
                            : !x.EmailConfirmed
                                ? "Email Confirmation Required"
                                : x.PasswordResetRequired
                                    ? "Password Reset Required"
                                    : x.LockoutEnabled && x.LockoutEndDateUtc > DateTime.UtcNow
                                        ? "Account Locked"
                                        : "Live",
                Ukprn = x.Providers2.Any()
                        ? "" + x.Providers2.FirstOrDefault().Ukprn
                        : x.Organisations2.Any() && x.Organisations2.FirstOrDefault().UKPRN != null
                            ? "" + x.Organisations2.FirstOrDefault().UKPRN
                            : noUkprn,
                ProviderName = x.Providers2.Any()
                        ? x.Providers2.FirstOrDefault().ProviderName
                        : x.Organisations2.Any()
                            ? x.Organisations2.FirstOrDefault().OrganisationName
                            : noProviderOrg,
                DisplayName        = x.Name,
                Role               = x.AspNetRoles.Any() ? x.AspNetRoles.FirstOrDefault().Name : noRole,
                LastLogInDate      = x.LastLoginDateTimeUtc,
                IsSecureAccessUser = x.IsSecureAccessUser
            })
                          .OrderByDescending(x => x.LastLogInDate)
                          .ToList();

            return(model);
        }
        public static BulkUploadHistoryViewModel GetHistoryFileUrl(this List <BulkUploadHistoryViewModel> model, UserContext.UserContextInfo userContext, ProviderPortalEntities db, int bulkUploadId)
        {
            var url = (from bulk in db.BulkUploads
                       where bulk.BulkUploadId == bulkUploadId
                       select bulk).FirstOrDefault();


            if ((userContext.IsOrganisation() && url.UserOrganisationId != userContext.ItemId.Value) ||
                (userContext.IsProvider() && url.UserProviderId != userContext.ItemId.Value))
            {
                return(null);
            }

            BulkUploadHistoryViewModel filteredModel = null;

            if (url != null)
            {
                filteredModel = new BulkUploadHistoryViewModel
                {
                    FileName    = url.FileName,
                    DownloadUrl = url.FilePath
                };
            }

            return(filteredModel);
        }
 public EntityToCsvConvertor(List <Provider> providers, UserContext.UserContextInfo userContext, Constants.BulkUpload_DataType dataType)
 {
     _providers   = providers;
     _userContext = userContext;
     _dataType    = dataType;
 }
        public static void Populate(this BulkUploadHistoryDetailViewModel model, UserContext.UserContextInfo userContext, ProviderPortalEntities db, int bulkUploadId)
        {
            var history = (from bulk in db.BulkUploads
                           where bulk.BulkUploadId == bulkUploadId
                           select bulk).FirstOrDefault();

            if (history == null)
            {
                model.AccessDenied = true;
                return;
            }
            if ((userContext.IsOrganisation() && history.UserOrganisationId != userContext.ItemId.Value) ||
                (userContext.IsProvider() && history.UserProviderId != userContext.ItemId.Value))
            {
                model.AccessDenied = true;
                return;
            }

            var currentStatus = history.BulkUploadStatusHistories.OrderByDescending(x => x.CreatedDateTimeUtc).FirstOrDefault();

            if (currentStatus == null)
            {
                model.AccessDenied = true;
                return;
            }

            model.BulkUploadId = bulkUploadId;

            model.FileName = history.FileName;

            if (history.FileContentType != null)
            {
                model.FileContentType = (Constants.FileContentType)Enum.Parse(typeof(Constants.FileContentType), history.FileContentType.ToString());
            }

            model.UserName = db.AspNetUsers.FirstOrDefault(x => x.Id.ToString() == currentStatus.LoggedInUserId).Name;

            model.UploadedDateTime = currentStatus.CreatedDateTimeUtc.ToLocalTime().ToString(Constants.ConfigSettings.ShortDateTimeFormat);

            model.UploadStatusText = currentStatus.BulkUploadStatu.BulkUploadStatusText;

            model.ExistingCourseCount = history.ExistingCourses ?? 0;

            model.TotalCourseCount = history.NewCourses ?? 0;

            model.InvalidCourseCount = history.InvalidCourses ?? 0;

            model.ExistingVenueCount = history.ExistingVenues ?? 0;

            model.TotalVenueCount = history.NewVenues ?? 0;

            model.InvalidVenueCount = history.InvalidVenues ?? 0;

            model.ExistingOpportunityCount = history.ExistingOpportunities ?? 0;

            model.TotalOpportunityCount = history.NewOpportunities ?? 0;

            model.InvalidOpportunityCount = history.InvalidOpportunities ?? 0;

            model.ExistingApprenticeshipCount = history.ExistingApprenticeships ?? 0;

            model.TotalApprenticeshipCount = history.NewApprenticeships ?? 0;

            model.InvalidApprenticeshipCount = history.InvalidApprenticeships ?? 0;

            model.ExistingLocationCount = history.ExistingLocations ?? 0;

            model.TotalLocationCount = history.NewLocations ?? 0;

            model.InvalidLocationCount = history.InvalidLocations ?? 0;

            model.ExistingDeliveryLocationCount = history.ExistingDeliveryLocations ?? 0;

            model.TotalDeliveryLocationCount = history.NewDeliveryLocations ?? 0;

            model.InvalidDeliveryLocationCount = history.InvalidDeliveryLocations ?? 0;


            model.UploadStatus = (Constants.BulkUploadStatus)Enum.Parse(typeof(Constants.BulkUploadStatus), currentStatus.BulkUploadStatu.BulkUploadStatusName);

            model.ErrorSummary = new BulkUploadHistoryErrorSummary
            {
                UploadSummaryDetails = new List <BulkUploadHistoryDetailItemsViewModel>()
            };

            if (history.FileContentType != null)
            {
                model.FileContentType = (Constants.FileContentType)Enum.Parse(typeof(Constants.FileContentType), history.FileContentType.ToString());
            }

            foreach (var item in db.BulkUploadExceptionItems.Where(x => x.BulkUploadId == bulkUploadId))
            {
                var bulkUploadHistoryDetailItemsViewModel = new BulkUploadHistoryDetailItemsViewModel
                {
                    ColumnName        = item.ColumnName,
                    RowId             = item.LineNumber,
                    ActualColumnValue = item.ColumnValue,
                    Provider          = item.ProviderId.HasValue ? item.ProviderId.ToString() : string.Empty,
                    Details           = item.Details,
                    ErrorType         = (Constants.BulkUpload_Validation_ErrorType)Enum.Parse(typeof(Constants.BulkUpload_Validation_ErrorType), item.BulkUploadErrorType.BulkUploadErrorTypeName),
                    SectionName       = (Constants.BulkUpload_SectionName)item.BulkUploadSectionId
                };
                model.ErrorSummary.UploadSummaryDetails.Add(bulkUploadHistoryDetailItemsViewModel);
            }
        }
Ejemplo n.º 19
0
        public static List <int> GetPermittedBulkUploadProviders(ProviderPortalEntities db, UserContext.UserContextInfo userContext, Constants.BulkUpload_DataType dataType)
        {
            var permittedBulkUploadProviders = new List <int>();

            var providerPermission     = (dataType == Constants.BulkUpload_DataType.CourseData ? Permission.PermissionName.CanBulkUploadProviderFiles : Permission.PermissionName.CanBulkUploadProviderApprenticeshipFiles);
            var organisationPermission = (dataType == Constants.BulkUpload_DataType.CourseData ? Permission.PermissionName.CanBulkUploadOrganisationFiles : Permission.PermissionName.CanBulkUploadOrganisationApprenticeshipFiles);

            if (userContext.IsProvider() && Permission.HasPermission(false, true, providerPermission))
            {
                permittedBulkUploadProviders.Add(userContext.ItemId.Value);
            }
            else if (userContext.IsOrganisation() && Permission.HasPermission(false, true, organisationPermission))
            {
                permittedBulkUploadProviders =
                    db.OrganisationProviders.Where(
                        o =>
                        o.OrganisationId.Equals(userContext.ItemId.Value) &&
                        o.CanOrganisationEditProvider &&
                        o.IsAccepted && !o.IsRejected)
                    .Select(o => o.ProviderId).ToList();
            }

            return(permittedBulkUploadProviders);
        }
Ejemplo n.º 20
0
        public static void InitiateBulkUpload(
            this BulkUploadViewModel model,
            UserContext.UserContextInfo userContext,
            ProviderPortalEntities db)
        {
            try
            {
                // copy data to local data store
                new FileHandler(model).CopyFileToDataStore();

                // get bulk upload service client
                var bulkUploadService = new BulkUploadWCFServiceClient();

                // when validating only ...
                if (!model.OverrideException)
                {
                    // ... build contextual parameters for bulk upload serivce
                    var parameters = new EnqueueParameters
                    {
                        FileName          = model.Summary.FileName,
                        FilePath          = model.Summary.FilePath,
                        UserId            = LoggedInUser(db),
                        UserContextType   = userContext.ContextName.ToString(),
                        UserContextItemId = (int)userContext.ItemId,
                        FileSize          = model.Summary.ContentLength
                    };

                    // ... and enqueue the bulk upload with the service
                    var result = bulkUploadService.Enqueue(parameters);
                }
            }
            catch (EndpointNotFoundException ex)
            {
                model.Message = AppGlobal.Language.GetText(
                    "BulkUpload_Exceptions_EndpointNotFoundException",
                    "The Bulk Upload service has encountered an error, and your upload has failed.  Please try your upload later.  If you encounter this message again, please contact the Support Team.");
                AppGlobal.Log.WriteLog(string.Concat(ex.Message, ":", ex.StackTrace));
            }
            catch (TimeoutException ex)
            {
                model.Message = AppGlobal.Language.GetText(
                    "BulkUpload_Exceptions_TimeoutException",
                    "The Bulk Upload service could not be contacted, and your upload has failed.  Please try your upload later.  If you encounter this message again, please contact the Support Team.");
                AppGlobal.Log.WriteLog(string.Concat(ex.Message, ":", ex.StackTrace));
            }
            catch (FaultException <BulkUploadProviderFault> ex)
            {
                var template = AppGlobal.Language.GetText("BulkUpload_Exceptions_BulkUploadProviderFaultException", "The Bulk Upload service has rejected your file, with the following error: {0}");
                model.Message = String.Format(template, ex.Detail.Message);
            }
            catch (FaultException <BulkUploadFault> ex)
            {
                model.Message = AppGlobal.Language.GetText("BulkUpload_Exceptions_BulkUploadFaultException", "The Bulk Upload service has encountered an error, and your upload has failed.  Please try your upload later.  If you encounter this message again, please contact the Support Team.");
                AppGlobal.Log.WriteLog(string.Concat(ex.Detail.Message, ":", ex.StackTrace));
            }
            catch (Exception ex)
            {
                model.Message = ex.Message;
                AppGlobal.Log.WriteLog(string.Concat(ex.Message, ":", ex.StackTrace));
            }
        }