The database is no working but no error come out, can someone explain to me what I did wrong. I want to update the column after the validation done.
public ActionResult Autherize(MoIS.Models.medicalassistant maModel)
{
using (DBModels dBModel = new DBModels())
{
var maDetails = dBModel.medicalassistants.Where(x => x.Username == maModel.Username && x.Password == maModel.Password).FirstOrDefault();
if (maDetails == null)
{
maModel.LoginErrorMessage = "Wrong username or password.";
return View("Index", maModel);
}
else
{
try
{
medicalassistant m = dBModel.medicalassistants.First(i => i.MaID == maDetails.MaID);
m.Name = "ali";
dBModel.SaveChanges();
Console.WriteLine("Updated");
}
catch (Exception ex) {
Console.WriteLine(ex.InnerException);
}
Session["maID"] = maDetails.MaID;
Session["username"] = maDetails.Username;
return RedirectToAction("Index", "Home");
}
}
}
Related
In ASP.NET Core-6 Web API using Entity Framework, I have this code:
public async Task<Response<NotificationCredentialListDto>> CreateNotificationCredentialAsync(CreateNotificationCredentialDto requestDto)
{
var userName = _currentUserService.UserName;
var response = new Response<NotificationCredentialListDto>();
using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
if (userName != null)
{
try
{
var notification = _mapper.Map<NotificationCredential>(requestDto);
var existingNotification = _dbContext.NotificationCredentials.LastOrDefault(e => e.MerchantId == notification.MerchantId && e.IsModified == false);
if (existingNotification != null)
{
existingNotification.IsModified = true;
_unitOfWork.MerchantNotificationCredentials.Update(notification);
await _unitOfWork.Save();
}
requestDto.IsModified = false;
notification.IsModified = requestDto.IsModified;
notification.UserName = requestDto.UserName;
requestDto.BasicAuth = encoded;
notification.BasicAuth = requestDto.BasicAuth;
notification.CreatedBy = _currentUserService.UserName;
await _unitOfWork.MerchantNotificationCredentials.InsertAsync(notification);
await _unitOfWork.Save();
return response;
}
catch (Exception ex)
{
_logger.Error("An error occured: " + ex);
transaction.Dispose();
return response;
}
}
_logger.Error("Registration failed");
transaction.Dispose();
response.StatusCode = (int)HttpStatusCode.BadRequest;
response.Successful = false;
response.Message = "Registration failed. Please try again";
return response;
}
}
What I want to achieve is that if record exist, it should update the last record as:
IsModified = true
and also insert a new one.
But I git this error:
An error occured: System.InvalidOperationException: Queries performing 'LastOrDefault' operation must have a deterministic sort order. Rewrite the query to apply an 'OrderBy' operation on the sequence before calling 'LastOrDefault'.
How do I resolve this?
Thanks
First, I think your code does not work correctly because after checking the condition existingNotification != null and updating the entity MerchantNotificationCredentials you are inserting it in next lines.
Second, I suggest change code to this:
public async Task<Response<NotificationCredentialListDto>> CreateNotificationCredentialAsync(CreateNotificationCredentialDto requestDto)
{
var userName = _currentUserService.UserName;
var response = new Response<NotificationCredentialListDto>();
using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
if (userName != null)
{
try
{
var notification = _mapper.Map<NotificationCredential>(requestDto);
var existingNotification = await _dbContext.NotificationCredentials.Where(e => e.MerchantId == notification.MerchantId && e.IsModified == false).OrderByDescending(x=>x.CreatedAt).FirstOrDefaultAsync();
if (existingNotification != null)
{
existingNotification.IsModified = true;
_unitOfWork.MerchantNotificationCredentials.Update(notification);
await _unitOfWork.Save();
return response;
}
requestDto.IsModified = false;
notification.IsModified = requestDto.IsModified;
notification.UserName = requestDto.UserName;
requestDto.BasicAuth = encoded;
notification.BasicAuth = requestDto.BasicAuth;
notification.CreatedBy = _currentUserService.UserName;
await _unitOfWork.MerchantNotificationCredentials.InsertAsync(notification);
await _unitOfWork.Save();
return response;
}
catch (Exception ex)
{
_logger.Error("An error occured: " + ex);
transaction.Dispose();
return response;
}
}
_logger.Error("Registration failed");
transaction.Dispose();
response.StatusCode = (int)HttpStatusCode.BadRequest;
response.Successful = false;
response.Message = "Registration failed. Please try again";
return response;
}
}
Like #Rafalon mentioned, you need to sort the collection using OrderBy() before using LastOrDefault().
var existingNotification = _dbContext.NotificationCredentials.OrderBy(e => e.CreatedAt).LastOrDefault(e => e.MerchantId == notification.MerchantId && e.IsModified == false);
But be careful because multiple records could have been added before CreateNotificationCredentialAsync is called. Maybe you should search for all records where MerchantId = notification.MerchantId and e.IsModified = false:
var existingNotifications = _dbContext.NotificationCredentials.Where(e => e.MerchantId == notification.MerchantId && e.IsModified == false).ToList();
and update IsModified property to all of them.
I have login controller and in this i get my session values
[HttpPost]
public ActionResult Login(Models.AdminUsers adminUsers)
{
try
{
if (Session["iUserId"] != null || GetCookie("iUserId") != null)
{
return Redirect("/Home/Index");
}
if (ModelState.IsValid)
{
using (Data.DataClassesDataContext dc = new Data.DataClassesDataContext())
{
var resultUsers =
(from tableAdminUsers in dc.AdminUsers
where
tableAdminUsers.cEmail == adminUsers.cEmail &&
tableAdminUsers.cPassaword == new Class.AesCryption().Encryption(adminUsers.cPassaword) &&
tableAdminUsers.iActive == 1
select new Models.AdminUsers
{
iUserId = tableAdminUsers.iUserId,
cEmail = tableAdminUsers.cEmail,
cUserName = tableAdminUsers.cUserName,
cUserSurname = tableAdminUsers.cUserSurname,
cImage = tableAdminUsers.cImage
}).FirstOrDefault();
if (resultUsers != null)
{
if (adminUsers.lBeniHatirla == false)
{
Session.Add("iUserId", resultUsers.iUserId);
Session.Add("cEmail", resultUsers.cEmail);
Session.Add("cUserName", new Class.TextLowerAndFirstUpper().Send(resultUsers.cUserName));
Session.Add("cUserSurname", resultUsers.cUserSurname.ToUpper());
Session.Add("cImage", resultUsers.cImage);
}
else
{
CreateCookie("iUserId", resultUsers.iUserId.ToString());
CreateCookie("cEmail", resultUsers.cEmail);
CreateCookie("cUserName", new Class.TextLowerAndFirstUpper().Send(resultUsers.cUserName));
CreateCookie("cUserSurname", resultUsers.cUserSurname.ToUpper());
CreateCookie("cImage", resultUsers.cImage);
}
return Redirect("/Home/Index");
}
else
{
ViewBag.iSonuc = -7;
}
}
}
else
{
ViewBag.iSonuc = -6;
}
}
catch (Exception Ex)
{
new Class.Log().Hata("AdminUsers", "AdminUsers_Post", Ex.Message);
}
return View();
}
And i want to control to session in another controller but my session value return null. My control like this :
if (Session["iUserId"] == null && GetCookie("iUserId") == null)
{
return Redirect("/AdminUsers/Login");
}
int iUserLogin = 0;
if (Session["iUserId"] != null && Convert.ToInt32(Session["iUserId"]) > 0)
{
iUserLogin = Convert.ToInt32(Session["iUserId"]);
}
else if (GetCookie("iUserId") != null && Convert.ToInt32(GetCookie("iUserId")) > 0)
{
iUserLogin = Convert.ToInt32(GetCookie("iUserId"));
}
if (Session["iUserId"] == null && GetCookie("iUserId") == null) this row return true and redict to login page again.But i getting cookie correctly Why session value return null?
Where am I making mistakes? Can you help me?
If it is a .net core, use httpcontext. You can solve it using a distribution cache such as Redis. https://learn.microsoft.com/tr-tr/aspnet/core/fundamentals/app-state?view=aspnetcore-5.0
If you want to develop a User Manager
Use a thirty part nuget like Jwt. What it does is sso logic gives you a token for the user you use it
Try using Session with HttpContext as below:-
HttpContext.Current.Session["iUserId"]=value;
Alternativly, you can try using TempData rather then Session.
TempData["iUserId"]=value;
There is a localization function that I use for language change, in this function I am changing the value of the culture using thread, I realized that this function resets my session value.
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.
I am trying to upload a file into my database with few changes in it but each time it keeps giving me this error and won't update the values...
if (!addRecord) {
if (currentShiipingAddress != null) {
var shippingAddress = existingAccount.AccountAddresses.FirstOrDefault(m => m.Name == currentShiipingAddress.Name && m.AddressLine1 == currentShiipingAddress.AddressLine1 && m.AddTypeShipping == true);
if (shippingAddress == null) {
existingAccount.AccountAddresses.Add(currentShiipingAddress);
}
else {
shippingAddress.PostCode = currentShiipingAddress.PostCode;
shippingAddress.AddressLine1 = currentShiipingAddress.AddressLine1;
shippingAddress.AddressLine2 = currentShiipingAddress.AddressLine2;
shippingAddress.AddressLine3 = currentShiipingAddress.AddressLine3;
shippingAddress.DateUpdated = DateTime.UtcNow;
shippingAddress.AddTypeShipping = true;
context.Entry(shippingAddress).State = EntityState.Modified;
}
}
if (currentBillingAddress != null) {
var billingAddress = existingAccount.AccountAddresses.FirstOrDefault(m => m.Name == currentBillingAddress.Name && m.AddressLine1 == currentBillingAddress.AddressLine1 && m.AddTypeBilling == true);
if (billingAddress == null) {
existingAccount.AccountAddresses.Add(currentBillingAddress);
}
else {
billingAddress.PostCode = currentBillingAddress.PostCode;
billingAddress.AddressLine1 = currentBillingAddress.AddressLine1;
billingAddress.AddressLine2 = currentBillingAddress.AddressLine2;
billingAddress.AddressLine3 = currentBillingAddress.AddressLine3;
billingAddress.DateUpdated = DateTime.UtcNow;
billingAddress.AddTypeBilling = true;
context.Entry(billingAddress).State = EntityState.Modified;
}
}
if (invoiceCurrentContact != null) {
var existingContact = existingAccount.AccountContacts.FirstOrDefault(m => m.ContactEmail == invoiceEmail);
if (existingContact == null) {
existingAccount.AccountContacts.Add(invoiceCurrentContact);
}
else {
existingContact.ContactEmail = invoiceCurrentContact.ContactEmail;
existingContact.ContactName = invoiceCurrentContact.ContactName;
existingContact.TenantContactPhone = invoiceCurrentContact.TenantContactPhone;
existingContact.DateUpdated = DateTime.UtcNow;
context.Entry(existingContact).State = EntityState.Modified;
}
}
if (purchaseCurrentContact != null) {
var existingContact = existingAccount.AccountContacts.FirstOrDefault(m => m.ContactEmail == purchaseEmail);
if (existingContact == null) {
existingAccount.AccountContacts.Add(purchaseCurrentContact);
}
else {
existingContact.ContactEmail = purchaseCurrentContact.ContactEmail;
existingContact.ContactName = purchaseCurrentContact.ContactName;
existingContact.TenantContactPhone = purchaseCurrentContact.TenantContactPhone;
existingContact.DateUpdated = DateTime.UtcNow;
context.Entry(existingContact).State = EntityState.Modified;
}
}
}
else {
if (invoiceCurrentContact != null) {
existingAccount.AccountContacts.Add(invoiceCurrentContact);
}
if (purchaseCurrentContact != null) {
existingAccount.AccountContacts.Add(purchaseCurrentContact);
}
if (currentShiipingAddress != null) {
existingAccount.AccountAddresses.Add(currentShiipingAddress);
}
if (currentBillingAddress != null) {
existingAccount.AccountAddresses.Add(currentBillingAddress);
}
}
if (addRecord) {
context.Account.Add(existingAccount);
}
else {
context.Entry(existingAccount).State = EntityState.Modified;
}
This is where I am committing the changes to be saved but it turns out to give me the above-mentioned error
}
context.SaveChanges();
}
}
}
catch (Exception ex)
{
return "Import Failed : " + ex.Message + " " + counter.ToString();
}
return $"Supplier Account details imported successfully. Added { addedSuppliers }, Updated = { updatedSuppliers }";
}
I am importing excel data into my DB, which works perfectly fine, but only if the spreadsheet is open. If it is not open, it gives an error of "Expected table not in correct format", any ideas why ? Thanks in advance for any help!
[HttpPost]
public ActionResult ImportExcel(PipelineDetails model, HttpPostedFileBase FileUpload, int ProjectID)
{
string Result = "";
if (FileUpload != null)
{
if (FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
string filename = FileUpload.FileName;
string pathToExcelFile = filename;
var excelFile = new ExcelQueryFactory();
excelFile.FileName = pathToExcelFile;
excelFile.AddMapping<PipelineDetails>(x => x.Accumulated_Length, "Accumulated Length");
excelFile.AddMapping<PipelineDetails>(x => x.Elevation, "Elevation");
excelFile.AddMapping<PipelineDetails>(x => x.Pipe_Outside_Diameter, "Pipe Outside Diameter");
excelFile.AddMapping<PipelineDetails>(x => x.Wall_Thickness, "Wall Thickness");
excelFile.AddMapping<PipelineDetails>(x => x.Control_Point_Description, "Control Point Description");
excelFile.AddMapping<PipelineDetails>(x => x.Control_Point_Size, "Control Point Size");
var pipelineData = from PLD in excelFile.Worksheet<PipelineDetails>() select PLD;
try
{
foreach (var a in pipelineData)
{
if (a.Accumulated_Length == null || a.Elevation == null || a.Pipe_Outside_Diameter == null ||
a.Wall_Thickness == null)
{
Result = "There is a problem with the Import File. Please check the file format or data.";
return RedirectToAction("Index", "Pipeline", new { id = ProjectID, result = Result });
}
}
}
catch (Exception ex)
{
Result = "There is a problem with the Import File. Please check the file format or data.";
return RedirectToAction("Index", "Pipeline", new { id = ProjectID, result = Result });
}
ProjectManager PM = new ProjectManager();
PM.DeleteALLPipeLine_forProject(ProjectID);
foreach (var a in pipelineData)
{
try
{
if (a.Accumulated_Length.ToString() != "" && a.Elevation.ToString() != "" && a.Pipe_Outside_Diameter.ToString() != "" &&
a.Wall_Thickness.ToString() != "")
{
using (RexusTradingEntities RTE = new RexusTradingEntities())
{
PipelineData PD = new PipelineData();
PD.Accumulated_Length = Convert.ToDecimal(a.Accumulated_Length);
PD.Elevation = Convert.ToDecimal(a.Elevation);
PD.Pipe_Outside_Diameter = Convert.ToDecimal(a.Pipe_Outside_Diameter);
PD.Wall_Thickness = Convert.ToDecimal(a.Wall_Thickness);
PD.Control_Point_Description = a.Control_Point_Description;
PD.Control_Point_Size = a.Control_Point_Size;
PD.fkiProjectID = ProjectID;
PD.CreateDateTimeStamp = DateTime.Now;
RTE.PipelineDatas.Add(PD);
RTE.SaveChanges();
}
}
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
}
}
}
}
//Adding the Node Numbers in sequencial order
PM.UpdatePipelineNodeNumbers(ProjectID, model);
Result = "Import Success";
return RedirectToAction("Index", "Pipeline", new { id = ProjectID, result = Result });
}
else
{
Result = "Only Excel file format is allowed.";
return RedirectToAction("Index", "Pipeline", new { id = ProjectID, result = Result });
}
}
else
{
Result = "No Import File Selected.";
return RedirectToAction("Index", "Pipeline", new { id = ProjectID, result = Result });
}
}
EDIT: I have also tried adding the following, but still get the error :
if (FileUpload.FileName.EndsWith("xlsx"))
{
excelFile.DatabaseEngine = LinqToExcel.Domain.DatabaseEngine.Ace;
}
if (FileUpload.FileName.EndsWith("xls"))
{
excelFile.DatabaseEngine = LinqToExcel.Domain.DatabaseEngine.Jet;
}
EDIT: I just saved my .xlsx file as .xls and it imported perfect!? Why not with the .xlsx ?
Unfortunately I needed to find a solution to this and as I did not get any help around this(i.e Replies and other posts), I had to make a decision and scrapped the above and only allowed importing of csv files.
public ReturnMessage EditCategories(Category objCategory)
{
ReturnMessage objReturnMessage = new ReturnMessage();
try
{
Category objCategoryNew = db.Categories.Where(x => x.CategoryId == objCategory.CategoryId).FirstOrDefault();
if (objCategoryNew != null)
{
objCategoryNew = objCategory;
db.SaveChanges();
objReturnMessage.isSuccessfull = true;
objReturnMessage.responseMessage = "Successfully updated.";
}
else
{
objReturnMessage.isSuccessfull = false;
objReturnMessage.responseMessage = "Category not present.";
}
}
catch (Exception ex)
{
objReturnMessage.isSuccessfull = false;
objReturnMessage.responseMessage = ex.Message;
}
return objReturnMessage;
}
Everything goes fine there are no exceptions still the data isn't getting updated. I don't know what's the issue. Please help?
The line:
objCategoryNew = objCategory;
will not work out since you change the reference objCategoryNew to objCategory, not the object itself, what you have to do is to assign each property of objCategory to objCategoryNew, something like:
objCategoryNew.Pro1 = objCategory.Pro1;
objCategoryNew.Pro2 = objCategory.Pro2;
....