"An error occurred while updating the entries." - c#

I get this error from my code:
{"An error occurred while updating the entries. See the inner exception for details."}
I see the inner exception and:
{"Parameter value '99999,999' is out of range."}
but when i upload only one archive he is fine, and when i upload more than one archive he throws the exception.
This is my code:
private void ProcessarCEP(int i,FileInfo file,string [] Lines)
{
string vNomeArquivo = string.Empty;
DBCEPEntities DBCEP = new DBCEPEntities();
DirectoryInfo info = new DirectoryInfo(file.DirectoryName);
FileInfo[] files = info.GetFiles("*.txt", SearchOption.AllDirectories);
int vTamanhoBase = DBCEP.CAD_CEP.Where(t => t.UF == file.Name.Substring(15,2)).Count();
for (int a = vTamanhoBase; a < i + vTamanhoBase; a++)
{
if (a >= Lines.Count()) break;
CAD_CEP CEP = new CAD_CEP();
string[] Registros = Lines[a].Split('#');
CEP.CEP = Convert.ToDecimal(Registros[7]);
CEP.UF = Registros[1];
CEP.LOGRADOURO = Registros[8];
CEP.ENDERECO = Registros[5];
if (Registros[2] != string.Empty)
{
decimal CodLocal = Convert.ToDecimal(Registros[2]);
var local = DBCEP.CAD_CIDADE.Where(c => c.CODLOCAL == CodLocal).FirstOrDefault();
CEP.LOCAL = local.LOCAL;
}
if (Registros[3] != string.Empty)
{
decimal CodBairro = Convert.ToDecimal(Registros[3]);
var bairro = DBCEP.CAD_BAIRRO.Where(c => c.CODBAIRRO == CodBairro).FirstOrDefault();
CEP.BAIRRO = bairro.BAIRRO;
}
vNomeArquivo = ConfigurationManager.AppSettings["NomeArquivoSequencia"].ToString();
if (files.Where(f => f.Name.ToUpper() == vNomeArquivo.ToUpper()).Count() > 0)
{
if (Registros[0] != string.Empty)
{
string[] LinesSec = File.ReadAllLines(files.Where(f => f.Name.ToUpper().StartsWith(vNomeArquivo.ToUpper())).FirstOrDefault().FullName.ToString(), Encoding.Default);
string vLinhaSec = LinesSec.Where(l => l.StartsWith(Registros[0] + "#")).FirstOrDefault();
if (vLinhaSec != null)
{
string[] vLinhaSplit = vLinhaSec.Split('#');
if (vLinhaSplit[1] != string.Empty)
{
CEP.DE = Convert.ToDecimal(vLinhaSplit[1]);
}
if (vLinhaSplit[2] != string.Empty)
{
CEP.ATE = Convert.ToDecimal(vLinhaSplit[2]);
}
CEP.FL_PAR_IMPAR = vLinhaSplit[3];
}
Registros = null;
LinesSec = null;
}
}
DBCEP.CAD_CEP.Add(CEP);
}
DBCEP.SaveChanges();
vTamanhoBase = DBCEP.CAD_CEP.Where(t => t.UF == file.Name.Substring(15, 2)).Count();
DBCEP.Dispose();
GC.WaitForPendingFinalizers();
GC.Collect();
if (Lines.Count() <= i + vTamanhoBase)
{
if(vTamanhoBase != Lines.Count())
{
ProcessarCEP(Lines.Count() - i, file, Lines);
}
}
else
{
if(vTamanhoBase != Lines.Count())
{
ProcessarCEP(i, file, Lines);
}
}
}

Related

how to ignore error records while updating the entries when error inner exception for details

How can I ignore writing of records giving error while updating the entities.
ERROR DISPLAY
private void btn_salary_Click(object sender, EventArgs e)
{
if (sg.HasRows(lib.tbl_pay) == true && chkShowOnly.Checked == false)
{
lib.ShowMessage(lib.tbl_pay + " has data can not import");
return;
}
sql = "SELECT * FROM PAY WHERE BankAc IS NOT null";
q1 = new DBFHelper(txt_olddir.Text).FillDataTable(sql);
dataGridView1.DataSource = q1;
if (chkShowOnly.Checked == true) return;
DateTime xdate = sg.ServerDate;
for (int x = 0; x < q1.Rows.Count; x++)
{
PAY q11 = new PAY
{
BANKAC = sg.AsString(q1.Rows[x]["BankAc"]),
MDATE = sg.AsDate(q1.Rows[x]["MDATE"].ToString()),
BYEAR = sg.AsDate(q1.Rows[x]["MDATE"].ToString()).Year,
BMONTH = sg.AsDate(q1.Rows[x]["MDATE"].ToString()).Month,
PERPAY = q1.AsDecimal("PERPAY", x),
BASIC = q1.AsDecimal("PERPAY", x),
DARATE = q1.AsDecimal("DA", x),
NEWDA = q1.AsDecimal("NEWDA",x),
ADNDA = q1.AsDecimal ("ADNDA",x),
HRA = q1.AsDecimal ("HRA",x),
ENTREL = q1.AsDecimal("ENTREL",x),
EXTRA = q1.AsDecimal("EXTRA",x),
INSKNP = q1.AsDecimal("INSGKP",x),
MEDI = q1.AsDecimal("MEDI",x),
RD = q1.AsDecimal("RD",x),
GPF = q1.AsDecimal("GPF",x),
GPFLOAN= q1.AsDecimal("GPFLOAN",x),
CPF = q1.AsDecimal("CPF",x),
CPFLOAN = q1.AsDecimal("CPFLOAN",x),
LICPRE = q1.AsDecimal("LICPRE",x),
LICLOAN = q1.AsDecimal("LICLOAN",x),
ITAX = q1.AsDecimal("ITAX",x),
JSBLOAN = q1.AsDecimal("JSBLOAN",x),
NSBLOAN = q1.AsDecimal("NSBLOAN",x),
STEMP = q1.AsDecimal("STEMP",x),
PROFUND = q1.AsDecimal("PROFUND",x),
TYPE_ATX = q1.AsString("TYPE",x),
GRADE = q1.AsString("GRADE",x),
TFUND = q1.AsDecimal("TFUND",x),
GFUND = q1.AsDecimal("GFUND",x),
OBCLOAN = q1.AsDecimal("OBCLOAN",x),
OTH1_LOAN = q1.AsDecimal("OTH1_LOAN",x),
OTH2_LOAN = q1.AsDecimal("OTH2_LOAN",x),
BSTGBANK = q1.AsDecimal("BSTGBANK",x),
EARNING = q1.AsDecimal("EARNING",x),
TOTDED = q1.AsDecimal("TOTDED",x),
NETPAY = q1.AsDecimal("NETPAY",x),
CITYALW = q1.AsDecimal("CITYALW",x),
user_code = lib.user_code,
modi_dt = xdate
};
g1.PAYs.Add(q11);
lbl_counter.Text = x.ToString() + " Records Inserted";
Application.DoEvents();
}
try
{
g1.SaveChanges();
}
catch (Exception ex)
{
string emsg = ex.Message;
if (ex.InnerException != null)
{
emsg = emsg + ex.InnerException.Message;
}
if (ex.InnerException.InnerException != null)
{
emsg = emsg + ex.InnerException.InnerException.Message;
}
if (ex.InnerException.InnerException.InnerException != null)
{
emsg = emsg + ex.InnerException.InnerException.InnerException.Message;
}
lib.ShowMessage(emsg);
}
lib.ShowMessage("Done..");
}

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.

Check each List item if Null

I am quite poor at writing code, hence the question. Below I am adding items into a SharePoint List from a DB while checking if any of the fields contains DBNulls. Rather than having to perform the check for each column like I am below, can someone help me to put it in a loop if possible? I would be forever grateful
using (OdbcConnection connection = new OdbcConnection())
{
connection.ConnectionString = "dsn=abc;uid=xyz;pwd=yuo;DataSource=aaa";
connection.ConnectionTimeout = 100;
connection.Open();
OdbcCommand command_donor = new OdbcCommand("Select * From vw_SP_aaa_bbb", connection);
try
{
using (OdbcDataReader reader = command_donor.ExecuteReader())
{
while (reader.Read())
{
var obj0 = reader.GetValue(48);
var obj1 = reader.GetValue(0);
var obj2 = reader.GetValue(33);
var obj3 = reader.GetValue(47);
var obj4 = reader.GetValue(42);
var obj5 = reader.GetValue(42);
ListItem oListItem_aaa = oList_aaa .AddItem(itemCreateInfo);
if (obj0 == null || obj0.Equals(DBNull.Value))
{ oListItem_aaa["Title"] = ""; }
else
{ oListItem_aaa["Title"] = reader.GetString(48).ToString(); }
if (obj1 == null || obj1.Equals(DBNull.Value))
{ oListItem_aaa["aaa_x0020_ID"] = ""; }
else
{ oListItem_aaa["aaa_x0020_ID"] = reader.GetString(0).ToString(); }
if (obj2 == null || obj2.Equals(DBNull.Value))
{ oListItem_aaa["Excluded_x0020_By"] = ""; }
else
{ oListItem_aaa["Excluded_x0020_By"] = reader.GetString(33).ToString(); }
if (obj3 == null || obj3.Equals(DBNull.Value))
{ oListItem_aaa["Excluded_x0020_On"] = ""; }
else
{ oListItem_aaa["Excluded_x0020_On"] = reader.GetDateTime(47).ToString("MM/dd/yyyy"); }
if (obj4 == null || obj4.Equals(DBNull.Value))
{ oListItem_aaa["Reason"] = ""; }
else
{ oListItem_aaa["Reason"] = reader.GetString(42).Substring(50, reader.GetString(42).ToString().Length-50); }
if (obj5 == null || obj5.Equals(DBNull.Value))
{ oListItem_aaa["Publish"] = ""; }
else
{ oListItem_aaa["Publish"] = reader.GetString(42).Substring(50, reader.GetString(42).ToString().Length - 50); }
oListItem_aaa.Update();
context.ExecuteQuery();
}
}
}
catch (Exception exception)
{
Console.WriteLine("The Error is:" + exception);
Console.ReadLine();
}
}
Use Short IIF like
oListItem_aaa["Excluded_x0020_By"] = (obj1 == null || obj1.Equals(DBNull.Value)) ? "" : reader.GetString(0).ToString();
or
var obj0 = (reader.GetValue(48) != DBNull.Value && !String.IsNullOrEmpty(Convert.ToString(reader.GetValue(48)))) ? reader.GetValue(48) : "");
in one line. Then you dont need to use the if then else's... described also in MSDN at Operator ?: (C#-Referenz).

order the events within button_Click

I am trying to get events to occur one at a time within my button_Click, but for some reason everything seems to wait to run until everything is complete. For instance image changes don't occur until everything else has occured.
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Image = Properties.Resources.running;
iTunesAppClass itunes = new iTunesAppClass();
IITLibraryPlaylist mainLibrary = itunes.LibraryPlaylist;
IITTrackCollection ittracks = mainLibrary.Tracks;
List<string> files = new List<string>();
List<string> musicfiles = new List<string>();
List<string> badfiles = new List<string>();
List<string> songlist = new List<string>();
int state = ((int)itunes.PlayerState);
string statestring = null;
if (state < 1) { statestring = "Stopped"; };
if (state == 1) { statestring = "Playing"; };
if (state == 1)
{
do
{
label5.Text = ("Pausing iTunes to maintain file integrity");
itunes.Pause();
state = (int)itunes.PlayerState;
}
while (state == 1);
}
if (state < 1) { statestring = "Stopped"; };
if (state == 1) { statestring = "Playing"; };
if (state != 1)
{
label5.Text = "Itunes is " + statestring;
}
string[] extensions = { "*.mp3", "*.mp4", "*.m4a", "*.m4v", "*.m4p", "*.m4b", "*.flac" };
string filepath = label4.Text;
foreach (string extension in extensions)
{
this.pictureBox1.Image = Properties.Resources.running;
try
{
files.AddRange(Directory.GetFiles(filepath, extension, SearchOption.AllDirectories));
}
catch (UnauthorizedAccessException) { }
}
foreach (string file in files)
{
try { string taglibfile = TagLib.File.Create(file).Tag.Title; musicfiles.Add(file); Console.WriteLine(taglibfile); }
catch { badfiles.Add(file); }
}
XDocument baddoc = new XDocument
(new XElement("Corrupt",
badfiles.Select(badfile =>
new XElement("File", badfile))));
baddoc.Save(label4.Text + "\\badfiles.xml");
// foreach(string musicfile in musicfiles)
//{ String Title = (TagLib.File.Create(musicfile).Tag.Title); }
this.pictureBox1.Image = Properties.Resources.skinitunes;
}

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;

Categories