GetUserContext() public static method

Gets the data context out of the system cache, or the database.
public static GetUserContext ( string user, Cache, cache, CodeReviewDataContext context ) : UserContext,
user string Authenticated user alias (no DOMAIN).
cache Cache, System cache.
context CodeReviewDataContext Data connection to the database.
return UserContext,
        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);
        }
Esempio n. 3
0
        public static bool Pending()
        {
            var db      = new ProviderPortalEntities();
            var context = UserContext.GetUserContext();

            return(context.ItemId != null &&
                   ((context.IsProvider() && db.Providers.Any(x => x.ProviderId == context.ItemId && x.BulkUploadPending)) ||
                    (context.IsOrganisation() && db.Organisations.Any(x => x.OrganisationId == context.ItemId && x.BulkUploadPending))));
        }
        public static AddEditAccountViewModel SetPermissionFlags(this AddEditAccountViewModel model)
        {
            model.EditingSelf = model.UserId == Permission.GetCurrentUserId();
            bool permission = !model.EditingSelf &&
                              UserContext.GetUserContext().ContextName == UserContext.UserContextName.Administration;

            model.CanEditProviderOrganisation = permission;
            model.CanEditRole     = !model.EditingSelf;
            model.CanEditUserType = permission;

            return(model);
        }
Esempio n. 5
0
 /// <summary>
 /// 获取当前用户, 在当前的Rpc请求周期内,只会初始化一次
 /// </summary>
 /// <returns>用户上下文</returns>
 public UserContext GetUserContext()
 {
     if (userContext == null)
     {
         lock (rootLock)
         {
             if (userContext == null && !string.IsNullOrEmpty(this.Args.tk))
             {
                 userContext = UserContext.GetUserContext(this.Args.tk);
             }
         }
     }
     return(userContext);
 }
        public static Apprenticeship ToEntity(this AddEditApprenticeshipViewModel model, ProviderPortalEntities db)
        {
            var userContext = UserContext.GetUserContext();
            var userId      = Permission.GetCurrentUserId();

            if (!userContext.IsProvider())
            {
                return(null);
            }
            Apprenticeship apprenticeship = model.ApprenticeshipId != 0
                ? db.Apprenticeships.FirstOrDefault(
                x =>
                x.ApprenticeshipId == model.ApprenticeshipId &&
                x.ProviderId == userContext.ItemId.Value)
                : null;

            apprenticeship = apprenticeship ?? new Apprenticeship
            {
                CreatedByUserId    = userId,
                CreatedDateTimeUtc = DateTime.UtcNow,
                ProviderId         = userContext.ItemId.Value,
                RecordStatusId     = (int)Constants.RecordStatus.Pending
            };
            apprenticeship.ModifiedByUserId     = userId;
            apprenticeship.ModifiedDateTimeUtc  = DateTime.UtcNow;
            apprenticeship.AddedByApplicationId = (int)Constants.Application.Portal;
            apprenticeship.MarketingInformation = Markdown.Sanitize(model.MarketingInformation);
            apprenticeship.Url = UrlHelper.GetFullUrl(model.Url);
            apprenticeship.ContactTelephone = model.ContactTelephone;
            apprenticeship.ContactEmail     = model.ContactEmail;
            apprenticeship.ContactWebsite   = UrlHelper.GetFullUrl(model.ContactWebsite);

            Apprenticeship frameworkOrStandard = ApprenticeshipExtensions.DecodeSearchFrameworkOrStandard(model.FrameworkOrStandardId) ?? ApprenticeshipExtensions.DecodeSearchFrameworkOrStandardByName(model.FrameworkOrStandard);

            if (frameworkOrStandard != null)
            {
                apprenticeship.StandardCode  = frameworkOrStandard.StandardCode;
                apprenticeship.Version       = frameworkOrStandard.Version;
                apprenticeship.FrameworkCode = frameworkOrStandard.FrameworkCode;
                apprenticeship.ProgType      = frameworkOrStandard.ProgType;
                apprenticeship.PathwayCode   = frameworkOrStandard.PathwayCode;
            }
            return(apprenticeship);
        }
        public static AddEditApprenticeshipViewModel Populate(this AddEditApprenticeshipViewModel model, int id,
                                                              ProviderPortalEntities db)
        {
            var apprenticeship = new Apprenticeship();

            if (id > 0)
            {
                var userContext = UserContext.GetUserContext();
                if (userContext.IsProvider())
                {
                    apprenticeship = db.Apprenticeships.FirstOrDefault(
                        x =>
                        x.ApprenticeshipId == id &&
                        x.ProviderId == userContext.ItemId.Value);
                }
            }
            model = new AddEditApprenticeshipViewModel
            {
                ApprenticeshipId      = apprenticeship.ApprenticeshipId,
                RecordStatusId        = apprenticeship.RecordStatusId,
                FrameworkOrStandardId = ApprenticeshipExtensions.GetFrameworkOrStandardId(apprenticeship),
                FrameworkOrStandard   = apprenticeship.ApprenticeshipDetails(),
                MarketingInformation  = apprenticeship.MarketingInformation,
                Url                       = UrlHelper.GetFullUrl(apprenticeship.Url),
                ContactEmail              = apprenticeship.ContactEmail,
                ContactTelephone          = apprenticeship.ContactTelephone,
                ContactWebsite            = UrlHelper.GetFullUrl(apprenticeship.ContactWebsite),
                DisplayNotPublishedBanner = !apprenticeship.Provider.ApprenticeshipContract,
                HasBeenQAdForCompliance   = apprenticeship.ApprenticeshipQACompliances.Any(),
                LastQAdForComplianceBy    = apprenticeship.ApprenticeshipQACompliances.Count == 0 ? null : apprenticeship.ApprenticeshipQACompliances.OrderByDescending(m => m.CreatedDateTimeUtc).First().AspNetUser.Name,
                LastQAdForComplianceOn    = apprenticeship.ApprenticeshipQACompliances.Count == 0 ? (DateTime?)null : apprenticeship.ApprenticeshipQACompliances.OrderByDescending(m => m.CreatedDateTimeUtc).First().CreatedDateTimeUtc,
                HasPassedComplianceChecks = apprenticeship.ApprenticeshipQACompliances.Count != 0 && apprenticeship.ApprenticeshipQACompliances.OrderByDescending(m => m.CreatedDateTimeUtc).First().Passed,
                HasBeenQAdForStyle        = apprenticeship.ApprenticeshipQAStyles.Any(),
                LastQAdForStyleBy         = apprenticeship.ApprenticeshipQAStyles.Count == 0 ? null : apprenticeship.ApprenticeshipQAStyles.OrderByDescending(m => m.CreatedDateTimeUtc).First().AspNetUser.Name,
                LastQAdForStyleOn         = apprenticeship.ApprenticeshipQAStyles.Count == 0 ? (DateTime?)null : apprenticeship.ApprenticeshipQAStyles.OrderByDescending(m => m.CreatedDateTimeUtc).First().CreatedDateTimeUtc,
                HasPassedStyleChecks      = apprenticeship.ApprenticeshipQAStyles.Count != 0 && apprenticeship.ApprenticeshipQAStyles.OrderByDescending(m => m.CreatedDateTimeUtc).First().Passed
            };
            var deliveryLocations = new DeliveryLocationListViewModel();

            model.DeliveryLocations = deliveryLocations.Populate(id, db);

            return(model);
        }
 public static bool Validate(this AddEditApprenticeshipViewModel model, ProviderPortalEntities db, ModelStateDictionary modelState)
 {
     if (modelState["FrameworkOrStandard"].Errors.Count == 0)
     {
         Apprenticeship frameworkOrStandard = ApprenticeshipExtensions.DecodeSearchFrameworkOrStandard(model.FrameworkOrStandardId) ?? ApprenticeshipExtensions.DecodeSearchFrameworkOrStandardByName(model.FrameworkOrStandard);
         if (frameworkOrStandard == null)
         {
             modelState.AddModelError("FrameworkOrStandard", AppGlobal.Language.GetText("Apprenticeship_Edit_FrameworkOrStandardRequired", "The Framework / Standard Name field is required."));
         }
         else
         {
             Int32          providerId = UserContext.GetUserContext().ItemId ?? 0;
             Apprenticeship app        = db.Apprenticeships.FirstOrDefault(x => x.ProviderId == providerId && x.StandardCode == frameworkOrStandard.StandardCode && x.Version == frameworkOrStandard.Version && x.FrameworkCode == frameworkOrStandard.FrameworkCode && x.ProgType == frameworkOrStandard.ProgType && x.PathwayCode == frameworkOrStandard.PathwayCode && (model.ApprenticeshipId == 0 || x.ApprenticeshipId != model.ApprenticeshipId));
             if (app != null)
             {
                 modelState.AddModelError("FrameworkOrStandard", AppGlobal.Language.GetText("Apprenticeship_Create_FrameworkOrStandardMustBeUnique", "The Framework / Standard Name supplied is already in use."));
             }
         }
     }
     return(modelState.IsValid);
 }
        /// <summary>
        ///     Get the configuration setting key that defines the user roles available in the current context.
        /// </summary>
        /// <returns>The configuration setting name.</returns>
        private static string GetContextRolesKey()
        {
            UserContext.UserContextName context = UserContext.GetUserContext().ContextName;
            string contextRolesKey = null;

            switch (context)
            {
            case UserContext.UserContextName.Provider:
                contextRolesKey = "ProviderContextCanAddRoles";
                break;

            case UserContext.UserContextName.Organisation:
                contextRolesKey = "OrganisationContextCanAddRoles";
                break;

            case UserContext.UserContextName.Administration:
                contextRolesKey = "AdminContextCanAddRoles";
                break;
            }
            return(contextRolesKey);
        }
        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);
        }
        public static AddEditDeliveryLocationViewModel PopulateNew(this AddEditDeliveryLocationViewModel model,
                                                                   int apprenticeshipId, ProviderPortalEntities db)
        {
            var userContext = UserContext.GetUserContext();

            model = new AddEditDeliveryLocationViewModel
            {
                RecordStatusId        = (Int32)Constants.RecordStatus.Live,
                ApprenticeshipId      = apprenticeshipId,
                SelectedDeliveryModes = new List <Int32>()
            };
            var apprenticeship = db.Apprenticeships
                                 .FirstOrDefault(x => x.ApprenticeshipId == apprenticeshipId);

            model.ApprenticeshipName = apprenticeship != null
                ? apprenticeship.ApprenticeshipDetails()
                : String.Empty;

            model.ProviderId = apprenticeship != null ? apprenticeship.ProviderId : 0;
            model.AddMetaData(db, userContext);
            return(model);
        }
        public static AddEditDeliveryLocationViewModel Populate(this AddEditDeliveryLocationViewModel model,
                                                                int apprenticeshipLocationId, ProviderPortalEntities db)
        {
            var userContext = UserContext.GetUserContext();

            if (!userContext.IsProvider())
            {
                return(null);
            }
            if (apprenticeshipLocationId == 0)
            {
                return(null);
            }

            var deliveryLocation = db.ApprenticeshipLocations
                                   .FirstOrDefault(x => x.Apprenticeship.ProviderId == userContext.ItemId.Value &&
                                                   x.ApprenticeshipLocationId == apprenticeshipLocationId);

            if (deliveryLocation == null)
            {
                return(null);
            }

            model = new AddEditDeliveryLocationViewModel
            {
                ProviderId = deliveryLocation.Apprenticeship.ProviderId,
                ApprenticeshipLocationId = deliveryLocation.ApprenticeshipLocationId,
                ApprenticeshipId         = deliveryLocation.ApprenticeshipId,
                RecordStatusId           = deliveryLocation.RecordStatusId,
                DeliveryModes            = db.DeliveryModes.ToList(),
                SelectedDeliveryModes    = deliveryLocation.DeliveryModes.Select(x => x.DeliveryModeId).ToList(),
                LocationId         = deliveryLocation.LocationId,
                Radius             = deliveryLocation.Radius,
                ApprenticeshipName = deliveryLocation.Apprenticeship.ApprenticeshipDetails()
            };
            model.AddMetaData(db, userContext);

            return(model);
        }
        public static ApprenticeshipSearchViewModel Populate(this ApprenticeshipSearchViewModel model,
                                                             ProviderPortalEntities db)
        {
            var userContext = UserContext.GetUserContext();

            if (model == null)
            {
                model = new ApprenticeshipSearchViewModel();
            }

            // Populate delivery modes
            model.DeliveryModes = db.DeliveryModes
                                  .Where(x => x.RecordStatusId == (int)Constants.RecordStatus.Live)
                                  .Select(x => new SelectListItem
            {
                Text = x.DeliveryModeName,
                // ReSharper disable once SpecifyACultureInStringConversionExplicitly
                Value = x.DeliveryModeId.ToString()
            }).OrderBy(x => x.Text).ToList();

            // Populate Locations
            if (userContext.IsProvider())
            {
                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()
                }).OrderBy(x => x.Text).ToList();
            }
            else
            {
                model.Locations = new List <SelectListItem>();
            }
            return(model);
        }
        /// <summary>
        ///     Get a list of <c ref="Providers" /> and <c ref="Organisations" />.
        /// </summary>
        /// <returns>Json formatted results.</returns>
        // GET Api/Typeahead/Providers
        public NewtonsoftJsonResult ProvidersAndOrganisations()
        {
            var showDeleted = UserContext.GetUserContext().IsAdministration();
            var result      = new NewtonsoftJsonResult
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = db.Providers
                       .Where(x => x.RecordStatu.IsPublished || showDeleted)
                       .Select(x =>
                               new TypeAheadProviderResult
                {
                    id       = "P" + x.ProviderId,
                    ukprn    = x.Ukprn,
                    name     = x.ProviderName ?? string.Empty,
                    alias    = x.ProviderNameAlias ?? string.Empty,
                    town     = x.Address == null ? string.Empty : x.Address.Town ?? string.Empty,
                    county   = x.Address == null ? string.Empty : x.Address.County ?? string.Empty,
                    postcode = x.Address == null ? string.Empty : x.Address.Postcode ?? string.Empty,
                    deleted  = x.RecordStatu.IsDeleted
                })
                       .Union(db.Organisations
                              .Where(x => x.RecordStatu.IsPublished || showDeleted)
                              .Select(x =>
                                      new TypeAheadProviderResult
                {
                    id       = "O" + x.OrganisationId,
                    ukprn    = (int)x.UKPRN,
                    name     = x.OrganisationName ?? string.Empty,
                    alias    = x.OrganisationAlias ?? string.Empty,
                    town     = x.Address == null ? string.Empty : x.Address.Town ?? string.Empty,
                    county   = x.Address == null ? string.Empty : x.Address.County ?? string.Empty,
                    postcode = x.Address == null ? string.Empty : x.Address.Postcode ?? string.Empty,
                    deleted  = x.RecordStatu.IsDeleted
                })).OrderBy(x => x.name).ToArray()
            };

            return(result);
        }
 private void AuthorizationForm_Load(object sender, EventArgs e)
 {
     userContext      = UserContext.GetUserContext();
     this.FormClosed += exit;
 }
        public static ApprenticeshipListViewModel Populate(this ApprenticeshipListViewModel model,
                                                           ProviderPortalEntities db)
        {
            var userContext = UserContext.GetUserContext();

            if (model.Search == null)
            {
                model.Search = new ApprenticeshipSearchViewModel();
            }
            model.Search.Populate(db);

            if (!userContext.IsProvider())
            {
                return(model);
            }

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

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

            model.DisplayNotPublishedBanner = !provider.ApprenticeshipContract;

            var apprenticeships = db.Apprenticeships
                                  .Where(x => x.ProviderId == userContext.ItemId.Value);

            if (model.Search.DeliveryModeId != null)
            {
                apprenticeships =
                    apprenticeships.Where(
                        x => x.ApprenticeshipLocations.Any(
                            y => y.DeliveryModes.Any(
                                z => z.DeliveryModeId == model.Search.DeliveryModeId)));
            }
            if (model.Search.LocationId != null)
            {
                apprenticeships =
                    apprenticeships.Where(
                        x => x.ApprenticeshipLocations.Any(y => y.LocationId == model.Search.LocationId));
            }
            if (!String.IsNullOrWhiteSpace(model.Search.FrameworkOrStandardId) &&
                !String.IsNullOrWhiteSpace(model.Search.FrameworkOrStandard))
            {
                var decodedValues = ApprenticeshipExtensions.DecodeSearchFrameworkOrStandard(model.Search.FrameworkOrStandardId);
                if (decodedValues.FrameworkCode != null)
                {
                    apprenticeships =
                        apprenticeships.Where(x =>
                                              x.FrameworkCode == decodedValues.FrameworkCode &&
                                              x.ProgType == decodedValues.ProgType &&
                                              x.PathwayCode == decodedValues.PathwayCode);
                }
                if (decodedValues.StandardCode != null)
                {
                    apprenticeships =
                        apprenticeships.Where(x =>
                                              x.StandardCode == decodedValues.StandardCode &&
                                              x.Version == decodedValues.Version);
                }
            }

            if (Permission.HasPermission(false, false, Permission.PermissionName.CanQAApprenticeships))
            {
                model.ApprenticeshipsQAed = provider.GetQualityAssuredApprenticeshipCount();
                model.NumberOfApprenticeshipsRequiredToQA = provider.GetNumberOfApprenticeshipsRequiredToQA();
                model.DataReadyForQA = provider.DataReadyToQA;
            }

            model.Apprenticeships = apprenticeships.ToList()
                                    .Select(x => new ApprenticeshipListViewModelItem
            {
                // [FrameworkCode], [ProgType], [PathwayCode]
                // [StandardCode], [Version]
                ApprenticeshipId      = x.ApprenticeshipId,
                ApprenticeshipDetails = x.ApprenticeshipDetails(),
                LastUpdate            = x.ModifiedDateTimeUtc ?? x.CreatedDateTimeUtc,
                Status             = x.RecordStatu.RecordStatusName,
                ComplianceQAResult = !x.ApprenticeshipQACompliances.Any() ? "" : x.ApprenticeshipQACompliances.OrderByDescending(o => o.CreatedDateTimeUtc).First().Passed ? AppGlobal.Language.GetText("Apprenticeship_QAResult_Passed", "Passed") : AppGlobal.Language.GetText("Apprenticeship_QAResult_Failed", "Failed"),
                StyleQAResult      = !x.ApprenticeshipQAStyles.Any() ? "" : x.ApprenticeshipQAStyles.OrderByDescending(o => o.CreatedDateTimeUtc).First().Passed ? AppGlobal.Language.GetText("Apprenticeship_QAResult_Passed", "Passed") : AppGlobal.Language.GetText("Apprenticeship_QAResult_Failed", "Failed")
            }).OrderByDescending(x => x.LastUpdate).ToList();

            return(model);
        }
Esempio n. 17
0
        public void RunMigration(string databaseName)
        {
            Logger.Log(string.Format("FaustManager.RunMigration:  Running Migrations for database {0}.", databaseName), TraceEventType.Verbose);
            Console.WriteLine("##teamcity[message text='FAUSTing Migrations']");

            UserContext userContext = UserContext.GetUserContext(databaseName);

            UnityCache.Resolve <IFaustMigrationsHistoryAccessor>().Initialize(userContext);

            List <DirectoryInfo> releaseDirs = Directory.GetDirectories(ConfigurationManager.AppSettings["MigrationsDirectory"] + databaseName)
                                               .Select(dir => new DirectoryInfo(dir))
                                               .Where(dir => int.Parse(dir.Name) > 0)
                                               .OrderBy(dir => int.Parse(dir.Name))
                                               .ToList();

            if (ConfigurationManager.AppSettings["RunDebugMigrations"] == "true")
            {
                List <DirectoryInfo> holdingDirs = Directory.GetDirectories(ConfigurationManager.AppSettings["MigrationsDirectory"] + databaseName)
                                                   .Select(dir => new DirectoryInfo(dir))
                                                   .Where(dir => int.Parse(dir.Name) < 0)
                                                   .OrderByDescending(dir => int.Parse(dir.Name))
                                                   .ToList();
                holdingDirs.ForEach(d => releaseDirs.Add(d));

                UnityCache.Resolve <IFaustMigrationsHistoryAccessor>().DeleteDebugEntries(userContext);
            }

            foreach (DirectoryInfo release in releaseDirs)
            {
                FaustMigrationScript[] scripts = UnityCache.Resolve <IFaustEngine>().GetReleaseMigrationScripts(release, userContext);

                List <FaustMigrationHistory> migrationHistories = new List <FaustMigrationHistory>();

                TransactionScopeOption scopeOption = TransactionScopeOption.Required;

                if (release.EnumerateFiles().Any(file => file.Name == "no.transaction"))
                {
                    scopeOption = TransactionScopeOption.Suppress;
                }
                TimeSpan desiredTimeout = TimeSpan.FromSeconds(int.Parse(ConfigurationManager.AppSettings["DefaultCommandTimeoutSecondsOverride"]));

                Settings.OverrideTransactionManagerMaximumTimeout(desiredTimeout);
                using (TransactionScope releaseScope = new TransactionScope(scopeOption, new TransactionOptions {
                    IsolationLevel = IsolationLevel.ReadCommitted
                }))
                {
                    foreach (FaustMigrationScript script in scripts)
                    {
                        FaustMigrationHistory migrationHistory = UnityCache.Resolve <IFaustEngine>().RunMigrationScript(script, userContext);

                        migrationHistories.Add(migrationHistory);

                        if (!migrationHistory.Successful ?? false)
                        {
                            releaseScope.Dispose();
                            migrationHistories.ForEach(m => m.Committed = false);
                            Console.WriteLine(string.Format("##teamcity[message text='{0}' errorDetails='' status='ERROR']", migrationHistory.Log));
                            Console.WriteLine("##teamcity[buildProblem description='FAUST Failed.  See build log for details.']");
                            Logger.Log(string.Format("FaustManager.RunMigration: {0}", migrationHistory.Log), TraceEventType.Error);
                            break;
                        }
                    }

                    if (Transaction.Current != null)
                    {
                        releaseScope.Complete();
                        Console.WriteLine("##teamcity[message text='FAUSTing completed without errors.']");
                    }

                    UnityCache.Resolve <IFaustEngine>().SaveMigrationsHistory(migrationHistories.ToArray(), userContext);
                }
            }
        }
Esempio n. 18
0
 // GET: api/GetSurvey
 public List <Survey> Get()
 {
     return(_dispatcher.Execute <GetSurvey, List <Survey> >(new GetSurvey {
         BrandName = UserContext.GetUserContext(Request).brand_name
     }));
 }
        private UKRLPDataModel GetUkrlpData(int ukprn, bool activeOnly)
        {
            var ukrlpModel = new UKRLPDataModel
            {
                UKRLP = ""
            };

            try
            {
                var ukrlpWebService = new ProviderQueryServiceV3
                {
                    Url = ConfigurationManager.AppSettings["UKRLP_Url"]
                };

                var scs = new SelectionCriteriaStructure
                {
                    StakeholderId = ConfigurationManager.AppSettings["UKRLP_Stakeholder_Id"],
                    UnitedKingdomProviderReferenceNumberList = new[] { ukprn.ToString() },
                    ApprovedProvidersOnly          = YesNoType.No,
                    ApprovedProvidersOnlySpecified = true,
                    ProviderStatus             = "A",
                    CriteriaCondition          = QueryCriteriaConditionType.OR,
                    CriteriaConditionSpecified = true
                };

                var pqs = new ProviderQueryStructure
                {
                    SelectionCriteria = scs,
                    QueryId           = "1"
                };

                string[] statuses = { "A", "V", "PD1", "PD2" };
                if (activeOnly)
                {
                    statuses = new[] { "A", "V" };
                }

                foreach (var status in statuses)
                {
                    scs.ProviderStatus = status;

                    var r = ukrlpWebService.retrieveAllProviders(pqs);
                    if (r.MatchingProviderRecords != null)
                    {
                        foreach (var provider in r.MatchingProviderRecords)
                        {
                            switch (status)
                            {
                            case "A":
                                ukrlpModel.Status = AppGlobal.Language.GetText(this, "StatusActive", "Active");
                                break;

                            case "V":
                                ukrlpModel.Status = AppGlobal.Language.GetText(this, "StatusVerified", "Verified");
                                break;

                            case "PD1":
                                ukrlpModel.Status = AppGlobal.Language.GetText(this, "StatusDeactiviationInProcess",
                                                                               "Provider deactivated, not verified");
                                break;

                            case "PD2":
                                ukrlpModel.Status = AppGlobal.Language.GetText(this, "StatusDeactivationComplete",
                                                                               "Provider deactivated");
                                break;
                            }
                            ukrlpModel.UKRLP       = provider.UnitedKingdomProviderReferenceNumber;
                            ukrlpModel.LegalName   = provider.ProviderName;
                            ukrlpModel.TradingName = provider.ProviderAliases == null || provider.ProviderAliases.Count() == 0 || provider.ProviderAliases[0].ProviderAlias == null ? "" : provider.ProviderAliases[0].ProviderAlias.Substring(0, Math.Min(provider.ProviderAliases[0].ProviderAlias.Length, 255)) ?? "";
                            foreach (var pcs in provider.ProviderContact)
                            {
                                switch (pcs.ContactType)
                                {
                                case "L":     // Legal
                                    ukrlpModel.LegalTelephone = pcs.ContactTelephone1 ?? "";
                                    ukrlpModel.LegalFax       = pcs.ContactFax ?? "";
                                    if (pcs.ContactAddress != null)
                                    {
                                        if (!string.IsNullOrEmpty(pcs.ContactAddress.PAON.Description))
                                        {
                                            ukrlpModel.LegalFullAddress += pcs.ContactAddress.PAON.Description + " ";
                                            ukrlpModel.LegalAddress1     = pcs.ContactAddress.PAON.Description + " ";
                                        }

                                        if (!string.IsNullOrEmpty(pcs.ContactAddress.SAON.Description))
                                        {
                                            ukrlpModel.LegalFullAddress += pcs.ContactAddress.SAON.Description + " ";
                                            ukrlpModel.LegalAddress1    += pcs.ContactAddress.SAON.Description + " ";
                                        }
                                        if (!string.IsNullOrEmpty(ukrlpModel.LegalFullAddress))
                                        {
                                            ukrlpModel.LegalFullAddress += "<br />";
                                        }
                                        ukrlpModel.LegalFullAddress += pcs.ContactAddress.StreetDescription +
                                                                       "<br />";
                                        ukrlpModel.LegalAddress1 += pcs.ContactAddress.StreetDescription;
                                        if (!string.IsNullOrEmpty(pcs.ContactAddress.Locality))
                                        {
                                            ukrlpModel.LegalFullAddress += pcs.ContactAddress.Locality + "<br />";
                                            ukrlpModel.LegalAddress2     = pcs.ContactAddress.Locality;
                                        }
                                        ukrlpModel.LegalFullAddress += pcs.ContactAddress.Items != null &&
                                                                       pcs.ContactAddress.Items.GetLength(0) > 0
                                                ? pcs.ContactAddress.Items[0] + "<br>"
                                                : "";
                                        ukrlpModel.LegalTown += pcs.ContactAddress.Items != null &&
                                                                pcs.ContactAddress.Items.GetLength(0) > 0
                                                ? pcs.ContactAddress.Items[0] + "<br>"
                                                : "";
                                        ukrlpModel.LegalFullAddress += pcs.ContactAddress.PostCode + "<br>";
                                        ukrlpModel.LegalPostcode    += pcs.ContactAddress.PostCode + "<br>";
                                    }
                                    break;

                                case "P":     // Primary
                                    ukrlpModel.ContactTelephone = pcs.ContactTelephone1 ?? "";
                                    ukrlpModel.ContactFax       = pcs.ContactFax ?? "";
                                    ukrlpModel.ContactName      =
                                        string.Format("{0} {1} {2}",
                                                      pcs.ContactPersonalDetails.PersonNameTitle == null
                                                    ? ""
                                                    : pcs.ContactPersonalDetails.PersonNameTitle[0],
                                                      pcs.ContactPersonalDetails.PersonGivenName == null
                                                    ? ""
                                                    : pcs.ContactPersonalDetails.PersonGivenName[0],
                                                      pcs.ContactPersonalDetails.PersonFamilyName).Replace("  ", " ").Trim();
                                    if (pcs.ContactAddress != null)
                                    {
                                        if (!string.IsNullOrEmpty(pcs.ContactAddress.PAON.Description))
                                        {
                                            ukrlpModel.ContactFullAddress += pcs.ContactAddress.PAON.Description +
                                                                             " ";
                                            ukrlpModel.ContactAddress1 = pcs.ContactAddress.PAON.Description + " ";
                                        }

                                        if (!string.IsNullOrEmpty(pcs.ContactAddress.SAON.Description))
                                        {
                                            ukrlpModel.ContactFullAddress += pcs.ContactAddress.SAON.Description +
                                                                             " ";
                                            ukrlpModel.ContactAddress1 += pcs.ContactAddress.SAON.Description + " ";
                                        }
                                        if (!string.IsNullOrEmpty(ukrlpModel.ContactFullAddress))
                                        {
                                            ukrlpModel.ContactFullAddress += "<br />";
                                        }
                                        ukrlpModel.ContactFullAddress += pcs.ContactAddress.StreetDescription +
                                                                         "<br />";
                                        ukrlpModel.ContactAddress1 += pcs.ContactAddress.StreetDescription;
                                        if (!string.IsNullOrEmpty(pcs.ContactAddress.Locality))
                                        {
                                            ukrlpModel.ContactFullAddress += pcs.ContactAddress.Locality + "<br />";
                                            ukrlpModel.ContactAddress2     = pcs.ContactAddress.Locality;
                                        }
                                        ukrlpModel.ContactFullAddress += pcs.ContactAddress.Items != null &&
                                                                         pcs.ContactAddress.Items.GetLength(0) > 0
                                                ? pcs.ContactAddress.Items[0] + "<br>"
                                                : "";
                                        ukrlpModel.ContactTown += pcs.ContactAddress.Items != null &&
                                                                  pcs.ContactAddress.Items.GetLength(0) > 0
                                                ? pcs.ContactAddress.Items[0] + "<br>"
                                                : "";
                                        ukrlpModel.ContactFullAddress += pcs.ContactAddress.PostCode + "<br>";
                                        ukrlpModel.ContactPostcode    += pcs.ContactAddress.PostCode + "<br>";
                                    }
                                    break;
                                }
                            }

                            foreach (var vds in provider.VerificationDetails)
                            {
                                switch (vds.VerificationAuthority.ToLower())
                                {
                                case "companies house":
                                    ukrlpModel.CompanyRegistrationNumber = vds.VerificationID ?? "";
                                    break;

                                case "charity commission":
                                    ukrlpModel.CharityRegistrationNumber = vds.VerificationID ?? "";
                                    break;
                                }
                            }

                            // Check if UKPRN is already in use
                            var providerId = 0;
                            var uc         = UserContext.GetUserContext();
                            if (uc.IsProvider())
                            {
                                providerId = uc.ItemId.Value;
                            }
                            var dbProvider =
                                db.Providers.FirstOrDefault(x => x.Ukprn == ukprn && x.ProviderId != providerId);
                            if (dbProvider != null)
                            {
                                ukrlpModel.InUse = true;
                            }

                            // Check if UKPRN is in use at an organisation
                            if (!ukrlpModel.InUse)
                            {
                                var orgId = 0;
                                if (uc.IsOrganisation())
                                {
                                    orgId = uc.ItemId.Value;
                                }
                                var dbOrganisation =
                                    db.Organisations.FirstOrDefault(x => x.UKPRN == ukprn && x.OrganisationId != orgId);
                                if (dbOrganisation != null)
                                {
                                    ukrlpModel.InUse = true;
                                }
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(ukrlpModel.UKRLP))
                    {
                        break;
                    }
                }
            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch (Exception)
            {
            }

            return(ukrlpModel);
        }
        public static ApprenticeshipLocation ToEntity(this AddEditDeliveryLocationViewModel model,
                                                      int apprenticeshipId, int apprenticeshipLocationId, ProviderPortalEntities db)
        {
            var userContext = UserContext.GetUserContext();
            var userId      = Permission.GetCurrentUserId();

            if (!userContext.IsProvider())
            {
                return(null);
            }
            var apprenticeshipLocation = model.ApprenticeshipLocationId != 0
                ? db.ApprenticeshipLocations.FirstOrDefault(
                x =>
                x.ApprenticeshipLocationId == model.ApprenticeshipLocationId &&
                x.Apprenticeship.ProviderId == userContext.ItemId.Value)
                : null;

            apprenticeshipLocation = apprenticeshipLocation ?? new ApprenticeshipLocation()
            {
                CreatedByUserId    = userId,
                CreatedDateTimeUtc = DateTime.UtcNow,
                ApprenticeshipId   = apprenticeshipId,
                RecordStatusId     = (int)Constants.RecordStatus.Live
            };
            apprenticeshipLocation.ModifiedByUserId     = userId;
            apprenticeshipLocation.ModifiedDateTimeUtc  = DateTime.UtcNow;
            apprenticeshipLocation.AddedByApplicationId = (int)Constants.Application.Portal;
            apprenticeshipLocation.Radius     = model.Radius;
            apprenticeshipLocation.LocationId = model.LocationId;
            var apprenticeship = apprenticeshipLocation.Apprenticeship
                                 ?? db.Apprenticeships.First(x => x.ApprenticeshipId == apprenticeshipId);

            apprenticeship.ModifiedByUserId    = userId;
            apprenticeship.ModifiedDateTimeUtc = DateTime.UtcNow;
            if (apprenticeshipLocation.RecordStatusId != (int)Constants.RecordStatus.Archived)
            {
                apprenticeshipLocation.RecordStatusId = (int)Constants.RecordStatus.Live;
                apprenticeship.RecordStatusId         = (int)Constants.RecordStatus.Live;
            }

            // Remove Existing Delivery Modes
            List <DeliveryMode> existingDeliveryModes = apprenticeshipLocation.DeliveryModes.ToList();

            foreach (var deliveryMode in existingDeliveryModes.Where(x => !model.SelectedDeliveryModes.Contains(x.DeliveryModeId)))
            {
                apprenticeshipLocation.DeliveryModes.Remove(deliveryMode);
            }

            // Add the Delivery Modes
            foreach (Int32 fcId in model.SelectedDeliveryModes)
            {
                DeliveryMode deliveryMode = apprenticeshipLocation.DeliveryModes.FirstOrDefault(x => x.DeliveryModeId == fcId);
                if (deliveryMode == null)
                {
                    deliveryMode = db.DeliveryModes.Find(fcId);
                    if (deliveryMode != null)
                    {
                        apprenticeshipLocation.DeliveryModes.Add(deliveryMode);
                    }
                }
            }

            return(apprenticeshipLocation);
        }