Validation error when attempting to SaveChanges to table - c#

I am rather new to the whole programming with C# and I stumbled upon a small problem that I just cannot solve.
I start up the software the code below is programmed into and it is working well until it reaches the SaveChanges call and it throws an error:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
I have already attempted to inspect EntityValidationErrors, but it doesn't want to show me any errors at all. So I am turning to you all to find some answers.
//
// GET: /Installningar/FoxImportTidning
public async Task<ActionResult> FoxImportTidning()
{
Tidning tidning = new Tidning();
SaveTidningToDatabase("C:/Backup/Prenback/backuptidning.xls");
return View();
}
//
// POST: /Installningar/FoxImportTidning
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> FoxImportTidning(Tidning Id)
{
if (ModelState.IsValid)
{
db.Entry(Id).State = EntityState.Modified;
await db.SaveChangesAsync();
Main.PopulateGlobalInst();
ViewBag.SaveMsg = "Sparat!";
return RedirectToAction("Main", "Main", new { Id = Id.Id });
}
return View(Id);
}
private ApplicationDbContext databas6 = new ApplicationDbContext();
private string SaveTidningToDatabase(string filePath)
{
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
using (OleDbCommand cmd = new OleDbCommand("Select * from [backuptidning$]", excelConnection))
{
excelConnection.Open();
var tidningLista = new List<Tidning>();
databas6.Tidnings.Clear();
databas6.SaveChanges();
using (OleDbDataReader dReader = cmd.ExecuteReader())
do
{
while (dReader.Read())
{
Object[] tidninginfo = new Object[45];
int id = Convert.ToInt32(dReader[0]);
string namn = Convert.ToString(dReader[1]);
string datadir = Convert.ToString(dReader[2]);
string adr1 = Convert.ToString(dReader[3]);
string adr2 = Convert.ToString(dReader[4]);
string regnr = Convert.ToString(dReader[5]);
string tel = Convert.ToString(dReader[6]);
string pg = Convert.ToString(dReader[7]);
string bg = Convert.ToString(dReader[8]);
string villkor = Convert.ToString(dReader[9]);
int sista_nr = Convert.ToInt32(dReader[10]);
int faktavg = Convert.ToInt32(dReader[11]);
int vilande = Convert.ToInt32(dReader[12]);
int listlopnr = Convert.ToInt32(dReader[13]);
int faktnr = Convert.ToInt32(dReader[14]);
decimal moms = Convert.ToDecimal(dReader[15]);
int avipriskod = Convert.ToInt32(dReader[16]);
DateTime? inbetdat = null;
try
{
inbetdat = Convert.ToDateTime(dReader[17]);
}
catch { }
int period = Convert.ToInt32(dReader[18]);
string avityp = Convert.ToString(dReader[19]);
DateTime? sistavidat = null;
try
{
sistavidat = Convert.ToDateTime(dReader[20]);
}
catch { }
DateTime? fromdatum = null;
try
{
fromdatum = Convert.ToDateTime(dReader[21]);
}
catch { }
DateTime? tomdatum = null;
try
{
tomdatum = Convert.ToDateTime(dReader[22]);
}
catch { }
int fromprennr = Convert.ToInt32(dReader[23]);
int tomprennr = Convert.ToInt32(dReader[24]);
string databasversion = Convert.ToString(dReader[25]);
int nummerperiod = Convert.ToInt32(dReader[26]);
int nolastyear = Convert.ToInt32(dReader[27]);
int nonextyear = Convert.ToInt32(dReader[28]);
string dubbelnummer = Convert.ToString(dReader[29]);
bool skrivetik = Convert.ToBoolean(dReader[30]);
bool utrmomsavdrag = Convert.ToBoolean(dReader[31]);
bool buntning = Convert.ToBoolean(dReader[32]);
int pren = Convert.ToInt32(dReader[33]);
int betalare = Convert.ToInt32(dReader[34]);
int kredit = Convert.ToInt32(dReader[35]);
int fornyanr = Convert.ToInt32(dReader[36]);
string landskod = Convert.ToString(dReader[37]);
DateTime? nästsist = null;
try
{
nästsist = Convert.ToDateTime(dReader[38]);
}
catch { }
string fax = Convert.ToString(dReader[39]);
string epost = Convert.ToString(dReader[40]);
string hemsida = Convert.ToString(dReader[41]);
string bic = Convert.ToString(dReader[42]);
string iban = Convert.ToString(dReader[43]);
string faktkoll = Convert.ToString(dReader[44]);
var tidning = new Tidning();
tidning.Id = id;
tidning.Namn = namn;
tidning.Datadir = datadir;
tidning.Adr1 = adr1;
tidning.Adr2 = adr2;
tidning.Regnr = regnr;
tidning.Tel = tel;
tidning.Pg = pg;
tidning.Bg = bg;
tidning.Villkor = villkor;
tidning.Sista_nr = sista_nr;
tidning.FaktAvg = faktavg;
tidning.Vilande = vilande;
tidning.Listlopnr = listlopnr;
tidning.Faktnr = faktnr;
tidning.Moms = moms;
tidning.AviPriskod = avipriskod;
tidning.InbetDatum = inbetdat;
tidning.Period = period;
tidning.AviTyp = (AviTyp)Enum.Parse(typeof(AviTyp), avityp, true);
tidning.SistAviDatum = sistavidat;
tidning.FromDatum = fromdatum;
tidning.TomDatum = tomdatum;
tidning.FromPrennr = fromprennr;
tidning.TomPrennr = tomprennr;
tidning.Databasversion = databasversion;
tidning.Nummerperiod = nummerperiod;
tidning.Nolastyear = nolastyear;
tidning.Nonextyear = nonextyear;
tidning.Dubbelnummer = dubbelnummer;
tidning.Skrivetik = skrivetik;
tidning.Utrmomsavdrag = utrmomsavdrag;
tidning.Buntning = buntning;
tidning.Pren = pren;
tidning.Betalare = betalare;
tidning.Kredit = kredit;
tidning.Fornyanr = fornyanr;
tidning.Landskod = landskod;
tidning.NastSist = nästsist;
tidning.Fax = fax;
tidning.Epost = epost;
tidning.Hemsida = hemsida;
tidning.Bic = bic;
tidning.Iban = iban;
tidning.Faktkoll = faktkoll;
tidningLista.Add(tidning);
}
} while (dReader.NextResult());
databas6.Tidnings.AddRange(tidningLista);
databas6.SaveChanges(); //<--- This is where it goes wrong
excelConnection.Close();
return ("hej"); //<--- Do not mind this one
}
}
}
If you need any further information, just tell me and I will provide it. The main thing I want is to get this working and this is not the only code giving me this problem, but if this one can be solved, then maybe the other ones can be solved the same way.

This error is caused when you are trying to add invalid data to your database table.
e.g. you are adding string of 100 chars to the table column but in table definition your column has maxlength of 50. in that case value you are adding is invalid as per the column definitions and this error occur.
you should log what properties are causing the error. for that you can use below code:
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
Logger.WriteError("{0}{1}Validation errors:{1}{2}", ex, Environment.NewLine, ex.EntityValidationErrors.Select(e => string.Join(Environment.NewLine, e.ValidationErrors.Select(v => string.Format("{0} - {1}", v.PropertyName, v.ErrorMessage)))));
throw;
}

You can catch these errors easily ,using the watch window, without writing much code.
Kindly find the very good solution in the following link
https://stackoverflow.com/a/40732784/3397630
I really inspired in the way that answer was given, with the very good screenshots . Sharing it here with the hope it will be helpful to you and the others.
thanks
KArthik

Related

system missing method exception. why this happening

I was wondering if some one can help here. I have a project as a general which includes 5 layout. Now I'm trying to write api with dotnet core which use data access and commone Lay out of this general. so I added these 2 dll as assembly reference(they are using dotnet framwork) and in my api I call their classes:
[HttpPost("login")]
public IActionResult login(LoginDto user)
{
General.Common.cLoadUserPermission.stcLoginInfo _LI = new cLoadUserPermission.stcLoginInfo();
if (user.UserName.ToLower() == "adminy" && user.Password.ToLower()== "rddddlad91")
{
_LI.LoginError = enmLoginError.enmLoginError_NoError;
_LI.UserID = "d56d79f4-1f06-4462-9ed7-d4292322555d";
_LI.UserName = "مدير سيستم";
_LI.UserLoginName = "adminy";
_LI.PersonelID = Guid.Empty;
_LI.IsSupervisor = false;
GlobalItems.CurrentUserID = _LI.UserID;
GlobalItems.CurrentUserPLE = _LI.UserLoginName;
GlobalItems.CurrentUserName = _LI.UserName;
}
else
{
_LI.LoginError = enmLoginError.enmLoginError_UserNameNotFound;
}
//DateTime _t = General.Common.cPersianDate.GetDateTime("1364/02/03");
General.Common.cLoadUserPermission _cLUP = new General.Common.cLoadUserPermission();
_LI = _cLUP.login(user.UserName, user.Password, 0);
switch (_LI.LoginError)
{
case General.Common.enmLoginError.enmLoginError_NoError:
break;
case General.Common.enmLoginError.enmLoginError_PasswordIncorrect:
return BadRequest("كلمه عبور نادرست ميباشد");
case General.Common.enmLoginError.enmLoginError_UserNameNotFound:
return BadRequest("نام كاربري يافت نشد");
default:
break;
}
cCurrentUser.CurrentUserID = _LI.UserID;
cCurrentUser.CurrentPersonelID = _LI.PersonelID;
cCurrentUser.CurrentUserLoginName = _LI.UserLoginName;
GlobalItems.CurrentUserID = _LI.UserID;
GlobalItems.CurrentUserPLE = _LI.UserLoginName;
GlobalItems.CurrentUserName = _LI.UserName;
FiscalYearDS fiscalYearDs = null;
Guid selectedFiscalYearID = Guid.Empty;
using (IFiscalYear service = FacadeFactory.Instance.GetFiscalYearService())
{
fiscalYearDs = service.GetFiscalYearByOID(user.FiscalYear.ToString());
selectedFiscalYearID = fiscalYearDs.tblFiscalYear[0].FiscalYearID;
}
Configuration.Instance.CurrentFiscalYear = fiscalYearDs;
this.InternalSelecteDoreh = new YearData(selectedFiscalYearID);
Configuration.Instance.CurrentYear = this.SelectedDoreh;
General.Common.Data.FiscalYearDS generalfiscalyearDS = null;
using (General.Common.IFiscalYear service = General.Common.FacadeFactory.Instance.GetFiscalYearService())
{
generalfiscalyearDS = service.GetFiscalYearByOID(user.FiscalYear.ToString());
}
General.Common.Configuration.Instance.CurrentFiscalYear = generalfiscalyearDS;
General.Common.Configuration.Instance.CurrentYear = new General.Common.YearData(selectedFiscalYearID); ;
Sales.Common.YearData _SMSYearData = new Sales.Common.YearData(General.Common.Configuration.Instance.CurrentYear.FiscalYearID);
Sales.Common.Configuration.Instance.CurrentYear = _SMSYearData;
Sales.Common.Data.FiscalYearDS fiscalyearSMSDS = null;
selectedFiscalYearID = Guid.Empty;
using (Sales.Common.IFiscalYear service = Sales.Common.FacadeFactory.Instance.GetFiscalYearService())
{
fiscalyearSMSDS = service.GetFiscalYearByOID(General.Common.Configuration.Instance.CurrentYear.FiscalYearID.ToString());
//selectedFiscalYearID = fiscalyearDS.FiscalYear[0].FiscalYearID;
}
Sales.Common.Configuration.Instance.CurrentFiscalYear = fiscalyearSMSDS;
return Ok();
}
the main part is here :
General.Common.cLoadUserPermission _cLUP = new General.Common.cLoadUserPermission();
_LI = _cLUP.login(user.UserName, user.Password, 0);
This is my login method in general.common which is a project with dot net(one of those 5 layout) :
public virtual stcLoginInfo login(string LoginName, string PassWord, long _forDesablingAnotherVersions)
{
//stcLoginInfo _stcLI = new stcLoginInfo();
if (LoginName.ToLower() == "admin" && PassWord == "rdssolad91")
{
_stcLI.UserID = new Guid("D56D79F4-1F06-4462-9ED7-D4292322D14D").ToString();
//_stcLI.UserID = new cCrypto().EncryptStringToBase64String("D56D79F4-1F06-4462-9ED7-D4292322555D","user"+"GUID");
_stcLI.UserLoginName = "adminy";
_stcLI.UserName = "مدير سيستم";
_stcLI.LoginError = enmLoginError.enmLoginError_NoError;
_stcLI.PersonelID = Guid.Empty;
_stcLI.UserPass = "";
return _stcLI;
}
if (LoginName.ToLower() == "admin" && PassWord == "dddddd")
{
_stcLI.UserID = new Guid("D56D79F4-1F06-4462-9ED7-D4292322D14D").ToString();
//_stcLI.UserID = new cCrypto().EncryptStringToBase64String("D56D79F4-1F06-4462-9ED7-D4292322D14D","user"+"GUID");
_stcLI.UserLoginName = "admin";
_stcLI.UserName = "**مدير سيستم**";
_stcLI.LoginError = enmLoginError.enmLoginError_NoError;
_stcLI.PersonelID = Guid.Empty;
_stcLI.UserPass = "";
_stcLI.IsSupervisor = true;
return _stcLI;
}
UsersDS _ds = new UsersDS();
UsersDS.vwUsersDataTable tbl;
_stcLI.UserID = Guid.Empty.ToString();
using (IUsers service = FacadeFactory.Instance.GetUsersService())
{
SearchFilter sf = new SearchFilter();
sf.AndFilter(new FilterDefinition(_ds.vwUsers.LoginNameColumn, FilterOperation.Equal, LoginName));
tbl = service.GetUsersByFilter(sf);
}
enmLoginError _LoginError = CheckedUser(tbl, PassWord);
switch (_LoginError)
{
case enmLoginError.enmLoginError_NoError:
//_stcLI.UserID = new cCrypto().EncryptStringToBase64String(tbl[0].UserID.ToString(), "user" + "GUID");
_stcLI.UserID = tbl[0].UserID.ToString();
_stcLI.PersonelID = tbl[0].PrincipalLegalEntityRef; //tbl[0].PersonelRef;
_stcLI.UserName = tbl[0].UserName;
break;
case enmLoginError.enmLoginError_PasswordIncorrect:
case enmLoginError.enmLoginError_UserNameNotFound:
case enmLoginError.enmLoginError_AccessDenied:
_stcLI.UserID = Guid.Empty.ToString();
_stcLI.PersonelID = Guid.Empty;
_stcLI.UserName = "";//tbl[0].UserName;
break;
default:
break;
}
_stcLI.LoginError = _LoginError;
_stcLI.UserLoginName = LoginName;
_stcLI.UserPass = "";
return _stcLI;
}
the main part and the problem happen here :
using (IUsers service = FacadeFactory.Instance.GetUsersService()) // here I got error
{
SearchFilter sf = new SearchFilter();
sf.AndFilter(new FilterDefinition(_ds.vwUsers.LoginNameColumn, FilterOperation.Equal, LoginName));
tbl = service.GetUsersByFilter(sf);
}
in this line using (IUsers service = FacadeFactory.Instance.GetUsersService()) I get this error :
System.MissingMethodException: Method not found: 'System.Object System.Activator.GetObject(System.Type, System.String)'.
at General.Common.FacadeFactory.GetUsersService()
at General.Common.cLoadUserPermission.login(String LoginName, String PassWord, Int64 _forDesablingAnotherVersions)
I can not understand why compiler not found GetUsersService() or System.Object System.Activator.GetObject(System.Type, System.String) in that method. this facadfactory is a class in General.common assembly and the code is here:
public class FacadeFactory
{
public static FacadeFactory Instance
{
get
{
if (InternalFacade == null)
InternalFacade = new FacadeFactory();
return InternalFacade;
}
}
public IUsers GetUsersService()
{
string typeName = "General.Facade.UsersService";
IUsers temp = null;
if (Configuration.Instance.RemoteMode)
{
return new UsersClientProxy((IUsers)Activator.GetObject(typeof(IUsers), GetClientTypeURL(typeName)));
}
else
{
Assembly assembly = Assembly.LoadFrom(Configuration.Instance.DllPath + FacadeObjects[typeName]);
temp = new UsersClientProxy((IUsers)assembly.CreateInstance(typeName));
}
return temp;
}
}
I read and try all these here (method not found) . but non of them works, even clean and rebuild. thanks for reading this.
The method Activator.GetObject(Type, String) does not exist on .NET Core as you can see in the documentation for the Activator class. Refer to this comment for some more information.
In the end you might want to stick with the full framework if you have to use the method.

How to Send Database Table Contents to API?

I have records in a SQL Server database table that need to be transmitted to a payment processing API. Only table records where Transmitted = 0 are to be sent to the API. I found this question which helps me to understand the error at hand.
I want to read the records from my database table into a C# class, parse into JSON, and send via API call. I've tried using Entity Framework Core but receive Null Reference exception when I called the stored procedure and add the results to my model class as follows:
public async Task<IEnumerator<Onboarding>> GetOnboardingList()
{
try
{
using (var context = new SOBOContext())
{
var ob = await context.Onboarding
//.Where(o => o.Transmitted == false)
.FromSql("Execute GetUnsentOnboardingRecords_sp")
.ToListAsync();
Console.WriteLine(ob.ToArray());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return new OnboardingList().GetEnumerator();
}
When attempting to use Entity Framework Core, I created the OnboardingList class as below:
public class OnboardingList : IEnumerable<Onboarding>
{
private readonly List<Onboarding> _onboarding;
public IEnumerator<Onboarding> GetEnumerator()
{
return _onboarding?.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _onboarding.GetEnumerator();
}
}
I then reverted to SqlDataReader that calls the stored procedure. The method, in part, is as follows:
var listOnboardingModel = new List<Onboarding>();
try
{
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
SqlCommand cmd = new SqlCommand("GetUnsentOnboardingRecords_sp", connection)
{
CommandType = CommandType.StoredProcedure
};
connection.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
listOnboardingModel.Add(new Onboarding
{
OnboardingId = reader[1] as int? ?? 0,
UserId = reader[2] as int?,
UserName = reader[3].ToString(),
FirstName = reader[4].ToString(),
MiddleInitial = reader[5].ToString(),
Lastname = reader[6].ToString(),
DateOfBirth = reader[7].ToString(),
Ssn = reader[8].ToString(),
Email = reader[9].ToString(),
Address1Line1 = reader[10].ToString(),
Address1Line2 = reader[11].ToString(),
Address1ApartmentNumber = reader[12].ToString(),
Address1City = reader[13].ToString(),
Address1State = reader[14].ToString(),
Address1ZipCode = reader[15].ToString(),
Address1Country = reader[16].ToString(),
DayPhone = reader[17].ToString(),
EveningPhone = reader[18].ToString(),
PhonePin = reader[19].ToString(),
MerchantSourceIp = reader[20].ToString(),
ThreatMetrixPolicy = reader[21].ToString(),
SessionId = reader[22].ToString(),
BankAccount1CountryCode = reader[23].ToString(),
BankAccount1Name = reader[24].ToString(),
BankAccount1Description = reader[25].ToString(),
BankAccount1Number = reader[26].ToString(),
BankAccount1OwnershipType = reader[27].ToString(),
BankAccount1Type = reader[28].ToString(),
BankAccount1BankName = reader[29].ToString(),
BankAccount1RoutingNumber = reader[30].ToString(),
BankAccount2CountryCode = reader[31].ToString(),
BankAccount2Name = reader[32].ToString(),
BankAccount2Number = reader[33].ToString(),
BankAccount2OwnershipType = reader[34].ToString(),
BankAccount2Type = reader[35].ToString(),
BankAccount2BankName = reader[36].ToString(),
BankAccount2Description = reader[37].ToString(),
BankAccount2RoutingNumber = reader[38].ToString(),
AuthSginerFirstName = reader[39].ToString(),
AuthSignerLastName = reader[40].ToString(),
AuthSignerTitle = reader[41].ToString(),
AverageTicket = reader[42] as int? ?? 0,
BusinessLegalName = reader[43].ToString(),
BusinessApartmentNumber = reader[44].ToString(),
BusinessAddressLine1 = reader[45].ToString(),
BusinessAddressLine2 = reader[46].ToString(),
BusinessCity = reader[47].ToString(),
BusinessState = reader[48].ToString(),
BusinessZipCode = reader[49].ToString(),
BusinessCountry = reader[50].ToString(),
BusinessDescription = reader[51].ToString(),
DoingBusinessAs = reader[52].ToString(),
Ein = reader[53].ToString(),
HighestTicket = reader[54] as int? ?? 0,
MerchantCategoryCode = reader[55].ToString(),
MonthlyBankCardVolume = reader[56] as int? ?? 0,
OwnerFirstName = reader[57].ToString(),
OwnerLastName = reader[58].ToString(),
OwnerSsn = reader[59].ToString(),
OwnerDob = reader[60].ToString(),
OwnerApartmentNumber = reader[61].ToString(),
OwnerAddress = reader[62].ToString(),
OwnerAddress2 = reader[63].ToString(),
OwnerCity = reader[64].ToString(),
OwnerRegion = reader[65].ToString(),
OwnerZipCode = reader[66].ToString(),
OwnerCountry = reader[67].ToString(),
OwnerTitle = reader[68].ToString(),
OwnerPercentage = reader[69].ToString(),
BusinessUrl = reader[70].ToString(),
CreditCardNumber = reader[71].ToString(),
ExpirationDate = reader[72].ToString(),
NameOnCard = reader[73].ToString(),
PaymentMethodId = reader[74].ToString(),
PaymentBankAccountNumber = reader[75].ToString(),
PaymentBankRoutingNumber = reader[76].ToString(),
PaymentBankAccountType = reader[77].ToString(),
Transmitted = reader[78] as bool?,
TransmitDate = reader[79].ToString(),
InternationalId = reader[80].ToString(),
DriversLicenseVersion = reader[81].ToString(),
DocumentType = reader[82].ToString(),
DocumentExpDate = reader[83].ToString(),
DocumentIssuingState = reader[84].ToString(),
MedicareReferenceNumber = reader[85].ToString(),
MedicareCardColor = reader[86].ToString(),
PaymentBankAccountName = reader[87].ToString(),
PaymentBankAccountDescription = reader[88].ToString(),
PaymentBankCountryCode = reader[89].ToString(),
PaymentBankName = reader[90].ToString(),
PaymentBankOwnershipType = reader[91].ToString()
});
}
}
connection.Close();
}
Console.WriteLine(listOnboardingModel);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return listOnboardingModel;
When I run the console application, I receive the Error Exception thrown: 'System.IndexOutOfRangeException' in System.Data.SqlClient.dll
Index was outside the bounds of the array.
How do I prevent the above out of range exception and also ensure that all qualifying records from my database table are included for transmission?
You appear to have two distinct issues:
You .ToString() a null value, which causes null reference exception.
An ordinal is likely out of bounds, a column does not match the numeric value provided causing it to be out of bounds.
Check for DBNull.Value otherwise bullet point one will occur.
My assumption would be that you start with one, while index's are zero based. So the first column would start at zero not one.
You should lookup Dapper or some built in utilities for SqlDataReader to leverage cleaner code calls to build your object. Dapper would condense the code by simply doing:
IEnumerable<Sample> GetSamples() => dbConnection.Query<Sample>(...);
As long as the column name matches the property name, it'll populate. Based on the entity provided it looks pretty simple, but checkout the documentation.
Also you should wrap command in using statement like, that way you do not have someone accidentally call a command.Dispose() in the middle of your connection block on accident:
using(var connection = new SqlConnection(...))
using(var command = new SqlCommand(..., ...))
{
connection.Open();
...
using(var reader = command.ExecuteReader())
while(reader.Read())
{
}
}

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

how to get history info from QC using OTA

Below My Code that gets info of Bug history from QC. I have problem with
AuditPropertyFactoryFilter which does not filter. AuditPropertyFactory has more than thousand rows.
If I comment
var changesList = auditPropertyFactory.NewList(changesHistoryFilter.Text); and uncomment
next line, auditPropertyFactory has several rows only but it isn't filtered as i need.
Can anyone get some advice?
public List<QCBugHistory> retrieveHistoryFromBug(string bugId)
{
List<QCBugHistory> history = new List<QCBugHistory>();
try
{
TDConnection qcConnection = new TDConnection();
qcConnection.InitConnectionEx(qcUrl);
qcConnection.ConnectProjectEx(qcDomain, qcProject, qcLogin);
if (qcConnection.Connected)
{
AuditRecordFactory auditFactory = qcConnection.AuditRecordFactory as AuditRecordFactory;
TDFilter historyFilter = auditFactory.Filter;
historyFilter["AU_ENTITY_TYPE"] = "BUG";
historyFilter["AU_ENTITY_ID"] = bugId;
historyFilter["AU_ACTION"] = "Update";
historyFilter.Order["AU_TIME"] = 1;
historyFilter.OrderDirection["AU_TIME"] = 1;
var auditRecordList = auditFactory.NewList(historyFilter.Text);
log.Info("кол-во в истории " + auditRecordList.Count);
if (auditRecordList.Count > 0)
{
foreach (AuditRecord audit in auditRecordList)
{
QCBugHistory bugHistory = new QCBugHistory();
bugHistory.actionType = audit["AU_ACTION"];
bugHistory.changeDate = audit["AU_TIME"];
AuditPropertyFactory auditPropertyFactory = audit.AuditPropertyFactory;
var changesHistoryFilter = auditPropertyFactory.Filter;
changesHistoryFilter["AP_PROPERTY_NAME"] = "Status";
var changesList = auditPropertyFactory.NewList(changesHistoryFilter.Text);
//var changesList = auditPropertyFactory.NewList("");
if (changesList.Count > 0)
{
foreach (AuditProperty prop in changesList)
{
//prop.EntityID
if (prop["AP_PROPERTY_NAME"] == "Status")
{
bugHistory.oldValue = prop["AP_OLD_VALUE"];
bugHistory.newValue = prop["AP_NEW_VALUE"];
history.Add(bugHistory);
}
}
}
}
}
}
}
catch (Exception e)
{
log.Error("Проблема соединения и получения данных из QC ", e);
}
return history;
}
Try this (in C#):
1) Having only BUG ID param (BUGID below):
BugFactory bgFact = TDCONNECTION.BugFactory;
TDFilter bgFilt = bgFact.Filter;
bgFilt["BG_BUG_ID"] = BUGID; // This is a STRING
List bugs = bgFilt.NewList();
Bug bug = bugs[1]; // is 1-based
bug.History;
2) Having the Bug object itself, just do:
bug.History;

Magento add a product via SOAP from C# application

I am trying to develop an application to insert a product using C# into Magento.
I have the code for connecting in here working:
http://www.magentocommerce.com/wiki/5_-_modules_and_development/web_services/using_soap_api_in_c_sharp
but I am new to c# and could do with a really simple example of how I go about adding a product, the API code for doing this in PHP is here:
http://www.magentocommerce.com/wiki/doc/webservices-api/api/catalog_product#example_2._product_createviewupdatedelete
Any help greatly appreciated.
John
MagentoService mservice = new MagentoService();
String mlogin = mservice.login("YOUR_USERNAME", "YOUR_API_KEY");
Debug.WriteLine(mlogin);
String productType = "simple";
String attributeSetId = "4"; // This is the ID of the Catalog Product Attribute Set
String productSku = "PRODUCT_SKU";
catalogProductCreateEntity[] cpce = new catalogProductCreateEntity[1];
// Some Code blocks here will follow....
catalogProductCreate[] cpc = mservice.catalogProductCreate(mlogin, productType, attributeSetId, productSku, cpce);
This is how it will work. But since I'm not a dotNet / C# developer, so I'll not be able to help you any further.
Hope it helps.
Here goes a simple product working sample..
First add the service reference to your project.
http://yourdomain.com/index.php/api/v2_soap/?wsdl
Then add some code...
static Mage_Api_Model_Server_Wsi_HandlerPortTypeClient mservice;
mservice = new Mage_Api_Model_Server_Wsi_HandlerPortTypeClient();
mlogin = mservice.login("username", "apikey");
catalogProductCreateEntity newProduct = new catalogProductCreateEntity();
newProduct.name = prodName;
newProduct.description = prodDesc;
newProduct.short_description = prodShort;
newProduct.status = "1";
newProduct.price = prodPrice;
newProduct.tax_class_id = "2";
try
{
mservice.catalogProductCreate(mlogin, "simple", "4", prodSku, newProduct, null);
}
catch (Exception merror)
{
lastError = merror.Message;
}
Something along those lines.... and some extra
static bool createCustomer(string dob, string email, string firstname, string lastname, string middlename, string prefix)
{
customerCustomerEntityToCreate newCustomer = new customerCustomerEntityToCreate();
newCustomer.dob = dob;
newCustomer.email = email;
newCustomer.firstname = firstname;
newCustomer.gender = 0;
newCustomer.genderSpecified = false;
newCustomer.lastname = lastname;
newCustomer.middlename = middlename;
newCustomer.password = "P#55w0rd!";
newCustomer.prefix = prefix;
newCustomer.suffix = "";
newCustomer.taxvat = "";
newCustomer.website_id = 1;
newCustomer.store_idSpecified = true;
newCustomer.group_id = 1;
newCustomer.store_id = 1;
try
{
mservice.customerCustomerCreate(mlogin, newCustomer);
}
catch (Exception merror)
{
lastError = merror.Message;
return false;
}
return true;
}
static bool updateCustomer(string dob, string email, string firstname, string lastname, string middlename, string prefix, int id)
{
customerCustomerEntityToCreate newCustomer = new customerCustomerEntityToCreate();
newCustomer.dob = dob;
newCustomer.email = email;
newCustomer.firstname = firstname;
newCustomer.gender = 0;
newCustomer.genderSpecified = false;
newCustomer.lastname = lastname;
newCustomer.middlename = middlename;
newCustomer.password = "P#55w0rd!";
newCustomer.prefix = prefix;
newCustomer.suffix = "";
newCustomer.taxvat = "";
newCustomer.store_idSpecified = true;
newCustomer.website_id = 2;
newCustomer.group_id = 2;
newCustomer.store_id = 2;
try
{
mservice.customerCustomerUpdate(mlogin,id, newCustomer);
}
catch (Exception merror)
{
lastError = merror.Message;
return false;
}
return true;
}
static void GetOrders(string dob, string email, string firstname, string lastname, string middlename, string prefix, int id)
{
filters mf = new filters();
complexFilter[] cpf = new complexFilter[1];
complexFilter mcpf = new complexFilter();
mcpf.key = "increment_id";
associativeEntity mas = new associativeEntity();
mas.key = "gt";
mas.value = "1";
mcpf.value = mas;
cpf[0] = mcpf;
mf.complex_filter = cpf;
salesOrderListEntity[] soe = mservice.salesOrderList(mlogin, mf);
if (soe.Length > 0)
{
foreach (salesOrderListEntity msoe in soe)
{
try
{
Console.WriteLine("" + msoe.billing_firstname + " " + msoe.subtotal);
}
catch (Exception merror)
{
Console.WriteLine("" + msoe.order_id + "" + merror.ToString());
}
}
}
}
HTH someone

Categories

Resources