asp.net mvc 3 dependency injection ninject - asp.net-mvc

I want to ask something about asp.net mvc 3 dependency injection ninject.
Here is my Interface,
public interface IRegistration<T>
{
bool Registration(T Entity);
}
This is ClsMembers class.
public class ClsMembers:IRegistration<Member>
{
private SmileWorkDbEntities db;
public ClsMembers()
{
db = new SmileWorkDbEntities();
}
public bool Registration(Member member)
{
db.Members.Add(member);
if (db.SaveChanges() != 0)
{
return true;
}
else
{
return false;
}
}
public int GetMemberId(string username, string pwd)
{
var Mem = (from m in db.Members where m.Member_username == username && m.Member_password == pwd select m).FirstOrDefault();
return Mem.Member_id;
}
}
here is my controller,
public class MembersRegistrationController : Controller
{
IRegistration<Member> ireg1;
public MembersRegistrationController(IRegistration<Member> _ireg1)
{
ireg1 = _ireg1;
}
public ActionResult MemberRegistration()
{
return View();
}
[HttpPost]
public ActionResult MemberRegistration(Member m)
{
if(ireg1.Registration(m))
{
return RedirectToAction("MemberProfileRegistration", new {mId = i });
}
else
{
return View();
}
}
}
Everything is ok... but i cannot access GetMemberId() method.. pls tell me how can i access GetMemberId() from my controller...
Regard,
MinThitTun

Modify your IRegistration interface by adding int GetMemberId(string username, string pwd) method:
public interface IRegistration<T>
{
bool Registration(T Entity);
int GetMemberId(string username, string pwd);
}
After all, I thing you should read Interfaces (C# Programming Guide)
UPDATE:
public interface IMembersRepository
{
int GetMemberId(string username, string password);
// Other stuff related to members...
}
public class MembersRepository : IMembersRepository
{
private SmileWorkDbEntities db = new SmileWorkDbEntities();
public int GetMemberId(string username, string password)
{
var Mem = (from m in db.Members where m.Member_username == username && m.Member_password == pwd select m).FirstOrDefault();
return Mem.Member_id;
}
// Other stuff related to members...
}
public class MembersRegistrationController : Controller
{
IRegistration<Member> ireg1;
IMembersRepository membersRepository;
public MembersRegistrationController(IRegistration<Member> _ireg1, IMembersRepository memRepository)
{
ireg1 = _ireg1;
membersRepository = memRepository;
}
// ...
}

Related

Webapi Response 500 Internal Server Error

I made an asp.net core web api and implemented some logic to register user.
But the issue is that whenever I call the controller from postman, it gives me 500 Internal Server Error.I also implemented an simple IActionResult to return welcome message, that also don't work. Here is my code.
[ApiController]
[Route("api/[controller]")]
public class AuthController : Controller
{
private readonly IAuthRepository _repo;
public AuthController(IAuthRepository repo)
{
_repo = repo;
}
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody]CreateUserDTO createUserDto)
{
createUserDto.Username=createUserDto.Username.ToLower();
if(await _repo.UserExists(createUserDto.Username))
return BadRequest("User With This User Name Already Exists");
var userToCreate=new User
{
UserName=createUserDto.Username
};
var createdUser=await _repo.Register(userToCreate,createUserDto.Password);
return Ok("user registered");
}
[HttpGet]
public IActionResult Get()
{
var message="welcome message";
return Ok(message);
}
}
Looking to hear from you soon.
Thanks
I figured out the problem.
The problem was with my AuthRepository constructor where I wasn't specifying the public modifier.
Here is my AuthRepository code (working)
public class AuthRepository : IAuthRepository
{
private readonly ApplicationDatabase _db;
public AuthRepository(ApplicationDatabase db)
{
_db = db;
}
public async Task<User> Login(string username, string password)
{
var user=await _db.Users.Where(x=>x.UserName==username).FirstOrDefaultAsync();
if (user==null)
return null;
if(!verifyPasswordHash(password,user.PasswordHash,user.PasswordSalt))
return null;
return user;
}
private bool verifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
{
using(var hmac=new System.Security.Cryptography.HMACSHA512(passwordSalt))
{
var computedPasswordHash=hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
for (int i = 0; i < computedPasswordHash.Length; i++)
{
if (computedPasswordHash[i]!=passwordHash[i])
{
return false;
}
}
}
return true;
}
public async Task<User> Register(User user, string password)
{
byte[] passwordHash,passwordSalt;
CreatePasswordHashSalt(password,out passwordHash,out passwordSalt);
user.PasswordHash=passwordHash;
user.PasswordSalt=passwordSalt;
await _db.Users.AddAsync(user);
_db.SaveChangesAsync();
return user;
}
private void CreatePasswordHashSalt(string password, out byte[] passwordHash, out byte[] passwordSalt)
{
using(var hmac=new System.Security.Cryptography.HMACSHA512())
{
passwordSalt=hmac.Key;
passwordHash=hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
}
}
public async Task<bool> UserExists(string username)
{
if(await _db.Users.AnyAsync(x=>x.UserName==username))
return true;
return false;
}
}

ASP.NET MVC 5 SignalR, SqlDependency and EntityFramework 6 - the sqlparameter is already contained by another sqlparametercollection

I am beginner with SignalR and SQLDepedency. I am trying to implement SignalR using EF Code First Approach. I am getting the error The sqlparameter is already contained by another sqlparametercollection if I am using where condition in LINQ class.
public class MessageHub : Hub
{
internal NotifierEntity NotifierEntity { get; private set; }
private MyDbContext db = new MyDbContext();
public void DispatchToClient()
{
Clients.All.broadcastMessage("Refresh");
}
public void Initialize(String userName)
{
if (!string.IsNullOrEmpty(userName))
{
NotifierEntity = db.GetNotifierEntity<Messages>(db.Messages.Where(x=>x.ApplicationUser.UserName== userName && !x.Status));
if (NotifierEntity == null)
return;
Action<String> dispatcher = (t) => { DispatchToClient(); };
PushSqlDependency.Instance(NotifierEntity, dispatcher);
}
}
}
The NotifierEntity Class
public class NotifierEntity
{
ICollection<SqlParameter> sqlParameters = new List<SqlParameter>();
public String SqlQuery { get; set; }
public String SqlConnectionString { get; set; }
public ICollection<SqlParameter> SqlParameters
{
get
{
return sqlParameters;
}
set
{
sqlParameters = value;
}
}
public static NotifierEntity FromJson(String value)
{
if (String.IsNullOrEmpty(value))
throw new ArgumentNullException("NotifierEntity Value can not be null!");
return new JavaScriptSerializer().Deserialize<NotifierEntity>(value);
}
}
public static class NotifierEntityExtentions
{
public static String ToJson(this NotifierEntity entity)
{
if (entity == null)
throw new ArgumentNullException("NotifierEntity can not be null!");
return new JavaScriptSerializer().Serialize(entity);
}
}
public class PushSqlDependency
{
static PushSqlDependency instance = null;
readonly SqlDependencyRegister sqlDependencyNotifier;
readonly Action<String> dispatcher;
public static PushSqlDependency Instance(NotifierEntity notifierEntity, Action<String> dispatcher)
{
if (instance == null)
instance = new PushSqlDependency(notifierEntity, dispatcher);
return instance;
}
private PushSqlDependency(NotifierEntity notifierEntity, Action<String> dispatcher)
{
this.dispatcher = dispatcher;
sqlDependencyNotifier = new SqlDependencyRegister(notifierEntity);
sqlDependencyNotifier.SqlNotification += OnSqlNotification;
}
internal void OnSqlNotification(object sender, SqlNotificationEventArgs e)
{
dispatcher("Refresh123");
}
}
public class SqlDependencyRegister
{
public event SqlNotificationEventHandler SqlNotification;
readonly NotifierEntity notificationEntity;
internal SqlDependencyRegister(NotifierEntity notificationEntity)
{
this.notificationEntity = notificationEntity;
RegisterForNotifications();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security",
"CA2100:Review SQL queries for security vulnerabilities")]
void RegisterForNotifications()
{
using (var sqlConnection = new SqlConnection(notificationEntity.SqlConnectionString))
using (var sqlCommand = new SqlCommand(notificationEntity.SqlQuery, sqlConnection))
{
foreach (var sqlParameter in notificationEntity.SqlParameters)
{
sqlCommand.Parameters.Add(sqlParameter);
}
sqlCommand.Notification = null;
var sqlDependency = new SqlDependency(sqlCommand);
sqlDependency.OnChange += OnSqlDependencyChange;
if (sqlConnection.State == ConnectionState.Closed)
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
}
}
void OnSqlDependencyChange(object sender, SqlNotificationEventArgs e)
{
if (SqlNotification != null)
SqlNotification(sender, e);
RegisterForNotifications();
}
}
public delegate void SqlNotificationEventHandler(object sender, SqlNotificationEventArgs e);
If I am using the same query without any parameters, the code is working perfectly. I can see the database changes instantly in frontend. The issue is coming after added a parameter in Where clause.
I got this idea from below link
https://www.codeproject.com/Tips/1075852/ASP-NET-MVC-SignalR-SqlDependency-and-EntityFramew
Sourcecode link
we.tl/njwwLl8g36

How to create a unique session for a user: ASP.NET

I have been learning ASP.NET and came to point where I realised that my web application is creating only a static session for all the users, that is if one logs out all the users are logged out, and sometimes the session is even swapped (lets say userA logs in and right after userB logs in, when the userA refreshes he is seeing the data of userB).
My SessionManager class is as below
SessionManager.cs
public class SessionManager
{
#region Private Data
private static String USER_KEY = "user";
#endregion
public static Employee CurrentUser
{
get;
set;
}
public static string UserType
{
get;
set;
}
public static Int32 SessionTimeout
{
get
{
return System.Web.HttpContext.Current.Session.Timeout;
}
}
public static String GetUserFullName()
{
if (SessionManager.CurrentUser != null)
return SessionManager.CurrentUser.FirstName;
else
return null;
}
public static Boolean IsUserLoggedIn
{
get
{
if (SessionManager.CurrentUser != null)
return true;
else
return false;
}
}
#region Methods
public static void AbandonSession()
{
for (int i = 0; i < System.Web.HttpContext.Current.Session.Count; i++)
{
System.Web.HttpContext.Current.Session[i] = null;
}
System.Web.HttpContext.Current.Session.Abandon();
}
#endregion
}
Login Controller:
[HttpPost]
public ActionResult Index(String txtUserName, String txtPassword)
if (User.Identity.IsAuthenticated)
{
return View();
}
else
{
if (ModelState.IsValid)
{
Employee obj = (from o in db.Employees
where o.Email == txtUserName && o.Password == txtPassword
select o).FirstOrDefault();
if (obj != null)
{
var dh = db.Departments.Where(x => x.LeadBy == obj.EmployeeId).FirstOrDefault();
var tl = db.Teams.Where(x => x.LeadBy == obj.EmployeeId).FirstOrDefault();
if (dh == null && tl == null)
{
Session["UserType"] = "EMP";
}
else if (dh != null && tl != null)
{
Session["UserType"] = "DH&TL";
}
else if (dh != null)
{
Session["UserType"] = "DH";
}
else if (tl != null)
{
Session["UserType"] = "TL";
}
SessionManager.CurrentUser = obj; //how can I create different obj for different users here?
var currentEnrollID = SessionManager.CurrentUser.EnrollNumber;
var currentEmployeeID = SessionManager.CurrentUser.EmployeeId;
var currentEmpName = SessionManager.CurrentUser.FirstName + " " + SessionManager.CurrentUser.LastName;
I have been using sessions like this in the whole application so a different approach would be hectic to amend the changes.
public ActionResult Logout()
{
if (SessionManager.IsUserLoggedIn)
{
SessionManager.CurrentUser.EmployeeId = 0;
SessionManager.AbandonSession();
Session.Clear();
Session.Abandon();
Session.RemoveAll();
}
return RedirectToAction("Index","Login");
}
This is not related to ASP.NET, but it is more on how static members work.
The real issue is your SessionsManager, which contains static methods that you store values every time the user logs-in. This means the same instance is shared across different session in the application.
I have an update SessionManager you can see below. I have stored the SessionManager object in the session object so that as long the session is alive. It will return the same instance by session when you call it using SessionManager.Current.
public class SessionManager {
#region Private Data
private static String USER_KEY = "user";
#endregion
public static SessionManager Current {
get{
if (HttpContext.Current.Session[USER_KEY] != null) {
return (SessionManager) HttpContext.Current.Session[USER_KEY];
} else {
var sess = new SessionManager ();
HttpContext.Current.Session[USER_KEY] = sess;
return sess;
}
}
}
public Employee CurrentUser {
get;
set;
}
public string UserType {
get;
set;
}
public Int32 SessionTimeout {
get {
return System.Web.HttpContext.Current.Session.Timeout;
}
}
public String GetUserFullName () {
if (SessionManager.Current.CurrentUser != null)
return SessionManager.Current.CurrentUser.FirstName;
else
return null;
}
public Boolean IsUserLoggedIn {
get {
if (SessionManager.Current.CurrentUser != null)
return true;
else
return false;
}
}
#region Methods
public void AbandonSession () {
for (int i = 0; i < System.Web.HttpContext.Current.Session.Count; i++) {
System.Web.HttpContext.Current.Session[i] = null;
}
System.Web.HttpContext.Current.Session.Abandon ();
}
#endregion
}

Get custom attribute for parameter when model binding

I've seen a lot of similar posts on this, but haven't found the answer specific to controller parameters.
I've written a custom attribute called AliasAttribute that allows me to define aliases for parameters during model binding. So for example if I have: public JsonResult EmailCheck(string email) on the server and I want the email parameter to be bound to fields named PrimaryEmail or SomeCrazyEmail I can "map" this using the aliasattribute like this: public JsonResult EmailCheck([Alias(Suffix = "Email")]string email).
The problem: In my custom model binder I can't get a hold of the AliasAttribute class applied to the email parameter. It always returns null.
I've seen what the DefaultModelBinder class is doing to get the BindAttribute in reflector and its the same but doesn't work for me.
Question: How do I get this attribute during binding?
AliasModelBinder:
public class AliasModelBinder : DefaultModelBinder
{
public static ICustomTypeDescriptor GetTypeDescriptor(Type type)
{
return new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);
}
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = base.BindModel(controllerContext, bindingContext);
var descriptor = GetTypeDescriptor(bindingContext.ModelType);
/*************************/
// this next statement returns null!
/*************************/
AliasAttribute attr = (AliasAttribute)descriptor.GetAttributes()[typeof(AliasAttribute)];
if (attr == null)
return null;
HttpRequestBase request = controllerContext.HttpContext.Request;
foreach (var key in request.Form.AllKeys)
{
if (string.IsNullOrEmpty(attr.Prefix) == false)
{
if (key.StartsWith(attr.Prefix, StringComparison.InvariantCultureIgnoreCase))
{
if (string.IsNullOrEmpty(attr.Suffix) == false)
{
if (key.EndsWith(attr.Suffix, StringComparison.InvariantCultureIgnoreCase))
{
return request.Form.Get(key);
}
}
return request.Form.Get(key);
}
}
else if (string.IsNullOrEmpty(attr.Suffix) == false)
{
if (key.EndsWith(attr.Suffix, StringComparison.InvariantCultureIgnoreCase))
{
return request.Form.Get(key);
}
}
if (attr.HasIncludes)
{
foreach (var include in attr.InlcludeSplit)
{
if (key.Equals(include, StringComparison.InvariantCultureIgnoreCase))
{
return request.Form.Get(include);
}
}
}
}
return null;
}
}
AliasAttribute:
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class AliasAttribute : Attribute
{
private string _include;
private string[] _inlcludeSplit = new string[0];
public string Prefix { get; set; }
public string Suffix { get; set; }
public string Include
{
get
{
return _include;
}
set
{
_include = value;
_inlcludeSplit = SplitString(_include);
}
}
public string[] InlcludeSplit
{
get
{
return _inlcludeSplit;
}
}
public bool HasIncludes { get { return InlcludeSplit.Length > 0; } }
internal static string[] SplitString(string original)
{
if (string.IsNullOrEmpty(original))
{
return new string[0];
}
return (from piece in original.Split(new char[] { ',' })
let trimmed = piece.Trim()
where !string.IsNullOrEmpty(trimmed)
select trimmed).ToArray<string>();
}
}
Usage:
public JsonResult EmailCheck([ModelBinder(typeof(AliasModelBinder)), Alias(Suffix = "Email")]string email)
{
// email will be assigned to any field suffixed with "Email". e.g. PrimaryEmail, SecondaryEmail and so on
}
Gave up on this and then stumbled across the Action Parameter Alias code base that will probably allow me to do this. It's not as flexible as what I started out to write but probably can be modified to allow wild cards.
what I did was make my attribute subclass System.Web.Mvc.CustomModelBinderAttribute which then allows you to return a version of your custom model binder modified with the aliases.
example:
public class AliasAttribute : System.Web.Mvc.CustomModelBinderAttribute
{
public AliasAttribute()
{
}
public AliasAttribute( string alias )
{
Alias = alias;
}
public string Alias { get; set; }
public override IModelBinder GetBinder()
{
var binder = new AliasModelBinder();
if ( !string.IsNullOrEmpty( Alias ) )
binder.Alias = Alias;
return binder;
}
}
which then allows this usage:
public ActionResult Edit( [Alias( "somethingElse" )] string email )
{
// ...
}

ASP.NET MVC 3 inheriting Membership userId

I am looking to extend the aspnet_membership in an MVC 3 application by storing extra member details in a separate model/table. I am not looking at using the ASP.NET ProfileProvider.
I would like to use the userId of a member as the primary/foreign key in the additional model/table. How can I achieve this? Is the example code along the right lines?
Thanks for any help.
public class Profile
{
[Key]
public Guid ProfileId { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public virtual MembershipUser User
{
get { return Membership.GetUser(ProfileId); }
}
public string FullName
{
get { return LastName + ", " + FirstName; }
}
}
That's what I do in my project, I have an other class wich is Member and inside I have the Email. I have a AuthenticationService that I use to sing in my user here's the code of this AuthenticationService...
In the web.config I have two differents connection string, one for the application BD and the other for the membership BD.
public class AuthenticationService : IAuthenticationService
{
private readonly IConfigHelper _configHelper;
private readonly ISession _session;
public AuthenticationService(IConfigHelper configHelper, ISession session)
{
_configHelper = configHelper;
_session = session;
}
public bool IsValidLogin(string email, string password)
{
CheckLocked(email);
return Membership.ValidateUser(email, password);
}
public void SignIn(string email, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
FormsAuthentication.SetAuthCookie(email, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
public User GetLoggedUser()
{
var email = GetLoggedInUserName();
if (IsMember())
return _session.Single<Member>(x => x.Email == email);
return _session.Single<DelegateMember>(x => x.Email == email);
}
public string GetLoggedInUserName()
{
return Membership.GetUser() != null ? Membership.GetUser().UserName : string.Empty;
}
public MembershipCreateStatus RegisterUser(string email, string password, string role)
{
MembershipCreateStatus status;
//On doit laisser Guid.NewGuid().ToString() sinon ça ne passe pas
Membership.CreateUser(email, password, email, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), true, out status);
if (status == MembershipCreateStatus.Success)
{
Roles.AddUserToRole(email, role);
}
return status;
}
public MembershipUserCollection GetAllUsers()
{
return Membership.GetAllUsers();
}
public string GeneratePassword()
{
var alphaCaps = "QWERTYUIOPASDFGHJKLZXCVBNM";
var alphaLow = "qwertyuiopasdfghjklzxcvbnm";
var numerics = "1234567890";
var special = "##$";
var allChars = alphaCaps + alphaLow + numerics + special;
var r = new Random();
var generatedPassword = "";
for (int i = 0; i < MinPasswordLength - 1; i++)
{
double rand = r.NextDouble();
if (i == 0)
{
//First character is an upper case alphabet
generatedPassword += alphaCaps.ToCharArray()[(int)Math.Floor(rand * alphaCaps.Length)];
//Next one is numeric
rand = r.NextDouble();
generatedPassword += numerics.ToCharArray()[(int) Math.Floor(rand*numerics.Length)];
}
else
{
generatedPassword += allChars.ToCharArray()[(int)Math.Floor(rand * allChars.Length)];
}
}
return generatedPassword;
}
public int MinPasswordLength
{
get
{
return Membership.Provider.MinRequiredPasswordLength;
}
}
public string AdminRole
{
get { return "admin"; }
}
public string MemberRole
{
get { return "member"; }
}
public string DelegateRole
{
get { return "delegate"; }
}
public string AgentRole
{
get { return "agent"; }
}
public bool Delete(string email)
{
return Membership.DeleteUser(email);
}
public bool IsAdmin()
{
return Roles.IsUserInRole(AdminRole);
}
public bool IsMember()
{
return Roles.IsUserInRole(MemberRole);
}
public bool IsDelegate()
{
return Roles.IsUserInRole(DelegateRole);
}
public bool IsAgent()
{
return Roles.IsUserInRole(AgentRole);
}
public bool ChangePassword(string email, string oldPassword, string newPassword)
{
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
if (String.IsNullOrEmpty(oldPassword)) throw new ArgumentException("Value cannot be null or empty.", "oldPassword");
if (String.IsNullOrEmpty(newPassword)) throw new ArgumentException("Value cannot be null or empty.", "newPassword");
// The underlying ChangePassword() will throw an exception rather
// than return false in certain failure scenarios.
try
{
var currentUser = Membership.Provider.GetUser(email, true);
return currentUser.ChangePassword(oldPassword, newPassword);
}
catch (ArgumentException)
{
return false;
}
catch (MembershipPasswordException)
{
return false;
}
}
public string ResetPassword(string email)
{
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
Unlock(email);
var currentUser = Membership.Provider.GetUser(email, false);
return currentUser.ResetPassword();
}
public bool CheckLocked(string email)
{
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
var currentUser = Membership.Provider.GetUser(email, false);
if (currentUser == null) return false;
if (!currentUser.IsLockedOut) return false;
if (currentUser.LastLockoutDate.AddMinutes(30) < DateTime.Now)
{
currentUser.UnlockUser();
return false;
}
return true;
}
public bool Unlock(string email)
{
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
var currentUser = Membership.Provider.GetUser(email, false);
if (currentUser == null) return false;
currentUser.UnlockUser();
return true;
}
}
I hope it can help!

Resources