UserProfile table to delete user - c#

I'm using MVC4 and VS_2012. I want to delete a user my admin panel.
I usually delete this way;
UsersContext dcUser = new UsersContext();
if (userId.HasValue)
{
var userToDelete = (from u in dcUser.UserProfiles
where u.UserId == userId
select u).Single();
// dcUser.UserProfiles.DeleteOnSubmit(userToDelete);
// dcUser.SubmitChanges();
}
But this case I can't access DeleteOnSubmit and SubmitChanges.
Is there any way to delete user?

Try like this:
dcUser.Entry<string>(userToDelete).State = System.Data.EntityState.Deleted;

you can try this:
[Authorize(Roles = "Admin")]
[HttpPost]
public ActionResult DeleteUser(int id)
{
var tmpuser = "";
var ctx = new UsersContext();
using (ctx)
{
var firstOrDefault = ctx.UserProfiles.FirstOrDefault(us => us.UserId==id);
if (firstOrDefault != null)
tmpuser = firstOrDefault.UserName;
}
string[] allRoles = Roles.GetRolesForUser(tmpuser);
Roles.RemoveUserFromRoles(tmpuser,allRoles);
((SimpleMembershipProvider)Membership.Provider).DeleteAccount(tmpuser);
Membership.Provider.DeleteUser(tmpuser, true);
Membership.DeleteUser(tmpuser, true);
ctx = new UsersContext();
return View(ctx.UserProfiles.OrderBy(user => user.UserName).ToList());
}

Related

How to update a record using LINQ LAMBDA in my ASP.NET MVC 5 Project

I am new to entity framework and LINQ. I am stuck at an issue where I need to firstly check if the record already exists, if it exists then I need to update the record with column RESUMEID accordingly. If not then I need to add the record. I am able to add successfully but I don't know how to update the record in LINQ.
Below is my attempt:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ReferralViewModel viewModel)
{
var candidateId = User.Identity.GetUserId();
// I AM CONFUSED ABOUT BELOW STATEMENT
var IsDupeReferral = _context.Referrals
.Where(r => (r.CandidateId == candidateId)
&& (r.CompanyId == viewModel.CompanyId) && (r.SkillId == viewModel.SkillId))
.Select(r=>r.ReferralId).SingleOrDefault();
if(IsDupeReferral!=0)
{
//IF I FIND DUPE REFERRAL RECORD I WANT TO UPDATE SOME OF THE VALUES IN THAT
_context.Referrals.Where(r => r.ReferralId == IsDupeReferral).
AND UPDATE r.resumeId with viewModel.ResumeId // How to do this?
// NOT SURE ABOUT BELOW LINE EITHER
_context.SaveChanges();
}
else
{
// BELOW CODE IS WORKING FINE
var referral = new Referral
{
ReferralName = viewModel.ReferralName,
ResumeId = viewModel.ResumeId,
CandidateId = candidateId,
DegreeId = viewModel.DegreeId,
CoverLetterId = viewModel.CoverLetterId,
SkillId = viewModel.SkillId
};
if (!string.IsNullOrEmpty(viewModel.TempCompany))
{
var newCompany = new Company
{
CompanyName = viewModel.TempCompany
};
newCompany.Referrals.Add(referral);
_context.Companies.Add(newCompany); ;
}
else
{
referral.CompanyId = viewModel.CompanyId.Value;
_context.Referrals.Add(referral);
}
_context.SaveChanges();
}
return RedirectToAction("ReferralCenter");
}
Here's the solution
//IF I FIND DUPE REFERRAL RECORD I WANT TO UPDATE SOME OF THE VALUES IN THAT
var referral = _context.Referrals.FirstOrDefault(r => r.ReferralId == IsDupeReferral);
// AND UPDATE r.resumeId with viewModel.ResumeId
if (referral !=null) {
referral.resumeId = viewModel.ResumeId;
_context.Entry(referral).State = System.Data.EntityState.Modified;
_context.SaveChanges();
}
Actually, you don't need getting the IsDupeReferral and then request the record again. Try to combine your code as the following:
var referral = _context.Referrals
.Where(r => (r.CandidateId == candidateId)
&& (r.CompanyId == viewModel.CompanyId) && (r.SkillId == viewModel.SkillId)).SingleOrDefault();
if (referral !=null) {
referral.resumeId = viewModel.ResumeId;
_context.Entry(referral).State = System.Data.EntityState.Modified;
_context.SaveChanges();
}
else {
// add a new record
}
Referral referral = _context.Referrals.FirstOrDefault(r=> r.ReferralId = SomeId);
if(referral == null) // then referral does not exist - add it
{
referral = new Referral{
ReferralName = viewModel.ReferralName,
ResumeId = viewModel.ResumeId,
CandidateId = candidateId,
DegreeId = viewModel.DegreeId,
CoverLetterId = viewModel.CoverLetterId,
SkillId = viewModel.SkillId
};
_context.Referrals.Add(referral);
}
else // referral already exists - update its values
{
//make changes to referral
referral.ReferralName = viewModel.ReferralName;
referral.ResumeId = viewModel.ResumeId;
referral.CandidateId = candidateId;
referral.DegreeId = viewModel.DegreeId;
referral.CoverLetterId = viewModel.CoverLetterId;
referral.SkillId = viewModel.SkillId;
}
_context.SaveChanges(); //no matter added or updated - save the changes

Checking for existing records on database wen i call web api

I am calling a web api and saving the records on the database through the controller, i want each time im calling the api to check if the record exists in the database if yes then dont save, if not then save.
var client = new WebClient();
var text = client.DownloadString("https://www.test.com/api/all-users?name=testusername%20&pass=334432");
var wclients = JsonConvert.DeserializeObject<dynamic>(text);
List<apicli> list1 = new List<apicli>();
var clie = new apicli();
if (wclients.message == "success")
{
var data = wclients.data;
//var account = wclients.account;
ViewBag.test = data;
foreach(var item in ViewBag.test)
{
clie.Email = item.email;
clie.Name = item.name;
clie.Aff = item.affiliated_id;
foreach(var item1 in #item.account.real)
{
clie.Login = item1.login;
clie.password = item1.pass;
}
list1.Add(clie);
db.apiclis.AddRange(list1);
db.SaveChanges();
};
}
I would assume you need something like this, although you need to check what is the unique id of each record:
foreach(var item in data){
var c = new apicli {
Email = item.email,
Name = item.name,
Aff = item.affiliated_id
Login = item.account.real.LastOrDefault()?login??"",
Login = item.account.real.LastOrDefault()?pass??""
}
if(!db.apiclis.Any(a => a.Email == c.Email && a.Name == c.Name && a.Aff == c.Aff)){
db.apiclis.Add(c);
}
}
Here I assume that email+name+aff = unique identificator.

Need to access and edit an attribute in a database

Orders are created and saved in this method
public async Task<ActionResult> FirstClassCreate(FormCollection values)
{
var order = new Order();
TryUpdateModel(order);
var customer = db.Users.FirstOrDefault(x => x.Email == User.Identity.Name);
var cart = ShoppingCart.GetCart(this.HttpContext);
try
{
order.DeliveryDate = DateTime.Now.AddDays(1);
order.DeliveryMethod = "First Class";
order.FirstName = customer.FirstName;
order.LastName = customer.LastName;
order.PostalCode = customer.PostalCode;
order.State = customer.State;
order.City = customer.City;
order.Email = customer.Email;
order.Country = customer.Country;
order.Phone = customer.PhoneNumber;
order.Address = customer.Address;
order.HasPaid = false;
order.Username = customer.Email;
order.OrderDate = DateTime.Now;
var currentUserId = User.Identity.GetUserId();
order.Total = cart.GetFirstClass();
if (order.SaveInfo && !order.Username.Equals("guest#guest.com"))
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var ctx = store.Context;
var currentUser = manager.FindById(User.Identity.GetUserId());
//Save this back
//http://stackoverflow.com/questions/20444022/updating-user-data-asp-net-identity
//var result = await UserManager.UpdateAsync(currentUser);
await ctx.SaveChangesAsync();
await storeDB.SaveChangesAsync();
}
//Save Order
storeDB.Orders.Add(order);
await storeDB.SaveChangesAsync();
//Process the order
cart = ShoppingCart.GetCart(this.HttpContext);
order.Total = cart.GetFirstClass();
order = cart.CreateOrder(order);
return RedirectToAction("FirstClass", "Checkouts", order);
}
catch
{
//Invalid - redisplay with errors
return View(order);
}
}
I need to be access the orders database and change attributes of a specific order, using the email as the Unique Identifier and search for the newest (find the newest using the Order Date where 'haspaid' = false).
using ()//Insert database context here)
{
//Search for order in the database, try using the email as the Unique Identifire and search for the newest where haspaid = false
//Change the haspaid attribute to true
var orders = from o in db.Orders
where o.Email == User.Identity.Name, o.HasPaid = false, //Newest
select o;
order.HasPaid = true;
db.Orders.SaveChanges();
//save database changes
}
If I understand you correctly, you don't know how to query the record you want to update. So you need to use the Where() to filter the record and use the Max() function to get the latest date.
var orderToBeChanged = db.Orders
.Where(o => o.HasPaid == false && o => o.Email == User.Identity.Name)
.Max(o => o.OrderDate);

Save the data in the list to another table

[HttpPost]
public ActionResult AddVotes(List<CampaignManager_tbl> list, int events_category_id, int candidates_info_id) {
if (ModelState.IsValid)
{
var events = db.Events_Info_tbl.Where(x => x.is_active == true).FirstOrDefault();
var username = User.Identity.Name;
var getID = db.Account_Info_tbl.Where(x => x.username == username).FirstOrDefault();
foreach (var i in list)
{
Votes_tbl vote = new Votes_tbl();
vote.candidates_info_id = i.candidates_info_id;
vote.C_voters_info_id = getID.account_info_id;
vote.events_info_id = events.events_info_id;
vote.events_category_id = i.events_category_id;
vote.votes_history = true;
db.Votes_tbl.Add(vote);
}
db.SaveChanges();
RedirectToAction("Index");
}
return View(list);
}
This is my code where I am going to save the data in the list into the database but it is not working. List<CampaignManager_tbl> List contains the data to be saved in the Votes_tbl.
What's wrong with this code? How I am gonna save this data?
Save your data outside the loop.
[HttpPost]
public ActionResult AddVotes(List<CampaignManager_tbl> list, int category_id, int candidates_info_id) {
if (ModelState.IsValid)
{
var events = db.Events_Info_tbl.Where(x => x.is_active == true).FirstOrDefault();
var username = User.Identity.Name;
var getID = db.Account_Info_tbl.Where(x => x.username == username).FirstOrDefault();
foreach (var i in list)
{
Votes_tbl vote = new Votes_tbl();
vote.candidates_info_id = i.candidates_info_id;
vote.C_voters_info_id = getID.account_info_id;
vote.events_info_id = events.events_info_id;
vote.events_category_id = category_id;
vote.votes_history = true;
db.Voters_Info_tbl.Add(vote);
}
db.SaveChanges();
RedirectToAction("Index");
}
return View(list);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddVotes(List<CampaignManager_tbl> list)
{
if (ModelState.IsValid)
{
var events = db.Events_Info_tbl.Where(x => x.is_active == true).FirstOrDefault();
var username = User.Identity.Name;
var getID = db.Account_Info_tbl.Where(x => x.username == username).FirstOrDefault();
foreach (var i in list)
{
int val = 1;
bool y = Convert.ToBoolean(val);
if (i.isSelected == y) {
Votes_tbl vote = new Votes_tbl();
vote.candidates_info_id = i.candidates_info_id;
vote.C_voters_info_id = getID.account_info_id;
vote.events_info_id = events.events_info_id;
vote.events_category_id = i.events_category_id;
vote.votes_history = true;
db.Votes_tbl.Add(vote);
}
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View(list);
}
I've come up to this solution but anyway thanks for giving advices. It helps a lot. Thank You.

Search in IQueryable<T>

I am pulling some data from database by this line below:
IQueryable<user> UserList = DatabaseContext.Users.GetAll();
I want to seach something in UserList such as:
foreach (var User in UserList)
{
if (User.type == (int)UserType.SuperUser)
{
IsRecordFound = true;
break;
}
}
Then i do something according to the state of flag:
if (!IsRecordFound)
{
AesCrypto aesCrypto = new AesCrypto();
user newuser = new user();
newuser.username = DEFAULT_SUPER_USER_NAME;
newuser.password = aesCrypto.Encrypt(DEFAULT_SUPER_USER_PASSWORD);
newuser.type = (int)UserType.SuperUser;
newuser.create_date = DateTime.Now;
newuser.last_login = newuser.create_date;
newuser.email_address = DEFAULT_SUPER_USER_EMAIL_ADDR;
newuser.login_count = 1;
DatabaseContext.Users.Add(newuser);
if (!DatabaseContext.Save())
return false;
}
Is there any easy or practical way to seach in IQueryable interface by using LINQ or something else?
if (!UserList.Any(x => x.Type == (int)UserType.SuperUser))
{
AesCrypto aesCrypto = new AesCrypto();
user newuser = new user();
newuser.username = DEFAULT_SUPER_USER_NAME;
newuser.password = aesCrypto.Encrypt(DEFAULT_SUPER_USER_PASSWORD);
newuser.type = (int)UserType.SuperUser;
newuser.create_date = DateTime.Now;
newuser.last_login = newuser.create_date;
newuser.email_address = DEFAULT_SUPER_USER_EMAIL_ADDR;
newuser.login_count = 1;
DatabaseContext.Users.Add(newuser);
if (!DatabaseContext.Save())
return false;
}
You can do it like
bool isSuperUser = UserList.Any(a=>a.type==a.SuperUser)
to search an IQueryable, use where
var foundUsers = UserList.Where( usr => usr.Type == (int)UserTypes.SuperUser );
if( foundUsers == null && foundUsers.Count() == 0 ) // only one of these is required.. I forget which though :s
{
AesCrypto aesCrypto = new AesCrypto();
user newuser = new user();
newuser.username = DEFAULT_SUPER_USER_NAME;
newuser.password = aesCrypto.Encrypt(DEFAULT_SUPER_USER_PASSWORD);
newuser.type = (int)UserType.SuperUser;
newuser.create_date = DateTime.Now;
newuser.last_login = newuser.create_date;
newuser.email_address = DEFAULT_SUPER_USER_EMAIL_ADDR;
newuser.login_count = 1;
DatabaseContext.Users.Add(newuser);
if (!DatabaseContext.Save())
return false;
}
UserList .Where(user => user.Type== (int)UserType.SuperUser);

Categories

Resources