Update NetSuite Item Fulfillment Record with Tracking - c#

Need help adding "packages" to Item Fulfillment records to allow CSRs to see which items were shipped out under which tracking numbers. I can instantiate an ItemFulfillment record and an ItemFulfillmentPackageList object but the ItemFulfillmentPackageList object is always null - can't figure out how to add ItemFulfillmentPackage objects to the collection. I've tried various methods to assign to the ItemFulfillmentPackageList object without luck. Creating an array of ItemFulfillmentPakage objects is the latest attempt. Here's the code I have.
foreach (DataRow dr in dt.Rows)
{
try
{
ItemFulfillment ifRecord = new ItemFulfillment();
ifRecord.packageList = new ItemFulfillmentPackageList();
ifRecord.internalId = dr["Item Fulfillment Internal ID"].ToString();
ItemFulfillmentPackage ifp = new ItemFulfillmentPackage();
ifp.packageDescr = dr["Package Description"].ToString();
ifp.packageTrackingNumber = dr["detail_tracking_information"].ToString();
ItemFulfillmentPackageList ifpl = new ItemFulfillmentPackageList();
Object[] objPackages = new Object[1];
objPackages[1] = ifp;
ifpl = (ItemFulfillmentPackageList)objPackages;
ifRecord.packageList = ifpl;
ifpl.replaceAll = false;
WriteResponse res = _service.update(ifRecord);
if (res.status.isSuccess)
{
;
}
else if (res.status.isSuccessSpecified)
{
;
}
else
displayError(res.status.statusDetail);
}
catch (Exception ex)
{
_logger.error(String.Format("Error in updateItemFulfillment DR method. {0}", ex.Message));
throw new Exception(String.Format("Error in updateItemFulfillment DR method. {0}", ex.Message));
}
}

Make sure that you configure your search preferences so that bodyFieldsOnly is true; by default its set to false and it won't load sublist items.

I had the same issue. What I ended up doing is to create the Item Fulfillment transaction, with all related line level information and add this to NetSuite.
After this, I search for the Item Fulfillment that I just added and add the tracking information to the record. I do this by checking which package field is not equal to null and adding the information to that package list.
In my case, only one tracking number is used per order and all packages will contain this. You can modify this to add tracking references as needed.
The variable called "msg" is a shipment notification which contains all shipping information.
My code:
TransactionSearch xactionSearch = new TransactionSearch();
TransactionSearchBasic xactionBasic = new TransactionSearchBasic();
xactionBasic.createdFrom = new SearchMultiSelectField();
xactionBasic.createdFrom.#operator = SearchMultiSelectFieldOperator.anyOf;
xactionBasic.createdFrom.operatorSpecified = true;
xactionBasic.createdFrom.searchValue = new RecordRef[1];
xactionBasic.createdFrom.searchValue[0] = new RecordRef { internalId = "SO Internal ID"};
xactionSearch.basic = xactionBasic;
if (useTba = "true".Equals(_custSettings["login.useTba"]))
login();
SearchResult res = _service.search(xactionSearch);
ReadResponse res2 = new ReadResponse();
for (int i = 0; i < res.recordList.Length; i++)
{
if (res.recordList[i] is ItemFulfillment)
{
if (useTba = "true".Equals(_custSettings["login.useTba"]))
login();
res2 = _service.get(new RecordRef { internalId = ((ItemFulfillment)res.recordList[i]).internalId, type = RecordType.itemFulfillment, typeSpecified = true });
}
}
ItemFulfillment item = (ItemFulfillment)res2.record;
ItemFulfillment NewItem = new ItemFulfillment { internalId = item.internalId };
//Fedex
if (item.packageFedExList != null)
{
if (item.packageFedExList.packageFedEx != null)
{
for (int i = 0; i < item.packageFedExList.packageFedEx.Length; i++)
{
item.packageFedExList.packageFedEx[i].packageTrackingNumberFedEx = msg.trackingRef;
}
}
NewItem.packageFedExList = item.packageFedExList;
}
if (item.packageList != null)
{
if (item.packageList.package != null)
{
for (int i = 0; i < item.packageList.package.Length; i++)
{
item.packageList.package[i].packageTrackingNumber = msg.trackingRef;
}
}
NewItem.packageList = item.packageList;
}
//UPS
if (item.packageUpsList != null)
{
if (item.packageUpsList.packageUps != null)
{
for (int i = 0; i < item.packageUpsList.packageUps.Length; i++)
{
item.packageUpsList.packageUps[i].packageTrackingNumberUps = msg.trackingRef;
}
}
NewItem.packageUpsList = item.packageUpsList;
}
//Usps
if (item.packageUspsList != null)
{
if (item.packageUspsList.packageUsps != null)
{
for (int i = 0; i < item.packageUspsList.packageUsps.Length; i++)
{
item.packageUspsList.packageUsps[i].packageTrackingNumberUsps = msg.trackingRef;
}
}
NewItem.packageUspsList = item.packageUspsList;
}
if (useTba = "true".Equals(_custSettings["login.useTba"]))
login();
_service.update(NewItem);

Related

SAP.Middleware.Connector.RfcInvalidParameterException: Table line 0 out of range: table is empty

I have a C# console aplication that connects to a SAP server to get data from some of its tables.
Sometimes this error pops up when i try to copy a value from a field in a SAP table called "SOHEADER" to a string variable.
Here's the stack trace:
SAP.Middleware.Connector.RfcInvalidParameterException: Table line 0
out of range: table is empty en
SAP.Middleware.Connector.RfcTable.get_Item(Int32 lineIndex) en
ExportarPedidosSAP.Program.ControlFacturasRemitosNotasCreditos(RfcDestination
rfcDest, String& nroerror) en
C:\Users\USER\Source\repos\BSCPY\BSCPY\ExportarPedidosSAP\Program.cs:línea
1220 en ExportarPedidosSAP.Program.ConnSAPNotasCreditos() en
C:\Users\USER\Source\repos\BSCPY\BSCPY\ExportarPedidosSAP\Program.cs:línea
936
Here is the ControlFacturasRemitosNotasCreditos function:
static void ControlFacturasRemitosNotasCreditos(RfcDestination rfcDest, out string nroerror)
{
Console.WriteLine("** Controlando remitos... ");
nroerror = "";
using (SqlBriefcaseCropScience db = new SqlBriefcaseCropScience())
{
using (var transaction = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = IsolationLevel.Snapshot }))
{
List<NotaCreditoCabecera> lstpedidos = new List<NotaCreditoCabecera>();
List<NotaCreditoItem> lstItemProducto = new List<NotaCreditoItem>();
IQueryable<NotaCreditoCabecera> ilstpedidos = null;
IQueryable<Compania> ilstcompanias = null;
List<NotaCreditoItem> lstprod = null;
NotaCreditoItem itProd = null;
int statuscode = 0;
decimal FKIMG = 0;
string ProdCode = "";
string statusdesc = "";
string status_doc = "";
string LEGALNUMBER = "";
string LEGALNUMBER_DEL = "";
bool savecabecera = false;
bool nolegalnumber = false;
bool itemfacturado = false;
bool pedidofacturado = false;
List<string> List_LEGALNUMBER_DEL = new List<string>();
List<string> List_LEGALNUMBER = new List<string>();
ilstcompanias = db.Compania;
DateTime unmes = Helpers.GetCurrentDateTime().AddMonths(1);
if (ilstcompanias != null)
{
foreach (Compania comp in ilstcompanias.ToList())
{
ilstpedidos = db.NotaCreditoCabecera.Where(c => c.CodigoCompania == comp.Codigo &&
(c.CodigoEstado == 5 || c.CodigoEstado == 11 && (DbFunctions.TruncateTime(c.FechaEstado) <= DbFunctions.TruncateTime(unmes))));
if (ilstpedidos != null)
{
lstpedidos = ilstpedidos.ToList<NotaCreditoCabecera>();
if (lstpedidos.Count() > 0)
{
RfcRepository rfcRep = rfcDest.Repository;
var funcionStatus = ConfigurationManager.AppSettings["SAP-RFC-Status"];
foreach (NotaCreditoCabecera cabecera in lstpedidos.ToList())
{
lstprod = db.NotaCreditoItem.Where(c => c.CodigoCompania == comp.Codigo && c.NroPedido == cabecera.NroPedido).ToList();
IRfcFunction functionStatus = rfcRep.CreateFunction(funcionStatus);
functionStatus.SetValue("SEL_ORDERSTATUS", "X");
functionStatus.SetValue("P_VKORG", cabecera.SalesOrg);
functionStatus.SetValue("P_BRIEFDOC", cabecera.NroPedido);
IRfcTable tableHstatus = functionStatus.GetTable(ConfigurationManager.AppSettings["SAP-TablaH-Status"]);
IRfcTable tableIstatus = functionStatus.GetTable(ConfigurationManager.AppSettings["SAP-TablaI-Status"]);
IRfcTable tablaEstatus = functionStatus.GetTable(ConfigurationManager.AppSettings["SAP-TablaE"]);
functionStatus.Invoke(rfcDest);
status_doc = Convert.ToString(tableHstatus[0].GetValue("GBSTK")).ToUpper();
itemfacturado = false;
pedidofacturado = false;
nolegalnumber = false;
if (tableIstatus.RowCount > 0)
{
for (int e = 0; e < tableIstatus.RowCount; e++)
{
if (Convert.ToString(tableIstatus[e].GetValue("NETWR")) != "")
{
ProdCode = Convert.ToString(tableIstatus[e].GetValue("MATERIAL"));
itProd = lstprod.FirstOrDefault(i => i.CodigoProducto == ProdCode);
if (itProd != null)
{
//Num Factura
LEGALNUMBER = Convert.ToString(tableIstatus[e].GetValue("LEGALNUMBER")).Trim();
if (!String.IsNullOrEmpty(LEGALNUMBER))
{
itemfacturado = true;
//Num Remito
LEGALNUMBER_DEL = Convert.ToString(tableIstatus[e].GetValue("LEGALNUMBER_DEL")).Trim();
//Cantidad
FKIMG = (decimal.TryParse(Convert.ToString(tableIstatus[e].GetValue("FKIMG")), out FKIMG) == true) ?
Convert.ToDecimal(Convert.ToString(tableIstatus[e].GetValue("FKIMG"))) : 0;
//Si algun item no esta completamente facturado se considera el pedido no facturado
if ((LEGALNUMBER != "" && LEGALNUMBER_DEL != "") && (itProd.CantidadDevolucion == Convert.ToDecimal(FKIMG)) && (nolegalnumber == false))
{
pedidofacturado = true;
}
else
{
pedidofacturado = false;
break;
}
}
else
{
nolegalnumber = true;
}
}
}
}
//statuscode = 0;
//if (itemfacturado == true)
//{
// if (pedidofacturado == true)
// {
// statuscode = 12;
// }
//}
//if (statuscode > 0)
//{
// statusdesc = repositorioAdm.CEstado(cabecera.IdTipoOrden, statuscode);
// int reslog = ALogAutorizacion(db, transaction, cabecera.CodigoCompania,
// cabecera.SalesOrg, cabecera.CodigoDivision,
// cabecera.IdTipoOrden, cabecera.TipoOrden,
// cabecera.NroPedido.ToString(),
// cabecera.CodigoEstado.ToString(), cabecera.Estado,
// statuscode.ToString(), statusdesc, "inter", "");
// cabecera.CodigoEstado = statuscode;
// cabecera.Estado = statusdesc;
// cabecera.FechaEstado = Helpers.GetCurrentDateTime();
// savecabecera = true;
//}
}
//Tabla de Error
if (tablaEstatus.RowCount > 0)
{
//Obtengo el Estado
statuscode = 9;
cabecera.CodigoEstado = statuscode;
statusdesc = repositorioAdm.CEstado(cabecera.IdTipoOrden, statuscode);
cabecera.Estado = statusdesc;
cabecera.FechaEstado = Helpers.GetCurrentDateTime();
savecabecera = true;
int reslog = ALogAutorizacion(db, transaction, cabecera.CodigoCompania,
cabecera.SalesOrg, cabecera.CodigoDivision,
cabecera.IdTipoOrden, cabecera.TipoOrden,
cabecera.NroPedido.ToString(),
cabecera.CodigoEstado.ToString(),
cabecera.Estado,
statuscode.ToString(),
statusdesc, "inter", "");
}
}
}
}
if (savecabecera)
{
db.Configuration.ValidateOnSaveEnabled = false;
db.SaveChanges();
}
transaction.Complete();
}
}
}
}
}
Line 1220 inside ControlFacturasRemitosNotasCreditos:
status_doc = Convert.ToString(tableHstatus[0].GetValue("GBSTK")).ToUpper();
Line 936 inside ConnSAPNotasCreditos that calls the ControlFacturasRemitosNotasCreditos function:
ControlFacturasRemitosNotasCreditos(rfcDest, out nroerror);
Can somebodoy tell me what could be the issue here? Could it be that the field comes empty from the SAP table and if i try to copy it somewhere the whole thing crashes? Is there a safe way to check if the field is null before trying to copy it?
in your line
status_doc = Convert.ToString(tableHstatus[0].GetValue("GBSTK")).ToUpper();
you are adressing the IRfcTable tableHstatus with index 0, which means you're trying to read the first entry from that table object. That only works if the table has entries. You should first check whether the table contains any rows and only then continue. After invoking the RFC function, check property RowCount of your IRfcTable.
functionStatus.Invoke(rfcDest);
if (tableHstatus.RowCount > 0) {
status_doc = Convert.ToString(tableHstatus[0].GetValue("GBSTK")).ToUpper();
}
there's a number of reasons why a RFC function might return an empty table. It could be standard behavior in some cases, or it could be because some query parameter was wrong and no data was found, or because an error occurred in the function. Standard SAP BAPIs usually return a status structure or table (often of type BAPIRETURN or BAPIRET2) that contains additional information about error codes, messages etc.

How can I insert more than 2 tables in LINQ using foreign keys

I am apparently Inserting data using LINQ by creating classes of tables in the databases but it just has error that says object is null.
This is my sample code using C# LINQ:
using (dc = new linqDBDataContext(conn))
{
Subject_Curriculum sc;
Subject_Schedule ss;
Subject_Department sd;
Subject_Standing sst;
Pre_Requisite pr;
Pre_Requisite_Year_Standing prys;
Curriculum cu = new Curriculum();
cu.Curriculum_Title = curriculumName;
cu.Course_Number = courseNumber;
foreach (var s in ssd)
{
sc = new Subject_Curriculum();
sc.Course_Code = s.courseCode;
sc.Course_Title = s.courseTitle;
cu.Subject_Curriculums.Add(sc);
dc.Subject_Curriculums.InsertOnSubmit(sc);
for (int i = 0; i < s.numberOfSchedules; i++)
{
ss = new Subject_Schedule();
if (i == 0)
{
ss.Units = s.unitsLec;
ss.Schedule_Type = "Lecture";
ss.Number_Of_Hours = s.numberOfHoursLec;
}
else
{
ss.Units = s.unitsLab;
ss.Schedule_Type = "Laboratory";
ss.Number_Of_Hours = s.numberOfHoursLab;
}
sc.Subject_Schedules.Add(ss);
dc.Subject_Schedules.InsertOnSubmit(ss);
}
foreach (var sdl in s.department)
{
sd = new Subject_Department();
sd.Department_Number = sdl;
sc.Subject_Departments.Add(sd);
dc.Subject_Departments.InsertOnSubmit(sd);
}
sst = new Subject_Standing();
sst.Year = s.year;
sst.Semester = s.semester;
cu.Subject_Standings.Add(sst);
dc.Subject_Standings.InsertOnSubmit(sst);
if (s.yearStandingStatus)
{
prys = new Pre_Requisite_Year_Standing();
prys.Year_Standing = Convert.ToInt32(s.yearStanding.ToString().Substring(0, 1));
sc.Pre_Requisite_Year_Standings.Add(prys);
dc.Pre_Requisite_Year_Standings.InsertOnSubmit(prys);
}
else
{
if (s.prereq.Count == 0)
{
pr = new Pre_Requisite();
pr.Pre_Requisite_Code = null;
sc.Pre_Requisites.Add(pr);
dc.Pre_Requisites.InsertOnSubmit(pr);
}
else
{
foreach (var p in s.prereq)
{
pr = new Pre_Requisite();
pr.Pre_Requisite_Code = Convert.ToInt32(p);
sc.Pre_Requisites.Add(pr);
dc.Pre_Requisites.InsertOnSubmit(pr);
}
}
}
}
dc.Curriculums.InsertOnSubmit(cu);
dc.SubmitChanges();
return true;
}
As you can see in the code, the Curriculum table has the highest hierarchy in the database and the other tables inherits its primary key into Subject_Curriculum, Pre_Requisite, Subject_Standing and Pre_Requisite_Year_Standing. While Subject_Schedules and Subject_Department inherits Subject_Curriculum's primary key. What can I do to make this insertion possible to all table at once?
I already solved my question. It is just by adding all tables from their foreign keys and insert and submit changes at the end of the loop. This makes this thread close.

insert only new data instead duplicate the existing data

I have this code running calling the data from the core system,
public int MuatTurunMTS(hopesWcfRef.Manifest2 entParam, string destination, int capacity)
{
try
{
EL.iSeriesWcf.IiSeriesClient iClient = new iSeriesWcf.IiSeriesClient();
EL.iSeriesWcf.Manifest2 manifest2 = new iSeriesWcf.Manifest2();
manifest2 = iClient.GetManifest2(entParam.NOKT, destination, capacity);
DataTable dt = new DataTable();
dt = manifest2.Manifest2Table;
List<hopesWcfRef.Manifest2> LstManifest2 = new List<hopesWcfRef.Manifest2>();
for (int i = 0; i < dt.Rows.Count; i++)
{
hopesWcfRef.Manifest2 newDataRow = new hopesWcfRef.Manifest2();
newDataRow.NOPASPOT = dt.Rows[i][1].ToString();
newDataRow.NOKT = dt.Rows[i][0].ToString();
newDataRow.KOD_PGKT = dt.Rows[i][2].ToString();
newDataRow.KOD_KLGA = dt.Rows[i][3].ToString();
newDataRow.NAMA = dt.Rows[i][4].ToString();
newDataRow.TKHLAHIR = (dt.Rows[i][5].ToString() == "1/1/0001 12:00:00 AM" ? DateTime.Now : Convert.ToDateTime(dt.Rows[i][5])); //Convert.ToDateTime(dt.Rows[i][5]);
newDataRow.JANTINA = dt.Rows[i][6].ToString();
newDataRow.WARGANEGARA = dt.Rows[i][7].ToString();
newDataRow.JNS_JEMAAH = dt.Rows[i][8].ToString();
newDataRow.NO_SIRI = dt.Rows[i][9].ToString();
newDataRow.NO_MS = Convert.ToInt16(dt.Rows[i][10]);
newDataRow.BARKOD = dt.Rows[i][13].ToString();
newDataRow.NO_DAFTAR = dt.Rows[i][14].ToString();
//bydefault make cell empty
newDataRow.STS_JEMAAH = "";
newDataRow.SEAT_NO = "";
newDataRow.SEAT_ZONE = "";
newDataRow.BERAT = 0;
newDataRow.JUM_BEG = 0;
LstManifest2.Add(newDataRow);
}
int cntr = 0;
if (LstManifest2.Count != 0)
{
foreach (hopesWcfRef.Manifest2 manifest in LstManifest2)
{
cntr++;
SaveManifestTS(manifest);
}
}
return LstManifest2.Count;
}
catch (Exception ex)
{
throw ex;
}
}
And goes to :
public void SaveManifestTS(hopesWcfRef.Manifest2 manifest)
{
try
{
ent.BeginSaveChanges(SaveChangesOptions.Batch, null, null);
ent.AddObject("Manifest2", manifest);
ent.SaveChanges(SaveChangesOptions.Batch);
}
catch (Exception ex)
{
//Uri u = new Uri(ent.BaseUri + "GetErrorMsg"
// , UriKind.RelativeOrAbsolute);
//string datas = (ent.Execute<string>(u)).FirstOrDefault();
//Exception ex = new Exception(datas);
throw ex;
}
}
When SaveChanges run, if the data exist it will duplicate the entire row,
How to avoid the data being duplicate when insert (savechanges)??????
Many Thanks
What about: Do not insert.
In these cases I am using a MERGE statement that updates existing data (based on primary key) and inserts new data.
Oh, and all the code example you loved to post is totally irrelevant to the question, which is a pure SQL side question. You literally quote your car manual then asking which direction to turn.

How to update a DataTable created on Main Thread by a new thread in C#?

I have a global DataTable named 'DTImageList' and an XtraGrid named 'uxImageGrid'. Now there is a Method named 'prcFillImagesVideosAndFiles' in which we bring image data from data base page wise i.e. say 500 rows at a time and we create mannual Pages on top of the Grid by using XtraTabControl depending on the total count of data exists according to search. Say if we get 700 Images then will load only 500 at a time and 2 pages will be created as 'Page 1', 'Page 2'.
But in 'prcFillImagesVideosAndFiles' method, we are not fetching the actual images but only its name, id etc. After this I created a new Thread and invoking a method runner which in turn calls a new method called 'FillImages' in which I look through DTImageList and bring actual image one by one from backend and update row with this image due to which XtraGrid starts showing images one by one.
This process works fine for few minutes i.e. loads 20-25 images and after that it gives 'Cross-thread operation not valid' error.
// My prcFillImagesVideosAndFiles method's Code is:
`if (DTImageList != null)
{
DTImageList.Rows.Clear(); DTImageList.Columns.Clear(); DTImageList = null;
}
string sql = #"select " + top + #" IM.Image_ID,IM.extension,IM.Is_Uploaded,cast(0 as varbinary) 'ActualImage',IM.description 'Description',IM.ContentType,IM.DateTime_Uploaded,IM.FolderName, '' as FilePath
from images as IM where IM.GCRecord is null and IM.Is_Uploaded=1 " + MainCriteria + #" " + Ob + #"";
string sql1 = LayoutPaging(sql);
DTImageList = new DataTable();
DTImageList = FillDataTable(sql1);
DataTable DTdeliv2 = new DataTable();
DTdeliv2.Columns.Add("Image");
DTdeliv2.Columns.Add("UniqueNumber");
DTdeliv2.Columns["Image"].DataType = typeof(Image);
DTdeliv2.Columns["UniqueNumber"].DataType = typeof(int);
DTImageList.Merge(DTdeliv2, true, MissingSchemaAction.Add);
uxImageGrid.DataSource = null;
uxImageGrid.DataSource = DTImageList;
RepositoryItemTextEdit riTextEdit = new RepositoryItemTextEdit();
riTextEdit.Appearance.TextOptions.HAlignment = HorzAlignment.Center;
layoutView1.Columns["Description"].AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
riTextEdit.Appearance.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128)))));
riTextEdit.Appearance.Options.UseBackColor = true;
riTextEdit.NullText = "";
uxImageGrid.RepositoryItems.Add(riTextEdit);
layoutView1.Columns["Description"].ColumnEdit = riTextEdit;
riTextEdit.Leave += new EventHandler(riTextEdit_Leave);
riTextEdit.KeyPress += new KeyPressEventHandler(riTextEdit_KeyPress);
RepositoryItemPictureEdit riPictureEdit = new RepositoryItemPictureEdit();
riPictureEdit.SizeMode = PictureSizeMode.Zoom;
riPictureEdit.ShowMenu = false;
riPictureEdit.NullText = " Loading Image";
riPictureEdit.Appearance.Image = Pionero.RetailTherapy.Properties.Resources.mag;
uxImageGrid.RepositoryItems.Add(riPictureEdit);
layoutView1.Columns["Image"].ColumnEdit = riPictureEdit;
riPictureEdit.MouseMove += new MouseEventHandler(riPictureEdit_MouseMove);
riPictureEdit.MouseDown += new MouseEventHandler(riPictureEdit_MouseDown);
layoutView1.Columns["Image"].Caption = "";
int k = DTImageList.Rows.Count;
if (k > 0)
{
DevExpress.Data.Filtering.CriteriaOperator expr1 = new DevExpress.Data.Filtering.BinaryOperator("Is_Uploaded", true);
layoutView1.ActiveFilterCriteria = expr1;
if (pthread != null)
{
StopRunningThread();
}
if (pthread == null || pthread.IsAlive==false)
{
pthread = new Thread(new ThreadStart(runner));
pthread.IsBackground = true;
Is_ThreadNeededtoWork = true;
pthread.Start();
}
else
{
Is_ThreadNeededtoWork = true;
pthread.Start();
}
}`
//The runner method is:
void runner()
{
if (Is_ThreadNeededtoWork == false)
{
if (dtImages != null)
{
dtImages.Rows.Clear(); dtImages.Columns.Clear(); dtImages = null;
}
return;
}
if (Is_ThreadNeededtoWork == true)
{
FillImages();
}
}
// FillImages method's code is:
try
{
if (DTImageList.Rows.Count <= 0) return;
StringBuilder sbImagesNotLoaded = new StringBuilder();
sbImagesNotLoaded.Append("Following images not loaded due to connection: ");
ArrayList lstImage_IDs = new ArrayList();
int NoOfAttempts = 0;
//if (dtImages != null)
//{
for (int i = 0; i < DTImageList.Rows.Count; i++)
{
NoOfAttempts = 0;
V:
string Qry = #" Select Image_ID,image from images where Image_ID = " + DTImageList.Rows[i]["Image_ID"].ToString();
dtImages = FillDataTable(Qry);
if (dtImages != null && dtImages.Rows.Count > 0)
{
if (DTImageList.Rows[i]["image"] == DBNull.Value)
{
// Thread.Sleep(100);
byte[] barr = (byte[])dtImages.Rows[0]["image"];
Image img = Global.byteArrayToImage(barr);
DTImageList.Rows[i]["Image"] = img;
DTImageList.AcceptChanges();
uxImageGrid.RefreshDataSource();
}
}
else
{
// Thread.Sleep(100);
if (Convert.ToInt32(DTImageList.Rows[i]["Image_ID"]) > 0)
if (NoOfAttempts < 3)
{
NoOfAttempts = NoOfAttempts + 1;
goto V;
}
else
{
if (lstImage_IDs.Count > 0)
sbImagesNotLoaded.Append("," + Convert.ToString(DTImageList.Rows[i]["Description"]));
else
sbImagesNotLoaded.Append(Convert.ToString(DTImageList.Rows[i]["Description"]));
lstImage_IDs.Add(DTImageList.Rows[i]["Image_ID"]);
}
}
}
//}
if (lstImage_IDs.Count > 0)
{
for (int i = 0; i < lstImage_IDs.Count; i++)
{
DataRow drImage = DTImageList.Select("Image_ID=" + Convert.ToString(lstImage_IDs[i]) + "").FirstOrDefault();
if (drImage != null)
DTImageList.Rows.Remove(drImage);
}
DTImageList.AcceptChanges();
XtraMessageBox.Show(sbImagesNotLoaded.ToString(), Global.Header, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
EnableDisablePanelControls(true);
if (pthread != null)
{
Is_ThreadNeededtoWork = false;
StopRunningThread();
}
}
catch (ThreadAbortException abortException)
{
}
catch (Exception emmp)
{
EnableDisablePanelControls(true);
//pthread.Abort();
}
finally
{
//Global.StopProg();
}
//StopRunningThread() 's code is:
void StopRunningThread()
{
if (dtImages != null)
{
dtImages.Rows.Clear(); dtImages.Columns.Clear(); dtImages = null;
}
Is_ThreadNeededtoWork = false;
}
Thanks
Vicky
You can try inserting images before you pass it as Datasource to uxImageGrid.
Add image column to DTImageLis.
DTImageList.Columns.Add("Image", typeof(System.Drawing.Image));
Add the image to datatable based on Name,Id etc and bind it to uxImageGrid
uxImageGrid.Datasource=DTImageList;

Import data into Quickbooks General Journal Entries

I try to import data from my POS System to Quickbooks to create General Journal entries. When i add some static(hard coded) data all saved successfully. But when I try to add data from my app QB add data to dataService but when i sync QB data didn't come. Please could you help with my problem. Here is my code.
//main code to add General Journal Entry to QB
var header = GenerateReportHeader(model);
var creditInfo = GenerateJournalEntryLines(model.CreditInformation, PostingTypeEnum.Credit);
var debitInfo = GenerateJournalEntryLines(model.DebitInformation, PostingTypeEnum.Debit);
var allLines = creditInfo.Concat(debitInfo).ToArray();
var result = new JournalEntry();
result.Header = header;
result.Line = allLines;
dataService.Add(result);
//Add Header
private JournalEntryHeader GenerateReportHeader(GeneralJournalModel model)
{
var result = new JournalEntryHeader
{
TxnDate = new DateTime(2013,7,1),
Status = "Payable",
Adjustment = false,
TxnDateSpecified = true
};
if (!String.IsNullOrEmpty(model.EntryNo))
{
result.DocNumber = model.EntryNo;
}
return result;
}
//Add Line
private JournalEntryLine[] GenerateJournalEntryLines(List<GeneralJournalEntryModel> model, PostingTypeEnum postType)
{
var result = new JournalEntryLine[model.Count];
for (int i = 0; i < model.Count; i++)
{
var journalEntryLine = model[i];
var account = GetAccountByNumber(journalEntryLine.AccountNumber);
var toAdd = new JournalEntryLine
{
AccountId = account.Id,
AccountType = account.Type,
AccountName = account.Name,
Amount = Convert.ToDecimal(journalEntryLine.Amount),
AmountSpecified = true,
PostingType = postType,
AccountTypeSpecified = true,
Id = new IdType(),
PostingTypeSpecified = true
};
if (journalEntryLine.EntityId != null)
{
toAdd.EntityId = GetEntityId(journalEntryLine.EntityType, journalEntryLine.EntityId);
toAdd.EntityType = GetEntityType(journalEntryLine.EntityType);
toAdd.EntityName = GetEntityName(journalEntryLine.EntityType, journalEntryLine.EntityId);
toAdd.EntityTypeSpecified = true;
}
result[i] = toAdd;
}
return result;
}
Did you check the SyncStatus, and find out why not?
This should be where you start:
https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0500_quickbooks_windows/0600_object_reference/syncstatus
It will give you more detail about specifically why the data failed to sync over.

Categories