Statement gets implemented although the if condition is false - c#

Let me ask the question differently , is there a way to check if BID=0 convert it to null else //do stuff
I'm adding a new feature on an old code . when a validation met the data is sent through an ajax from view to controller . the data sent correctly , the problem is in the controller as i added an if...else.
Supposedly
if(BID == 0)
{
//implement something
}
else
{
//implement another thing
}
the issue is the condition whether it's false or true , the first statement gets executed and i don't know why . any ideas?
here is the ajax
function SubmitTermination() {
chkVisibility()
validate();
if (EmployeeIsValid && bossIdvalid && ResignationDateIdvalid && PhoneIsvalid) {
var EmployeeID = $('#EmpID').val();
var BossID = $('#MangrID').val();
var RDDate = $('#resignationDate').val();
var RDReason = $('#TerminationType').val();
var RDReasonDetail = $('#terminationDescription').val();
var phone = $('#EmployeePhone').val();
var remember = document.getElementById('IsAgent');
var LDDate = $('#LeavingDate').val();
var isAgent = false;
if (remember.checked) {
isAgent = true;
} else {
isAgent = false;
}
var data = {
UserId: EmployeeID,
BID: BossID,
TDate: RDDate,
LDate: LDDate,
TReason: RDReason,
TPhoneNum: phone,
Agent: isAgent,
TReasonDetail: RDReasonDetail
};
$.ajax({
type: 'POST',
url: '/Resignation/SaveTermination',
daatype: 'json',
data: data,
success: function (result) {
document.getElementById('statusResult').textContent = result;
$('#PopUP').modal('show');
setTimeout(location.reload.bind(location), 4000);
}
});
}
else if (EmployeeIsValid && !bossIdvalid && BossEmpty && ResignationDateIdvalid && PhoneIsvalid) {
var EmployeeID = $('#EmpID').val();
var RDDate = $('#resignationDate').val();
var RDReason = $('#TerminationType').val();
var RDReasonDetail = $('#terminationDescription').val();
var phone = $('#EmployeePhone').val();
var remember = document.getElementById('IsAgent');
var LDDate = $('#LeavingDate').val();
var isAgent = false;
if (remember.checked) {
isAgent = true;
} else {
isAgent = false;
}
var data = {
UserId: EmployeeID,
BID: 0,
TDate: RDDate,
LDate: LDDate,
TReason: RDReason,
TPhoneNum: phone,
Agent: isAgent,
TReasonDetail: RDReasonDetail
};
$.ajax({
type: 'POST',
url: '/Resignation/SaveTermination',
daatype: 'json',
data: data,
success: function (result) {
document.getElementById('statusResult').textContent = result;
$('#PopUP').modal('show');
setTimeout(location.reload.bind(location), 4000);
}
});
}
}
here is the controller with the issue
public JsonResult SaveTermination(int UserId, int BID, string TDate, string LDate, int TReason, Int32 TPhoneNum, bool Agent, string TReasonDetail = "No Details")
{
string result = "nothign yet";
//my try inside the original
#region transfer
//the issue is here
if (BID == 0)
{
bool userInDb = userCheck.checkUserInDB(UserId);
bool BossInDb = false;
bool userAddFromOracle = false;
bool resignationDateCheck = false;
bool leavingDateCheck = false;
bool exsistingResignations = false;
bool ResignationsCount = false;
ExitApplication.Models.User user;
using (db = new ExitApplication2015Entities())
{
user = db.Users.Where(u => u.UserID == UserId).SingleOrDefault();
}
#region Check users in DBS
if (!userInDb)
{
userAddFromOracle = userCheck.GetUserDataFromOracle(UserId.ToString());
if (!userAddFromOracle)
{
result = "Could not find Your User in database or in oracle";
userInDb = false;
}
else
{
userInDb = true;
}
}
#endregion
DateTime resignDate = DateTime.ParseExact(TDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);
DateTime leavDate = DateTime.ParseExact(LDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);
#region Check the Resignation Date
if (resignDate >= DateTime.Now.Date)
{
resignationDateCheck = true;
}
#endregion
#region Check the Leaving Date
if (leavDate >= DateTime.Now.Date)
{
leavingDateCheck = true;
}
#endregion
var resdt = new Resignation();
using (db = new ExitApplication2015Entities())
{
resdt = db.Resignations.Where(r => r.EmployeeID == UserId && r.OpsRetained == false && r.IsCanceled == false && r.IsCompleted == false && r.IsRejected == false && r.HRRetained == false && r.IsTerminated == false).DefaultIfEmpty().SingleOrDefault();
}
#region Previous Resignation check
if (resdt == null)
{
exsistingResignations = false;
}
else
{
exsistingResignations = true;
}
#endregion
var LeavDateCount = 0;
using (db = new ExitApplication2015Entities())
{
LeavDateCount = db.Resignations.Count(r => r.LeavDate == leavDate);
}
#region Leav Date Count Check
if (LeavDateCount < 30)
{
ResignationsCount = true;
}
else
{
ResignationsCount = false;
}
#endregion
if (userInDb && !BossInDb && BID == 0 && !exsistingResignations && ResignationsCount && leavingDateCheck)
{
Resignation ResignApplication = new Resignation
{
EmployeeID = UserId,
ResignStatusID = 3,
ResignDate = resignDate,
LeavDate = leavDate,
IsActive = true,
IsRejected = false,
OpsRetained = false,
HRRetained = false,
IsTerminated = false,
IsCanceled = false,
IsCompleted = false,
insertedBy = "System",
insertedOn = DateTime.Now,
DepartmentID = user.UserDepartmentID,
AccountOrOUID = (user.UserAccountOUID)
};
using (db = new ExitApplication2015Entities())
{
db.Resignations.Add(ResignApplication);
db.Entry<Resignation>(ResignApplication).State = EntityState.Added;
db.SaveChanges();
}
int resignID = ResignApplication.ResignID;
ResignationDetail resignDetails = new ResignationDetail
{
ResignID = resignID,
ResignReason1 = TReason,
ResignReasonDetail1 = TReasonDetail
};
using (db = new ExitApplication2015Entities())
{
db.ResignationDetails.Add(resignDetails);
db.Entry<ResignationDetail>(resignDetails).State = EntityState.Added;
db.SaveChanges();
}
List<ConcernedParty> ConcernedParties;
using (db = new ExitApplication2015Entities())
{
ConcernedParties = db.ConcernedParties.Where(g => g.IsActive == true).ToList();
}
foreach (ConcernedParty ConcernedParty in ConcernedParties)
{
ResignReleaseDetail relDet = new ResignReleaseDetail
{
/*##*/
ResignID = resignID,
ConcernedPartyID = ConcernedParty.ConcernedPartyID,
ReleaseStatusID = 3,
InsertedBy = Users.CurrentUserId.ToString(),
InsertedOn = DateTime.Now,
IsActive = true
};
using (db = new ExitApplication2015Entities())
{
db.ResignReleaseDetails.Add(relDet);
db.Entry<ResignReleaseDetail>(relDet).State = EntityState.Added;
db.SaveChanges();
}
}
try
{
// Mailing mail = new Mailing(ResignApplication);
// mail.sendMail(1, Int32.Parse(BID.ToString()));
result = "Resignation Submitted Sucessfully";
}
catch
{
result = "The Resignation was submitted but the emails were not sent properly,please contact concerned parties on the mail.";
}
}
else
{
if (!userInDb)
{
result = "Sorry Could not Find your User ID in System database or Oracle database";
}
if (!resignationDateCheck)
{
result = "Sorry you Can not submit a resination with a resign date older than today";
}
if (exsistingResignations)
{
result = "Sorry you have a pending Termination please follow up on it";
}
if (!leavingDateCheck)
{
result = "Sorry you Can not submit a resignation with a Leaving date older than resignation date";
}
if (!ResignationsCount)
{
result = "Resignation Capacity is 30 per day.Sorry you have to choose another Monday or Thursday";
}
}
return Json(result);
}
#endregion
else
{
//string result = "nothign yet";
bool userInDb = userCheck.checkUserInDB(UserId);
bool BossInDb = userCheck.checkUserInDB(BID);
bool userAddFromOracle = false;
bool BossAddFromOracle = false;
bool resignationDateCheck = false;
bool leavingDateCheck = false;
bool exsistingResignations = false;
bool ResignationsCount = false;
ExitApplication.Models.User user;
using (db = new ExitApplication2015Entities())
{
user = db.Users.Where(u => u.UserID == UserId).SingleOrDefault();
}
#region Check users in DBS
if (!userInDb)
{
userAddFromOracle = userCheck.GetUserDataFromOracle(UserId.ToString());
if (!userAddFromOracle)
{
result = "Could not find Your User in database or in oracle";
userInDb = false;
}
else
{
userInDb = true;
}
}
if (!BossInDb)
{
BossAddFromOracle = userCheck.GetUserDataFromOracle(BID.ToString());
if (!BossAddFromOracle)
{
result = "Could not find Your Boss User in database or in oracle";
BossInDb = false;
}
else
{
BossInDb = true;
}
}
#endregion
DateTime resignDate = DateTime.ParseExact(TDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);
DateTime leavDate = DateTime.ParseExact(LDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);
#region Check the Resignation Date
if (resignDate >= DateTime.Now.Date)
{
resignationDateCheck = true;
}
#endregion
#region Check the Leaving Date
if (leavDate >= DateTime.Now.Date)
{
leavingDateCheck = true;
}
#endregion
var resdt = new Resignation();
using (db = new ExitApplication2015Entities())
{
resdt = db.Resignations.Where(r => r.EmployeeID == UserId && r.OpsRetained == false && r.IsCanceled == false && r.IsCompleted == false && r.IsRejected == false && r.HRRetained == false && r.IsTerminated == false).DefaultIfEmpty().SingleOrDefault();
}
#region Previous Resignation check
if (resdt == null)
{
exsistingResignations = false;
}
else
{
exsistingResignations = true;
}
#endregion
var LeavDateCount = 0;
using (db = new ExitApplication2015Entities())
{
LeavDateCount = db.Resignations.Count(r => r.LeavDate == leavDate);
}
#region Leav Date Count Check
if (LeavDateCount < 30)
{
ResignationsCount = true;
}
else
{
ResignationsCount = false;
}
#endregion
if (userInDb && BossInDb && !exsistingResignations && ResignationsCount && leavingDateCheck)
{
Resignation ResignApplication = new Resignation
{
EmployeeID = UserId,
ManagerID = BID,
ResignStatusID = 1,
ResignDate = resignDate,
LeavDate = leavDate,
IsActive = true,
IsRejected = false,
OpsRetained = false,
HRRetained = false,
IsTerminated = false,
IsCanceled = false,
IsCompleted = false,
insertedBy = "System",
insertedOn = DateTime.Now,
DepartmentID = user.UserDepartmentID,
AccountOrOUID = (user.UserAccountOUID)
};
using (db = new ExitApplication2015Entities())
{
db.Resignations.Add(ResignApplication);
db.Entry<Resignation>(ResignApplication).State = EntityState.Added;
db.SaveChanges();
}
int resignID = ResignApplication.ResignID;
ResignationDetail resignDetails = new ResignationDetail
{
ResignID = resignID,
ResignReason1 = TReason,
ResignReasonDetail1 = TReasonDetail
};
using (db = new ExitApplication2015Entities())
{
db.ResignationDetails.Add(resignDetails);
db.Entry<ResignationDetail>(resignDetails).State = EntityState.Added;
db.SaveChanges();
}
List<ConcernedParty> ConcernedParties;
using (db = new ExitApplication2015Entities())
{
ConcernedParties = db.ConcernedParties.Where(g => g.IsActive == true).ToList();
}
foreach (ConcernedParty ConcernedParty in ConcernedParties)
{
ResignReleaseDetail relDet = new ResignReleaseDetail
{
/*##*/
ResignID = resignID,
ConcernedPartyID = ConcernedParty.ConcernedPartyID,
ReleaseStatusID = 3,
InsertedBy = Users.CurrentUserId.ToString(),
InsertedOn = DateTime.Now,
IsActive = true
};
using (db = new ExitApplication2015Entities())
{
db.ResignReleaseDetails.Add(relDet);
db.Entry<ResignReleaseDetail>(relDet).State = EntityState.Added;
db.SaveChanges();
}
}
try
{
// Mailing mail = new Mailing(ResignApplication);
// mail.sendMail(1, Int32.Parse(BID.ToString()));
result = "Resignation Submitted Sucessfully";
}
catch
{
result = "The Resignation was submitted but the emails were not sent properly,please contact concerned parties on the mail.";
}
}
else
{
if (!userInDb)
{
result = "Sorry Could not Find your User ID in System database or Oracle database";
}
if (!BossInDb)
{
result = "Sorry Could not Find your Direct Manager ID in System database or Oracle database";
}
if (!resignationDateCheck)
{
result = "Sorry you Can not submit a resination with a resign date older than today";
}
if (exsistingResignations)
{
result = "Sorry you have a pending Termination please follow up on it";
}
if (!leavingDateCheck)
{
result = "Sorry you Can not submit a resignation with a Leaving date older than resignation date";
}
if (!ResignationsCount)
{
result = "Resignation Capacity is 30 per day.Sorry you have to choose another Monday or Thursday";
}
}
return Json(result);
}
}

Related

Store update, insert, or delete statement affected an unexpected number of rows (0)..how do I resolve this issue

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 }";
}

SQLite table doesn't get updated

I have a problem. I created a SwitchButton and want to store the state in a database table. So I created this code to debug:
SettingSwitch.CheckedChange += (s, b) =>
{
SettingDb testsetting = new SettingDb
{
Name = mItems[position].Name,
};
SettingDb test = MainActivity.db.SelectRowFromTableSettings(testsetting);
if (test != null)
{
bool SwitchValueBool = Convert.ToBoolean(test.Value);
}
bool isChecked = ValueDictionary[position];
if(isChecked == true)
{
isChecked = false;
}
else if(isChecked == false)
{
isChecked = true;
}
SettingDb setting = new SettingDb()
{
Name = SettingName.Text,
Type = "Switch",
Value = isChecked.ToString()
};
MainActivity.db.UpdateTableSettings(setting);
ValueDictionary[position] = isChecked;
SettingDb test2 = MainActivity.db.SelectRowFromTableSettings(testsetting);
if (test2 != null)
{
bool SwitchValueBool = Convert.ToBoolean(test2.Value);
}
};
The expected outcome should be:
test.Value = False
test2.Value = Opposite of test.Value, so True
But now the value I get from the table is always False. Here is the update function:
string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
public bool UpdateTableSettings(SettingDb setting)
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Settings.db")))
{
connection.BeginTransaction();
connection.Query<SettingDb>("UPDATE SettingDb SET Value=? WHERE Name=?", setting.Value, setting.Name);
//connection.Update(setting);
connection.Commit();
return true;
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return false;
}
}
public SettingDb SelectRowFromTableSettings(SettingDb setting)
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Settings.db")))
{
return connection.Query<SettingDb>("SELECT * FROM SettingDb WHERE Name=?", setting.Name).FirstOrDefault();
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return null;
}
}
The table value doesn't get updated!!!
Can someone tell me what I am doing wrong?
Please let me know!
According to your description, you want to update sqlite database table, please take a look the following code and modify the update function.
static void UpdateDatabase(int primaryKey, string newText, int newValue)
{
string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "mydatabase.db");
var db = new SQLiteConnection(path, false);
string sql = "UPDATE MyTable SET MyTextColumn = ?, MyValueColumn = ? WHERE MyPrimaryKey= ?";
string[] parms = new String[] { newText, newValue.ToString(), primaryKey.ToString() };
var cmd = db.CreateCommand(sql, parms);
cmd.ExecuteNonQuery();
}

Dynamic change Microsoft BOT Framework Form's Field Step: hiding and showing the confirmation

I'm new to MS BOT Framework.
I changed MS github MultiDialogsBot.sln , I added a HotelsQuery property to init Form's Field value at HotelsDialog.cs,
public class HotelsDialog : IDialog<object>
{
public HotelsQuery _HotelsQuery { get; set; }
public HotelsDialog()
{
_HotelsQuery = new HotelsQuery{
Destination = "Taiwan",
CheckIn = new DateTime(2017,10,29),
Nights = 3
};
}
public async Task StartAsync(IDialogContext context)
{
await context.PostAsync("Welcome to the Hotels finder!");
var hotelsFormDialog = FormDialog.FromForm(this.BuildHotelsForm, FormOptions.PromptInStart);
context.Call(hotelsFormDialog, this.ResumeAfterHotelsFormDialog);
}
public IForm<HotelsQuery> BuildHotelsForm()
{
OnCompletionAsyncDelegate<HotelsQuery> processHotelsSearch = async (context, state) =>
{
await context.PostAsync($"Ok. Searching for Hotels in {state.Destination} from {state.CheckIn.ToString("MM/dd")} to {state.CheckIn.AddDays(state.Nights).ToString("MM/dd")}...");
};
var destField = new FieldReflector<HotelsQuery>(nameof(HotelsQuery.Destination))
.SetActive((state) =>
{
//depend on _HotelsQuery's values
bool isActive = string.IsNullOrWhiteSpace(_HotelsQuery.Destination);
if (!isActive) state.Destination = _HotelsQuery.Destination;
return isActive;
});
var checkInField = new FieldReflector<HotelsQuery>(nameof(HotelsQuery.CheckIn))
.SetActive((state) =>
{
//depend on _HotelsQuery's values
bool isActive = _HotelsQuery.CheckIn == DateTime.MinValue;
if (!isActive) state.CheckIn = _HotelsQuery.CheckIn;
return isActive;
});
var nightsField = new FieldReflector<HotelsQuery>(nameof(HotelsQuery.Nights))
.SetActive((state) =>
{
//depend on _HotelsQuery's values
bool isActive = _HotelsQuery.Nights == 0;
if (!isActive) state.Nights = _HotelsQuery.Nights;
return isActive;
});
var form = new FormBuilder<HotelsQuery>()
.Field(destField)
.Message("Looking for hotels in {Destination}...")
.Field(checkInField)
.Message("Check in {CheckIn}...")
.Field(nightsField)
.Message("Nights : {Nights}...")
.Confirm("Is this your selection?\n {*}", state =>
{
//clean all fields for showing fields in confirmation
_HotelsQuery.Destination = string.Empty;
_HotelsQuery.CheckIn = DateTime.MinValue;
_HotelsQuery.Nights = 0;
return true;
}, new List<string>())
.Message("Thanks you ...")
.OnCompletion(processHotelsSearch)
.Build();
return form;
}
public async Task ResumeAfterHotelsFormDialog(IDialogContext context, IAwaitable<HotelsQuery> result)
{
try
{
var searchQuery = await result;
var hotels = await this.GetHotelsAsync(searchQuery);
await context.PostAsync($"I found in total {hotels.Count()} hotels for your dates:");
var resultMessage = context.MakeMessage();
resultMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel;
resultMessage.Attachments = new List<Attachment>();
foreach (var hotel in hotels)
{
HeroCard heroCard = new HeroCard()
{
Title = hotel.Name,
Subtitle = $"{hotel.Rating} starts. {hotel.NumberOfReviews} reviews. From ${hotel.PriceStarting} per night.",
Images = new List<CardImage>()
{
new CardImage() { Url = hotel.Image }
},
Buttons = new List<CardAction>()
{
new CardAction()
{
Title = "More details",
Type = ActionTypes.OpenUrl,
Value = $"https://www.bing.com/search?q=hotels+in+" + HttpUtility.UrlEncode(hotel.Location)
}
}
};
resultMessage.Attachments.Add(heroCard.ToAttachment());
}
await context.PostAsync(resultMessage);
}
catch (FormCanceledException ex)
{
string reply;
if (ex.InnerException == null)
{
reply = "You have canceled the operation. Quitting from the HotelsDialog";
}
else
{
reply = $"Oops! Something went wrong :( Technical Details: {ex.InnerException.Message}";
}
await context.PostAsync(reply);
}
finally
{
context.Done<object>(null);
}
}
private async Task<IEnumerable<Hotel>> GetHotelsAsync(HotelsQuery searchQuery)
{
var hotels = new List<Hotel>();
// Filling the hotels results manually just for demo purposes
for (int i = 1; i <= 5; i++)
{
var random = new Random(i);
Hotel hotel = new Hotel()
{
Name = $"{searchQuery.Destination} Hotel {i}",
Location = searchQuery.Destination,
Rating = random.Next(1, 5),
NumberOfReviews = random.Next(0, 5000),
PriceStarting = random.Next(80, 450),
Image = $"https://placeholdit.imgix.net/~text?txtsize=35&txt=Hotel+{i}&w=500&h=260"
};
hotels.Add(hotel);
}
hotels.Sort((h1, h2) => h1.PriceStarting.CompareTo(h2.PriceStarting));
return hotels;
}
}
I have trouble after the confirmation shows. When a user answers yes, BOT will ask CheckIn's prompt.
Why does it not go to the OnCompletion event?
Thanks for your help.
You are clearing out the values in the .Confirm
Try something like this:
var form = new FormBuilder<HotelsQuery>()
.Field(destField)
.Message("Looking for hotels in {Destination}...")
.Field(checkInField)
.Message("Check in {CheckIn}...")
.Field(nightsField)
.Message("Nights : {Nights}...")
.Confirm("Is this your selection?\n {*}", state =>
{
if (_HotelsQuery.Destination == string.Empty ||
_HotelsQuery.CheckIn == DateTime.MinValue ||
_HotelsQuery.Nights == 0)
return false;
return true;
}, new List<string>())
.Message("Thanks you ...")
.OnCompletion(processHotelsSearch)
.Build();

Entity attaching to context and unable to remove it

I am creating a context in a method inside my entity to check something but I am not tracking anything with it but when I try to save in the calling code context it throws an exception.
This is the calling code in the main context where I want to save:
var espToProcess = db.RootDomainEmailSeriesProgresses;
foreach (var esp in espToProcess)
{
bool carryOn = esp.MoveNext();
db.SaveChanges(); //Exception
if (!carryOn) continue;
//--> rest of my code
}
This is the methods inside the RootDomainEmailSeriesProgress class.
public bool MoveNext()
{
if (this.CompletedTargets == null) this.CompletedTargets = new List<EmailAddress>();
if (this.CurrentTarget != null)
{
this.CompletedTargets.Add(this.CurrentTarget);
this.CurrentTarget = null;
}
this.CurrentProgress = "";
if (this.RootDomain.ContactFilter != RootDomain.ContactFilterType.None)
{
this.Status = EmailSeriesStatus.Aborted;
return false;
}
var allTargets = RootDomainEmailManager.SortDomainsEmailsByDesirability(this.RootDomain.ID);
var toDo = allTargets.Except(this.CompletedTargets);
if (toDo.Count() < 1)
{
this.Status = EmailSeriesStatus.Completed;
return false;
}
List<string> targetEmailList = allTargets.Select(e => e.Email).ToList();
List<EmailFilter> emailFilters = this.GetFilters(allTargets);
if (emailFilters.Any(x => x.Filter == EmailFilterType.Unsubscribe || x.Filter == EmailFilterType.Responded || x.Filter == EmailFilterType.ManualContactOnly))
{
this.Status = EmailSeriesStatus.Aborted;
if (this.RootDomain.ContactFilter == 0) this.RootDomain.ContactFilter = RootDomain.ContactFilterType.HasAssociatedEmailFilter;
return false;
}
this.CurrentTarget = toDo.First();
return true;
}
private List<EmailFilter> GetFilters(List<EmailAddress> allTargets)
{
using (var db = new PlaceDBContext())
{
db.Configuration.AutoDetectChangesEnabled = false;
db.Configuration.LazyLoadingEnabled = false;
var targetEmailList = allTargets.Select(e => e.Email).ToList();
return db.EmailFilters.AsNoTracking().Where(x => targetEmailList.Contains(x.Email)).ToList();
}
}
It throws out this exception:
The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
I can't see why esp gets attached to the other context. I only need that context briefly, how do I kill it off so it stops causing me issues?
that because there are difference DbContext instances in foreach loop and GetFilters method
You can retry this code
var espToProcess = db.RootDomainEmailSeriesProgresses;
foreach (var esp in espToProcess)
{
bool carryOn = esp.MoveNext(db);
db.SaveChanges(); //Exception
if (!carryOn) continue;
//--> rest of my code
}
public bool MoveNext(DbContext db)
{
if (this.CompletedTargets == null) this.CompletedTargets = new
List<EmailAddress>();
if (this.CurrentTarget != null)
{
this.CompletedTargets.Add(this.CurrentTarget);
this.CurrentTarget = null;
}
this.CurrentProgress = "";
if (this.RootDomain.ContactFilter != RootDomain.ContactFilterType.None)
{
this.Status = EmailSeriesStatus.Aborted;
return false;
}
var allTargets =
RootDomainEmailManager.SortDomainsEmailsByDesirability(this.RootDomain.ID);
var toDo = allTargets.Except(this.CompletedTargets);
if (toDo.Count() < 1)
{
this.Status = EmailSeriesStatus.Completed;
return false;
}
List<string> targetEmailList = allTargets.Select(e => e.Email).ToList();
List<EmailFilter> emailFilters = this.GetFilters(allTargets, db);
if (emailFilters.Any(x => x.Filter == EmailFilterType.Unsubscribe ||
x.Filter == EmailFilterType.Responded || x.Filter ==
EmailFilterType.ManualContactOnly))
{
this.Status = EmailSeriesStatus.Aborted;
if (this.RootDomain.ContactFilter == 0)
this.RootDomain.ContactFilter =
RootDomain.ContactFilterType.HasAssociatedEmailFilter;
return false;
}
this.CurrentTarget = toDo.First();
return true;
}
private List<EmailFilter> GetFilters(List<EmailAddress> allTargets, DbContext db)
{
db.Configuration.AutoDetectChangesEnabled = false;
db.Configuration.LazyLoadingEnabled = false;
var targetEmailList = allTargets.Select(e => e.Email).ToList();
return db.EmailFilters.AsNoTracking().Where(x =>
targetEmailList.Contains(x.Email)).ToList();
}

How to show message or alert when record insertion success of fail in the controller

In my _Layout.cshtml page there is a textbox that allows user to type his/her email address(this is for newsletter).if typed email address exists it does not insert to the database and if not it insert to the database. at the same time if not inserted I want to show an error message and if insert I want to show success message.this is how I insert to the database,
public ActionResult getNewsLetterMail(string N_id, string N_EmailAdd)
{
Session["Ealert"] = null;
Random random = new Random();
int idONe = random.Next(99, 999);
int idTwo = random.Next(999, 9999);
string middle = "menuka";
string fullID = idONe.ToString() + middle + idTwo.ToString();
var N_ID = fullID;
var N_Email = N_EmailAdd;
TourCenterDBEntities NewsLetterEntities = new TourCenterDBEntities();
var existing = NewsLetterEntities.News_Letter.Where(l => l.N_Email == N_EmailAdd);
Debug.WriteLine(existing.Count());
if (existing.Count() == 0)
{
News_Letter NewsLetterDetails = new News_Letter();
NewsLetterDetails.N_id = N_ID;
NewsLetterDetails.N_Email = N_Email;
NewsLetterEntities.News_Letter.Add(NewsLetterDetails);
NewsLetterEntities.SaveChanges();
//want to send success text
}
else
{
//want to send error text
}
return Json(new { });
}
if success or error it returns to the same _Layout.csthml page.
how can I do that.hope your help.
You can use. return content.
if (existing.Count() == 0)
{
News_Letter NewsLetterDetails = new News_Letter();
NewsLetterDetails.N_id = N_ID;
NewsLetterDetails.N_Email = N_Email;
NewsLetterEntities.News_Letter.Add(NewsLetterDetails);
NewsLetterEntities.SaveChanges();
//return Content("Your information saved successfully");
return new JavascriptResult { Script = "alert('Your information saved successfully');" };
}
else
{
//return Content("Already exist. Please choose another.");
return new JavascriptResult { Script = "alert('Your information saved successfully');" };
}
public ActionResult getNewsLetterMail(string N_id, string N_EmailAdd)
{
Session["Ealert"] = null;
Random random = new Random();
int idONe = random.Next(99, 999);
int idTwo = random.Next(999, 9999);
string middle = "menuka";
string fullID = idONe.ToString() + middle + idTwo.ToString();
var N_ID = fullID;
var N_Email = N_EmailAdd;
TourCenterDBEntities NewsLetterEntities = new TourCenterDBEntities();
var existing = NewsLetterEntities.News_Letter.Where(l => l.N_Email == N_EmailAdd);
Debug.WriteLine(existing.Count());
string myMessage="";
if (existing.Count() == 0)
{
News_Letter NewsLetterDetails = new News_Letter();
NewsLetterDetails.N_id = N_ID;
NewsLetterDetails.N_Email = N_Email;
NewsLetterEntities.News_Letter.Add(NewsLetterDetails);
NewsLetterEntities.SaveChanges();
myMessage="success";
}
else
{
myMessage="failed";
}
return Json(myMessage, JsonRequestBehavior.AllowGet);
}
In your view.
$.post('#Url.Action("getNewsLetterMail", "yourControllerName")', { N_id: N_id, N_EmailAdd: N_EmailAdd }).done(function (data) {
if (data == "success") {
alert("Success!");
}
if( data== "failed") {
alert("Failed!");
}
}
I have no experience but I would try something like that:
in my viewmodel I would put
string info
then in my razor view
#Html.DisplayFor(m=>m.info)
and in controller
if(existing){info="success"}
You would have to pass info to the viewmodel in your controller
public ActionResult getNewsLetterMail(string N_id, string N_EmailAdd)
{
Session["Ealert"] = null;
Random random = new Random();
int idONe = random.Next(99, 999);
int idTwo = random.Next(999, 9999);
string middle = "menuka";
string fullID = idONe.ToString() + middle + idTwo.ToString();
var N_ID = fullID;
var N_Email = N_EmailAdd;
TourCenterDBEntities NewsLetterEntities = new TourCenterDBEntities();
var existing = NewsLetterEntities.News_Letter.Where(l => l.N_Email == N_EmailAdd);
Debug.WriteLine(existing.Count());
string myMessage="";
if (existing.Count() == 0)
{
News_Letter NewsLetterDetails = new News_Letter();
NewsLetterDetails.N_id = N_ID;
NewsLetterDetails.N_Email = N_Email;
NewsLetterEntities.News_Letter.Add(NewsLetterDetails);
NewsLetterEntities.SaveChanges();
myMessage="success!";
}
else
{
myMessage="Failed!";
}
return Json(myMessage, JsonRequestBehavior.AllowGet);
}
In Views, you can add jquery to display the message. Following is an example to retrieve the message in Views. You can edit the names in your form accordingly.
`<script type="text/javascript">
$(document).ready(function () {
$("#yourForm").submit(function (e) {
e.preventDefault();
var valid = $("#yourForm").valid();
if (valid) {
$.ajax({
url: "/getNewsLetterMail",
type: "POST",
data: {
Name: $("#N_id").val(),
Email: $("#N_EmailAdd").val(),
},
success: function (data) {
alert(data);
reset();
}
});
}
});
});
</script>'

Categories