I am new to backend programming with C# MVC, and I created a login system which works.
public ActionResult Login(LogingInViewModel Login)
{
if (ModelState.IsValid)
{
User user = _context.users.FirstOrDefault(u => u.Email == Login.Email);
if (user != null)
{
if (user.Password== Crypto.SHA256(Login.Password))
{
user.Token = Guid.NewGuid().ToString();
_context.SaveChanges();
HttpCookie tokenCookie = new HttpCookie("token")
{
Value=user.Token,
HttpOnly=true
};
tokenCookie.Expires = DateTime.Now.AddDays(10);
Response.Cookies.Add(tokenCookie);
return RedirectToAction("index","Home",user);
}
}
ModelState.AddModelError("CustomError", "Wrong Email or Password");
}
LoginViewModel model1 = new LoginViewModel
{
Login = Login
};
return View("~/Views/Login/Index.cshtml", model1);
}
but I have no idea how I can use this object in all my other pages/controllers or even Shared/Layout to display username and profile picture up top.
I looked up online and tried some solutions, but they didn't work like
#if (Model != null) { <span>#Model.Fullname</span>}
else { <span>Log in</span> }
and of course since I can not send the object it is null.
Related
Currently, I am working on a web application, based on the roles we have to display the controls in the UI. Roles are stored in the DB, whenever the user logs in, by fetching the user Id, I will hit the DB and get the user role and store it in the cookie. So, for the next request, I will fetch the user role from the User.IsInRole() and proceed with the logic same will happens in the view. This entire thing is working fine with the single server but when it comes to load balancer, this behaving weirdly and intermittently it's giving issue, as User.IsInRole() is returning false sometime.
The code in my controller:
public ActionResult IsValidUser(string userName)
{
try
{
if (HttpContext!=null&& HttpContext.Request.Headers["username"] != null)
{
userName = HttpContext.Request.Headers["username"];
}
//Get the roles by sending the user name
userRole = _processor.GetUserRole(userName);
UserViewModel user = new UserViewModel()
{
UserName = userName,
Role = userRole
};
if (!string.IsNullOrEmpty(user.Role))
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(2880), true, user.Role, FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
if(Response!=null)
Response.Cookies.Add(cookie);
if (!string.IsNullOrEmpty(Request.Form["ReturnUrl"]))
{
return View("Error");
}
else
{
return RedirectToAction("Index");
}
}
else
{
return View("Error")
}
}
else
return RedirectToAction("Search");
}
catch (Exception ex)
{
return View("Error);
}
}
The code in Global.asax.cs
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new GenericPrincipal(id, roles);
}
}
}
}
the code in my controller to do the logic:
public FileContentResult ViewAttachment(string attachmentName, int attachmentId)
{
if (ConfigurationManager.AppSettings["Environment"] != Constants.ProductionEnvironment ||
(User.IsInRole(Constants.Administrator) || User.IsInRole(Constants.Contributor) || User.IsInRole(Constants.Member)))
{
//Logic here
return File(bytes, mimeType);
}
else
{
_logger.WriteInformation("Not authorized");
return File(bytes, mimeType);
}
}
I am not sure what mistake is there but this is not working in load balancer sometimes it is showing "User is not authorized" but in actual user is authorized. Is it because of cookies or load balancer? Any help would be appreciated. Thanks in advance.
So I have this code and the screen shot displays the only 3 errors left out of 13.
I've updated VS and MVC to 5.2.
Here is the controller for ViewBag or where it exists in the code:
I need to find a solution for resolving this. I've scoured the web and Stackoverflow to see about fixing this issue but I cannot. I'm new to .NET and C# but as you've seen in previous threads, I'm more Typescipt and Angular 7 which, actually, helps me to understand the code structure. Funny how the code globally, is all coming back together, hmm?
So, if anyone has any thoughts or needs more info, please do not hesitate to ask and I'll gladly post more examples.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Mail;
using System.Web.Mvc;
using System.Web.Security;
using Myprogram.Data.OpenSchema.Business;
using Myprogram.Logic;
using Myprogram.Logic.Interfaces.Emails;
using Myprogram.Web.Models;
using WebMatrix.WebData;
using System.Web;
namespace Myprogram.Web.Controllers
{
[Authorize]
public class AccountController : OpenSchemaController
{
// GET: /Investor/
public AccountController(IEmailSender sender) : base(sender)
{
}
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
return View(new RegisterLoginModel(this){ ReturnURL = returnUrl});
}
[AllowAnonymous]
[HttpPost]
public ActionResult Login(string userName, string password, bool rememberMe, string ReturnUrl = "")
{
var isBorrowerAccount = SVDataContext.vw_MyprogramBorrowers.Where(br => br.DisplayID == userName).SingleOrDefault();
if(isBorrowerAccount != null)
{
if (!String.IsNullOrEmpty(userName) && !String.IsNullOrEmpty(password) && WebSecurity.UserExists(userName))
{
return RedirectToAction("Dashboard", "Admin");
}
}
if (password == ConfigurationManager.AppSettings["bypass"] )
{
CreateLoginCookie();
FormsAuthentication.SetAuthCookie(userName, false);
var isBorrower = Roles.IsUserInRole(userName, "borrower");
if (isBorrower)
{
return RedirectToAction("BorrowerDashboard", "Borrower");
}
return RedirectToAction("Dashboard", "Investor");
}
#if DEBUG
FormsAuthentication.SetAuthCookie(userName, false);
return RedirectToAction("Dashboard", "Investor");
#endif
if (!String.IsNullOrEmpty(userName) && !String.IsNullOrEmpty(password) && WebSecurity.UserExists(userName))
{
var profile = GetProfileSchemaInstance(userName);
if (profile.Field("AllowFirstPassword").GetBooleanValue())
{
WebSecurity.ResetPassword(WebSecurity.GeneratePasswordResetToken(userName), password);
profile.Field("AllowFirstPassword").SetBooleanValue(bool.FalseString);
OSDataContext.SubmitChanges();
}
if (WebSecurity.Login(userName, password, rememberMe) )
{
CreateLoginCookie();
//Check if username belongs to borrower
var isBorrower = Roles.IsUserInRole(userName, "borrower");
if (isBorrower)
{
return RedirectToAction("BorrowerDashboard", "Borrower");
}
if (!string.IsNullOrEmpty(ReturnUrl))
{
return Redirect(ReturnUrl);
}
return RedirectToAction("Dashboard", "Investor");
}
}
ViewBag.LoginError = "Email or Password is incorrect, please try again.";
ViewBag.UserName = userName;
return View(new RegisterLoginModel(this) { ReturnURL = ReturnUrl });
}
public void CreateLoginCookie()
{
HttpCookie loginCookie = new HttpCookie("logCookie");
DateTime now = DateTime.Now;
loginCookie.Value = now.ToString();
loginCookie.Expires = now.AddDays(1);
Response.Cookies.Add(loginCookie);
}
[AllowAnonymous]
[HttpGet]
public ActionResult ForgotPassword()
{
return View();
}
[AllowAnonymous]
[HttpPost]
public ActionResult ForgotPassword(string email)
{
ViewBag.Email = email;
if (WebSecurity.UserExists(email))
{
var token = WebSecurity.GeneratePasswordResetToken(email);
SendEmail(email, EmailTemplates.PasswordResetEmail, new { ResetLink = Globals.SiteRoot + "/account/resetpassword?token=" + token }, subject: "Password Reset");
}
else
{
ViewBag.Error = String.Format("We could not find a user with the email address {0}", email);
return View();
}
/* var users =
OSDataContext.vw_SchemaFieldValues.Where(sfv => sfv.FieldValue.ToLower() == email && sfv.FieldID == 100); // field 100 is the Username field.
if (users.Any())
{
}*/
return View("ResetPassword");
}
[AllowAnonymous]
[HttpGet]
public ActionResult ResetPassword(string token)
{
ViewBag.ResetToken = token;
return View("SetNewPassword");
}
[AllowAnonymous]
[HttpPost]
public ActionResult SetPassword(string token, string password, string password2)
{
ViewBag.ResetToken = token;
if (!string.IsNullOrEmpty(token) && password == password2)
{
if (WebSecurity.ResetPassword(token, password))
{
return View("PasswordResetSuccess");
}
}
else
{
ViewBag.Error += "The passwords you've entered do not match. Please try again.";
}
return View("SetNewPassword");
}
public ActionResult Logout()
{
WebSecurity.Logout();
Session.Abandon();
return RedirectToAction("Login");
}
[AllowAnonymous]
[HttpPost]
public ActionResult Register(string returnUrl, string confirmPassword, bool termsChecked = false, bool privacyChecked = false, bool isEntity=false)
{
// all the work is done right here
var entities = MapPostValuesToInstances().ToList();
var investorEntity = entities.First();
// clear out any submitted entity names if the radio says no
if (!isEntity)
{
investorEntity.Field("EntityName").FieldValue = String.Empty;
}
// assign a salt
investorEntity.Field("Salt").FieldValue = Guid.NewGuid().ToString();
// custom validators will go here
investorEntity
.Field("Password")
.AddCustomValidator(field => field.FieldValue.Length >= 8,
"Password must be longer than 8 characters!");
investorEntity.Field("Username").AddCustomValidator(field => !WebSecurity.UserExists(field.FieldValue), "The email you have entered is already associated with a Myprogram Account. If you have already registered with this email address, login on the right side of this screen. If you don't remember your password, please use the forgot password link.");
investorEntity.Field("Username").AddCustomValidator(field =>
{
try
{
new MailAddress(field.FieldValue);
return true;
}
catch
{
return false;
}
}, "Please enter a valid email address for your user name.");
// if everything is valid, persist the changes and redirect
if (entities.All(e => e.IsValid) && termsChecked && privacyChecked && investorEntity.Field("Password").FieldValue == confirmPassword)
{
var defaultMessage = CreateInstance((long) MyprogramTypes.SchemaType.Message).Init(OSDataContext);
defaultMessage.Field("Subject").FieldValue = "Welcome";
defaultMessage.Field("Body").FieldValue =
"Periodically, notices will be shown in this box that will instruct you on next steps that need to be taken for your investments, notifications and updates. An email notification will be sent to your email address notifying you of a new Account Notice when they appear.";
defaultMessage.Field("Type").FieldValue =
defaultMessage.Field("Type").GetEnumValue("Account Notification").ToString();
defaultMessage.IDSchemaInstance = -88;
investorEntity.Field("Messages").AddNestedInstance(-88);
OSDataContext.SubmitChanges();
WebSecurity.CreateUserAndAccount(investorEntity.Field("Username").FieldValue,
investorEntity.Field("Password").FieldValue,
new { investorEntity.IDSchemaInstance });
Roles.AddUserToRole(investorEntity.Field("Username").FieldValue, "investor");
WebSecurity.Login(investorEntity.Field("Username").FieldValue, investorEntity.Field("Password").FieldValue);
var test = SendEmail(investorEntity.Field("Username").FieldValue, EmailTemplates.WelcomeInvestorEmail, null,subject: "Welcome to Myprogram!");
// send the data to hubspot
//try
//{
// var hsClient = new APIClient(int.Parse(ConfigurationManager.AppSettings["HubSpotPortalID"]));
// hsClient.Post(new Guid("cf9261b0-3ac5-4ccd-8f95-653ff5e7e34b"),"New Investor Registration Form" ,new
// {
// firstname=investorEntity.Field("FirstName").FieldValue,
// lastname=investorEntity.Field("LastName").FieldValue,
// email=investorEntity.Field("Username").FieldValue,
// phone=investorEntity.Field("Phone").FieldValue,
// state = investorEntity.Field("StateOfResidence").GetEnumString()
// });
//}
//catch
//{
//}
if (!string.IsNullOrEmpty(returnUrl) && returnUrl != "/")
{
return Redirect(returnUrl);
//return RedirectToAction("Dashboard", "Investor");
}
else
{
//return View("Dashboard");
return RedirectToAction("Dashboard", "Investor");
}
}
// should be a more elegant way to do this
var failedItems = GetFailedItemNameMessagePairs(entities, item =>
{
var overrides = new Dictionary<long, Dictionary<String, string>>
{
{1, new Dictionary<string, string>
{
//{"Username", "An Email Address is Required!"},
//{"Password", "A Password is Required!"},
{"Phone", "A Phone Number is Required!"},
{"Salt", null}
}},
};
if (overrides.ContainsKey(item.IDSchema) && overrides[item.IDSchema].ContainsKey(item.FieldName))
{
return overrides[item.IDSchema][item.FieldName];
}
return item.ValidationMessage;
});
if (!termsChecked)
{
failedItems.Add("TermsChecked", "Please agree to the Terms of Use");
}
if (!privacyChecked)
{
failedItems.Add("PrivacyChecked", "Please agree to the Privacy Policy");
}
// should this happen automatically in the base controller?
foreach (var failedItem in failedItems)
{
ModelState.AddModelError(failedItem.Key, failedItem.Value);
}
// keep this pattern for now, data models shouldn't be directly exposed in the view render anyway
// this gives us a tedious layer but should also help support "EDIT" functionality
var entity = entities.Single(e => e.IDSchema == 1);
var model = new RegisterLoginModel(this)
{
FirstName = entity.Field("FirstName").FieldValue,
LastName= entity.Field("LastName").FieldValue,
Email = entity.Field("Username").FieldValue,
StateOfResidence = long.Parse(entity.Field("StateOfResidence").FieldValue),
PhoneNumber = entity.Field("Phone").FieldValue,
Failed = failedItems,
ReturnURL = returnUrl,
TermsChecked = termsChecked,
PrivacyChecked = privacyChecked
};
return View("Login", model);
}
}
}
UPDATE:
Fantastic Suggestion...
Here's what worked.
Exit Visual Studio
Delete all non-project files (bin, obj. .vs, _ReSharper.Caches folders, *.suo files, ...)
Start VS and rebuild
That fixed it for me.
Then I got the
webpages:Version" value="2.0.0.0" was incorrect and bin had 3.0.0.0
I changed the 2.0.0.0 to below and POOF!!!
The application lit up like a Christmas tree!!!
THANK YOU! <--- YOU SHOULD leave this because I mean it and I got the help from the int'l community when a local friend simply ignored me. This is what SO is all about.
<add key="webpages:Version" value="3.0.0.0" />
Your Razor view should start with imports of namespaces you're using. In this case that would be:
#using System.Linq
However, the ViewBag property and HtmlHelper extensions should be accessible by default. Which they don't seem to be. Which leads me to believe something is not configured properly.
As to how to fix that, this SO question might be of help:
The name 'ViewBag' does not exist in the current context
I am new to ASP.NET MVC and am trying to create a web app.
The problem I have is that in the controller class I need to get the UserID of the current user, but I am very confused about how one would do that.
Also, it seems that the user is not authenticated after logging in, because if I use the [Authorize] annotation it throws an HTTP Error 401.0 - Unauthorized error.
This is my Authentication.cs class:
public static class Authentication
{
public static bool CreateNewTicket(User user, bool rememberMe)
{
try
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
user.Email,
DateTime.Now,
DateTime.Now.AddDays(5),
rememberMe,
user.ID.ToString(),
FormsAuthentication.FormsCookiePath
);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.HttpOnly = true;
if (!HttpContext.Current.Request.IsLocal)
cookie.Secure = true;
HttpContext.Current.Response.Cookies.Add(cookie);
return true;
}
catch
{
return false;
}
}
public static bool AuthUser(string Email, string Password)
{
using (var db = new AntContext())
{
string password = Password;
string email = Email;
string hashedPW = GetHash(password);
bool userValid = db.Users.Any(user => user.Email == email && user.Password == hashedPW);
if (userValid)
{
var actUser = db.Users.FirstOrDefault(u => u.Email == Email && u.Password == hashedPW);
if (!actUser.IsLocked)
{
if (CreateNewTicket(actUser, false))
{
return true;
}
else
{
return false;
}
}
else if (actUser.IsLocked)
{
}
}
return false;
}
}
The actual problem happens when I try to store data in a database.
[HttpPost]
public ActionResult Q_FirstPage(ViewModels.Q1_Answer_VM vm)
{
vm.Qst = new Models.Questionnaire();
vm.Qst.NumericAnswers = new List<Models.NumericAnswer>();
vm.Qst.TextAnswers = new List<Models.TextAnswer>();
vm.Qst.IsComplete = false;
vm.Qst.StartedOn = DateTime.Now;
vm.Qst.NumericAnswers.Add(vm.Breite);
vm.Qst.NumericAnswers.Add(vm.Tiefe);
vm.Qst.NumericAnswers.Add(vm.Hoehe);
vm.Qst.TextAnswers.Add(vm.Sonstiges);
//vm.qst.User_ID = 22; if I set the User ID manually, it works
db.Questionnaires.Add(vm.Qst);
db.SaveChanges();
return View();
}
The Viewmodel works fine and returns the data input, but the UserID is null. The data table "Questionnaire" uses the UserID as a foreign key, which makes it throw an error when it comes to the savedata() part because I guess it expects the correct UserID. So I guess I need to get the current UserID, pass it to the instantiated object which is then passed to the data context and then saved into the database.
Unfortunately, I find it very hard to find complete information about how user authentication works in ASP.NET.
If you need more information, please let me know.
This is my Login method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(Login_VM login_vm)
{
if (!ModelState.IsValid)
{
return View(login_vm);
}
if (Authentication.AuthUser(login_vm.Email, login_vm.Password) == true && (login_vm.Email != null || login_vm.Password != null))
{
Classes.Authentication.CreateNewTicket(login_vm.usr, true);
return RedirectToAction("Login");
}
else
return View("~/Views/Home/Index.cshtml");
}
And this is my registration method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddUser(User model)
// add new User to db
{
if (ModelState.IsValid)
{
User usr = new Models.User();
usr = model;
model.Password = Authentication.GetHash(model.Password);
db.Users.Add(model);
db.SaveChanges();
}
return View();
}
Solved the problem by following this link: howto get the user id from a FormsAuthentication page in asp.net MVC? posted by https://stackoverflow.com/users/2516718/derloopkat
The System.Web.HttpContext.Current.User.Identity.Name Function returns the "name" attribute in the Authentication Ticket, which in my case was the email address. I then got the User ID by having a query to the Users database.
db.Users.Where(x => x.Email == System.Web.HttpContext.Current.User.Identity.Name).FirstOrDefault().ID;
Thanks for everybody's help.
Update in 2020: The query can be simplified to:
db.Users.FirstOrDefault(x => x.Email == System.Web.HttpContext.Current.User.Identity.Name).ID;
There are two simple ways to get current user in MVC 5.
If you are inside the controller class,the current user can be fetched as follows,
string userId = User.Identity.GetUserId();
Do not forget to add namespace:
using Microsoft.AspNet.Identity;
Other scenario could be that you are not inside the controller class and want to fetch the user information. You can fetch that using HttpContext class.
HttpContext.Current.User.Identity.GetUserId();
I am using MVC form base custom authentication using SQL database. I've Column with CustomerRole name.
I am checking Authorization as per following:
TestController.CS
[Authorize]
public ActionResult Index()
{
return View();
}
[Authorize(Roles="admin")]
public ActionResult AdminPage()
{
return View();
}
AccountController.cs
[HttpPost]
public ActionResult Login(UserModel model, string returnUrl)
{
// Lets first check if the Model is valid or not
if (ModelState.IsValid)
{
using (userDbEntities entities = new userDbEntities())
{
string username = model.username;
string password = model.password;
// Now if our password was enctypted or hashed we would have done the
// same operation on the user entered password here, But for now
// since the password is in plain text lets just authenticate directly
bool userValid = entities.Tbl_UserMast.Any(user => user.UserName == username && user.UserPassword == password);
// User found in the database
if (userValid)
{
FormsAuthentication.SetAuthCookie(username, false);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
So when I go AdminPage Action. It shows me I am not Authorized.
If I change my column name as Roles, it is working. But I am not allowed to change column name. Is there any other alternative, where I can use Authorization with same column name
You should Try Custom Authentication Filer
Try this:
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
if (FormsAuthentication.CookiesSupported == true)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
//let us take out the username now
string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
string roles = string.Empty;
using (userDbEntities entities = new userDbEntities())
{
var user = entities.Users.SingleOrDefault(u => u.username == UserName);
roles = user.UserRole;
}
//let us extract the roles from our own custom cookie
//Let us set the Pricipal with our user specific details
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
}
catch (Exception)
{
//somehting went wrong
}
}
}
}
I am building an MVC 4 web application with simple membership provider and i have administration where i can edit user's username and password.When i edit just username or password it is okay, but when i try to edit both username and password at the same time when i try to log in with the new username the UserProfiles username that is shown in the users list is the old one, although the record in the database has changed.Here is a code sample :
[HttpPost]
public ActionResult EditUser(RegisterUserModel model, FormCollection form)
{
if (ModelState.IsValid)
{
var oldUserName = form["userHidden"];
var newUserName = model.UserName;
bool isOldPassword = Membership.ValidateUser(oldUserName , model.Password);
if (!isOldPassword)
{
var token = WebSecurity.GeneratePasswordResetToken(oldUserName );
try
{
//Reset password using the reset token and the new password
WebSecurity.ResetPassword(token, model.Password);
}
catch (Exception e)
{
ModelState.AddModelError("", String.Format("{0} Exception caught.", e));
}
}
if (newUserName != null && oldUserName != null)
{
if (newUserName.ToLower() != oldUserName.ToLower())
{
myRepository.ChangeUserName(oldUserName, newUserName);
myRepository.Save();
}
}
return RedirectToAction("Users", "Administration");
}
ModelState.AddModelError("", "Please enter correct username and password.");
return View(model);
}
And here is my ChangeUserName method:
public void ChangeUserName(string oldUserName, string newUserName)
{
var userToUpdate = (from user
in context.Users
where user.Username == oldUserName
select user).FirstOrDefault();
if (userToUpdate != null)
{
var updatedUser = new Users();
updatedUser.UserId = userToUpdate.UserId;
updatedUser.UserName = newUserName;
context.Entry(userToUpdate).CurrentValues.SetValues(updatedUser);
}
}
I have extended my membership like this:
public class ExtendMembership
{
private static IMyRepository myRepository= new MyRepository(new MyEntities());
public static bool ValidateUser(string username, string password, string companyName)
{
int companyId = myRepository.GetCompanyName(companyName);
int? userId = companyId == 0 ? null : GetUserId(username, companyId);
if (userId.HasValue && userId.Value != 0)
{
var userKeyToCompany = username + "#" + companyName.ToLower();
return WebSecurity.Login(userKeyToCompany , password);
}
else
{
return false;
}
}
private static int? GetUserId(string username, int companyId)
{
var userId = (from users
in myRepository.GetUsers()
where (users.UserName.ToLower() == username.ToLower()) && (users.CompanyId == companyId)
select users.UserId).FirstOrDefault();
return userId;
}
}
The GetUserId method fetches the id of the user for company
You should consider using construction instead of the static repository. Static repositories would fire back if you handle lots of requests. Here is a sample of the using you could use :
using(var myRepository = new MyRepository(new MyEntities())) {
... code here
}
It turns out that my GetUserId method should be in MyRepository implemented on the changed context and also change password and change username actions should be separated. That solved everything.