Exemple #1
0
        public static DataTable GetCoursesWithExpiredLAR(Int32?providerId = null)
        {
            //If there are courses which are linked to a no-longer-valid (expired) LAR (learning aim reference) code,
            //then the number of courses like this should be indicated.
            ProviderPortalEntities db = new ProviderPortalEntities();

            UserContext.UserContextInfo context = UserContext.GetUserContext();
            DataTable dt = new DataTable();

            DbCommand cmd = db.Database.Connection.CreateCommand();

            cmd.CommandText = "exec [dbo].[up_GetProviderCoursesWithExpiredLAR] @ProviderId";
            cmd.Parameters.Add(new SqlParameter("@ProviderId", providerId ?? context.ItemId));

            try
            {
                db.Database.Connection.Open();
                using (DbDataReader reader = cmd.ExecuteReader())
                {
                    dt.Load(reader);
                }
            }
            finally
            {
                db.Database.Connection.Close();
            }

            return(dt);
        }
Exemple #2
0
        public static DataTable GetOutOfDateCourses(Int32?providerId = null)
        {
            ProviderPortalEntities db = new ProviderPortalEntities();

            UserContext.UserContextInfo context = UserContext.GetUserContext();
            DataTable dt = new DataTable();

            DbCommand cmd = db.Database.Connection.CreateCommand();

            cmd.CommandText = "exec [dbo].[up_GetProviderCoursesOutOfDate] @ProviderId, @LongCourseMinDurationWeeks, @LongCourseMaxStartDateInPastDays";
            cmd.Parameters.Add(new SqlParameter("@ProviderId", providerId ?? context.ItemId));
            cmd.Parameters.Add(new SqlParameter("@LongCourseMinDurationWeeks", Constants.ConfigSettings.LongCourseMinDurationWeeks));
            cmd.Parameters.Add(new SqlParameter("@LongCourseMaxStartDateInPastDays", Constants.ConfigSettings.LongCourseMaxStartDateInPastDays));

            try
            {
                db.Database.Connection.Open();
                using (DbDataReader reader = cmd.ExecuteReader())
                {
                    dt.Load(reader);
                }
            }
            finally
            {
                db.Database.Connection.Close();
            }

            return(dt);
        }
Exemple #3
0
        /// <summary>
        /// Convert an <see cref="AddEditLocationModel"/> to an <see cref="Location"/>.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <param name="db">
        /// The db.
        /// </param>
        /// <returns>
        /// The <see cref="Location"/>.
        /// </returns>
        public static Location ToEntity(this AddEditLocationModel model, ProviderPortalEntities db)
        {
            Location location;

            if (model.LocationId == null)
            {
                location = new Location
                {
                    CreatedByUserId    = Permission.GetCurrentUserId(),
                    CreatedDateTimeUtc = DateTime.UtcNow
                };
            }
            else
            {
                location = db.Locations.Find(model.LocationId);
                if (location == null)
                {
                    return(null);
                }
            }

            location.ProviderOwnLocationRef = model.ProviderOwnLocationRef;
            location.LocationName           = model.LocationName;
            location.Email     = model.Email;
            location.Website   = UrlHelper.GetFullUrl(model.Website);
            location.Telephone = model.Telephone;

            return(location);
        }
 public static void ValidateEntry(this ImportBatchesViewModelItem model, ProviderPortalEntities db, ModelStateDictionary modelState)
 {
     if (db.ImportBatches.Any(x => x.ImportBatchName == model.ImportBatchName && x.ImportBatchId != model.ImportBatchId))
     {
         modelState.AddModelError("ImportBatchName", AppGlobal.Language.GetText("ImportBatches_Create_NameInUse", "The batch name must be unique."));
     }
 }
        /// <summary>
        /// Loads this instance.
        /// </summary>
        /// <param name="refresh">Force a reload of the data</param>
        public void Load(bool refresh = false)
        {
            Cache = (RecentProvisionCache)CacheManagement.CacheHandler.Get(CacheKey);
            if (Cache != null && !refresh)
            {
                return;
            }

            var db    = new ProviderPortalEntities();
            var items = db.UserProvisionHistories.Where(x => x.UserId == UserId);

            Cache = new RecentProvisionCache
            {
                Organisations = items
                                .Where(x => x.OrganisationId != null)
                                .OrderBy(x => x.DisplayOrder)
                                .Select(x => new SelectListItem
                {
                    Text  = x.Organisation.OrganisationName,
                    Value = "O" + x.OrganisationId
                }).ToList(),
                Providers = items
                            .Where(x => x.ProviderId != null)
                            .OrderBy(x => x.DisplayOrder)
                            .Select(x => new SelectListItem
                {
                    Text  = x.Provider.ProviderName,
                    Value = "P" + x.ProviderId
                }).ToList(),
            };
            CacheManagement.CacheHandler.Add(CacheKey, Cache);
        }
        /// <summary>
        /// Saves this instance.
        /// </summary>
        private void Save()
        {
            CacheManagement.CacheHandler.Add(CacheKey, Cache);

            var db = new ProviderPortalEntities();

            foreach (UserProvisionHistory item in db.UserProvisionHistories.Where(x => x.UserId == UserId).ToList())
            {
                db.Entry(item).State = EntityState.Deleted;
            }
            db.SaveChanges();
            int displayOrder = 0;

            foreach (var item in Cache.Organisations)
            {
                db.UserProvisionHistories.Add(new UserProvisionHistory
                {
                    UserId         = UserId,
                    OrganisationId = Int32.Parse(item.Value.Substring(1)),
                    DisplayOrder   = ++displayOrder
                });
            }
            displayOrder = 0;
            foreach (var item in Cache.Providers)
            {
                db.UserProvisionHistories.Add(new UserProvisionHistory
                {
                    UserId       = UserId,
                    ProviderId   = Int32.Parse(item.Value.Substring(1)),
                    DisplayOrder = ++displayOrder
                });
            }
            db.SaveChanges();
        }
Exemple #7
0
        /// <summary>
        /// Finds all permissions from the constants in the Permissions Class, and adds the missing ones to the DB.
        /// </summary>
        public static void AddMissingPermissions()
        {
            // Get Database Permissions
            using (ProviderPortalEntities databaseContext = new ProviderPortalEntities())
            {
                var permissions = from perm in databaseContext.Permissions
                                  select new { PermissionId = perm.PermissionId };

                System.Array enumValues = System.Enum.GetValues(typeof(Permission.PermissionName));
                for (int index = 1; index < enumValues.Length; index++)
                {
                    int permissionId = index;
                    if (!permissions.Any(p => p.PermissionId == permissionId))
                    {
                        // Add permission
                        string permissionName = ((Permission.PermissionName)(int) enumValues.GetValue(index)).ToString();

                        Entities.Permission newPermission = new Entities.Permission
                        {
                            PermissionName        = permissionName,
                            PermissionId          = permissionId,
                            PermissionDescription =
                                "Automatically added by the site code, description required"
                        };
                        databaseContext.Permissions.Add(newPermission);
                    }
                }

                databaseContext.SaveChanges();
            }
        }
        /// <summary>
        /// Convert an <see cref="AddEditDeliveryInformationModel"/> to an <see cref="Provider"/>.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <param name="db">
        /// The db.
        /// </param>
        /// <returns>
        /// The <see cref="Provider"/>.
        /// </returns>
        public static Provider ToEntity(this AddEditDeliveryInformationModel model, ProviderPortalEntities db)
        {
            Provider provider;

            if (model.ProviderId == null)
            {
                return(null);
            }
            else
            {
                provider = db.Providers.Find(model.ProviderId);
                if (provider == null)
                {
                    return(null);
                }
            }

            var canEditSpecialFields = Permission.HasPermission(false, true,
                                                                Permission.PermissionName.CanEditProviderSpecialFields);

            if (canEditSpecialFields && model.ProviderId != null)
            {
                provider.RoATPFFlag = model.RoATP;
            }

            provider.ApprenticeshipContract         = model.ApprenticeshipContract;
            provider.NationalApprenticeshipProvider = model.NationalApprenticeshipProvider;

            if (!provider.PassedOverallQAChecks || Permission.HasPermission(false, false, Permission.PermissionName.CanQAProviders))
            {
                provider.MarketingInformation = Markdown.Sanitize(model.MarketingInformation);
            }

            return(provider);
        }
        /// <summary>
        /// Determines whether a provision name is in use when <cref>onstants.ConfigSettings.RequireUniqueProvisionNames</cref> is set to <c>true</c>; otherwise returns <c>false</c>.
        /// </summary>
        /// <param name="db"></param>
        /// <param name="name">Provision name to check</param>
        /// <param name="providerId">Provider Id to ignore or null for none.</param>
        /// <param name="organisationId">Organisation Id to ignore or null for none.</param>
        /// <returns></returns>
        public static bool IsNameInUse(ProviderPortalEntities db, string name, int?providerId, int?organisationId)
        {
            if (!Constants.ConfigSettings.RequireUniqueProvisionNames)
            {
                return(false);
            }

            name = name.Trim();
            var orgs = db.Organisations.AsQueryable();

            if (organisationId != null)
            {
                orgs = orgs.Where(x => x.OrganisationId != organisationId);
            }

            var providers = db.Providers.AsQueryable();

            if (providerId != null)
            {
                providers = providers.Where(x => x.ProviderId != providerId);
            }

            return(orgs.Any(x => x.OrganisationName.Equals(name, StringComparison.CurrentCultureIgnoreCase)) ||
                   providers.Any(x => x.ProviderName.Equals(name, StringComparison.CurrentCultureIgnoreCase)));
        }
 public static List <OrganisationUserContactDetails> GetOrganisationUsers(ProviderPortalEntities db,
                                                                          int organisationId, bool includeNormalUsers, bool includePrimaryContacts)
 {
     return(GetOrganisationUsers(db, new List <int> {
         organisationId
     }, includeNormalUsers, includePrimaryContacts));
 }
 public static List <ProviderUserContactDetails> GetProviderUsers(ProviderPortalEntities db,
                                                                  int providerId, bool includeNormalUsers, bool includePrimaryContacts)
 {
     return(GetProviderUsers(db, new List <int> {
         providerId
     }, includeNormalUsers, includePrimaryContacts));
 }
        private static void ImportValidity(SqlConnection conn, String userId, ProviderPortalEntities db)
        {
            MetadataUpload metadataUpload = new MetadataUpload
            {
                MetadataUploadTypeId = (int)Constants.MetadataUploadType.LearningAimValidity,
                CreatedByUserId      = userId,
                CreatedDateTimeUtc   = DateTime.UtcNow,
                FileName             = Path.GetFileName(mdbFilename),
                FileSizeInBytes      = (int)mdbFileSize,
                RowsBefore           = db.LearningAimValidities.Count()
            };
            Stopwatch sw = new Stopwatch();

            sw.Start();

            // Import Validity
            SqlCommand comm = new SqlCommand("TRUNCATE TABLE [dbo].[Import_LearningAimValidity];", conn);

            comm.ExecuteNonQuery();
            DataTable dt = OpenDataTable("SELECT LearnAimRef AS LearningAimRefId, ValidityCategory, StartDate, EndDate, LastNewStartDate FROM Core_LARS_Validity;");

            BulkImportData(conn, dt, "[dbo].[Import_LearningAimValidity]");
            comm = new SqlCommand("MERGE [dbo].[LearningAimValidity] dest USING [dbo].[Import_LearningAimValidity] source ON dest.LearningAimRefId = source.LearningAimRefId AND dest.ValidityCategory = source.ValidityCategory WHEN MATCHED THEN UPDATE SET dest.StartDate = source.StartDate, dest.EndDate = source.EndDate, dest.LastNewStartDate = source.LastNewStartDate WHEN NOT MATCHED THEN INSERT (LearningAimRefId, ValidityCategory, StartDate, EndDate, LastNewStartDate) VALUES (source.LearningAimRefId, source.ValidityCategory, source.StartDate, source.EndDate, source.LastNewStartDate);", conn);
            comm.ExecuteNonQuery();

            sw.Stop();
            metadataUpload.DurationInMilliseconds = (int)sw.ElapsedMilliseconds;
            metadataUpload.RowsAfter = db.LearningAimValidities.Count();
            db.MetadataUploads.Add(metadataUpload);
        }
Exemple #13
0
        private static string LoggedInUser(ProviderPortalEntities db)
        {
            var loggedInUserName = HttpContext.Current.User.Identity.Name;
            var user             = db.AspNetUsers.FirstOrDefault(u => u.UserName.Equals(loggedInUserName));

            return(user != null ? user.Id : string.Empty);
        }
        private static void ImportLearningAims(SqlConnection conn, String userId, ProviderPortalEntities db)
        {
            MetadataUpload metadataUpload = new MetadataUpload
            {
                MetadataUploadTypeId = (int)Constants.MetadataUploadType.LearningAim,
                CreatedByUserId      = userId,
                CreatedDateTimeUtc   = DateTime.UtcNow,
                FileName             = Path.GetFileName(mdbFilename),
                FileSizeInBytes      = (int)mdbFileSize,
                RowsBefore           = db.LearningAims.Count()
            };
            Stopwatch sw = new Stopwatch();

            sw.Start();

            // Import Learning Aims
            SqlCommand comm = new SqlCommand("TRUNCATE TABLE [dbo].[Import_LearningAim];", conn);

            comm.ExecuteNonQuery();
            DataTable dt = OpenDataTable("SELECT LearnAimRef AS LearningAimRefId, LearnAimRefTitle AS LearningAimTitle, AwardOrgCode AS LearningAimAwardOrgCode, 0 AS IndependentLivingSkills, IIF(LearnDirectClassSystemCode1 = 'NUL', NULL, LearnDirectClassSystemCode1) AS LDCS1, IIF(LearnDirectClassSystemCode2 = 'NUL', NULL, LearnDirectClassSystemCode2) AS LDCS2, IIF(LearnDirectClassSystemCode3 = 'NUL', NULL, LearnDirectClassSystemCode3) AS LDCS3,  Switch (NotionalNVQLevelv2 = 'X',  '11', NotionalNVQLevelv2 = 'E', '10', NotionalNVQLevelv2 = '1', '1', NotionalNVQLevelv2 BETWEEN '2' AND '8', NotionalNVQLevelv2, NotionalNVQLevelv2 = 'H', '9') AS QualificationLevelId FROM Core_LARS_LearningDelivery WHERE (EffectiveTo IS NULL OR EffectiveTo > Now);");

            BulkImportData(conn, dt, "[dbo].[Import_LearningAim]");
            comm = new SqlCommand("MERGE [dbo].[LearningAim] dest USING [dbo].[Import_LearningAim] source ON  dest.LearningAimRefId = source.LearningAimRefId WHEN MATCHED THEN UPDATE SET dest.LearningAimTitle = source.LearningAimTitle, dest.LearningAimAwardOrgCode = source.LearningAimAwardOrgCode, dest.IndependentLivingSkills = source.IndependentLivingSkills, dest.LearnDirectClassSystemCode1 = source.LDCS1, dest.LearnDirectClassSystemCode2 = source.LDCS2, dest.LearnDirectClassSystemCode3 = source.LDCS3, dest.QualificationLevelId = CAST(source.QualificationLevelId AS INT), dest.RecordStatusId = 2 WHEN NOT MATCHED THEN INSERT (LearningAimRefId, Qualification, LearningAimTitle, LearningAimAwardOrgCode, IndependentLivingSkills, LearnDirectClassSystemCode1, LearnDirectClassSystemCode2, LearnDirectClassSystemCode3, QualificationLevelId, RecordStatusId) VALUES (source.LearningAimRefId, '', source.LearningAimTitle, source.LearningAimAwardOrgCode, source.IndependentLivingSkills, source.LDCS1, source.LDCS2, source.LDCS3, CAST(source.QualificationLevelId AS INT), 2);", conn);
            comm.ExecuteNonQuery();

            // Set status to delete for items not in import table
            comm = new SqlCommand("UPDATE [dbo].[LearningAim] SET RecordStatusId = 4 WHERE LearningAimRefId NOT IN (SELECT LearningAimRefId FROM [dbo].[Import_LearningAim]);", conn);
            comm.ExecuteNonQuery();

            sw.Stop();
            metadataUpload.DurationInMilliseconds = (int)sw.ElapsedMilliseconds;
            metadataUpload.RowsAfter = db.LearningAims.Count();
            db.MetadataUploads.Add(metadataUpload);
        }
Exemple #15
0
        /// <summary>
        /// Convert an <see cref="AddEditVenueModel"/> to an <see cref="Venue"/>.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <param name="db">
        /// The db.
        /// </param>
        /// <returns>
        /// The <see cref="Venue"/>.
        /// </returns>
        public static Venue ToEntity(this AddEditVenueModel model, ProviderPortalEntities db)
        {
            Venue venue;

            if (model.VenueId == null)
            {
                venue = new Venue
                {
                    CreatedByUserId    = Permission.GetCurrentUserId(),
                    CreatedDateTimeUtc = DateTime.UtcNow
                };
            }
            else
            {
                venue = db.Venues.Find(model.VenueId);
                if (venue == null)
                {
                    return(null);
                }
            }

            venue.ProviderOwnVenueRef = model.ProviderOwnVenueRef;
            venue.VenueName           = model.VenueName;
            venue.Email      = model.Email;
            venue.Website    = UrlHelper.GetFullUrl(model.Website);
            venue.Telephone  = model.Telephone;
            venue.Fax        = model.Fax;
            venue.Facilities = model.Facilities;

            return(venue);
        }
Exemple #16
0
        private Boolean IsCancellingImport(ProviderPortalEntities _db)
        {
            // Check if we have stopped the import
            ProgressMessage pm = _db.ProgressMessages.FirstOrDefault(x => x.MessageArea == MessageArea);

            return(pm == null || pm.MessageText == cancelImportMessage);
        }
Exemple #17
0
        /// <summary>
        /// Go through all the published pages for the specified path and
        /// archive the content or update its availability as appropriate.
        /// </summary>
        /// <param name="db">The database.</param>
        /// <param name="contentId">The content identifier.</param>
        /// <param name="path">The path.</param>
        /// <param name="context">The context.</param>
        private static void EnsureContextAvailability(ProviderPortalEntities db, int contentId, string path, UserContext.UserContextName context)
        {
            var pages =
                db.Contents.Where(
                    x =>
                    x.RecordStatusId == (int)Constants.RecordStatus.Live &&
                    x.Path.Equals(path, StringComparison.CurrentCultureIgnoreCase) &&
                    x.UserContext != (int)UserContext.UserContextName.None &&
                    x.ContentId != contentId);

            if (!pages.Any())
            {
                return;
            }

            var userContext = (int)context;

            foreach (var page in pages)
            {
                // User context is a flag enumeration so we can use
                // bitwise arithmetic to manipulate the values.

                // Clear all bits that
                var newContext = (userContext ^ page.UserContext) & page.UserContext;

                if (newContext == (int)UserContext.UserContextName.None)
                {
                    page.RecordStatusId = (int)Constants.RecordStatus.Archived;
                }
                else
                {
                    page.UserContext = newContext;
                }
            }
        }
Exemple #18
0
        public static void CheckQAUpToDate()
        {
            var providerQALastCalculated = (DateTime?)HttpContext.Current.Session[Constants.SessionFieldNames.ProviderQALastCalculated];

            if (!providerQALastCalculated.HasValue)
            {
                return;
            }

            var context = UserContext.GetUserContext();

            if (context == null)
            {
                return;
            }

            using (var db = new ProviderPortalEntities())
            {
                var currentLastCalculated = db.QualityScores.Where(s => s.ProviderId == context.ItemId).Select(x => x.CalculatedDateTimeUtc).FirstOrDefault();
                if (currentLastCalculated != null && currentLastCalculated > providerQALastCalculated.Value)
                {
                    //Quality score values in session are out of date and require updating with current values
                    SetSessionInformation(context);
                }
            }
        }
 public static void ValidateNewEntry(this A10FundingCodeViewModelItem model, ProviderPortalEntities db, ModelStateDictionary modelState)
 {
     if (db.A10FundingCode.Any(x => x.A10FundingCodeId == model.A10FundingCodeId))
     {
         modelState.AddModelError("A10FundingCodeId", AppGlobal.Language.GetText("A10FundingCode_Create_CodeInUse", "The A10 Funding Code field must be unique."));
     }
 }
Exemple #20
0
        /// <summary>
        /// Gets a list of all changes for a specified path.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="db">The database.</param>
        /// <param name="path">The path.</param>
        /// <returns></returns>
        public static ContentListViewModel Populate(this ContentListViewModel model, ProviderPortalEntities db,
                                                    string path)
        {
            model = new ContentListViewModel
            {
                Items       = new List <ContentListViewModelItem>(),
                DisplayMode = ContentListDisplayMode.History
            };

            bool canManageContent = Permission.HasPermission(false, true, Permission.PermissionName.CanManageContent);

            if (!canManageContent)
            {
                return(model);
            }

            path        = ContentManager.TrimPath(path);
            model.Items = db.Contents
                          .Where(x => x.Path.Equals(path) && x.RecordStatusId != (int)Constants.RecordStatus.Deleted)
                          .Select(x => new ContentListViewModelItem
            {
                ContentId               = x.ContentId,
                Path                    = x.Path,
                Title                   = x.Title,
                UserContext             = (UserContext.UserContextName)x.UserContext,
                RecordStatus            = (Constants.RecordStatus)x.RecordStatusId,
                Embed                   = x.Embed,
                LastModifiedDateTimeUtc = x.ModifiedDateTimeUtc ?? x.CreatedDateTimeUtc,
                LastModifiedBy          = x.AspNetUser1.Name ?? x.AspNetUser.Name,
                Language                = x.Language.DefaultText,
                Version                 = x.Version,
                Summary                 = x.Summary
            }).OrderByDescending(x => x.Version).ToList();
            return(model);
        }
Exemple #21
0
 /// <summary>
 /// Unarchives the <see cref="SearchPhrase"/> and also manages status of it's associated <see cref="Course"/>
 /// </summary>
 /// <param name="SearchPhrase">The <see cref="SearchPhrase"/> object</param>
 /// <param name="db">The <see cref="ProviderPortalEntities"/> object</param>
 public static void Unarchive(this SearchPhrase SearchPhrase, ProviderPortalEntities db)
 {
     SearchPhrase.RecordStatusId      = (Int32)Constants.RecordStatus.Live;
     SearchPhrase.ModifiedByUserId    = Permission.GetCurrentUserId();
     SearchPhrase.ModifiedDateTimeUtc = DateTime.UtcNow;
     db.Entry(SearchPhrase).State     = EntityState.Modified;
 }
        /// <summary>
        /// Deletes the <see cref="Apprenticeship"/> and also deletes it's associated <see cref="CourseInstance"/>s-->
        /// </summary>
        /// <param name="apprenticeship">The <see cref="Course"/> object</param>
        /// <param name="db">The <see cref="ProviderPortalEntities"/> object</param>
        public static void Delete(this Apprenticeship apprenticeship, ProviderPortalEntities db)
        {
            foreach (ApprenticeshipLocation apprenticeshipLocation in apprenticeship.ApprenticeshipLocations.ToList())
            {
                foreach (DeliveryMode deliveryMode in apprenticeshipLocation.DeliveryModes.ToList())
                {
                    apprenticeshipLocation.DeliveryModes.Remove(deliveryMode);
                }
                db.Entry(apprenticeshipLocation).State = EntityState.Deleted;
            }

            foreach (ApprenticeshipQACompliance qaCompliance in apprenticeship.ApprenticeshipQACompliances.ToList())
            {
                foreach (QAComplianceFailureReason complianceFailureReason in qaCompliance.QAComplianceFailureReasons.ToList())
                {
                    qaCompliance.QAComplianceFailureReasons.Remove(complianceFailureReason);
                }
                db.Entry(qaCompliance).State = EntityState.Deleted;
            }

            foreach (ApprenticeshipQAStyle qaStyle in apprenticeship.ApprenticeshipQAStyles.ToList())
            {
                foreach (QAStyleFailureReason styleFailureReason in qaStyle.QAStyleFailureReasons.ToList())
                {
                    qaStyle.QAStyleFailureReasons.Remove(styleFailureReason);
                }
                db.Entry(qaStyle).State = EntityState.Deleted;
            }

            db.Entry(apprenticeship).State = EntityState.Deleted;
        }
        public static Apprenticeship DecodeSearchFrameworkOrStandardByName(String frameworkOrStandardName)
        {
            if (frameworkOrStandardName == null)
            {
                return(null);
            }

            ProviderPortalEntities _db = new ProviderPortalEntities();

            String[] nameParts = frameworkOrStandardName.Split('-');
            switch (nameParts.GetLength(0))
            {
            case 2:     // Must be a standard

                String standardSectorCode = nameParts[0].Trim();
                String standardName       = nameParts[1].Trim();

                StandardSectorCode ssc = _db.StandardSectorCodes.FirstOrDefault(x => x.StandardSectorCodeDesc == standardSectorCode);
                if (ssc != null)
                {
                    Standard s = _db.Standards.FirstOrDefault(x => x.StandardName == standardName && x.StandardSectorCode == ssc.StandardSectorCodeId && x.RecordStatusId == (Int32)Constants.RecordStatus.Live);
                    if (s != null)
                    {
                        return(new Apprenticeship
                        {
                            StandardCode = s.StandardCode,
                            Version = s.Version
                        });
                    }
                }

                break;

            case 3:     // Must be a framework

                String nasTitle     = nameParts[0].Trim();
                String progTypeDesc = nameParts[1].Trim();
                String pathwayName  = nameParts[2].Trim();

                ProgType pt = _db.ProgTypes.FirstOrDefault(x => x.ProgTypeDesc == progTypeDesc);
                if (pt != null)
                {
                    Framework fw = _db.Frameworks.FirstOrDefault(x => x.NasTitle == nasTitle && x.ProgType == pt.ProgTypeId && x.PathwayName == pathwayName && x.RecordStatusId == (Int32)Constants.RecordStatus.Live);
                    if (fw != null)
                    {
                        return(new Apprenticeship
                        {
                            FrameworkCode = fw.FrameworkCode,
                            ProgType = fw.ProgType,
                            PathwayCode = fw.PathwayCode
                        });
                    }
                }

                break;
            }

            return(null);
        }
Exemple #24
0
        /// <summary>
        ///     Get the initial <c ref="UserContextInfo" /> for the current user.
        /// </summary>
        /// <returns>The initial <c ref="UserContextInfo" /> for the current user.</returns>
        public static UserContextInfo GetDefaultContextForCurrentUser()
        {
            // Not authenticated
            if (!HttpContext.Current.Request.IsAuthenticated)
            {
                return(new UserContextInfo(UserContextName.Unauthenticated));
            }

            if (Permission.HasPermission(false, true, Permission.PermissionName.CanViewAdministratorHomePage))
            {
                return(new UserContextInfo(UserContextName.Administration));
            }

            using (var db = new ProviderPortalEntities())
            {
                string     userId = Permission.GetCurrentUserId();
                AspNetUser user   = db.AspNetUsers.FirstOrDefault(x => x.Id == userId);
                if (user == null)
                {
                    return(new UserContextInfo(UserContextName.Unauthenticated));
                }

                List <EntityInfo> organisations = user.Organisations2
                                                  .Select(x => new EntityInfo
                {
                    EntityId  = x.OrganisationId,
                    IsDeleted = (Constants.RecordStatus)x.RecordStatusId == Constants.RecordStatus.Deleted
                }).ToList();
                List <EntityInfo> providers = user.Providers2
                                              .Select(x => new EntityInfo
                {
                    EntityId  = x.ProviderId,
                    IsDeleted = (Constants.RecordStatus)x.RecordStatusId == Constants.RecordStatus.Deleted
                }).ToList();

                // Provider and organisation users should only be associated with one entity
                // so choosing the first
                if (organisations.Any() &&
                    Permission.HasPermission(false, true, Permission.PermissionName.CanViewOrganisationHomePage))
                {
                    return
                        (new UserContextInfo(
                             organisations.First().IsDeleted
                                ? UserContextName.DeletedOrganisation
                                : UserContextName.Organisation, organisations.First().EntityId));
                }

                if (providers.Any() &&
                    Permission.HasPermission(false, true, Permission.PermissionName.CanViewProviderHomePage))
                {
                    return(new UserContextInfo(
                               providers.First().IsDeleted
                            ? UserContextName.DeletedProvider
                            : UserContextName.Provider, providers.First().EntityId));
                }

                return(new UserContextInfo(UserContextName.AuthenticatedNoAccess));
            }
        }
 /// <summary>
 /// Unarchives the <see cref="Apprenticeship"/>
 /// </summary>
 /// <param name="apprenticeship">The <see cref="Apprenticeship"/> object</param>
 /// <param name="db">The <see cref="ProviderPortalEntities"/> object</param>
 public static void Unarchive(this Apprenticeship apprenticeship, ProviderPortalEntities db)
 {
     apprenticeship.RecordStatusId       = (Int32)Constants.RecordStatus.Pending;
     apprenticeship.AddedByApplicationId = (Int32)Constants.Application.Portal;
     apprenticeship.ModifiedDateTimeUtc  = DateTime.UtcNow;
     apprenticeship.ModifiedByUserId     = Permission.GetCurrentUserId();
     db.Entry(apprenticeship).State      = EntityState.Modified;
 }
 /// <summary>
 /// Unarchives the <see cref="Course"/>
 /// </summary>
 /// <param name="course">The <see cref="Course"/> object</param>
 /// <param name="db">The <see cref="ProviderPortalEntities"/> object</param>
 public static void Unarchive(this Course course, ProviderPortalEntities db)
 {
     course.RecordStatusId       = (Int32)Constants.RecordStatus.Pending;
     course.AddedByApplicationId = (Int32)Constants.Application.Portal;
     course.ModifiedDateTimeUtc  = DateTime.UtcNow;
     course.ModifiedByUserId     = Permission.GetCurrentUserId();
     db.Entry(course).State      = EntityState.Modified;
 }
 /// <summary>
 /// Validate an <see cref="AddressViewModel"/>. Base validation is done via model annotations this does additional sanity checks.
 /// </summary>
 /// <param name="model">
 /// The model.
 /// </param>
 /// <param name="db">
 /// The db.
 /// </param>
 /// <param name="state">
 /// The state.
 /// </param>
 public static void Validate(this AddressViewModel model, ProviderPortalEntities db, ModelStateDictionary state)
 {
     if (model.RegionId != null && GetRegions(db, model).All(x => x.Value != model.RegionId.Value.ToString(CultureInfo.InvariantCulture)))
     {
         state.AddModelError("Address.RegionId",
                             AppGlobal.Language.GetText("Address_Region_InvalidRegion", "Invalid region"));
     }
 }
        /// <summary>
        /// Deletes the <see cref="Location"/> and also archives it's associated <see cref="CourseInstance"/>s
        /// </summary>
        /// <param name="location">The <see cref="Location"/> object</param>
        /// <param name="db">The <see cref="ProviderPortalEntities"/> object</param>
        public static void Delete(this Location location, ProviderPortalEntities db)
        {
            foreach (ApprenticeshipLocation apprenticeshipLocation in location.ApprenticeshipLocations.ToList())
            {
                apprenticeshipLocation.Delete(db);
            }

            db.Entry(location).State = EntityState.Deleted;
        }
Exemple #29
0
        /// <summary>
        /// Create an EmailMessage based on a template.
        /// </summary>
        /// <param name="userId">The UserID to sent the email to.</param>
        /// <param name="from">The MailAddress to sent the email from, or NULL to use the site defaults.</param>
        /// <param name="emailTemplate">The <see cref="Constants.EmailTemplates"/> to send.</param>
        /// <param name="parameters">A list of <see cref="TribalTechnology.InformationManagement.Net.Mail.EmailParameter"/>s, or null for none.</param>
        /// <param name="overrideRecipientText">n option text to add when the override recipient option is in use.  Leave blank tp get text from language sub-system</param>
        /// <returns>A <see cref="TribalTechnology.InformationManagement.Net.Mail.EmailMessage"/>.</returns>
        public static EmailMessage EmailMessage(string userId, MailAddress from, Constants.EmailTemplates emailTemplate,
                                                List <EmailParameter> parameters = null, String overrideRecipientText = "")
        {
            var db   = new ProviderPortalEntities();
            var user = db.AspNetUsers.First(x => x.Id == userId);
            var to   = new MailAddress(user.Email, user.Name);

            return(EmailMessage(to, null, null, emailTemplate, parameters, overrideRecipientText));
        }
Exemple #30
0
        /// <summary>
        /// Deletes the <see cref="Venue"/> and also archives it's associated <see cref="CourseInstance"/>s
        /// </summary>
        /// <param name="venue">The <see cref="Venue"/> object</param>
        /// <param name="db">The <see cref="ProviderPortalEntities"/> object</param>
        public static void Delete(this Venue venue, ProviderPortalEntities db)
        {
            foreach (CourseInstance courseInstance in venue.CourseInstances.ToList())
            {
                courseInstance.Archive(db);
            }

            db.Entry(venue).State = EntityState.Deleted;
        }