Search code examples
c#asp.net-mvc-3linqmongodb-.net-driver

Either an issue with my linq statement or with my GetCollection<T>()


Here is my code: This is the function being called by fiddler using:

http://localhost:3334/Service/Login/?json={'username':'cara','password':'password'}

public ActionResult Login(JObject JSON)
{
    var response = JsonResponse.OKResponse();
    var username = JSON["username"].ToString();
    var password = JSON["password"].ToString();

    var helper = new MemberHelper();

    //goes into here and never returns
    if (helper.ValidateUser(username, password))
    {
        MongoCollection<User> users = db.GetCollection<User>();
        var usr = users.FindAll().FirstOrDefault(u => u.UserName.Equals(username));
        response.data.Add(usr);
    }
    else
    {
        return Json(JsonResponse.ErrorResponse("Invalid username or password provided!"), JsonRequestBehavior.AllowGet);
    }

    return Json(response, JsonRequestBehavior.AllowGet);
}

And the validateUser method within MemberHelper:

public override bool ValidateUser(string username, string password)
{
    var hash = Encoding.ASCII.GetBytes(password);
    var provider = new SHA256CryptoServiceProvider();
    for (int i = 0; i < 1024; i++) // 1024 round SHA256 is decent
         hash = provider.ComputeHash(hash);
    var pass = Convert.ToBase64String(hash);


    MongoCollection<User> users = db.GetCollection<User>();

    //***The following statement is where the program just stops***    
    var usr = users.FindAll().FirstOrDefault(u => u.UserName.Equals(username) && u.Password.Equals(pass));
   ...
}

And getCollection....

public MongoCollection<T> GetCollection<T>(string name = null)
{
    string collectionName = name; 
    if (collectionName == null) { 
        collectionName = typeof(T).Name; 
    }
    return Database.GetCollection<T>(collectionName); 
}

I really don't know what is going wrong. I am new to linq so I am not sure if there is some golden rule that I am breaking. Please help! Let me know if there is anything else I need to add.


Solution

  • The problem was indeed within the method GetCollection<>() once I replaced it with the following code, it worked just fine:

    public MongoCollection<T> GetCollection<T>(string name = null)
            {
                string collectionName = name;
                if (collectionName == null)
                    collectionName = typeof(T).Name;
                if (Database.CollectionExists(collectionName) == false)
                    Database.CreateCollection(collectionName);
                return Database.GetCollection<T>(collectionName);
            }