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.
Related
Searching, I found the PRAGMA as a possible solution for my problem, but it only returns the index of each column. There's any other method to return all columns names?
I thought using a For to go through my column indexes returning their names would works fine, but I dont exactly know how the syntax of this would be, either the stop condition.
void FillColumnList()
{
try
{
string check = "SELECT * FROM PRAGMA table_info(Produtos)";
sqlCon.Open();
SQLiteCommand tst2 = new SQLiteCommand(check, sqlCon);
SQLiteDataReader rdr2 = tst2.ExecuteReader();
if (rdr2.HasRows)
{
while (rdr2.Read())
{
string columns = rdr2[0].ToString();
Columns.Add(columns);
}
sqlCon.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
This code should return and fill the Global variable list Columns with the name of each column of "Produtos" table. Instead of it, my DataReader 'rdr2' return false in the HasRows, even when there's columns and Datas in my table "Produtos"
You can use the connection's GetSchema method to retrieve the column information. I'm using the following code to insert information my own class TableColumn not shown here:
string[] restrictions = new string[] { null, null, tableName };
using (DataTable columns = conn.GetSchema("Columns", restrictions)) {
int nameIndex = columns.Columns.IndexOf("COLUMN_NAME");
int ordinalPosIndex = columns.Columns.IndexOf("ORDINAL_POSITION");
int isNullableIndex = columns.Columns.IndexOf("IS_NULLABLE");
int maxLengthIndex = columns.Columns.IndexOf("CHARACTER_MAXIMUM_LENGTH");
int dataTypeIndex = columns.Columns.IndexOf("DATA_TYPE");
int isPrimaryKeyIndex = columns.Columns.IndexOf("PRIMARY_KEY");
int hasDefaultIndex = columns.Columns.IndexOf("COLUMN_HASDEFAULT");
int defaultValueIndex = columns.Columns.IndexOf("COLUMN_DEFAULT");
foreach (DataRow row in columns.Rows) {
var col = new TableColumn {
ColumnName = (string)row[nameIndex]
};
try {
col.ColumnNameForMapping = prepareColumnNameForMapping(col.ColumnName);
} catch (Exception ex) {
throw new UnimatrixExecutionException("Error in delegate 'prepareColumnNameForMapping'", ex);
}
col.ColumnOrdinalPosition = (int)row[ordinalPosIndex];
col.ColumnAllowsDBNull = (bool)row[isNullableIndex];
col.ColumnMaxLength = (int)row[maxLengthIndex];
string explicitDataType = ((string)row[dataTypeIndex]).ToLowerInvariant();
col.ColumnDbType = GetColumnDbType(explicitDataType);
col.ColumnIsPrimaryKey = (bool)row[isPrimaryKeyIndex];
col.ColumnIsIdentity = explicitDataType == "integer" && col.ColumnIsPrimaryKey;
col.ColumnIsReadOnly = col.ColumnIsIdentity;
if ((bool)row[hasDefaultIndex]) {
col.ColumnDefaultValue = GetDefaultValue(col.ColumnDbType, (string)row[defaultValueIndex]);
if (col.ColumnDefaultValue == null) { // Default value could not be determined. Probably expression.
col.AutoAction = ColumnAction.RetrieveAfterInsert;
}
}
tableSchema.ColumnSchema.Add(col);
}
}
You can simplify this code considerably if you only need the column names.
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);
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;
private void SaveButton_Click(object sender, EventArgs e)
{
try
{
if (CashPaymentGridView.Rows.Count > 1)
{
CashPaymentandReceivedE cashpament =new CashPaymentandReceivedE();
List<CashPaymentandReceivedE> cashpaymentList = new List<CashPaymentandReceivedE>();
foreach ( DataGridViewRow rows in CashPaymentGridView.Rows)
{
if (rows.IsNewRow )
{
break ;
}
cashpament.VR_NO= Convert.ToInt16(VoucherNoTextBox.Text);
cashpament.VR_DATE = VrDate.Value ;
cashpament.ETYPE = "CPV";
cashpament.USER_ID = "1";
cashpament.PARTY_ID= Convert.ToString (rows.Cells[2].Value) ;
cashpament.DESCRIPTION = Convert.ToString ( rows.Cells[3].Value);
cashpament.INVOICE = Convert.ToString(rows.Cells[4].Value);
cashpament.DEBIT = Convert.ToInt32(rows.Cells[5].Value);
cashpament.CREDIT = 0;
cashpaymentList.Add(cashpament);
cashpament = new CashPaymentandReceivedE();
cashpament.VR_NO =Convert.ToInt16(VoucherNoTextBox.Text);
cashpament.VR_DATE = VrDate.Value;
cashpament.ETYPE = "CPV";
cashpament.USER_ID = "1";
cashpament.PARTY_ID = NewAccountsDAL.Get_Id_Name ("CASH");
cashpament.DESCRIPTION = Convert.ToString(rows.Cells[3].Value);
cashpament.INVOICE = Convert.ToString(rows.Cells[4].Value);
cashpament.CREDIT = Convert.ToInt32(rows.Cells[5].Value);
cashpament.DEBIT = 0;
cashpaymentList.Add(cashpament);
}
if (CashPaymentandReceivedDAL.Save(cashpaymentList))
{
MessageBox.Show("SAVE SUCCESSFULLY...............");
ResetForm();
}
}
else
{
MessageBox.Show ("Please select atleast one record.....");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message );
}
}
Stored Procedure for saving data is given as.
public static bool Save(List <CashPaymentandReceivedE> cashreceivedpayment)
{
bool blnResult = false;
SqlConnection objSqlConnection = new SqlConnection(ConnectionString.Connection);
//SqlTransaction objSqlTransaction = null;
try
{
objSqlConnection.Open();
//objSqlTransaction = objSqlConnection.BeginTransaction();
int R = 0;
while (R < cashreceivedpayment.Count )
{
SqlCommand objSqlCommand = new SqlCommand("CASHRECEIVED_Save", objSqlConnection);
objSqlCommand.CommandType = CommandType.StoredProcedure;
//SqlParameter objIdentityParameter = objSqlCommand.Parameters.Add("#PLED_ID", SqlDbType.BigInt);
//objIdentityParameter.Direction = ParameterDirection.Output;
//objSqlCommand.Parameters.AddWithValue("#PLED_ID", cashreceivedpayment[R].PLED_ID);
objSqlCommand.Parameters.AddWithValue("#COMPANY_ID", "1");
objSqlCommand.Parameters.AddWithValue("#PARTY_ID", cashreceivedpayment[R].PARTY_ID);
objSqlCommand.Parameters.AddWithValue("#VR_NO", cashreceivedpayment[R].VR_NO);
objSqlCommand.Parameters.AddWithValue("#ETYPE", cashreceivedpayment[R].ETYPE);
objSqlCommand.Parameters.AddWithValue("#VR_DATE", cashreceivedpayment[R].VR_DATE);
objSqlCommand.Parameters.AddWithValue("#DESCRIPTION", cashreceivedpayment[R].DESCRIPTION);
objSqlCommand.Parameters.AddWithValue("#DEBIT", cashreceivedpayment[R].DEBIT);
objSqlCommand.Parameters.AddWithValue("#CREDIT", cashreceivedpayment[R].CREDIT);
objSqlCommand.Parameters.AddWithValue("#USER_ID", cashreceivedpayment[R].USER_ID);
//objSqlCommand.Parameters.AddWithValue("#COMPNAY_ID", cashreceivedpayment[R].COMPANY_ID);
objSqlCommand.Parameters.AddWithValue("#DESCRIPTION2", "DESCRIPTION2");
objSqlCommand.Parameters.AddWithValue("#INVOICE", cashreceivedpayment[R].INVOICE);
objSqlCommand.ExecuteNonQuery();
R++;
blnResult = true;
}
}
catch (Exception ex)
{
//objSqlTransaction.Rollback();
MessageBox.Show(ex.Message);
}
finally
{
//objSqlTransaction.Commit();
objSqlConnection.Close();
}
return blnResult;
}
When i save the record, one record should be of Party_id and one should be of cash.
but when i select more than one record just one entry saving to cash. when when i load the record jst one record is loaded.plz help if u understand.....
You're creating one CashPaymentandReceivedE object, and adding the reference to it on each iteration of the list. You're then also changing all the data within that single object on each iteration. Just move this line:
CashPaymentandReceivedE cashpament =new CashPaymentandReceivedE();
... inside your foreach statement and the problem should be resolved.
Before you do so though, make sure you understand why your code is behaving like this. It's really important to understand that the list doesn't contain objects - it contains references to objects. In your case, it would contain several references to a single object, until you fix it.
I'd also strongly suggest using a foreach in your Save method - or if you really need the index for some reason, use a for loop instead of a while.
what would be the best way to compare two data table. i populate two data table reading two different xml and now i need to compare and return the difference in terms of datatable.my compare logic was
private DataTable CompareDataTables(DataTable dtFirst, DataTable dtSecond)
{
int result = 0;
bool flag = false;
DataTable dtNoRows = new DataTable();
dtNoRows.Columns.Add("Result");
DataTable dtDiff = new DataTable();
dtDiff.Columns.Add("Field Name");
dtDiff.Columns.Add("Old Value");
dtDiff.Columns.Add("New Value");
DataRow dr = null;
if (dtFirst.Columns.Count == dtSecond.Columns.Count)
{
for (int i = 0; i <= dtFirst.Columns.Count - 1; i++)
{
try
{
DateTime.Parse(dtFirst.Rows[0][dtFirst.Columns[i].ColumnName.ToString()].ToString().Trim());
flag = true;
}
catch (Exception ex)
{
flag = false;
}
if (!flag)
{
if (dtFirst.Rows[0][dtFirst.Columns[i].ColumnName.ToString()].ToString().Trim().ToUpper() != dtSecond.Rows[0][dtSecond.Columns[i].ColumnName.ToString()].ToString().Trim().ToUpper())
{
dr = dtDiff.NewRow();
dr["Field Name"] = dtFirst.Columns[i].ColumnName.ToString();
dr["Old Value"] = dtFirst.Rows[0][dtFirst.Columns[i].ColumnName.ToString()].ToString().Trim();
dr["New Value"] = dtSecond.Rows[0][dtSecond.Columns[i].ColumnName.ToString()].ToString().Trim();
dtDiff.Rows.Add(dr);
}
}
else
{
result = DateTime.Compare(DateTime.Parse(dtFirst.Rows[0][dtFirst.Columns[i].ColumnName.ToString()].ToString()), DateTime.Parse(dtSecond.Rows[0][dtSecond.Columns[i].ColumnName.ToString()].ToString()));
if (result != 0)
{
dr = dtDiff.NewRow();
dr["Field Name"] = dtFirst.Columns[i].ColumnName.ToString();
dr["Old Value"] = DateTime.Parse(dtFirst.Rows[0][dtFirst.Columns[i].ColumnName.ToString()].ToString().Trim()).ToString("MM/dd/yyyy") + " - " + DateTime.Parse(dtFirst.Rows[0][dtFirst.Columns[i].ColumnName.ToString()].ToString().Trim()).ToString("hh:mm:ss");
dr["New Value"] = DateTime.Parse(dtSecond.Rows[0][dtSecond.Columns[i].ColumnName.ToString()].ToString().Trim()).ToString("MM/dd/yyyy") + " - " + DateTime.Parse(dtSecond.Rows[0][dtSecond.Columns[i].ColumnName.ToString()].ToString().Trim()).ToString("hh:mm:ss");
dtDiff.Rows.Add(dr);
}
flag = false;
}
}
}
return dtDiff;
}
my code is working fine but i need to the is there any best way out. please guide me.
you can use LINQ to comparing tables values(two table must have the same structure)
bool flag = false;
if (dtFirst.Columns.Count == dtSecond.Columns.Count)
{
for (int i = 0; i <= dtFirst.Columns.Count - 1; i++)
{
String colName = dtFirst.Columns[i].ColumnName;
var colDataType = dtFirst.Columns[i].DataType.GetType();
var colValue = dtFirst.Columns[i];
flag = dtSecond.AsEnumerable().Any(T => typeof(T).GetProperty(colName).GetValue(T, typeof(colDataType)) == colValue);
}
}
var qry1 = dtDuplicate.AsEnumerable().Select(a => new { SchoolID = a["SchoolMID"].ToString()});
var qry2 = dsValadateSchoolInfo.Tables[1].AsEnumerable().Select(b => new { SchoolID = ["SchoolMID"].ToString() });
var exceptAB = qry1.Except(qry2);
DataTable dtMisMatch = (from a in dtDuplicate.AsEnumerable()
join ab in exceptAB on a["SchoolMID"].ToString() equals ab.SchoolID
select a).CopyToDataTable();