Inserting a row into Relational database table - c#

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]

Related

MVC Session id loading data from database of users with a different id

I have developed a career application page using MVC and EF where the user when loading the page gets a random unique id to which I add some extra numbers and then assign(?) it to a session id variable like below:
var uniqueID = System.Guid.NewGuid().ToString();
var tempcount = (db.Applicants.Select(x => x)).Count();
user.FormId = tempcount + "_" + uniqueID;
Session["id"] = user.FormId;
Scrolling down the form the user must complete tables that include previous work experience, qualifications etc.
To load data on each for the specific user I do the following:
public ActionResult GetData(Applicant applicant)
{
db.Configuration.LazyLoadingEnabled = false;
db.Configuration.ProxyCreationEnabled = false;
var tosee = (string)Session["id"];
IEnumerable<WorkExp> workexpList = db.WorkExps.Where(x => x.FormId == tosee).ToList();
return Json(new { data = workexpList }, JsonRequestBehavior.AllowGet);
}
For each table there is a similar method like the above.
Every once in a few months I receive complaints from users telling me they can see the data of other random applicants!
Can someone explain me why could this be happening?

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/

CreateUserAndAccount and db.SaveChanges causes duplicate user entry

I am working on a ASP.NET MVC 4 web application. The following code causes that the user will be created two times in the UserProfile Table.
...
WebSecurity.CreateUserAndAccount(UserName, Password);
var UserProfile = (from UserProf in _db.Users
where UserProf.UserName == UserName
select UserProf).FirstOrDefault();
UserCustomAttribute = new UserCustomAttribute();
UserCustomAttribute.UserProfile = UserProfile;
UserCustomAttribute.Name = "BelongsToAccountId";
UserCustomAttribute.Value = model.AgentModel.AccountId;
using (db = new xDb())
{
db.UserCustomAttributes.Add(UserCustomAttribute);
db.SaveChanges();
}
...
Using VS2012 debugging feature, I discovered that one entry is created when calling
WebSecurity.CreateUserAndAccount(UserName, Password);
And, the duplicate is created when calling
db.SaveChanges();
This is weird. I would expect that SaveChanges() is called in CreateUserAndAccount(...)?!
So, how to add something to database without duplicating created user?

Can't update an entity with Poco Code Generation Item

I have the following scenario:
the below 2 global variables in my page:
MainContext db = new MainContext();
User user = new User();
A method to fill the properties that is called on the button update:
private void FillProperties()
{
user.FirstName = txtFirstName.Text;
user.LastName = txtLastName.Text;
user.Email = txtEmail.Text;
}
on the button update i am doing the following:
FillProperties();
user.ID = Request.QueryString("userid");
db.SaveChanges();
but the record isn't been updated which i think is logical since the user variable isn't related to db object, but i a, not being able to do this:
db.Users.AddObject(user);
since AddObject isn't found in the db properties.
What can I do to update user?
Your answers are appreciated.
If you are using the DbContext API simply use
db.Entry(user).State = EntityState.Modified;
Where do you add your user to the DB?
If the user exists in the DB, in order to update it, you should do, for example:
user = db.Users.Where(x => x.ID == Request.QueryString("userid")).Single();
FillProperties();
db.SaveChanges();

Having problems while updation in asp.net mvc project

My create and delete operations are working well. But, the Edit function is giving the following error :- Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
NOTE:- CatPicView is a ViewModel merging the two entities Category and Picture
Following is the code for my Edit action code :-
[HttpPost]
public ActionResult Edit(CatPicView catPic)
{
if (ModelState.IsValid)
{
if (!String.IsNullOrEmpty(catPic.Picture.PictureUrl))
{
if (catPic.Category.PictureId == null)
{
Picture picture = new Picture();
picture.PictureUrl = catPic.Picture.PictureUrl;
db.Pictures.Add(picture);
catPic.Category.PictureId = picture.Id;
}
else
{
db.Entry(catPic.Picture).State = EntityState.Modified;
}
}
db.Entry(catPic.Category).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ParentCategoryId = new SelectList(db.Categories, "Id", "Name", catPic.Category.ParentCategoryId);
return View(catPic);
}
Using the debuger, check the properties of the object you are trying to update. The most likely is that you have an ID in null.
To fix this, you should place a hidden field holding the id of the modified object so when posting the form it became mapped to your object.
You are using an ID that does not exist in the current context which is picture.Id. At the time that you are using it an ID has not yet been generated, add db.SaveChanges before attempting to use the ID.
if (catPic.Category.PictureId == null)
{
Picture picture = new Picture();
picture.PictureUrl = catPic.Picture.PictureUrl;
db.Pictures.Add(picture);
db.SaveChanges();
catPic.Category.PictureId = picture.Id;
}

Categories