could not find new column in aspnet_Membership table - c#

I had added in a new column called "ForgotPasswordDate" into aspnet_Membership table. When a user hit the submit button in the Password Recovery Control, it would store the timing that user hit the button into the "ForgotPasswordDate" column by using the getDate() method.
After which, user would receive an email which contain an URL directing them into ChangePassword.apsx.
I wanted to make the ChangePassword.aspx page expired after 1 day the user had requested for new password. This would be done by using the time in "ForgotPasswordDate" column and using the AddDay() method.
However, the code gave me a problem. Which I think they could not recognize the "ForgotPasswordDate" column inside the Membership table.
This is the code which had an error:
if (DateTime.Now < user.ForgotPasswordDate.AddMinutes(3))
for testing purposes, currently I just set the logic as 3 minutes.
And the error message is:
System.Web.Security.MembershipUser' does not contain a definition for 'ForgotPasswordDate' and no extension method 'ForgotPasswordDate' accepting a first argument of type 'System.Web.Security.MembershipUser' could be found (are you missing a using directive or an assembly reference?
Here is the whole code:
protected void Page_Load(object sender, EventArgs e)
{
//if the id is in the query string
if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
{
//store the user id
Guid userId = new Guid(Request.QueryString["ID"]);
//attempt to get the user's information
MembershipUser user = Membership.GetUser(userId);
if (DateTime.Now < user.ForgotPasswordDate.AddMinutes(3)) //here is the part
{
//Page not expire yet.
hidden.Text = user.ProviderUserKey.ToString();
Server.Transfer("~/ChangePassword.aspx");
}
else
{
//Expired; direct to Page Expired Page
Server.Transfer("~/PageExpired.aspx");
}
}
}
is there anyway that the system could recognize the new column in aspnet_membership table?

I would find out which stored procedure the membership uses, modify and include the new columns. Then you may have to override the current membership class to include the new properties.

Related

Inserting a row into Relational database table

I am very new to c# and asp.net mvc. I'm building a HR portal for our company where a user can submit a leave form among other things... So I'm using mssql as the database server and using Entity Frame work to communicate with it. I have 3 entities, user (Containing user details), permissions (the user permissions for allowing actions in the app) and then the leave form table (where the leave form details are stored). There is a one to many relationship between user - permission and then a one to many relationship between user-leave. I am not fazed about the permissions as that gets created when the user account is being created.
The problem I am facing is, how do I add a leave form for a specific user? Below is my controller code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Leave(MasterViewModel model)
{
DocSubViewModel mv = model.DSModel;
int userId = Convert.ToInt32(Session["userID"]);
try
{
using (HrDcpDBContainer db = new HrDcpDBContainer())
{
var leave = db.leaves.Create();
leave.dateFrom = mv.DateFrom;
leave.dateSubmitted = DateTime.Now;
leave.dateTo = mv.DateTo;
leave.nrDays = mv.NrDays;
leave.reason = mv.SpecialLeave;
leave.TLApproval = null;
leave.TLApprovalDate = null;
leave.TLApprovalID = mv.TeamLeaderID;
leave.DMApprovalDate = null;
leave.DMApprovalID = mv.DepManagerID;
leave.DMApproval = null;
leave.type = mv.Type;
leave.user = userId;
db.leaves.Add(leave);
db.SaveChanges();
}
ViewBag.Message = "Leave Form submitted Successfully. You will be redirected shortly...";
return View("result");
}
catch (Exception ex)
{
ViewBag.Message = ex;
//ViewBag.Message = "Leave Form submitted Successfully. You will be redirected shortly...";
return View("result");
}
The problem comes in leave.user = userId;. It says:
Cannot implicitly convert int to Portal.Model.user
I can't seem to find out how to do this...
You're telling it to put the UserId where your leave model is asking for a User.
Your relationship requires a User to go in there, so you'll have to update your code a little bit:
using (HrDcpDBContainer db = new HrDcpDBContainer())
{
var leave = db.leaves.Create();
leave.user = db.users.First(x => x.Id == userId);
}
This will put reference to the actual user in the new leave record. If you go later and check it out you'll see a column in the leave table called user_Id that has an integer value in it and is set as a foreign key to the users table.
Note that this will error if no user exists having the specified Id value. If you anticipate this to be a problem, rather use .FirstOrDefault() instead of .First() and then account for the value being null before you add it to your new leave object.
That's expected since User is a object and not int. What you should be doing probably is leave.user.UserId = userId; instead [Assuming leave.user is of type User which has a UserId property]

Data is not entering in dbo.AspNetUsers (which is empty) and still showing that username is already taken ( while registering)

I am working on a project which was almost complete. I didn't use SQL server, rather I used inbuilt database in Asp.net 4.5.1. At first everything was perfect - like when I am registering a user, AspNetUsers table gets updated. Now I deleted all the contents of my table and registering the same user - it says name asag******#gmail.com has already taken. Even if I registered new user, AspNetUsers table is not updated...
Code-(inbuilt)
protected void btnsubmit_Click(object sender, EventArgs e)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
var user = new ApplicationUser() { UserName = txtemailid.Text, Email = txtemailid.Text };
IdentityResult result = manager.Create(user, txtpass.Text);
if (result.Succeeded)
{
-
-
-
-
}
I am getting result =false. It says user already exists.

Search DNN Portal User using custom Module

Hello to all programmers out there!
I am currently developing a module wherein I need to have a search for all users in my DNN portal. And I don't know what is the right way of doing so. I just have to populate a gridview with the users username and UserID with a field populated with a button. So overall. I need to have 3 fields wherein:
1st field = Username
2nd field = UserID
3rd Field = a Button(Which I already know how to include in a gridview)
I also have a textbox and a buttonSearch wherein in the textbox I will search for an existing username else, I shall throw an exception or message perhaps. So whenever there is a username existing prior to what I searched, the gridview will return with the information.
As of now I'm really puzzled here. And I only have this:
public static UserInfo GetUserByName(int portalId, string username)
{
}
And I'm not sure what to do next.
Any response would be really appreciated.
I updated my answer to reflect the function wrap that you originally suggested. I am using the GetUsersBasicSearch function of DotNetNuke.Entities.Users to look for a user by username. I'm not sure what you need a gridview for? If you are searching for a username, it will likely return just 1 user. Are you wanting to partially match the username and show multiple matches in a gridview?
public static UserInfo GetUserByName(int portalId, string username)
{
var foundUsers = UserController.Instance.GetUsersBasicSearch(portalId, 0, 10, "UserID", true, "UserName", username);
if (foundUsers.Any())
{
return foundUsers.FirstOrDefault();
}
else
{
return null;
}
}

How to store login user id in asp.net?

i am new to asp.net. my question is that how one can save login userid in asp.net webform?
code i am writing in asp.net webform is:
foreach (var s in db.Users)
{
if (tbUserName.Text==s.user_name && tbPassword.Text == s.user_password)
{
if (string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
{
FormsAuthentication.SetAuthCookie(tbUserName.Text, false);
Response.Redirect("~/");
}
else
{
FormsAuthentication.RedirectFromLoginPage(tbUserName.Text, false);
}
flag = 1;
break;
}
else
flag=0;
}
if(flag==0)
{
tbUserName.ErrorText = "Invalid user";
tbUserName.IsValid = false;
}
}
As Tim said, you can get the authenticated user with
User.Identity.Name
You can also get the AuthenticationType and IsAuthenticated properties from the same object.
A suggestion would be to NOT query your DB for all of the users and then loop through them for the correct one. Based off of the user input, you should query the db for the one and only user which matches the form post.
Based off of what you wrote, it looks like the passwords are in clear text and not encrypted, which is a huge security issue. Being new to .Net, take a look at the .Net Membership Providers or SimpleMembership or a comparable pattern.
Good luck!
I would suggest you look at using the Session object to store the user ID. A Session will be available throughout that user's session on the site. Thus, you can call Session anywhere in your site's code to reference that user ID.
For example, to store the id, simply do this, pretend we're in Page_Load()
Session["UserId"] = userID // Or wherever you get the ID from.
then in your code behind, you can do this:
string userId = Session["UserId"]
If the user ID is a number, say an int, then you will need to cast the userID:
int userId = 0;
int.TryParse(Session["UserID"], out userID)
Quick dirty link to a Session example :
http://asp.net-tutorials.com/state/sessions/

How to add a module on my page in DNN programatically

So far, I have tried below code to add a module through code on my page in DNN.
protected void Page_Load(object sender, EventArgs e)
{
ModuleController MC = new ModuleController();
ModuleInfo MInfo = new ModuleInfo();
MInfo = MC.GetModule(507, 116,false);//Just Hard coded for testing
MInfo.TabID = PortalSettings.ActiveTab.TabID;
MInfo.PaneName = "ContentPane";
MInfo.Alignment = "left";
MC.AddModule(MInfo);//Line throwing error :-
}
I am trying to add a module which is present on tabid=116 and having moduleId=507 on my current tab or page in pageLoad Event.But the last line throwing a error saying
"Violation of UNIQUE KEY constraint 'IX_TabModules_UniqueId'. Cannot insert duplicate key in object 'dbo.TabModules'. The duplicate key value is (555ba77a-be19-40a0-bb72-559672230345)."
Please tell me where i am doing wrong ? and is this the correct way to add a module ?
The first thing that I notice is that you're effectively trying to add the same instance of the module to the database. You've changed the TabID, but otherwise all of the other IDs within the ModuleInfo instance are still there.
Looking at how DNN adds an existing module (look in the DoAddExistingModule method), they start by calling Clone() on the ModuleInfo instance, and then reset the UniqueId (which is the constraint you're hitting):
newModule.UniqueId = Guid.NewGuid();

Categories