Click here to Skip to main content
15,901,035 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Login Model


C#
namespace jury_service.Models
{
    public class LoginModel
    {
        [Display(Name = "Username")]
        [Required]
        public string username { get; set; }


        [Display(Name = "Password")]
        [Required]
        public string Password { get; set; }
        //protected readonly WebClient Client;

        //public LoginModel(WebClient client)
        //{
        //    Client = client;
        //}
        public FCC_Users infoModel;

        public FCC_Users info;

        public List<FCC_Users> infos;

        public bool DoLogin(LoginModel login)
        {
             var ffcuser = GetInfoREcordByName(login.username);

            //Check if user model pulled back from API is null
             if (ffcuser != null)
             {
                 //if not null check to see if it has a password/intial value of '1'...
                 if (!String.IsNullOrEmpty(ffcuser.Secret))
                 {
                         if (ffcuser.Secret == login.Password)
                         {                   
                             //Check if user login is initial login...
                            if (ffcuser.Initial.Equals(1))
                            {
                                 return true;
                            }
                     }

                 }
                 else

                 {
                     return false;
                 }
             }

             return false;
        }

        //public bool DoLogin()
        //{
        //    if (Initial == "1" && Password != "null")
        //    {
        //        return true;
        //    }

        //    return false;
        //}

        //public User GetUser(LoginModel login)
        //{
        //    try
        //    {
        //        //Add Request Headers
        //        Client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
        //        //Make Request to API and return results
        //        return JsonConvert.DeserializeObject<User>(Client.DownloadString(new Uri(Properties.Settings.Default.Api_Url + "Info" + "/?username=" + login.username + "/")));
        //    }
        //    catch (Exception ex)
        //    {
        //        return null;
        //    }
        //}
        public FCC_Users GetInfoREcordByName(string infoName)
        {
            WebClient client = new WebClient();
            string url = Properties.Settings.Default.Api_Url + "Info/?infoName=" + infoName;
            info = JsonConvert.DeserializeObject<FCC_Users>(client.DownloadString(url));
            return info;
        }
        public FCC_Users GetAllInfoRecords(string infoName)
        {
            WebClient client = new WebClient();
            string url = Properties.Settings.Default.Api_Url + "Info";
            infos = JsonConvert.DeserializeObject<List<FCC_Users>>(client.DownloadString(url));
            return infos.Where(x => x.Username == infoName).First()
        }

    }
}





Login Controller

C#
namespace jury_service.Controllers
{
    public class FCCLoginController : Controller
    {
        //private FCC_Users username;
        //
        // GET: /FCCLogin/

        public ActionResult Index()
        {
            return View();
        }


        [HttpPost]
        public ActionResult Index(LoginModel login)
        {
            if (ModelState.IsValid)
            {

                var ffcuser = login.GetAllInfoRecords(login.username);
                //Check to see if user exists...
                if (ffcuser != null)
                {
                //If user exists, check password matches...

                //If password matches, check if initial login...
                      if (!String.IsNullOrEmpty(ffcuser.Secret))
                        {

                         if (ffcuser.Secret == login.Password)
                         {                   
                             //Check if user login is initial login...
                            if (ffcuser.Initial)
                            {
                             return RedirectToAction("CreatePassword", "Newpassword");
                            }
                            //else
                            // if (ffcuser != username)
                                {
                                    ModelState.AddModelError("Error", "Wrong Username and/or Password");
                                    //ModelState.Clear();
                                }

                                    
                }
                      }
                    return RedirectToAction("fccindex", "FCCLogin");
               
                }
                 

            }

            return View();
        }

        public ActionResult fccindex()
        {
            return View();

        }


What I have tried:

My attempt at a login authentication. If username & password is correct not error, but if incorrect the error happens in here at .First

return infos.Where(x => x.Username == infoName).First();
Posted
Updated 13-Jun-16 6:29am
Comments
Dave Kreskowiak 10-Jun-16 18:25pm    
and the error message would be .....?? Hint: The most important piece of information when troubleshooting a problem.
ynettep 13-Jun-16 9:56am    
return infos.Where(x => x.Username == infoName).First(); error @.FIRST


Invalid Operation Exception was unhandled by user code.
(Sequence contains no elements)

When I login with credentials the are true no issue, but when I enter invalid credentials to test that's when I get the error.
Dave Kreskowiak 13-Jun-16 10:04am    
The line before it where you deserialize some JSON file returned nothing. Set a breakpoint on the return line to verify that.

First cannot be called on a null object.
Karthik_Mahalingam 10-Jun-16 22:35pm    
what is the issue?
ynettep 13-Jun-16 9:57am    
Invalid Operation Exception was unhandled by user code.
(Sequence contains no elements)

When I login with credentials the are true no issue, but when I enter invalid credentials to test that's when I get the error.

I guess as it is not finding any result, so it is null and exception happens.

Refer - Enumerable.First(TSource) Method (IEnumerable(TSource)) (System.Linq)[^]
Quote:

The First<TSource>(IEnumerable<TSource>) method throws an exception if source contains no elements. To instead return a default value when the source sequence is empty, use the FirstOrDefault method.

You should user FirstOrDefault.
 
Share this answer
 
remove this
C#
return infos.Where(x => x.Username == infoName).First()

add
C#
return infos.FirstOrDefault(x => x.Username == infoName);


make sure you are validating for null values.
 
Share this answer
 
Comments
ynettep 13-Jun-16 13:30pm    
return infos.Where(x => x.Username == infoName).FirstOrDefault();
I added it at the end and I'm no longer receiving the error message, but if model state is false it's not returning my error message for invalid info. I moved .FirstOrDefault to where you suggested and my error message still does not display. The page just reloads when submit..

Thank you for your help..
Karthik_Mahalingam 13-Jun-16 13:39pm    
yes, if the user is not present it will go the else part of the condition , and there is no else block in your code, so it will return to the same view ( return View(); )
ynettep 20-Jun-16 10:22am    
Thank you for your feedback and assistance.
Karthik_Mahalingam 20-Jun-16 10:23am    
Welcome
If your issue is resolved
Pls close this post

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900