How to differentiate between two similar fields in Linq Join tables - asp.net

How to differentiate between two select new fields e.g. Description
c.Description and lt.Description
DataTable lDt = new DataTable();
try
{
lDt.Columns.Add(new DataColumn("AreaTypeID", typeof(Int32)));
lDt.Columns.Add(new DataColumn("CategoryRef", typeof(Int32)));
lDt.Columns.Add(new DataColumn("Description", typeof(String)));
lDt.Columns.Add(new DataColumn("CatDescription", typeof(String)));
EzEagleDBDataContext lDc = new EzEagleDBDataContext();
var lAreaType = (from lt in lDc.tbl_AreaTypes
join c in lDc.tbl_AreaCategories on lt.CategoryRef equals c.CategoryID
where lt.AreaTypeID== pTypeId
select new { lt.AreaTypeID, lt.Description, lt.CategoryRef, c.Description }).ToArray();
for (int j = 0; j< lAreaType.Count; j++)
{
DataRow dr = lDt.NewRow();
dr["AreaTypeID"] = lAreaType[j].LandmarkTypeID;
dr["CategoryRef"] = lAreaType[j].CategoryRef;
dr["Description"] = lAreaType[j].Description;
dr["CatDescription"] = lAreaType[j].;
lDt.Rows.Add(dr);
}
}
catch (Exception ex)
{
}

You can give them an explicit name when selecting:
select new { lt.AreaTypeID, LtDescr = lt.Description, lt.CategoryRef, CDescr = c.Description }
And then:
dr["Description"] = lAreaType[j].LtDescr;
dr["CatDescription"] = lAreaType[j].CDescr;

Change:
select new { lt.AreaTypeID, lt.Description, lt.CategoryRef, c.Description }
To:
select new { AreaTypeID = lt.AreaTypeID,
LtDescription = lt.Description,
CategoryRef = lt.CategoryRef,
CatDescription = c.Description }
That will give each property in the anonymous type a different explicit name rather than simply relying on the existing name. You can then access them later using:
dr["Description"] = lAreaType[j].LtDescription;
dr["CatDescription"] = lAreaType[j].CatDescription;

Related

How to perform Rollback in asp.net when using Stored Procedure

I want to insert data into 12 different tables on a single click of a button. For this I am using single stored procedure. But my problem is when I am doing this and if there is any exception occurs my data is getting inserted partially i.e values is getting inserted in some tables and some remains empty and due to this problem occurs since all are related to one another. So wanted to know is there any way to perform Rollback so that if any exception occurs entire query is rolled back and data is not inserted in any of the table.
This is the code I am currently using for inserting values.
public int Sp_InsertUpdateDelete(string s, SqlParameter[] spa)
{
SqlConnection sc = new SqlConnection(cs);
sc.Open();
SqlCommand scm = new SqlCommand(s, sc);
scm.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter sql in spa)
{
scm.Parameters.Add(sql);
}
int k = scm.ExecuteNonQuery();
sc.Close();
return k;
}
protected void btnHostingSubmit_Click(object sender, EventArgs e)
{
string select = "select * from tbl_Hosting where Customer_Id='" + ddlCustomerName.SelectedValue + "'";
DataSet s = gs.select(select);
if (s.Tables[0].Rows.Count > 0)
{
Response.Write("<script>alert('Customer Already Exist');</script>");
}
else
{
if (ddlHosting.SelectedValue == "Yes")
{
SqlParameter[] spa = new SqlParameter[29];
spa[0] = new SqlParameter("#Customer_Id", Convert.ToInt16(ddlCustomerName.SelectedValue));
spa[1] = new SqlParameter("#Type", 2);
//Hosting
if (txtHostingSDate.Text == "" || txtHostingSDate.Text == null)
{
spa[2] = new SqlParameter("#Hosting_start_date", null);
}
else
{
spa[2] = new SqlParameter("#Hosting_start_date", Convert.ToDateTime(txtHostingSDate.Text));
}
if (txtHosingEDate.Text == "" || txtHosingEDate.Text == null)
{
spa[3] = new SqlParameter("#Hosting_end_date", null);
}
else
{
spa[3] = new SqlParameter("#Hosting_end_date", Convert.ToDateTime(txtHosingEDate.Text));
}
spa[4] = new SqlParameter("#Hosting_provider", ddlHostingPro.SelectedItem.ToString());
spa[5] = new SqlParameter("#Hosting_type", ddlHostingType.SelectedItem.ToString());
spa[6] = new SqlParameter("#Hosting_server", ddlHostingServer.SelectedItem.ToString());
spa[7] = new SqlParameter("#Hosting_total_id", Convert.ToInt16(txtHostingId.Text));
spa[8] = new SqlParameter("#Hosting_mail_tracking", ddlHostingMailTracking.SelectedItem.ToString());
spa[9] = new SqlParameter("#Hosting_mail_tracking_users", Convert.ToInt16(txtHostingMtUser.Text));
spa[10] = new SqlParameter("#Hosting_dns", ddlHostingDns.SelectedItem.ToString());
spa[11] = new SqlParameter("#Hosting_mail", ddlHostingMail.SelectedItem.ToString());
spa[12] = new SqlParameter("#Hosting_web", ddlHostingWeb.SelectedItem.ToString());
spa[13] = new SqlParameter("#Hosting_manage_dns", ddlHostingMngDns.SelectedItem.ToString());
if (ddlHostingDns.SelectedValue == "No" && (ddlHostingMail.SelectedValue == "Yes" || ddlHostingWeb.SelectedValue == "Yes"))
{
spa[14] = new SqlParameter("#Hosting_ns1", txtNS1.Text);
spa[15] = new SqlParameter("#Hosting_ns2", txtNS2.Text);
}
else
{
spa[14] = new SqlParameter("#Hosting_ns1", ddlHostingNS1.SelectedItem.ToString());
spa[15] = new SqlParameter("#Hosting_ns2", ddlHostingNS2.SelectedItem.ToString());
}
spa[16] = new SqlParameter("#Hosting_rec_ip", txtHostingARecordIp.Text);
spa[17] = new SqlParameter("#Hosting_mx_rec1", txtMXRecord1.Text);
spa[18] = new SqlParameter("#Hosting_mx_rec2", txtMXRecord2.Text);
spa[19] = new SqlParameter("#Hosting_mx_ip1", txtHostingMxIp1.Text);
spa[20] = new SqlParameter("#Hosting_space", ddlHostingSpace.SelectedItem.ToString());
spa[21] = new SqlParameter("#Hosting_mx_ip2", txtHostingMxIp2.Text);
spa[22] = new SqlParameter("#Hosting_data_transfer", ddlhostingDataTrans.SelectedItem.ToString());
spa[23] = new SqlParameter("#Hosting_manage_dns_amt", txtHostingMangDnsAmt0.Text);
spa[24] = new SqlParameter("#Hosting_amt", txtHostingAmt0.Text);
spa[25] = new SqlParameter("#Hosting_c_ns1", txtHostingNS1.Text);
spa[26] = new SqlParameter("#Hosting_c_ns2", txtHostingNS2.Text);
spa[27] = new SqlParameter("#Hosting_c_ns3", txtHostingNS3.Text);
spa[28] = new SqlParameter("#Hosting_c_ns4", txtHostingNS4.Text);
int k = gs.Sp_InsertUpdateDelete("Sp_Hosting", spa);
if (k > 0)
{
Response.Write("<script>alert('Hosting Added Success');</script>");
}
Clear();
}
using(SqlConnection conn = new SqlConnection())
{
try
{
conn.Open();
SqlTransaction tran = conn.BeginTransaction("Transaction1");
Cmd = new SqlCommand(sQuery, Conn);
Cmd.Transaction = tran;
//Your Code
tran.Commit(); //both are successful
}
catch(Exception ex)
{
//if error occurred, reverse all actions. By this, your data consistent and correct
tran.Rollback();
}
}
https://msdn.microsoft.com/en-us/library/a90c30fy.aspx
You need to modify your Stored procedure and use Transactions for this feature.
Something like this:
DECLARE #TranName VARCHAR(20);
SELECT #TranName = 'MyTransaction';
BEGIN TRANSACTION #TranName;
USE AdventureWorks2012;
DELETE FROM AdventureWorks2012.HumanResources.JobCandidate
WHERE JobCandidateID = 13;
COMMIT TRANSACTION #TranName;
GO
MSDN Reference

SQL MDF Database every cell displays: "System.__ComObject"

When I execute this program the Excel part generates and string array: cellValue just fine.
When it inserts into the SQL MDF Database: MDFExcel every cell displays: "System.__ComObject".
How do you display the string value instead of the "System.__ComObject"?
protected void Button1_Click(Object sender, EventArgs e)
{
DataSet ds = new DataSet();
//From Excel
Microsoft.Office.Interop.Excel.Application exlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook exlWb = exlApp.Workbooks.Open(#"C:\Users\Optiplex760\Documents\a Excel\ExcelToMDF.xls");
Microsoft.Office.Interop.Excel.Worksheet exlWs= exlWb.Sheets["Sheet1"];
Microsoft.Office.Interop.Excel.Range usedRange = exlWs.UsedRange;
int col = Convert.ToInt32(usedRange.Columns.Count);
int row = Convert.ToInt32(usedRange.Rows.Count);
exlApp.Visible = true;
string[,] cellValue = new string[row + 1, col + 1];
for (int j = 1; j <= row-1; j++)
{
for (int k = 1; k <= col-1; k++)
{
cellValue[j, k] = exlWs.Cells[j+1,k+1].ToString();
}
}
exlWb.Close();
exlWs = null;
exlWb = null;
exlApp.Quit();
exlApp = null;
//To MSSQL
String connStr, cmdStr;
connStr = ConfigurationManager.ConnectionStrings["MDFExceldb"].ConnectionString;
for (int h = 1; h<row; h++)
{
cmdStr = "INSERT INTO [Table1] (col1,col2,col3) VALUES (#col1,#col2,#col3);";
try
{
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#col1", cellValue[1, h]);
cmd.Parameters.AddWithValue("#col2", cellValue[2, h]);
cmd.Parameters.AddWithValue("#col3", cellValue[3, h]);
cmd.ExecuteNonQuery();
conn.Close();
cmd.Dispose();
conn.Dispose();
}
}
}
catch (Exception ex)
{
Label2.Text = ex.ToString();
}
}
}
Worksheet.Cells returns a Range and not a single value - and a Range (an RCW object) does not implemented a sensible ToString; thus it defaults to the "System.__ComObject" value shown.
Use the Text property of the Range, eg.
cellValue[j, k] = Convert.ToString(exlWs.Cells[j+1,k+1].Text);
While this should fix the immediate problem, it is also an inefficient process. See this response (using the Value/Value2 property) for how to access the Range values as a 2-dimensional array and reduce excessive range-slicing.

Editable gridview based on list

Is it possible to create a gridview based on a list? I have the following list:
ID = 1
Name = John
Zip = 33141
ID = 2
Name = Tim
Zip = 33139
I want to be able to create an editable gridview with this list
When i bind it to the grid view, it seems to put everyting in one column, and i can't figure out how to get it to seperate it into different columns
Here is my code for setting the DataSource of the GridView:
DataTable table = ConvertListToDataTable(personList);
GridView1.DataSource = table;
GridView1.DataBind();
static DataTable ConvertListToDataTable(List<string> list)
{
// New table.
DataTable table = new DataTable();
// Get max columns.
int columns = 7;
// Add columns.
for (int i = 0; i < columns; i++)
{
table.Columns.Add();
}
// Add rows.
foreach (var rd in list)
{
table.Rows.Add(rd);
}
return table;
}
Here is an example:
private class Person
{
int m_iID;
string m_sName;
string m_sZip;
public int ID { get { return m_iID; } }
public string Name { get { return m_sName; } }
public string Zip { get { return m_sZip; } }
public Person(int iID, string sName, string sZip)
{
m_iID = iID;
m_sName = sName;
m_sZip = sZip;
}
}
private List<Person> m_People;
private void ConvertListToDataTable(List<Person> People)
{
DataTable table = new DataTable();
DataColumn col1 = new DataColumn("ID");
DataColumn col2 = new DataColumn("Name");
DataColumn col3 = new DataColumn("Zip");
col1.DataType = System.Type.GetType("System.String");
col2.DataType = System.Type.GetType("System.String");
col3.DataType = System.Type.GetType("System.String");
table.Columns.Add(col1);
table.Columns.Add(col2);
table.Columns.Add(col3);
foreach (Person person in People)
{
DataRow row = table.NewRow();
row[col1] = person.ID;
row[col2] = person.Name;
row[col3] = person.Zip;
table.Rows.Add(row);
}
GridView1.DataSource = table;
GridView1.DataBind();
}

Add parent row and add child for that new parent row

i am creating new record in 'Timecard' table and at the same time i want to create one record in 'TimecardStatusTrack' table using entity framework. i am able to create parent record but while adding child record i am getting exception. the code i have written is like
var fEmpManager = DependencyContainer.GetInstance<IBusinessService<FacilityEmployee>>();
int timecardStatusDidNotWork =
Convert.ToInt32(GeneralCodeId.TimeCardStatusDidNotWork, CultureInfo.InvariantCulture);
Timecard timecard = new Timecard();
TimecardStatusTrack timecardStatus = new TimecardStatusTrack();
try
{
var fEmp = fEmpManager.Where(w => w.JobId == jobId && w.AgencyBiddingProfile.AgencyCandidateId == agencyCandidateId).FirstOrDefault();
timecard.JobId = jobId;
timecard.AgencyCandidateId = agencyCandidateId;
timecard.WeekStartDate = Convert.ToDateTime(weekStartDate, CultureInfo.InvariantCulture);
timecard.WeekEndDate = Convert.ToDateTime(weekEndDate, CultureInfo.InvariantCulture);
timecard.FacilityEmployeeId = fEmp.Id;
timecard.FacilityId = fEmp.FacilityId;
timecard.TimecardStatusGCId = timecardStatusDidNotWork;
timecard.AddUser = SessionManager.AuthorizedInfo.UserId;
timecard.AddDate = DateTime.Now;
timecardStatus.TimecardStatusGCId = timecardStatusDidNotWork;
timecardStatus.AddUser = SessionManager.AuthorizedInfo.UserId;
timecardStatus.AddDate = DateTime.Now;
timecardStatus.UpdatedBy = SessionManager.AuthorizedInfo.UserId;
timecardStatus.Comments = string.Empty;
_ViewTimeCardBusibessService.Create(timecard);
timecard.TimecardStatusTracks.Add(timecardStatus);
_ViewTimeCardBusibessService.Update(timecard);
}
catch (Exception ex)
{
HandleValidationErrors(ex);
}
finally
{
DependencyContainer.ReleaseInstance(fEmpManager);
}

Error cannot find Column 2 dr = ds.Tables[0].Rows[0]

I've been searching for an answer since this code was working fine like an hour ago and I did not make any editting so it turns a little confuse to recognize the error if any of you could help I would appreciate it much. Thanks in advance.
I've checked and there are no errors on the SQL query, as I said it was working fine dr is defined globally as:
DataRow dr = new DataRow();
and MyTable is defined globally also as
DataTable MyTable = new DataTable();
here's the related code:
sentencia = "select * from Facturas" + Session["sociotabla"].ToString() + " where IdFactura = " + Session["idFactura"].ToString();
ds = bd.Consulta(sentencia);
if (ds != null)
{
dr = MyTable.NewRow();
dr = ds.Tables[0].Rows[0];
LimpiarControles();
tbFactura.Text = dr[0].ToString();
ListItem li;
for (int i = 0; i < ddlCliente.Items.Count; i++)
{
li = ddlCliente.Items[i];
if (li.Value == dr[2].ToString()) //Error here Cannot find Column 2
{
ddlCliente.SelectedIndex = i;
Session["idCliente"] = dr[2].ToString();
break;
}
}

Resources