How me for Incorrect syntax near 'stock' - asp.net

public string update()
{
try
{
myConnection.ConnectionString = GlobalVariabel.connString;
myConnection.Open();
string query = "update phoneproduct set ";
query += "model = #model,";
query += "price = #price ";
query += "stock = #stock ";
query += "employeeid = #employeeid";
query += "where pin = #pin";
SqlCommand com = new SqlCommand(query, myConnection);
com.Parameters.AddWithValue("#pin", pin);
com.Parameters.AddWithValue("#model", model);
com.Parameters.AddWithValue("#price", price);
com.Parameters.AddWithValue("#stock", stock);
com.Parameters.AddWithValue("#employeeid", employeeid);
int i = com.ExecuteNonQuery();
if (i > 0)
{
flag = "OK";
}
else
{
flag = "FAIL";
}
}
catch (Exception ex)
{
flag = ex.Message;
}
finally
{
if (myConnection.State == ConnectionState.Open)
{
myConnection.Close();
myConnection = null;
}
}
return flag;
}

string query = "update phoneproduct set ";
query += "model = #model,";
query += "price = #price ";
query += "stock = #stock ";
query += "employeeid = #employeeid";
query += "where pin = #pin";
the above will build the query
UPDATE phoneproduct
SET model = #model,
price = #price
stock = #stock
employeeid = #employeeid
WHERE pin = #pin
The issue is that you are missing a comma after #price and #stock

Related

Validate last 2 letters into dynamic query

Im doing a Dynamic Query into ASP.NET using SQL Server 2016.
Basically i have some checkbox and textbox:
<asp:CheckBox ID="chk_Precio" runat="server" OnCheckedChanged="chk_Precio_CheckedChanged" AutoPostBack="true" />
<asp:TextBox ID="txtPrecio" runat="server" CssClass="enjoy-css" style="margin-bottom: 0"></asp:TextBox>
<asp:CheckBox ID="chk_Modelo" runat="server" AutoPostBack="true" OnCheckedChanged="chk_Modelo_CheckedChanged" />
<asp:TextBox ID="txtModelo" runat="server" CssClass="enjoy-css" style="margin-bottom: 0"></asp:TextBox>
<asp:Button ID="btnBuscar" CssClass="button" runat="server" Text="Buscar" OnClick="btnBuscar_Click" />
These are validated in chk_Modelo_CheckedChanged.
Inside btnBuscar_Click i have:
protected void btnBuscar_Click(object sender, EventArgs e)
{
string query = "SELECT p.OrderId AS Orden, p.OrderDate as Fechadecompra, '$'+Convert(varchar,convert(money,p.Amount),1) as PrecioCompra, c.ModelCar as Modelo, b.Description_Brand as Marca, c.Color, t.Description_Transmision as Transmision, s.StatusName AS Estado FROM PurchaseOrder AS p INNER JOIN Cars AS c ON p.IdCar = c.IdCar INNER JOIN Brand AS b ON c.IdBrand = b.IdBrand INNER JOIN TransmisionType AS t ON c.IdTransmision = t.IdTransmision INNER JOIN Status AS s on c.IdStatus = s.IdStatus where ";
string varprecio = txtPrecio.Text;
string varModelo = txtModelo.Text;
try
{
if (varprecio != "")
{
query += "(p.Amount = '"+varprecio +"') or";
}
else if(varModelo != "")
{
query += "(c.ModelCar = '"+varModelo +"') or";
}
string str = "Data Source=DESKTOP-77G5EDB\\SQLEXPRESS;Initial Catalog=TallerDB;Integrated Security=True";
SqlConnection sqlConnection = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(query, sqlConnection);
sqlConnection.Open();
SqlDataReader dr = cmd.ExecuteReader();
dtgv_Compras.DataSource = dr;
dtgv_Compras.DataBind();
}
catch (Exception ex)
{
Response.Write("<script>alert('ERROR: " + ex.Message + "')</script>");
}
}
My question is:
How can i validate if my query ends with: OR, delete these OR and my query finish correctly.
query += "(p.Amount = '"+varprecio +"') or";
F.E.:
SELECT p.OrderId AS Orden, p.OrderDate as Fechadecompra, '$'+Convert(varchar,convert(money,p.Amount),1) as PrecioCompra, c.ModelCar as Modelo, b.Description_Brand as Marca, c.Color, t.Description_Transmision as Transmision, s.StatusName AS Estado
FROM PurchaseOrder AS p
INNER JOIN Cars AS c ON p.IdCar = c.IdCar
INNER JOIN Brand AS b ON c.IdBrand = b.IdBrand
INNER JOIN TransmisionType AS t ON c.IdTransmision = t.IdTransmision
INNER JOIN Status AS s on c.IdStatus = s.IdStatus where (p.Amount = '5000')
Thanks in advance
I made some changes in your button click.
protected void btnBuscar_Click(object sender, EventArgs e)
{
string query = "SELECT p.OrderId AS Orden, p.OrderDate as Fechadecompra, '$'+Convert(varchar,convert(money,p.Amount),1) as PrecioCompra, c.ModelCar as Modelo, b.Description_Brand as Marca, c.Color, t.Description_Transmision as Transmision, s.StatusName AS Estado FROM PurchaseOrder AS p INNER JOIN Cars AS c ON p.IdCar = c.IdCar INNER JOIN Brand AS b ON c.IdBrand = b.IdBrand INNER JOIN TransmisionType AS t ON c.IdTransmision = t.IdTransmision INNER JOIN Status AS s on c.IdStatus = s.IdStatus ";
string varprecio = txtPrecio.Text;
string varModelo = txtModelo.Text;
try
{
if (varprecio != "" || varModelo != "")
query += "where ";
if (varprecio != "")
{
query += "(p.Amount = '" + varprecio + "')";
if (varModelo != "")
query += " or ";
}
if (varModelo != "")
{
query += "(c.ModelCar = '" + varModelo + "')";
}
string str = "Data Source=DESKTOP-77G5EDB\\SQLEXPRESS;Initial Catalog=TallerDB;Integrated Security=True";
SqlConnection sqlConnection = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(query, sqlConnection);
sqlConnection.Open();
SqlDataReader dr = cmd.ExecuteReader();
dtgv_Compras.DataSource = dr;
dtgv_Compras.DataBind();
}
catch (Exception ex)
{
Response.Write("<script>alert('ERROR: " + ex.Message + "')</script>");
}
}
Hope this will work for you. Please let me know if you will still facing issue.
Try this so you don't have to check whether they are blank or not
query += "('" + varprecio +"' = '''' or p.Amount = '" + varprecio +"') AND"
query += "('" + varModelo +"' = '''' or c.ModelCar = '"+varModelo +"')";
Which will give you
WHERE ('' = '' OR p.amount = '') AND ('' = '' or c.ModelCar = '')
or
WHERE ('abc' = '' OR p.amount = 'abc') AND ('xyz' = '' or c.ModelCar = 'xyz')
so if they are blank they are ignored on the SQL side.
I was trying in my work with oracle and i found this:
SELECT SUBSTR('select * from table where condicion = value or', 1, (LENGTH('select * from table where condicion = value or') - 2))
FROM dual where (SUBSTR ('select * from table where condicion = value or', -2,LENGTH('select * from table where condicion = value or')) = 'or');
Query:
select * from table where condicion = value or
Result:
I'll convert later to transact-sql in case someone uses the code into oracle.

Java servlet - export to an excell using string buffer

I am new to JAVA. I am trying to export Excel through servlet from resultset.
When i am trying to store data in String buffer the it is not actually saving it.
Testfirst.java
String assingee_name = req.getParameter("firstName");
String track_name = req.getParameter("track");
String sla_id = req.getParameter("sla");
StringBuffer sb = new StringBuffer();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Databasethree");
stmt = con.createStatement();
//pw.println("'" +assingee_name + "'");
length = track_name.length();
if (length > 0) {
rs = stmt.executeQuery("SELECT* FROM casedetails where track =" + "'" + track_name + "'");
}
length = sla_id.length();
if (length > 0) {
//rs = stmt.executeQuery("SELECT* FROM casedetails where case_age >"+"'" +sla_id + "'");
rs = stmt.executeQuery("SELECT* FROM cdoscase where Incident_Submit_Fiscal_Year=" + "'" + sla_id + "'");
}
length = assingee_name.length();
if (length > 0) {
rs = stmt.executeQuery("SELECT* FROM casedetails where Assingee_name =" + "'" + assingee_name + "'");
}
pw.println("<html><body>");
pw.println("<H1> CDOS Case Management Version 1.1 </H1>");
pw.println("<Head><style>table,th,td{border:1px solid black;}</style></head>");
pw.println("<table>");
ResultSetMetaData rm = rs.getMetaData();
int clm = rm.getColumnCount();
StringBuffer sb1 = new StringBuffer();
String sb2 = new String();
for (int j = 1; j <= clm; j++) {
sb2 = rm.getColumnName(j);
pw.println("<th>");
pw.println(sb2);
pw.println("</th>");
}
ArrayList Rows = new ArrayList();
ArrayList row = new ArrayList();
Object a = new Object();
int jj = 0; // to find out the number rows
while (rs.next()) {
jj = jj + 1;
pw.println("<tr>");
for (int i = 1; i <= clm; i++) {
//data1[i]=rs.getString(i);
pw.println("<td>");
//pw.println(rs.getObject(i).toString());
pw.println(rs.getString(i));
pw.println("</td>");
sb2.append(rs.getString(i);
//row.add(rs.getString(i));
//sb2=sb2+rs.getObject(i).toString();
}
pw.println("</tr>");
} sb1.append("fd");
//Rows.add(row);
pw.println("Total Records found" + sb1);
pw.println("</table>");
//sb2=sb2+rs.getObject(clm).toString();
//sb1.append(sb2);
//sb1.append(sb2);
a = rs.getString(4).toString();
pw.println("this is data " + a);
pw.println("<p>");
pw.println("<td>Do you want to download report </td>");
req.setAttribute("data", Rows);
pw.println("<input type=\"submit\" name =\"submit1\" value=\"Export To Excel\">");
pw.println("</form>");
} catch (SQLException e) {
pw.println(e.getNextException());
} catch (ClassNotFoundException e) {
pw.println(e.getException());
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
pw.close();
}
}
}
Any help on this is highly appreciated.
Thanks,
SR

Label does not show up in asp.net

I have a label in asp.net page and change its text in certain situations. Here is the code:
<asp:Label ID="errorMessage" runat="server" Text="Label" Visible="False"></asp:Label>
errorMessage.Text = MyGlobals.student.registerCourse(c, ref addList, course).ToString();
errorMessage.ForeColor = System.Drawing.Color.Red;
errorMessage.Visible = true;
When i debugged, i saw that MyGlobals.student.registerCourse(c, ref addList, course).ToString() method returns my error message well. Then i set the label visible, but when page loads i cannot see the label. Also, while debugging i saw that "textsetbyaddparsedsubobject" property of the label is false. Can that be the problem? Why is not the label being showed in my page? Can anyone help?
Thanks.
Edit: Here is the full code:
protected void bSubmitChanges_Click1(object sender, EventArgs e)
{
Userfunctions function = new Userfunctions();
List<string> dropList = new List<string>();
List<string> addList = new List<string>();
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
SqlCommand cmd;
con.Open();
string ID = MyGlobals.currentID;
try
{
for (int i = 1; i <= 6; i++)
{
string course;
if ((course = boxCRN(i)) != "")
{
cmd = new SqlCommand("select count (*) from CourseTable where CRN=#course", con);
cmd.Parameters.AddWithValue("#course", course);
int result = Convert.ToInt32(cmd.ExecuteScalar());
if (result > 0)
{
cmd = new SqlCommand("select * from CourseTable where CRN=#course", con);
cmd.Parameters.AddWithValue("#course", course);
cmd.ExecuteScalar();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
string query = "SELECT * FROM CourseTable WHERE CourseCode='" + dr["CourseCode"] + "' AND CourseNumber='" + dr["CourseNumber"] + "' AND Term='" + dr["Term"] + "'";
cmd = new SqlCommand(query, con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
DataRow dr2 = dt2.Rows[0];
cmd = new SqlCommand("select * from PrereqTable where CourseCode='" + dr["CourseCode"] + "' AND CourseNumber='" + dr["CourseNumber"] + "' AND Term='" + dr["Term"] + "'", con);
da2 = new SqlDataAdapter(cmd);
dt2 = new DataTable();
da2.Fill(dt2);
List<string> pre = new List<string>();
foreach (DataRow dr5 in dt2.Rows)
{
pre.Add(Convert.ToString(dr5["pCourseCode"]) + Convert.ToString(dr5["pCourseNumber"]));
}
Course c = new Course(dr2["InstructorID"].ToString(), dr2["CourseCode"].ToString(), dr2["CourseNumber"].ToString(), dr2["CourseName"].ToString(), dr2["Term"].ToString(), dr2["CRN"].ToString(), dr2["Level"].ToString(), dr2["Credit"].ToString(), dr2["Description"].ToString(), dr2["Capacity"].ToString());
c.addPrereq(pre);
string message = MyGlobals.student.registerCourse(c, ref addList, course).ToString();
errorMessage.Text = message;
errorMessage.ForeColor = System.Drawing.Color.Red;
errorMessage.Visible = true;
Label1.Visible = true;
Label1.Text = "asdasdasd";
}
}
}
}
}
catch (Exception) { }
for (int i = 0; i < showCourses.Rows.Count; i++)
{
string a = ((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue;
if (((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue == "1")
{
string courseCode = showCourses.Rows[i].Cells[1].Text, courseNumber = showCourses.Rows[i].Cells[2].Text;
SqlCommand com = new SqlCommand("select * from CourseTable where CourseCode=#courseCode and CourseNumber=#courseNumber", con);
com.Parameters.AddWithValue("courseCode", courseCode);
com.Parameters.AddWithValue("courseNumber", courseNumber);
try
{
SqlDataAdapter da2 = new SqlDataAdapter(com);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
DataRow dr2 = dt2.Rows[0];
Course c = new Course(dr2["InstructorID"].ToString(), dr2["CourseCode"].ToString(), dr2["CourseNumber"].ToString(), dr2["CourseName"].ToString(), dr2["Term"].ToString(), dr2["CRN"].ToString(), dr2["Level"].ToString(), dr2["Credit"].ToString(), dr2["Description"].ToString(), dr2["Capacity"].ToString());
Register reg = new Register(c, MyGlobals.student);
MyGlobals.student.dropCourse(reg);
dropList.Add(showCourses.Rows[i].Cells[1].Text + showCourses.Rows[i].Cells[2].Text);
}
catch (Exception) { }
}
}
foreach (string course in dropList)
{
for (int i = 0; i < MyGlobals.student.getRegistered().Count; i++ )
{
if (MyGlobals.student.getRegistered()[i].getCourse().getCode().ToString() + MyGlobals.student.getRegistered()[i].getCourse().getNumber().ToString() == course)
MyGlobals.student.dropCourse(MyGlobals.student.getRegistered()[i]);
}
cmd = new SqlCommand("delete from RegisterTable where StudentID='" + MyGlobals.currentID + "' and CourseCode='" + course.Substring(0, course.Length - 3) + "' and CourseNumber='" + course.Substring(course.Length - 3, 3) + "'", con);
cmd.ExecuteNonQuery();
}
try
{
foreach (string courses in addList)
{
string courseCode = "";
string courseNumber = "";
string term = MyGlobals.currentTerm + " " + MyGlobals.currentYear;
string q = ("select CourseCode from CourseTable where CRN=#courses");
string grade = "";
SqlCommand command = new SqlCommand(q, con);
command.Parameters.AddWithValue("#courses", courses);
courseCode = Convert.ToString(command.ExecuteScalar());
q = ("select CourseNumber from CourseTable where CRN=#courses");
command = new SqlCommand(q, con);
command.Parameters.AddWithValue("#courses", courses);
courseNumber = Convert.ToString(command.ExecuteScalar());
cmd = new SqlCommand("insert into RegisterTable (CourseCode,CourseNumber,Term,StudentID,Grade) values(#courseCode,#courseNumber,#term, #ID,'U')", con);
cmd.Parameters.AddWithValue("#courseCode", courseCode);
cmd.Parameters.AddWithValue("#courseNumber", courseNumber);
cmd.Parameters.AddWithValue("#term", term);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#grade", grade);
cmd.ExecuteNonQuery();
}
}
catch (Exception) { }
con.Close();
Response.Redirect("AddDropClasses.aspx");
}
}
And the registerCourse function:
public string registerCourse(Course course, ref List <string> addList, string crn) {
bool registered = true;
string message ="";
foreach (string s in course.getTime())
{
Userfunctions f = new Userfunctions();
foreach (Register r in this.register) {
if (r.getCourse().getTerm() == MyGlobals.currentTerm.ToString() + " " + MyGlobals.currentYear.ToString() && !f.TimeCheck(s, r.getCourse().getTime()))
{
registered = false;
message = "Time conflict";
}
}
}
if (registered) {
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
string id = MyGlobals.currentID;
SqlCommand cmd = new SqlCommand("SELECT count (*) from RegisterTable where CourseCode ='" + course.getCode() +"' and CourseNumber='" + course.getNumber() + "' and Term='" + course.getTerm()+"'" , con);
cmd.Parameters.AddWithValue("#id", id);
int active = Convert.ToInt32(cmd.ExecuteScalar());
if (active >= Convert.ToInt32(course.getCapacity())){
registered = false;
message = "Not enough capacity";
}
if (registered) {
foreach (string s in course.getPrerequisites()) {
if (!hasPassedCourse(s)) {
registered = false;
message = "Prerequisite error";
}
}
}
}
if (registered)
{
Register reg = new Register(course, MyGlobals.student);
MyGlobals.student.addToSchedule(reg);
addList.Add(crn);
}
return message;
}
Remove below line
Response.Redirect("AddDropClasses.aspx");
it will load your page again as new page
When you have Visible="false" set on the control then the control properties may not been instatiated fully.
I would try hiding the control using, errorMessage.Visible=false in the code-behind in your Page_Load instead.

SQL Parameters won't apply to command

Im trying to use the sql parameters to avoid sql injection in my query however the parameters don't seem to apply to the command.
public static IList<Call> GetCallsFilter(string startdate, string enddate,List<String>ContextName, List<String>ValueName, List<String>TypeName)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["BAMConnectionString"].ConnectionString))
{
connection.Open();
startdate += " 00:00:00";
enddate += " 23:59:59";
using (SqlCommand cmd = new SqlCommand("", connection))
{
cmd.CommandText = "SELECT dbo.Calls.CallID, dbo.Connections.Connectionname,dbo.Calls.ConnectionID, dbo.Calls.ParentID, dbo.Calls.StartTime, dbo.Calls.EndTime, REPLACE(dbo.Calls.Querytime, ',', '.') AS Querytijd, dbo.Calls.Template, dbo.Calls.Profilecall, dbo.Calls.Objectcall, dbo.Calls.Method, dbo.Calls.Error, dbo.Calls.Category, dbo.Calls.Uur, dbo.Calls.DayOfMonth, dbo.Repositorys.RepositoryName,dbo.Calls.ResultLink, REPLACE(MAX(Querytime) OVER (PARTITION BY DATEPART(yyyy, dbo.Calls.StartTime), DATEPART(M, dbo.Calls.StartTime), dbo.Calls.DayOfMonth, dbo.Calls.Uur, DATEPART(MINUTE, dbo.Calls.StartTime)), ',', '.') AS MaxQueryTime FROM dbo.Calls INNER JOIN dbo.Connections ON dbo.Calls.ConnectionID = dbo.Connections.ConnectionID INNER JOIN dbo.Repositorys ON dbo.Connections.RepositoryID = dbo.Repositorys.RepositoryID where StartTime BETWEEN '" + startdate + "' AND '" + enddate + "'";
if (ContextName != null && ValueName != null)
{
for (int i = 0; i < ContextName.Count; i++)
{
if (ContextName[i].ToString() != "Filter")
{
if (TypeName[i].ToString() == "LIKE")
{
cmd.CommandText += " AND exists (Select * from dbo.Context where CallID = dbo.Calls.CallID and Name=#Name and Value like #Value)";
cmd.Parameters.Add(new SqlParameter("Name", ContextName[i].ToString()));
cmd.Parameters.Add(new SqlParameter("Value", ValueName[i].ToString()));
}
else if (TypeName[i].ToString() == "=")
{
cmd.CommandText += " AND exists (Select * from dbo.Context where CallID = dbo.Calls.CallID and Name='" + Regex.Escape(ContextName[i].ToString()) + "' and Value = '" + Regex.Escape(ValueName[i].ToString()) + "')";
}
else if (TypeName[i].ToString() == "NOT LIKE")
{
cmd.CommandText += " AND exists (Select * from dbo.Context where CallID = dbo.Calls.CallID and Name='" + Regex.Escape(ContextName[i].ToString()) + "' and Value NOT like '%" + Regex.Escape(ValueName[i].ToString()) + "%')";
}
}
}
}
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
CallData = new List<Call>();
DataTable table = new DataTable();
adapter.Fill(table);
foreach (DataRow rij in table.Rows)
{
CallData.Add(new Call() { CallID = Int64.Parse(rij[0].ToString()), Connectionname = rij[1].ToString(), ConnectionID = rij[2].ToString(), ParentID = rij[3].ToString(), StartTime = ((DateTime)rij[4]).ToString("d/MM/yyyy hh:mm:ss.fff"), EndTime = ((DateTime)rij[5]).ToString("d/MM/yyyy hh:mm:ss.fff"), Querytime = rij[6].ToString(), Template = rij[7].ToString(), Profile = rij[8].ToString(), Object = rij[9].ToString(), Method = rij[10].ToString(), Error = rij[11].ToString(), Category = rij[12].ToString(), Uur = rij[13].ToString(), DayOfMonth = rij[14].ToString(), Repository = rij[15].ToString(), Datum = rij[4].ToString(), ResultLink = rij[16].ToString(), MaxQuerytime = rij[17].ToString() });
}
}
}
}
return CallData;
}
Im currently just trying it out in the IF LIKE function but won't work atm.
public static IList<Call> GetCallsFilter(string startdate, string enddate,List<String>ContextName, List<String>ValueName, List<String>TypeName)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["BAMConnectionString"].ConnectionString))
{
connection.Open();
startdate += " 00:00:00";
enddate += " 23:59:59";
using (SqlCommand cmd = new SqlCommand("", connection))
{
cmd.CommandText = "SELECT ";
cmd.CommandText += " dbo.Calls.CallID, ";
cmd.CommandText += " dbo.Connections.Connectionname, ";
cmd.CommandText += " dbo.Calls.ConnectionID, ";
cmd.CommandText += " dbo.Calls.ParentID, ";
cmd.CommandText += " dbo.Calls.StartTime, ";
cmd.CommandText += " dbo.Calls.EndTime, ";
cmd.CommandText += " REPLACE(dbo.Calls.Querytime, ',', '.') ";
cmd.CommandText += " AS ";
cmd.CommandText += " Querytijd, ";
cmd.CommandText += " dbo.Calls.Template, ";
cmd.CommandText += " dbo.Calls.Profilecall, ";
cmd.CommandText += " dbo.Calls.Objectcall, ";
cmd.CommandText += " dbo.Calls.Method, ";
cmd.CommandText += " dbo.Calls.Error, ";
cmd.CommandText += " dbo.Calls.Category, ";
cmd.CommandText += " dbo.Calls.Uur, ";
cmd.CommandText += " dbo.Calls.DayOfMonth, ";
cmd.CommandText += " dbo.Repositorys.RepositoryName, ";
cmd.CommandText += " dbo.Calls.ResultLink, ";
cmd.CommandText += " REPLACE(MAX(Querytime) OVER (PARTITION BY DATEPART(yyyy, dbo.Calls.StartTime), ";
cmd.CommandText += " DATEPART(M, dbo.Calls.StartTime), ";
cmd.CommandText += " dbo.Calls.DayOfMonth, ";
cmd.CommandText += " dbo.Calls.Uur, ";
cmd.CommandText += " DATEPART(MINUTE, dbo.Calls.StartTime)), ',', '.') ";
cmd.CommandText += " AS MaxQueryTime FROM dbo.Calls ";
cmd.CommandText += " INNER JOIN dbo.Connections ON ";
cmd.CommandText += " dbo.Calls.ConnectionID = dbo.Connections.ConnectionID ";
cmd.CommandText += " INNER JOIN dbo.Repositorys ON dbo.Connections.RepositoryID = dbo.Repositorys.RepositoryID ";
cmd.CommandText += " where StartTime BETWEEN #stardate AND #enddate ";
if (ContextName != null && ValueName != null)
{
for (int i = 0; i < ContextName.Count; i++)
{
if (ContextName[i].ToString() != "Filter")
{
cmd.CommandText += " AND exists ";
cmd.CommandText += "(Select * from dbo.Context ";
cmd.CommandText += " where CallID = dbo.Calls.CallID and Name=#Name and Value ";
cmd.CommandText += TypeName[i].ToString();
cmd.CommandText += " #Value)";
cmd.Parameters.AddWithValue("#Context", ContextName[i].ToString());
cmd.Parameters.AddWithValue("#Value", ValueName[i].ToString());
}
}
}
cmd.Parameters.AddWithValue("#startdate", startdate);
cmd.Parameters.AddWithValue("#enddate", enddate);
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
CallData = new List<Call>();
DataTable table = new DataTable();
adapter.Fill(table);
foreach (DataRow rij in table.Rows)
{
CallData.Add(new Call() { CallID = Int64.Parse(rij[0].ToString()), Connectionname = rij[1].ToString(), ConnectionID = rij[2].ToString(), ParentID = rij[3].ToString(), StartTime = ((DateTime)rij[4]).ToString("d/MM/yyyy hh:mm:ss.fff"), EndTime = ((DateTime)rij[5]).ToString("d/MM/yyyy hh:mm:ss.fff"), Querytime = rij[6].ToString(), Template = rij[7].ToString(), Profile = rij[8].ToString(), Object = rij[9].ToString(), Method = rij[10].ToString(), Error = rij[11].ToString(), Category = rij[12].ToString(), Uur = rij[13].ToString(), DayOfMonth = rij[14].ToString(), Repository = rij[15].ToString(), Datum = rij[4].ToString(), ResultLink = rij[16].ToString(), MaxQuerytime = rij[17].ToString() });
}
}
}
}
return CallData;
}
Try using this
cmd.Parameters.AddWithValue("#Name", ContextName[i].ToString());
cmd.Parameters.AddWithValue("#Value", ValueName[i].ToString());
You have to add "#" to the parameter name.
new SqlParameter("#Name", ContextName[i].ToString())
new SqlParameter("#Value", ValueName[i].ToString())

ArgumentNull exception in asp.net web application

I have developed an asp.net application in which input will be given through an excel sheet.
This application is working fine in a system with WINDOWS XP and MS office 2008.
If i try to run the same application in a system with WINDOWS 7 and MS office 2010 i am getting a Argument Null Exception.
Code:
foreach (var dr in data)
{
LHSupdate = new LHSUpdate();
if (!string.IsNullOrEmpty(Convert.ToString(dr["Associate Id"])))
{
AssociateID = Convert.ToString(dr["Associate Id"]);
}
LHSupdate.AssciateID = AssociateID;
if (!string.IsNullOrEmpty(Convert.ToString(dr["Associate Name"])))
{
AssociateName = Convert.ToString(dr["Associate Name"]);
}
LHSupdate.Name = AssociateName;
var designation = dsData.Tables["LHS"].AsEnumerable().Where(r => Convert.ToString(r["Associate Id"]).Trim() == LHSupdate.AssciateID.Trim());
if (designation != null)
{
foreach (var de in designation)
{
LHSupdate.Designation = Convert.ToString(de["Level"]);
}
}
else
{
LHSupdate.Designation = "";
}
LHSupdate.CourseName = Convert.ToString(dr["Trainings "]);
LHSupdate.CourseStatus = Convert.ToString(dr["Training Status"]);
LHSupdate.Score = Convert.ToString(dr["Credits"]);
LHSupdate.LearningMode = Convert.ToString(dr["Venue"]);
LHSupdate.StartDate = Convert.ToString(dr["Start Date"]);
LHSupdate.EndDate = Convert.ToString(dr["End Date"]);
lstLHS.Add(LHSupdate);
}
I am getting error in the line:
var designation = dsData.Tables["LHS"].AsEnumerable().Where(r => Convert.ToString(r["Associate Id"]).Trim() == LHSupdate.AssciateID.Trim());
Code:
private DataSet Getdata()
{
string connectionString = "";
string getExcelSheetName = string.Empty;
if (fuLHSEntry.HasFile)
{
string fileName = Path.GetFileName(fuLHSEntry.PostedFile.FileName);
string fileExtension = Path.GetExtension(fuLHSEntry.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
fuLHSEntry.SaveAs(fileLocation);
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + #";Extended Properties=" + Convert.ToChar(34).ToString() + #"Excel 8.0;Imex=1;HDR=Yes;" + Convert.ToChar(34).ToString();
}
else if (fileExtension == ".xlsx" || fileExtension == ".xlsm")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + #";Extended Properties=" + Convert.ToChar(34).ToString() + #"Excel 12.0;IMEX=2;HDR=Yes;" + Convert.ToChar(34).ToString();
}
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
int count = 0;
foreach (DataRow dr in dtExcelSheetName.Rows)
{
getExcelSheetName = GetSheetName(dr);
if (!string.IsNullOrEmpty(getExcelSheetName))
{
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
if (getExcelSheetName.ToUpper().Contains("LEARNING"))
{
getExcelSheetName = "LEARNING";
}
else
{
getExcelSheetName = "LHS";
}
dAdapter.Fill(dsData, getExcelSheetName);
count++;
if (count == 2)
{
break;
}
}
}
con.Close();
}
return dsData;
}
Please help me in resolving this issue.
Thanks,
Raji
From your code it appears that the table can have two possible names.
Either give it always the same name that you're using later when reading:
dAdapter.Fill(dsData, "LHS");
Or you can take the table by index ignoring its name altogether:
var designation = dsData.Tables[0].AsEnumerable().Where(r => Convert.ToString(r["Associate Id"]).Trim() == LHSupdate.AssciateID.Trim());

Resources