/// <summary>
        /// Checks whether the user-entered login details authenticate against the identity provider
        /// </summary>
        /// <param name="accountModel">user-entered login details</param>
        public static bool LoginIsValid(AccountModel accountModel)
        {
            var loginSuccessful = false;

            // Check if we have access by trying to access the odata feed for the specified tenant/user/password

            var context = DataAccessHelper.GetContext(accountModel);

            try
            {
                context.Assessments.Take(0).ToList();

                loginSuccessful = true;
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null && (
                    ex.InnerException.Message.ToLower().Contains("401 - unauthorized") ||
                    ex.InnerException.Message.ToLower().Contains("401 unauthorized")))
                {
                    // login wasn't successful so swallow exception and prompt user again
                }
                else
                {
                    // something else went wrong so just dump out the exception
                    throw;
                }
            }

            return loginSuccessful;
        }
        public static IEnumerable<Result> GetResultsForAssessment(AccountModel accountModel, int assessmentKey)
        {
            var results = new List<Result>();

            var context = DataAccessHelper.GetContext(accountModel);

            var query =
                context.Results
                    .Where(r => r.AssessmentKey == assessmentKey)
                    as DataServiceQuery;

            if (query != null)
            {
                var response = query.Execute() as QueryOperationResponse<Result>;
                if (response != null)
                {
                    results.AddRange(response);

                    var continuationToken = response.GetContinuation();
                    while (continuationToken != null)
                    {
                        response = context.Execute(continuationToken);
                        results.AddRange(response);

                        continuationToken = response.GetContinuation();
                    }
                }
            }

            return results;
        }
        public ScoreCorrelationModel(IEnumerable<Assessment> orderedAssessments, AccountModel accountModel)
        {
            SetAssessmentItems(orderedAssessments);

            TenantId = accountModel.TenantId;
            Username = accountModel.Username;
        }
        /// <summary>
        /// Gets list of all assessments for the supplied login details
        /// </summary>
        /// <param name="accountModel">The login details</param>
        public static IEnumerable<Assessment> GetAssessments(AccountModel accountModel)
        {
            var assessments = new List<Assessment>();

            var context = DataAccessHelper.GetContext(accountModel);

            var query =
                context.Assessments
                    .OrderBy(a => a.Name)
                    .ThenBy(a => a.RevisionNumber)
                    as DataServiceQuery;

            if (query != null)
            {
                var response = query.Execute() as QueryOperationResponse<Assessment>;
                if (response != null)
                {
                    assessments.AddRange(response);

                    var continuationToken = response.GetContinuation();
                    while (continuationToken != null)
                    {
                        response = context.Execute(continuationToken);
                        assessments.AddRange(response);

                        continuationToken = response.GetContinuation();
                    }
                }
            }

            return assessments;
        }
        public AttemptDistributionModel(IEnumerable<Assessment> orderedAssessments, AccountModel accountModel)
        {
            SetAssessmentItems(orderedAssessments);
            ScorebandNameForPass = "******"; // default value

            TenantId = accountModel.TenantId;
            Username = accountModel.Username;
        }
        public PreTestPostTestModel(IEnumerable<Assessment> orderedAssessments, AccountModel accountModel)
        {
            SetAssessmentItems(orderedAssessments);
            FirstAssessmentAttemptToUse = Attempt.First; // default value
            FirstAssessmentAttemptNumber = 1; // default value
            SecondAssessmentAttemptToUse = Attempt.First; // default value
            SecondAssessmentAttemptNumber = 1; // default value

            TenantId = accountModel.TenantId;
            Username = accountModel.Username;
        }
        /// <summary>
        /// Gets the odata context, using login details passed in to the method
        /// </summary>
        /// <param name="accountModel">The login details to use to connect</param>
        public static Entities GetContext(AccountModel accountModel)
        {
            var odataRoot = ConfigurationManager.AppSettings["odata.root"];
            var odataUrl = string.Format(odataRoot, accountModel.TenantId);
            var odataUri = new Uri(odataUrl);

            var context = new Entities(odataUri);

            var credentials = new NetworkCredential(accountModel.Username, accountModel.Password);
            context.Credentials = credentials;

            context.IgnoreResourceNotFoundException = true;

            return context;
        }
        /// <summary>
        /// Saves the user-entered login details into the forms authentication cookie
        /// </summary>
        /// <param name="response">The response to add the updated forms authentication cookie to</param>
        /// <param name="accountModel">The user-entered details to store in the cookie</param>
        public static void SaveAccountModelToFormsAuthCookie(HttpResponseBase response, AccountModel accountModel)
        {
            // serialize account model to a json string for storage
            var userData = Serialize(accountModel);

            // get the forms authentication cookie so we can update the forms authentication ticket stored within it
            var cookie = FormsAuthentication.GetAuthCookie(accountModel.Username, accountModel.RememberMe);

            // update the forms authentication ticket with our serialized account model
            var updatedTicket = GetUpdatedTicket(cookie, userData);

            // set the updated forms authentication ticket in the forms authentication cookie, encrypted of course
            cookie.Value = FormsAuthentication.Encrypt(updatedTicket);

            // add the forms authentication cookie back into the cookies collection
            response.Cookies.Add(cookie);
        }
        public ActionResult Login(AccountModel accountModel, string returnUrl)
        {
            ActionResult result;

            if (ModelState.IsValid && AuthHelper.LoginIsValid(accountModel))
            {
                AuthHelper.SaveAccountModelToFormsAuthCookie(Response, accountModel);

                // we don't use RedirectFromLoginPage() because it would overwrite the cookie
                result = new RedirectResult(returnUrl);
            }
            else
            {
                ViewBag.FailedLogin = true;
                ViewBag.ReturnUrl = returnUrl;
                result = View(accountModel);
            }

            return result;
        }
        private static string Serialize(AccountModel accountModel)
        {
            var jss = new JavaScriptSerializer();

            var userData = jss.Serialize(accountModel);

            return userData;
        }