Modified entity is not applied into the database - c#

I am trying to update loan balance based on the payment made by a member.
Payment goes well and it is inserted as expected but during the update of the table LOANBAl, nothing is modified, bellow is my code:
public void UpdateLoanBal(MPAreceipting mpa, string id)
{
using (BOSAEntities db = new BOSAEntities())
{
General gn = new General();
gn.GetUser();
gn.GetServerDate();
LoanRepayment lr = new LoanRepayment();
lr.GetMemberDeduction(loanno);
var lOANBAL = db.LOANBALs.Find(id);
var lb = new LOANBAL();
lb.AuditID = gn.sysUser;
lb.AuditTime = gn.serverDate;
lb.Balance = Convert.ToDecimal(lr.loanBalance);
lb.IntrOwed = Convert.ToDecimal(lr.intOwed);
lb.LastDate = mpa.dateDeposited;
db.Entry(lOANBAL).State = EntityState.Modified;
db.SaveChanges();
}
}

I used the lOANBAL which is an entity and update its properties.
public void UpdateLoanBal(MPAreceipting mpa, string id)
{
var db = new BOSAEntities();
using (var dbContextTransaction = db.Database.BeginTransaction())
{
try
{
var lOANBAL = db.LOANBALs.Find(loanno);
General gn = new General();
gn.GetUser();
gn.GetServerDate();
LoanRepayment lr = new LoanRepayment();
lr.GetMemberDeduction(loanno);
lOANBAL.LoanNo = loanno;
lOANBAL.AuditID = gn.sysUser;
lOANBAL.AuditTime = gn.serverDate;
lOANBAL.Balance = Convert.ToDecimal(lr.loanBalance);
lOANBAL.IntrOwed = Convert.ToDecimal(lr.intOwed);
lOANBAL.LastDate = mpa.dateDeposited;
lOANBAL.TransactionNo=lr.
db.Entry(lOANBAL).State = EntityState.Modified;
db.SaveChanges();
dbContextTransaction.Commit();
}
catch (DbEntityValidationException Exc)
{
dbContextTransaction.Rollback();
string errormessage = string.Join(";",
Exc.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage));
throw new DbEntityValidationException(errormessage);
}
}
}

Related

SaveChanges() doesn't insert any records to database

I'm using Entity Framework to add new records to the database, everything goes ok without any errors, but I don't see the new record in the database.
Update code works, but insert code doesn't work. No errors appear, but no records are inserted into the database.
My code :
var DBs2 = ConnectionTools.OpenConn();
DBs2.Configuration.AutoDetectChangesEnabled = false;
DBs2.Configuration.ValidateOnSaveEnabled = false;
var resList = CreatedSerials.Where(u => u.Item4 == VID).ToList();
foreach (var r in resList)
{
// if serial id ==0 => new then add it as new
if ( r.Item7 == 0)
{
try
{
var purchasesItemSerials = new purchases_item_seriels()
{
pitem_ID = pitem_ID,
stitems_ID = r.Item1,
pmain_ID = PurchasesID,
pitem_virtualID = r.Item4,
pis_CustomSerial = r.Item2,
pis_ExpireDate = r.Item3,
pis_Statues = 0,
ss_StoreID = Convert.ToInt32(gridView1.GetRowCellValue(ItemImdex, "storeID")),
Purchases_Price = Convert.ToDecimal(gridView1.GetRowCellValue(ItemImdex, "item_NetSmallestUnitPrice")),
};
ss.Add(purchasesItemSerials);
}
catch (Exception eeeeee)
{
Msg.Show("", eeeeee.ToString(), 0);return;
}
}
else
{
var DBs350 = ConnectionTools.OpenConn();
var UpdateSerial = DBs350.purchases_item_seriels.Find(r.Item7);
UpdateSerial.pitem_ID = pitem_ID;
UpdateSerial.stitems_ID = r.Item1;
UpdateSerial. pmain_ID = PurchasesID;
UpdateSerial.pitem_virtualID = r.Item4;
UpdateSerial.pis_CustomSerial = r.Item2;
UpdateSerial.pis_ExpireDate = r.Item3;
UpdateSerial.pis_Statues = r.Item6;
UpdateSerial.ss_StoreID = Convert.ToInt32(gridView1.GetRowCellValue(ItemImdex, "storeID"));
UpdateSerial.Purchases_Price = Convert.ToDecimal(gridView1.GetRowCellValue(ItemImdex, "item_NetSmallestUnitPrice"));
DBs350.SaveChanges();
}
}
try
{
DBs2.purchases_item_seriels.AddRange(ss);
DBs2.SaveChanges();
}
catch (Exception eeeeee)
{
Msg.Show("", eeeeee.ToString(), 0);return;
}
I also tried :
DBs2.Configuration.AutoDetectChangesEnabled = true;
DBs2.Configuration.ValidateOnSaveEnabled = true;
but again: no data is inserted, no errors appear
I also tried :
int returnCode = DBs2.SaveChanges();
and returnCode = 0
**I also tried : inserting just a single item then SaveChanges **
// if this serial is new
var NewSerialresList = CreatedSerials.Where(u => u.Item4 == VID && u.Item7 == 0).ToList();
if (NewSerialresList.Count() > 0)
{
var ss = new List<purchases_item_seriels>();
foreach (var r in NewSerialresList)
{
try
{
mrsalesdbEntities DBs002 = new mrsalesdbEntities();
var purchasesItemSerials = new purchases_item_seriels()
{
pitem_ID = pitem_ID,
stitems_ID = r.Item1,
pmain_ID = PurchasesID,
pitem_virtualID = r.Item4,
pis_CustomSerial = r.Item2,
pis_ExpireDate = r.Item3,
pis_Statues = 0,
ss_StoreID = Convert.ToInt32(gridView1.GetRowCellValue(ItemImdex, "storeID")),
Purchases_Price = Convert.ToDecimal(gridView1.GetRowCellValue(ItemImdex, "item_NetSmallestUnitPrice")),
};
//ss.Add(purchasesItemSerials);
DBs002.purchases_item_seriels.Add(purchasesItemSerials);
DBs002.SaveChanges();
}
catch (Exception ex)
{
Msg.Show("", ex.ToString(), 0);
}
}
int CC = ss.Count();
}
i use this function to change the connection variables at run-time :
public static mrsalesdbEntities OpenConn()
{
mrsalesdbEntities MrSalesContext = new mrsalesdbEntities();
MrSalesContext.ChangeDatabase
(
initialCatalog: myconn.database,
port: Convert.ToUInt32( myconn.port),
userId: myconn.uid,
password: myconn.password,
dataSource: myconn.server
);
return MrSalesContext;
}
public static void ChangeDatabase(
this DbContext source,
string initialCatalog = "",
uint port = 3307,
string dataSource = "",
string userId = "",
string password = "",
bool integratedSecuity = true,
string configConnectionStringName = "mrsalesdbEntities")
/* this would be used if the
* connectionString name varied from
* the base EF class name */
{
try
{
// use the const name if it's not null, otherwise
// using the convention of connection string = EF contextname
// grab the type name and we're done
var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
? source.GetType().Name
: configConnectionStringName;
// add a reference to System.Configuration
var entityCnxStringBuilder = new EntityConnectionStringBuilder
(System.Configuration.ConfigurationManager
.ConnectionStrings[configNameEf].ConnectionString);
// init the sqlbuilder with the full EF connectionstring cargo
var sqlCnxStringBuilder = new MySqlConnectionStringBuilder
(entityCnxStringBuilder.ProviderConnectionString);
// only populate parameters with values if added
if (!string.IsNullOrEmpty(initialCatalog))
sqlCnxStringBuilder.Database = initialCatalog;
if ((port) != 0)
sqlCnxStringBuilder.Port = port;
if (!string.IsNullOrEmpty(dataSource))
sqlCnxStringBuilder.Server = dataSource;
if (!string.IsNullOrEmpty(userId))
sqlCnxStringBuilder.UserID = userId;
if (!string.IsNullOrEmpty(password))
sqlCnxStringBuilder.Password = password;
// set the integrated security status
//sqlCnxStringBuilder.IntegratedSecurity = integratedSecuity;
// now flip the properties that were changed
source.Database.Connection.ConnectionString
= sqlCnxStringBuilder.ConnectionString;
}
catch (Exception ex)
{
// set log item if required
}
}
}

Entity saves ok but will not update record no matter what I do

Context is not saving to the database no matter what i do it will insert a new record fine but not save. This is using sql server and the user had permissions ot update data have already checked this
private void btnOk_Click(object sender, EventArgs e)
{
SourceContext SourceDal = new SourceContext();
Appointment _appointment = new Appointment();
int errorCount = 0;
Patient _patient = new Patient();
_patient = SourceDal.getPatientByPatientId(txtPatientId.Text);
_patient.SSN = txtSSN.Text;
_patient.FirstName = txtPatientFirstName.Text;
_patient.LastName = txtPatientLastName.Text;
_patient.Middle = txtPatientMiddle.Text;
_patient.AddressOne = txtPatientAddressOne.Text;
_patient.City = txtPatientCity.Text;
_patient.State = txtPatientState.Text;
_patient.ZipCode = txtPatientZip.Text;
_patient.HomePhone = txtPatientHomePhone.Text;
_patient.WorkPhone = txtPatientWorkPhone.Text;
_patient.CellPhone = txtPatientCellPhone.Text;
if (rBtnHomePhone.Checked == true)
_patient.ApptPhone = txtPatientHomePhone.Text;
if (rBtnHomePhone.Checked == true)
_patient.ApptPhone = txtPatientHomePhone.Text;
if (rBtnWorkPhone.Checked == true)
_patient.ApptPhone = txtPatientWorkPhone.Text;
_patient.BirthDate = dtBirthDate.DateTime;
_patient.emailAddress = txtPatientEmail.Text;
_patient.Race = (int)dpRace.SelectedValue;
_patient.Ethnicity = (int)dpEthnicity.SelectedValue;
_patient.Language = (int)dpLanguages.SelectedValue;
_patient.AlertNote = txtPatientNotes.Text;
if (dpGender.Text == "")
{
dpGender.Focus();
errorCount = 1;
lblGenderRequired.Text = "* Gender is required.";
}
else
{
errorCount = 0;
lblGenderRequired.Visible = false;
}
_patient.Gender = dpGender.Text.Substring(0, 1);
_patient.PatientID = txtPatientId.Text;
txtPatientFirstName.Text = _patient.FirstName;
txtPatientLastName.Text = _patient.LastName;
// IF ITS SAVE NEW GO AHEAD ADD IT TO THE CONTEXT.
SourceDal.AddToPatient(_patient);
}
Add to paitent has the following
public void AddToPatient(Patient newPatient)
{
using (var myContext = new SMBASchedulerEntities(this.Connectionstring))
{
myContext.Patients.Add(newPatient);
if (newPatient.ID == 0)
{
myContext.Entry(newPatient).State = EntityState.Added;
}
else
{
myContext.Entry(newPatient).State = EntityState.Modified;
}
try
{
myContext.SaveChanges();
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Console.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
}
}
}
}
}
It adds in the record fine but it just wont save the current record no matter what i do even though all the details are correct. But when i reload the form and the application the update is not there the email address is not saved no are any the other updates.
I suspect I'm not familiar with that entity framework, as I'm unfamiliar with the some of that syntax, but you should be able to use something like this:
public void AddToPatient(Patient newPatient)
{
SMBASchedulerEntities dbContext = new SMBASchedulerEntities();
if (newPatient.ID.ToString() != "0")
{//Update the record
Patient updatePatient = dbContext.Patients.Single(p => p.ID == newPatient.ID);
updatePatient.FirstName = newPatient.FirstName;
updatePatient.LastName = newPatient.LastName;
...
...
dbContext.SubmitChanges();
}
else
{//Insert a new record
Patient insertPatient = new Patient();
insertPatient.FirstName = newPatient.FirstName;
insertPatient.LastName = newPatient.LastName;
...
...
dbContext.Patients.InsertOnSubmit(insertPatient);
dbContext.SubmitChanges();
}
}
To put this another way, check to see if you need to insert or update a new patient first, before inserting it every time.

C# : set default payment method in stripe

I am new in stripe, how can we set default payment method in stripe.
And can we pass cardId/sourceId to charge customer along with customerId.
Code:-
private static async Task<string> ChargeCustomer(string customerId)
{
return await System.Threading.Tasks.Task.Run(() =>
{
var myCharge = new StripeChargeCreateOptions
{
Amount = 50,
Currency = "gbp",
Description = "Charge for property sign and postage",
CustomerId = customerId
};
var chargeService = new StripeChargeService();
var stripeCharge = chargeService.Create(myCharge);
return stripeCharge.Id;
});
}
And 1 more question, how to get charge-list, I am using below code but getting exception(conversion error):-
private IEnumerable<StripeCharge> GetChargeList()
{
var chargeService = new StripeChargeService();
return chargeService.List();
}
This is what I ended up doing. Not sure why Stripe Checkout didn't set the card for the subscription setup as the default. Anyway, this fires triggered from the payment_intent.succeeded web hook. Sure there is a better way, but...
var customerService = new CustomerService(Configs.STRIPE_SECRET_KEY);
var c = customerService.Get(pi.CustomerId);
if (!string.IsNullOrEmpty(c.InvoiceSettings.DefaultPaymentMethodId)) {
status = "already has default payment method, no action";
hsc = HttpStatusCode.OK;
return;
}
var paymentMethodService = new PaymentMethodService(Configs.STRIPE_SECRET_KEY);
var lopm = paymentMethodService.ListAutoPaging(options: new PaymentMethodListOptions {
CustomerId = pi.CustomerId,
Type = "card"
});
if (!lopm.Any()) {
status = "customer has no payment methods";
hsc = HttpStatusCode.BadRequest;
return;
}
var pm = lopm.FirstOrDefault();
customerService.Update(pi.CustomerId, options: new CustomerUpdateOptions {
InvoiceSettings = new CustomerInvoiceSettingsOptions {
DefaultPaymentMethodId = pm.Id
}
});
hsc = HttpStatusCode.OK;
return;
We can pass cardId/BankAccountId/TokenId/SourceId in SourceTokenOrExistingSourceId property of StripeChargeCreateOptions,
private static async Task<string> ChargeCustomer(string customerId, string cardId)
{
try
{
return await System.Threading.Tasks.Task.Run(() =>
{
var myCharge = new StripeChargeCreateOptions
{
Amount = 50,
Currency = "gbp",
Description = "Charge for property sign and postage",
CustomerId = customerId,
SourceTokenOrExistingSourceId = cardId
};
var chargeService = new StripeChargeService();
var stripeCharge = chargeService.Create(myCharge);
return stripeCharge.Id;
});
}
catch(Exception ex)
{
return "";
}
}
To set/change default payment method:-
public void ChangeDefaultPayment(string customerId, string sourceId)
{
var myCustomer = new StripeCustomerUpdateOptions();
myCustomer.DefaultSource = sourceId;
var customerService = new StripeCustomerService();
StripeCustomer stripeCustomer = customerService.Update(customerId, myCustomer);
}
Still looking for how to get charge-list.

How save my changes to database with Entity Framework?

I was wondering if someone can help me in this case: I'm trying to save my changes to database, so I use a context, and I have _tblcustomer which is an object from my entity classes, here is my code:
private void BtnSaveCustomer_Click(object sender, EventArgs e)
{
if (CustomerMode == (int)CustomerModeOperaton.insert)
{
if (!string.IsNullOrWhiteSpace(TxtCustomerName.Text) ||
!string.IsNullOrWhiteSpace(TxtLastName.Text) ||
!string.IsNullOrWhiteSpace(TxtCustomerCode.Text))
{
tblCustomer Customer = new tblCustomer();
Customer.CustomerName = TxtCustomerName.Text.ToString();
Customer.CustomerCode = Convert.ToInt32(TxtCustomerCode.Text);
if (!string.IsNullOrWhiteSpace(TxtCustomerAdress.Text))
{
Customer.CustomerAdresse = TxtCustomerAdress.Text.ToString();
}
else
{
Customer.CustomerAdresse = null;
}
if (!string.IsNullOrWhiteSpace(TxtCustomerPhone.Text))
{
Customer.CustomerPhone = Convert.ToInt32(TxtCustomerPhone.Text);
}
else
{
Customer.CustomerPhone = null;
}
if (!string.IsNullOrWhiteSpace(TxtCustomerCellphone.Text))
{
Customer.CustomerCellPhone = Convert.ToInt32(TxtCustomerCellphone.Text);
}
else
{
Customer.CustomerCellPhone = null;
}
Customer.CustomerLastName = TxtLastName.Text.ToString();
Customer.CustomerID = Guid.NewGuid();
Customer.rowguid = Guid.NewGuid();
using (var Context = new FactorEntities())
{
Context.tblCustomers.Add(Customer);
Context.SaveChanges();
}
MessageBox.Show("اطلاعات مشتری در سیستم ثبت شد");
// status=1;
}
else
{
MessageBox.Show("نام مشتری و نام خانوادگی و کد مشتری باید پر شوند");
}
}
else
{
using (var context = new FactorEntities())
{
var CustomerDetaile = context.tblCustomers.Find(CustomerID);
_tblCustomer = new tblCustomer();
_tblCustomer.CustomerID = CustomerDetaile.CustomerID;
_tblCustomer.CustomerName = TxtCustomerName.Text;
_tblCustomer.CustomerLastName = TxtLastName.Text;
_tblCustomer.CustomerCode = Convert.ToInt32(TxtCustomerCode.Text);
_tblCustomer.CustomerAdresse = TxtCustomerAdress.Text;
context.SaveChanges();
}
MessageBox.Show("اطلاعات در سیستم ثبت شد");
}
}
Main part is here:
using (var context =new FactorEntities())
{
var CustomerDetaile = context.tblCustomers.Find(CustomerID);
_tblCustomer = new tblCustomer();
_tblCustomer.CustomerID = CustomerDetaile.CustomerID;
_tblCustomer.CustomerName = TxtCustomerName.Text;
_tblCustomer.CustomerLastName = TxtLastName.Text;
_tblCustomer.CustomerCode = Convert.ToInt32(TxtCustomerCode.Text);
_tblCustomer.CustomerAdresse = TxtCustomerAdress.Text;
context.SaveChanges();
}
but I don't know why it does not save yet...
Thanks in advance.
I don't see anywhere you add the _tblCustomer object in the context, with something like in your "main part"
context.tblCustomers.Add(_tblCustomer);
If instead you want to modify an exiting object, you should write instead
CustomerDetaile.CustomerId = "the new id"
And now it will be saved.
What you are doing now, is creating a new customer, assigning its values and do nothing with it.
To save new object to database in this case you would need to use:
var obj = context.TableName.New();
obj.Name = "BLA";
obj.Salary = 32;
context.TableName.Add(obj);
context.SaveChanges();
To edit existing object in the table:
var obj = context.TableName.Find(id);
obj.Name = "BLA";
obj.Salary = 32;
context.Entry(obj).State = EntryState.Modified;
context.SaveChanges();
It always worked for me=) Apply this concept to your code and it may work.
I shouldn't make a new ... I have to write code for my select... I got it by #ChristianKouamé help here is my code:
using (var context =new FactorEntities())
{
var CustomerDetaile= context.tblCustomers.Find(CustomerID);
CustomerDetaile.CustomerID = CustomerID;
if (!string.IsNullOrWhiteSpace(TxtCustomerName.Text))
{
CustomerDetaile.CustomerName = TxtCustomerName.Text;
}
CustomerDetaile.CustomerLastName = TxtLastName.Text;
CustomerDetaile.CustomerAdresse = TxtCustomerAdress.Text;
CustomerDetaile.CustomerCellPhone = Convert.ToInt32(TxtCustomerCellphone.Text);
CustomerDetaile.CustomerCode = Convert.ToInt32(TxtCustomerCode.Text);
context.SaveChanges();
}
thanks a lot.

How to Update campaign in Bing Ads?

For Update campaign I am using this Code
public async Task<List<long?>> updateCampaign(Campaign campaign,string status)
{
try
{
campaign.Status = (CampaignStatus)(int)Enum.Parse(typeof(CampaignStatus), status);
var request = new UpdateCampaignsRequest
{
Campaigns = new Campaign[] { campaign },
CustomerId = "xxxxxx",
UserName = "something#outlook.com",
Password = "something#123",
ApplicationToken = "myApplicationToken",
CustomerAccountId = "123456",
DeveloperToken = "1234567890"
};
CampaignService = new ServiceClient<ICampaignManagementService>(_authorizationData);
CampaignService.RefreshOAuthTokensAutomatically = false;
var result = (await CampaignService.CallAsync((s, r) => s.UpdateCampaignsAsync(r), request));
if (result.TrackingId != null)
{
return result.CampaignIds.ToList();
}
else
{
return new List<long?>();
}
}
catch (Exception ex)
{
ErrorLog.log(ex);
return new List<long?>();
}
}
When I run this code, I got this error "Invalid client data. Check the SOAP fault details for more information"
thanks.
For updating the Campaign we can use "BulkServiceManager" for bulk updating of the campaign,you can use this service single campaign update also.
public async Task<List<long?>> updateCampaign(List<Campaign> campaigns)
{
try
{
var listBulkCampaign = new List<BulkCampaign>();
foreach (var campaign in campaigns)
{
var _bulkCampaign = new BulkCampaign()
{
Campaign = campaign
};
listBulkCampaign.Add(_bulkCampaign);
}
BulkServiceManager bulkServiceManager = new BulkServiceManager(_authorizationData);
string fileName = bingCampaignUpdate.csv;
var campaigns = (await bulkServiceManager.UploadEntitiesAsync(new EntityUploadParameters
{
Entities = listBulkCampaign,
OverwriteResultFile = true,
ResultFileDirectory = FileDirectory,
ResultFileName = fileName,
ResponseMode = ResponseMode.ErrorsAndResults
})).OfType<BulkCampaign>().ToList();
return new List<long?>();
}
catch (Exception ex)
{
ErrorLog.log(ex);
return new List<long?>();
}
}
You have to download .csv report and update the Campaigns.
I hope it helps you

Categories

Resources