asp.net sql or collection problem - asp.net

following is the code on Placementsearch.aspx.cs
protected void Ok_Click(object sender, EventArgs e)
{
try
{
if (Page.IsValid)
{
int course_id = Convert.ToInt32(course.SelectedValue);
int passoutYear = Convert.ToInt32(passout.SelectedValue);
int currentBacklog = Convert.ToInt32(currrentBacklogDDL.SelectedValue);
int sex = Convert.ToInt32(gender.SelectedValue);
int? eGap = null;
int? firstYrPercent = null;
int? secondYrPercent = null;
int? thirdYrPercent = null;
int? finalYearpercent = null;
int? currentDegeePercentage = null;
int? highSchoolPercentge = null;
int? higherSchoolPercentage = null;
int? grauationPercentage = null;
int? diplomaPercentage = null;
int? noOfAtkt = null;
DateTime? date = null;
if (!string.IsNullOrEmpty(DOB.Text.Trim()))
{
string dateOfBirth = DOB.Text.Trim();
DateTime birthDate = DateTime.ParseExact(dateOfBirth, "dd/mm/yyyy", System.Globalization.CultureInfo.InvariantCulture);
string outPut = birthDate.ToString("mm/dd/YYYY");
date = Convert.ToDateTime(outPut);
}
if (!String.IsNullOrEmpty(educationGap.Text.Trim()))
{
eGap = Convert.ToInt32(educationGap.Text.Trim());
}
if (!string.IsNullOrEmpty(firstYear.Text))
{
firstYrPercent = Convert.ToInt32(firstYear.Text.Trim());
}
if (!string.IsNullOrEmpty(secondYear.Text.Trim()))
{
secondYrPercent = Convert.ToInt32(secondYear.Text.Trim());
}
if (!string.IsNullOrEmpty(thirdYear.Text))
{
thirdYrPercent = Convert.ToInt32(thirdYear.Text.Trim());
}
if (!string.IsNullOrEmpty(finalyear.Text.Trim()))
{
finalYearpercent = Convert.ToInt32(finalyear.Text.Trim());
}
if (!string.IsNullOrEmpty(currentDegree.Text.Trim()))
{
currentDegeePercentage = Convert.ToInt32(currentDegree.Text.Trim());
}
if (!string.IsNullOrEmpty(higherSchool.Text.Trim()))
{
higherSchoolPercentage = Convert.ToInt32(higherSchool.Text.Trim());
}
if (!string.IsNullOrEmpty(highSchool.Text.Trim()))
{
highSchoolPercentge = Convert.ToInt32(highSchool.Text.Trim());
}
if (!string.IsNullOrEmpty(graduation.Text.Trim()))
{
grauationPercentage = Convert.ToInt32(graduation.Text.Trim());
}
if (!string.IsNullOrEmpty(diploma.Text.Trim()))
{
diplomaPercentage = Convert.ToInt32(diploma.Text.Trim());
}
if (!string.IsNullOrEmpty(atkt.Text.Trim()))
{
noOfAtkt = Convert.ToInt32(atkt.Text.Trim());
}
Dictionary<string, object> paramList = new Dictionary<string, object>();
paramList.Add("#courseId", course_id);
paramList.Add("#passoutYear", passoutYear);
paramList.Add("#currentBacklog", currentBacklog);
paramList.Add("#sex", sex);
paramList.Add("#eGap", eGap);
paramList.Add("#firstYrPercent", firstYrPercent);
paramList.Add("#secondYrPercent", secondYrPercent);
paramList.Add("#thirdYrPercent", thirdYrPercent);
paramList.Add("#finalYearpercent", finalYearpercent);
paramList.Add("#currentDegeePercentage", currentDegeePercentage);
paramList.Add("#highSchoolPercentge", highSchoolPercentge);
paramList.Add("#higherSchoolPercentage", higherSchoolPercentage);
paramList.Add("#grauationPercentage", grauationPercentage);
paramList.Add("#diplomaPercentage", diplomaPercentage);
paramList.Add("#noOfAtkt", noOfAtkt);
paramList.Add("#date", date);
StringBuilder branchId= new StringBuilder();
foreach (ListItem li in branch.Items)
{
if (li.Selected)
{
branchId.Append(Convert.ToInt32(li.Value));
}
}
DataTable dt = searchManager.GetEligibleStudent(paramList, branchId);
}
}
catch (Exception ex)
{
COMMON.logger.Error("Error On Button click Ok", ex);
}
this is the method which is called from above page. this method is on class searchstudentDAO.cs
public DataTable GetEligibleStudent(Dictionary<string, object> paramList, StringBuilder branchId)
{
try
{
string cmd = #"SELECT * FROM [tbl_students] WHERE course_id=#courseId
AND branch_id IN(" + branchId + #")
AND (#firstYrPercent is null OR first_year_percent>=#firstYrPercent)
AND (#secondYrpercent is null OR second_year_percent>=#secondYrPercent)
AND (#thirdYrPercent is null OR third_year_percent>=#thirdYrPercent)
AND (#finalYearpercent is null OR final_year_percent>=#finalYearpercent)
AND (#currentDegeePercentage is null OR current_degree_percent>=#currentDegeePercentage)
AND (#passoutYear is null OR passing_year>=#passoutYear)
AND (#currentBacklog is null OR current_backlog<=#currentBacklog)
AND gender=#sex
AND (#eGap is null OR gapin_education<=#eGap)
AND (#highSchoolPercentge is null OR highschool_percentage>=#highSchoolPercentge)
AND (#higherSchoolPercentage is null OR ssc_percentage>=#higherSchoolPercentage)
AND (#grauationPercentage is null OR graduation_percentage>=#grauationPercentage)
AND (#diplomaPercentage is null OR diploma_percentage>=#diplomaPercentage)
AND (#noOfAtkt is null OR number_of_ATKT<=#noOfAtkt)
AND (#date is null OR DOB>=#date)";
//string cmd = "SELECT * FROM [tbl_branch] WHERE course_id IN(" + sb + ")";
if (dbManager.OpenConnection())
{
dt = dbManager.GetDataTable(cmd, paramList);
return dt;
}
else
{
dt = null;
return dt;
}
}
catch (Exception ex)
{
COMMON.logger.Error("Error ON Method Getting Eligible Students:SearchStudentDAO", ex);
dt = null;
return dt;
throw;
}
finally
{
dbManager.CloseConnection();
}
}
And followin is code called from the above method on paage App_Code/DBManager.cs
public DataTable GetDataTable(string strCmd, Dictionary<string, object> paramList)
{
try
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand(strCmd, _sqlCon);
foreach (KeyValuePair<string, object> kvp in paramList)
{
cmd.Parameters.AddWithValue(kvp.Key, kvp.Value);
}
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
catch (Exception ex)
{
logger.Error("Error when executing Query " + strCmd, ex);
throw;
return null;
}
}
Now i am getting exception for those null parameter which are not provided
"Parameterized Query '(#courseId int,#passoutYear int,#currentBacklog int,#sex int,#eG' expects parameter #finalYearpercent, which was not supplied."
please correct me where i am wrong

Instead of simply not adding those parameters if they're null, you need to add them, but with the "value" set to DBNull.Value.

Related

How to call a procedure if the procedure does not have parameter

create proc sp_dropdown
as
begin
SELECT r1.regid, r.registration
FROM table1 as r1
INNER JOIN table2 as r ON r1.regid=r.registration and r1.status=r.status
end
this above class is my sp return type,
public class GetAllTableNames_Result
{
public string Name { get; set; }
}
and i can call this like
public List<GetAllTableNames_Result> GetTableNames()
{
List<GetAllTableNames_Result> gatnr = new List<GetAllTableNames_Result>();
SqlCommand cmd = new SqlCommand(
"GetAllTableNames", _connection) {CommandType = CommandType.StoredProcedure};
try
{
_connection.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//do something with data
gatnr.Add(new GetAllTableNames_Result()
{
Name = rdr[0].ToString()
});
}
_connection.Close();
return gatnr;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
finally
{
_connection.Close();
}
}
i believe you can get point

bulk data export to excel and download in ashx file

I have an asp.net application in which I have a js file and an ashx file. Here in a download button click Im calling handler file in ajax call and retrieving sql table data in a json formatted string/data table and Im trying to export json formated string/data table to excel/csv file and download it. Please help me to find a solution. (Need a solution which help to export large amount of data and download)
I tried the below code but its not downloading excel file.
public void ProcessRequest(HttpContext context)
{
context.Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
context.Response.ContentType = "application/csv";
HttpResponse response = context.Response;
string exportContent = ExportToSpreadsheet(JsonStringToDataTable(GetDataFromTable()),'excelfilename');
response.Write(exportContent);
context.Response.End();
}
public DataTable JsonStringToDataTable(string jsonString)
{
DataTable dt = new DataTable();
string[] jsonStringArray = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");
List<string> ColumnsName = new List<string>();
foreach (string jSA in jsonStringArray)
{
string[] jsonStringData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
foreach (string ColumnsNameData in jsonStringData)
{
try
{
int idx = ColumnsNameData.IndexOf(":");
string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", "");
if (!ColumnsName.Contains(ColumnsNameString))
{
ColumnsName.Add(ColumnsNameString);
}
}
catch (Exception ex)
{
//throw new Exception(string.Format(ex.Message + "Error Parsing Column Name : {0}", ColumnsNameData));
throw ex;
}
}
break;
}
foreach (string AddColumnName in ColumnsName)
{
dt.Columns.Add(AddColumnName);
}
foreach (string jSA in jsonStringArray)
{
string[] RowData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
DataRow nr = dt.NewRow();
foreach (string rowData in RowData)
{
try
{
int idx = rowData.IndexOf(":");
string RowColumns = rowData.Substring(0, idx - 1).Replace("\"", "");
string RowDataString = rowData.Substring(idx + 1).Replace("\"", "");
nr[RowColumns] = RowDataString;
}
catch (Exception ex)
{
continue;
}
}
dt.Rows.Add(nr);
}
return dt;
}
private static string GetDataFromTable()
{
string returnValue = string.Empty;
var serializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue };
try
{
var result = //get data from sql table;
returnValue = serializer.Serialize(result);
}
catch (Exception e)
{
returnValue = serializer.Serialize(e.Message);
}
return returnValue;
}
public string ExportToSpreadsheet(DataTable table, string name)
{
string res = string.Empty;
try
{
//var resp = Response;
System.Web.HttpResponse resp = System.Web.HttpContext.Current.Response;
resp.Clear();
if (table != null)
{
foreach (DataColumn column in table.Columns)
{
resp.Write(column.ColumnName + ",");
}
}
resp.Write(Environment.NewLine);
if (table != null)
{
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
resp.Write(row[i].ToString().Replace(",", string.Empty) + ",");
}
resp.Write(Environment.NewLine);
}
}
res = "successfully downloaded";
resp.ContentType = "text/csv";
resp.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".csv");
// resp.End();
}
catch(Exception ex)
{
res = ex.Message;
}
return res;
}
Start using a specialized libary like EPPlus. It will create real Excel files.
private void exportToExcel(DataTable dataTable)
{
using (ExcelPackage excelPackage = new ExcelPackage())
{
//create the worksheet
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
//load the datatable into the sheet, with headers
worksheet.Cells["A1"].LoadFromDataTable(dataTable, true);
//send the file to the browser
byte[] bin = excelPackage.GetAsByteArray();
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-length", bin.Length.ToString());
Response.AddHeader("content-disposition", "attachment; filename=\"ExcelDemo.xlsx\"");
Response.OutputStream.Write(bin, 0, bin.Length);
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}

show message when incorrect login

I have tried this code
When i login with incorrect username and password then it redirect to webform2.aspx where i want to show message Wrong username and password
how i do that ?
i am trying below code but it is not working
protected void Button1_Click(object sender, EventArgs e)
{
if(loginmethod(txt_us.Text,txt_pwd.Text)!="NA")
{
FormsAuthentication.Initialize();
String strRole =Assignroles(txt_us.Text);
FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1, txt_us.Text, DateTime.Now, DateTime.Now.AddMinutes(30), false, strRole, FormsAuthentication.FormsCookiePath);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(fat)));
loginmethod(txt_us.Text, txt_pwd.Text);
Response.Redirect("WebForm2.aspx");
}
else
{
Label1.Text = ("Incorrect UserName/Password");
Label1.Visible = true;
}
txt_us.Text = "";
txt_pwd.Text = "";
}
private string loginmethod(string UserName, string Password)
{
try
{
login_class lg_class = new login_class();
Entities2 login = new Entities2();
string logn = Convert.ToString(lg_class.loginfu(UserName, Password).Rows[0]["id"]);
Session["ID"] = logn.ToString();
return (logn);
}
catch (Exception ex)
{
return (ex.Message.ToString());
}
}
loginfu method
public DataTable loginfunction(string username,string password)
{
try
{
Entities2 lg = new Entities2();
List<SP_GetLogin_Result> gr = lg.SP_GetLogin(username, password).ToList();
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(string));
foreach (var l in gr)
{
dt.Rows.Add(l.id);
}
return dt;
}
catch (Exception)
{
throw new Exception();
}
}
UPDATE
I do this but this show error
Entities2 lg = new Entities2();
DataTable dt = new DataTable();
dt=lg.SP_GetLogin(username,password).ToList();
if (dt.Rows.Count== 0)
{
return "NA";
}
else
{
return dt.Rows[0].ID.ToString();
}
'System.Data.DataRow' does not contain a definition for 'ID' and no extension method 'ID' accepting a first argument of type 'System.Data.DataRow'
could be found (are you missing a using directive or an assembly reference?)
Cannot implicitly convert type 'string' to 'System.Data.DataTable'
'System.Collections.Generic.List' to 'System.Data.DataTable'
Replace
Entities2 lg = new Entities2();
List<SP_GetLogin_Result> gr = lg.SP_GetLogin(username, password).ToList();
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(string));
foreach (var l in gr)
{
dt.Rows.Add(l.id);
}
by
Entities2 lg = new Entities2();
DataTable dt = new DataTable();
dt = lg.SP_GetLogin(username, password);
if(dt.rows.count == 0)
{
return "NA";
}
else
{
return dt.rows[0].something. tostring();
}
try this

Error: Input string was not in a correct format - ASP.Net

Some assistance with sorting this error message would be gratefully appropriated. The error message is triggered when clicking on the submit button after populating the page.
AddNewProduct
public partial class AddNewProduct : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetCategories();
}
}
private void GetCategories()
{
ShoppingCart k = new ShoppingCart();
DataTable dt = k.GetCategories();
if (dt.Rows.Count > 0)
{
ddlProductCategory.DataValueField = "CategoryID";
ddlProductCategory.DataValueField = "CategoryName";
ddlProductCategory.DataSource = dt;
ddlProductCategory.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (UploadProductPhoto.PostedFile != null)
{
SaveProductPhoto();
ShoppingCart k = new ShoppingCart()
{
ProductName = txtProductName.Text,
CategoryID = Convert.ToInt32(ddlProductCategory.SelectedValue),
ProductDescription = txtProductDescription.Text,
ProductPrice = txtProductPrice.Text,
ProductStock = txtProductStock.Text,
ProductImageUrl = string.Format("/ProductImages/{0}", UploadProductPhoto.FileName)
};
k.AddProduct();
ClearText();
Response.Redirect("~/Admin/AdminFillerPage.aspx");
}
}
private void ClearText()
{
txtProductName.Text = string.Empty;
txtProductDescription.Text = string.Empty;
txtProductPrice.Text = string.Empty;
txtProductStock.Text = string.Empty;
UploadProductPhoto = null;
}
private void SaveProductPhoto()
{
if (UploadProductPhoto.PostedFile != null)
{
string fileName = UploadProductPhoto.PostedFile.FileName.ToString();
string fileExtension = System.IO.Path.GetExtension(UploadProductPhoto.FileName);
//check file name legnth
if (fileName.Length > 96)
{
//Alert.Show("image name should not exceed 96 characters !");
}
//check filetype
else if (fileExtension != ".jpeg" && fileExtension != ".jpg" && fileExtension != ".png" && fileExtension != ".bmp")
{
//Alert.Show("Only jpeg,jpg,bmp & png imags are allowed!");
}
//check file size
else if (UploadProductPhoto.PostedFile.ContentLength > 4000000)
{
//Alert.Show("image size should not be greater than 4MB !");
}
//Save images into Images folder
else
{
UploadProductPhoto.SaveAs(System.IO.Path.Combine(Server.MapPath("~/ProductImages/"), fileName));
}
}
}
Shopping Cart
public class ShoppingCart
{
//Declaring Variables
public int CategoryID;
public string CategoryName;
public string ProductName;
public string ProductDescription;
public string ProductPrice;
public string ProductStock;
public string ProductImageUrl;
public void AddCategory()
{
SqlParameter[] parameters = new SqlParameter[1];
parameters[0] = DataAccess.AddParamater("#CategoryName", CategoryName, System.Data.SqlDbType.VarChar, 200);
DataTable dt = DataAccess.ExecuteDTByProcedure("mj350.AddCategory", parameters);
}
public void AddProduct()
{
SqlParameter[] parameters = new SqlParameter[6];
//Passing all the parameters that needed to be saved into the database
parameters[0] = DataLayer.DataAccess.AddParamater("#ProductName", ProductName, System.Data.SqlDbType.VarChar, 500);
parameters[1] = DataLayer.DataAccess.AddParamater("#CategoryID", CategoryID, System.Data.SqlDbType.Int, 100);
parameters[2] = DataLayer.DataAccess.AddParamater("#ProductDescription", ProductDescription, System.Data.SqlDbType.VarChar, 800);
parameters[3] = DataLayer.DataAccess.AddParamater("#ProductPrice", ProductPrice, System.Data.SqlDbType.VarChar, 500);
parameters[4] = DataLayer.DataAccess.AddParamater("#ProductStock", ProductStock, System.Data.SqlDbType.VarChar, 500);
parameters[5] = DataLayer.DataAccess.AddParamater("#ProductImage", ProductImageUrl, System.Data.SqlDbType.VarChar, 500);
//Executes the saved procedure that is saved in the database
DataTable dt = DataLayer.DataAccess.ExecuteDTByProcedure("mj350.AddProduct", parameters);
}
Stored Procedure - Add Product
CREATE PROCEDURE [AddProduct]
(
#ProductName varchar(500),
#CategoryID int,
#ProductDescription varchar(800),
#ProductPrice varchar(500),
#ProductStock varchar(500),
#ProductImage varchar(500)
)
AS
BEGIN
BEGIN TRY
INSERT INTO Product VALUES
(
#ProductName,
#CategoryID,
#ProductDescription,
#ProductPrice,
#ProductStock,
#ProductImage
)
END TRY
BEGIN CATCH
-- INSERT INTO dbo.ErrorLog
--VALUES(ERROR_MESSAGE(),'sp_GetAllData')
PRINT( 'Error occured' )
END CATCH
END
Stored Procedure - Get Categories
CREATE PROCEDURE [mj350].[ListCategories]
AS
BEGIN
BEGIN TRY
SELECT * FROM Category
END TRY
BEGIN CATCH
-- INSRET INTO dbo.ErrorLog
-- VALYES(ERROR_MESSAGE(), 'SP_GetAllData')
PRINT( 'Data Insert Error - Please review' )
END CATCH
END
Sorry if it's a silly mistake - coding skills not the best. All help gratefully received.
Thanks
Jack
Example of data form is populated with &
Where error message is triggered in code
You have this error because of the following code
private void GetCategories()
{
ShoppingCart k = new ShoppingCart();
DataTable dt = k.GetCategories();
if (dt.Rows.Count > 0)
{
ddlProductCategory.DataValueField = "CategoryID";
ddlProductCategory.DataValueField = "CategoryName"; // Here you overwrite the DataValueField.
ddlProductCategory.DataSource = dt;
ddlProductCategory.DataBind();
}
}
You overwrite the DataValueField with CategoryName property name. Then when you submit your form you are executing the following code :
ShoppingCart k = new ShoppingCart()
{
ProductName = txtProductName.Text,
CategoryID = Convert.ToInt32(ddlProductCategory.SelectedValue), // Here SelectedValue is in incorrect format.
ProductDescription = txtProductDescription.Text,
ProductPrice = txtProductPrice.Text,
ProductStock = txtProductStock.Text,
ProductImageUrl = string.Format("/ProductImages/{0}", UploadProductPhoto.FileName)
};
The exception is thrown because of this line CategoryID = Convert.ToInt32(ddlProductCategory.SelectedValue). The posted Selected value is not in correct format because you bind the value of your dropdown list with the name of the category.
To solve this you must replace this line ddlProductCategory.DataValueField = "CategoryName"; in your GetCategories by this line ddlProductCategory.DataTextField = "CategoryName";

Arithmetic operation resulted in an overflow

After updating my website on ii7 on window server 2008 from framework 3.5 to work with framework 4
i got my c# base database class stop working copmlitly with this error: "Arithmetic operation resulted in an overflow".
I am working with mysql server from different server.
I did not find any solution on this so i had very sadness to role bakce to framework 3.5
here is some of my logs for this error in the event viewr on my server:
Process information:
Process ID: 3680
Process name: w3wp.exe
Account name: NT AUTHORITY\NETWORK SERVICE
Exception information:
Exception type: OverflowException
Exception message: Arithmetic operation resulted in an overflow.
at DataAccess.ExecuteStringQuery(String strSQL) in d:\webSites\s2s\App_Code\DB\DataAccess.cs:line 214
at DataSelect.generalString(String rowName, String tableName, String idName, String ID) in d:\webSites\s2s\App_Code\DB\DataSelect.cs:line 48
at camsBaseShowWeb.OnPreInit(EventArgs e) in d:\webSites\s2s\App_Code\Bases\camsBaseShowWeb.cs:line 134
at System.Web.UI.Page.PerformPreInit()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
big thanks for any halp
i got this error - no matter wich function i try to call from this code
here is my code:
using System;
using System.Data;
//using Microsoft.Data.Odbc;
using System.Data.Odbc;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public class DataAccess
{
#region Private Variables
private static DataAccess _DataAccess = null;
private static object _SyncLock = new object();
private string _strCon = "Driver={MySQL ODBC 5.1 Driver};Server=theIP;Database=theDatabase; UID=root;Password=thePassword;Option=3;";
private OdbcConnection myConnection = null;
#endregion
#region Instance Method
public static DataAccess Instance
{
get
{
lock (_SyncLock)
{
if (_DataAccess == null)
_DataAccess = new DataAccess();
return _DataAccess;
}
}
}
#endregion
#region Constractors
public DataAccess()
{
myConnection = new OdbcConnection(_strCon);
myConnection.Open();
}
#endregion
#region Public Functions
public OdbcDataReader ExecuteQueryReader(string strSQL)
{
try
{
OdbcCommand myCommand = new OdbcCommand(strSQL, myConnection);
return myCommand.ExecuteReader();
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteQueryReader SQL s2s", strSQL, ex);
}
throw ex;
}
}
public DataTable ExecuteQuery(string strSQL)
{
DataTable dt = new DataTable();
OdbcDataAdapter objDataAdapter = null;
try
{
objDataAdapter = new OdbcDataAdapter(strSQL, myConnection);
objDataAdapter.Fill(dt);
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (objDataAdapter != null) objDataAdapter.Dispose();
}
return dt;
}
public DataView ExecuteQueryDV(string strSQL)
{
DataTable dt = new DataTable();
OdbcDataAdapter objDataAdapter = null;
try
{
objDataAdapter = new OdbcDataAdapter(strSQL, myConnection);
objDataAdapter.Fill(dt);
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (objDataAdapter != null) objDataAdapter.Dispose();
}
return new DataView(dt);
}
public DataTable ExecuteLimitedQuery(string strSQL, int startRow, int rowNum)
{
DataTable dt;
DataSet ds = new DataSet();
OdbcDataAdapter objDataAdapter = null;
try
{
objDataAdapter = new OdbcDataAdapter(strSQL, myConnection);
objDataAdapter.Fill(ds, startRow, rowNum, "rowTable");
dt = (DataTable)ds.Tables["rowTable"];
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteLimitedQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (objDataAdapter != null) objDataAdapter.Dispose();
}
return dt;
}
public object ExecuteScalarQuery(string strSQL)
{
OdbcCommand myCommand = null;
object obj = null;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
obj = myCommand.ExecuteScalar();
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteScalarQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return obj;
}
public string ExecuteStringQuery(string strSQL)
{
OdbcCommand myCommand = null;
object obj = null;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
obj = myCommand.ExecuteScalar();
}
catch (Exception ex)
{
if (myConnection.State != ConnectionState.Open)
{
myConnection.Open();
if (myCommand != null) myCommand.Dispose();
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
obj = myCommand.ExecuteScalar();
}
catch (Exception ex2)
{
if (Dict.IsRemote == true)
{
sendMail("error - לאחר ניסיון שני ExecuteStringQuery SQL s2s", strSQL, ex2);
}
throw ex2;
}
}
else
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteStringQuery SQL s2s", strSQL, ex);
}
throw ex;
}
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return obj != null ? obj.ToString() : string.Empty;
}
public int ExecuteNoneQuery(string strSQL)
{
OdbcCommand myCommand = null;
int i;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
i = myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteNoneQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return i;
}
public int InsertGetLastID(string strSQL)
{
OdbcCommand myCommand = null;
int LastID = 0;
object objID = null;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
if (myCommand.ExecuteNonQuery() == 1)
{
myCommand = new OdbcCommand("SELECT LAST_INSERT_ID()", myConnection);
objID = myCommand.ExecuteScalar();
if (objID != null)
{
LastID = int.Parse(objID.ToString());
}
}
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error InsertGetLastID SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return LastID;
}
private void sendMail(string title, string sql, Exception ex)
{
string body = string.Empty +
"SQL:\n\n" + sql + "\n\n" +
"Exeption:\n\n" + ex.Message + "\n\n" +
"Stack Trace:\n\n" + ex.StackTrace + "\n\n" +
"Source:\n\n" + ex.Source + "\n\n";
mailSend mailS = new mailSend("theMail", "mailTo", title, body);
}
#endregion
}
I was getting this too since the upgrade to .Net 4.0
System.OverflowException: Arithmetic operation resulted in an overflow.
at System.Data.Odbc.OdbcDataReader.GetSqlType(Int32 i)
at System.Data.Odbc.OdbcDataReader.GetValue(Int32 i)
at System.Data.Odbc.OdbcCommand.ExecuteScalar()
at Server.Engines.MyRunUO.DatabaseCommandQueue.Thread_Start() in d:\RunUO\Sec
ondAge\Scripts\Engines\MyRunUO\DatabaseCommandQueue.cs:line 117
OdbcConnection version is System.Data.dll, v4.0.30319
Using "{MySQL ODBC 5.1 Driver}" (actually 5.01.06.00) against MySQL 5.1.40-community via TCP/IP on localhost.
The query was any variation of:
SELECT COUNT(*) FROM myrunuo_timestamps WHERE time_type='chardb'
The (apparently) offending lines:
command.CommandText = string.Format("SELECT COUNT(*) FROM myrunuo_timestamps WHERE time_type='{0}'", m_timeStampName); // Line 116
object result = command.ExecuteScalar(); // Line 117
This occurred with an x64 compile only, i.e. using the x64 mySQL driver.
This was fixed by upgrading from mySQL ODBC driver 5.01.06.00 to 5.01.08.00
conver to boolean function does not work when
1. Development is done on 32 bit OS
2. Implementation is done on 64 bit OS
When I altered the code for Convert.ToBoolean function, It worked normally.

Resources