ASP.NET Core issues with DB2 queries in IIS - c#

I'm working on a web app in ASP.Net Core v1.0 in VS2015. The premise of this application is simply to retrieve information from our DB2 database and display it for our dispatchers to use. The issue I'm running into is while on my development PC the application runs fine in IIS Express but once deployed I get the following error:
Index (zero based) must be greater than or equal to zero.
So I know that my query is coming back with no results, I have tried changing settings in IIS but I can't seem to get this to work. The results are retrieved and displayed correctly when debugging on my PC. Also this is the code behind of the retrieving controller:
public ViewResult EvvCityFull()
{
DB2Command myDB2Command = null;
string myDb2ConnectionString = "Server=Server;Database=DB;UID=User;PWD=Pass;";
DB2Connection myDb2Connection = new DB2Connection(myDb2ConnectionString);
myDb2Connection.Open();
myDB2Command = myDb2Connection.CreateCommand();
myDB2Command.CommandText = "SELECT DISTINCT FINAL_DRIVERS.DRIVER_ID, FINAL_DRIVERS.NAME, FINAL_DRIVERS.STATUS, FINAL_DRIVERS.REMAINING_HOURS, FINAL_DRIVERS.LAST_SAT_LOC, FINAL_DRIVERS.LAST_SAT_DATE FROM " +
"(" +
"SELECT BASE_DRIVERS.DRIVER_ID, BASE_DRIVERS.NAME, BASE_DRIVERS.STATUS, BASE_DRIVERS.REMAINING_HOURS, BASE_DRIVERS.LAST_SAT_LOC, BASE_DRIVERS.LAST_SAT_DATE, DATA AS EMPLOYMENT " +
"FROM " +
"(" +
"SELECT BOARD_DRIVERS.DRIVER_ID, BOARD_DRIVERS.NAME, BOARD_DRIVERS.STATUS, BOARD_DRIVERS.REMAINING_HOURS, BOARD_DRIVERS.LAST_SAT_LOC, BOARD_DRIVERS.LAST_SAT_DATE, DATA AS CITY " +
"FROM " +
"(" +
"SELECT DRIVER_ID, NAME, STATUS, REMAINING_HOURS, LAST_SAT_LOC, LAST_SAT_DATE, DATA AS BOARD FROM TMWIN.DRIVER, TMWIN.CUSTOM_DATA " +
"WHERE DRIVER_ID = SRC_TABLE_KEY " +
"AND ACTIVE_IN_DISP = 'True' " +
"AND CUSTDEF_ID = 6 " +
"AND DATA IN('CITY') " +
"AND REMAINING_HOURS IS NOT NULL " +
"AND STATUS IS NOT NULL " +
") BOARD_DRIVERS, " +
"TMWIN.CUSTOM_DATA " +
"WHERE BOARD_DRIVERS.DRIVER_ID = SRC_TABLE_KEY " +
"AND CUSTDEF_ID = 7 " +
"AND DATA IN('EVANSVILLE') " +
") BASE_DRIVERS, " +
"TMWIN.CUSTOM_DATA " +
"WHERE BASE_DRIVERS.DRIVER_ID = SRC_TABLE_KEY " +
"AND CUSTDEF_ID = 9 " +
"AND DATA IN('FULL-TIME') " +
") FINAL_DRIVERS LEFT JOIN TMWIN.CUSTOM_DATA " +
"ON FINAL_DRIVERS.DRIVER_ID = SRC_TABLE_KEY ORDER BY FINAL_DRIVERS.DRIVER_ID ASC";
DB2DataReader myDb2DataReader = null;
List<Driver> result = new List<Driver>();
using (myDb2DataReader = myDB2Command.ExecuteReader())
{
while (myDb2DataReader.Read())
{
Driver driver = new Driver();
driver.DRIVER_ID = myDb2DataReader["DRIVER_ID"].ToString();
driver.NAME = myDb2DataReader["NAME"].ToString();
driver.STATUS = myDb2DataReader["STATUS"].ToString();
driver.REMAINING_HOURS = Convert.ToDouble(myDb2DataReader["REMAINING_HOURS"].ToString());
driver.LAST_SAT_LOC = myDb2DataReader["LAST_SAT_LOC"].ToString();
driver.LAST_SAT_DATE = Convert.ToDateTime(myDb2DataReader["LAST_SAT_DATE"].ToString());
result.Add(driver);
}
}
myDb2DataReader.Close();
myDB2Command.Dispose();
myDb2Connection.Close();
ViewBag.Drivers = result;
return View(ViewBag.Drivers);
}
I cannot figure out the difference in the environments that makes this query work and return the appropriate data on my machine but fails to return anything when deployed. If anyone has any answers for me it'd be greatly appreciated, thank you.

Related

Input string was not in a correct format. using MYSQL

I had a code that was working the past few weeks and am getting an ERROR "Input string was not in a correct format"
NB:(MVC Asp.net)
the view gets data from the Razor page URL and Execute a query
the URL is like this: https://localhost:44348/Devices/Details/5?typeName=Dongle
and the following the View code :
public ActionResult Details(string typeName, int? id)
{
var sql = "SELECT A.*," +
" COALESCE(ps.first_name, '') as firstname," +
" COALESCE(ps.last_name, '') as lastname," +
" COALESCE(p.program_name, '') as program_Name, " +
" COALESCE(l.loan_date, '') as loan_date, " +
" COALESCE(l.return_date, '') as return_date" +
" FROM devices A" +
" LEFT JOIN device_loans l on l.device_id = A.device_id" +
" LEFT JOIN persons ps on ps.person_id = l.person_id" +
" LEFT JOIN programs p on A.program_id = p.program_id" +
" WHERE A.device_type = '" + typeName + "' and p.program_id = "+ id +";";
var devices = _context.DeviceDetails
.FromSqlRaw(sql)
.ToList();
return View(devices);
}
I have tried Passing parameters with parameter placeholders but still not working
please help.
Because your parameter id: is nullable, you need combine sql like:
var sql = "SELECT A.*," +
" COALESCE(ps.first_name, '') as firstname," +
" COALESCE(ps.last_name, '') as lastname," +
" COALESCE(p.program_name, '') as program_Name, " +
" COALESCE(l.loan_date, '') as loan_date, " +
" COALESCE(l.return_date, '') as return_date" +
" FROM devices A" +
" LEFT JOIN device_loans l on l.device_id = A.device_id" +
" LEFT JOIN persons ps on ps.person_id = l.person_id" +
" LEFT JOIN programs p on A.program_id = p.program_id" +
" WHERE A.device_type = '" + typeName + "'";
if(id!=null){
sql += " and p.program_id = "+ id +";";
}
BTW: your code has SQL injection risk

Creating a database programmatically in SQL Server with parameters

As of right now I have a working piece of code, that looks something like this:
string sqlCreateDBQuery = " CREATE DATABASE "
+ "["+databaseName+"]"
+ " ON PRIMARY "
+ " (NAME = Data, "
+ " FILENAME = '" + strDataPath + databaseName + ".mdf', "
+ " FILEGROWTH = 1MB) "
+ " LOG ON (NAME = Log, "
+ " FILENAME = '" + strLogPath + databaseName + "_log.ldf', "
+ " FILEGROWTH = 10%) "
+ " COLLATE Latin1_General_CI_AS ;";
SqlCommand command = new SqlCommand(sqlCreateDBQuery, connection);
This has, with my current understanding, the potential issue of SQL-Injection attacks and well, user input errors.
So my question is, how do I safely create a database programmatically on an SQL Server where the user is able to name the database?
I know that one should use parameterized SQL-Queries to avoid SQL-Injection attempts, but for some reason I can´t seem to figure out how to do this for creating a new database or users/logins.
I´ve also read, that there is the option to use the SQL Server Management Object API as described in this answer here: Creating a database programmatically in SQL Server
Unfortunately this is not an option for us.
As of right now I haven´t figured out how to use a parameterized Query for this task.
This is what I would assume what the Code should look like to achieve this, but with no working result.
SqlCommand command = connection.CreateCommand();
command.CommandText = " CREATE DATABASE "
+ "#dbName"
+ " ON PRIMARY "
+ " (NAME = Data, "
+ " FILENAME = #dataPath, "
+ " FILEGROWTH = 1MB) "
+ " LOG ON (NAME = Log, "
+ " FILENAME = #logPath, "
+ " FILEGROWTH = 10%) "
+ " COLLATE Latin1_General_CI_AS ;";
command.Parameters.AddWithValue("#dbName", StrDBName);
command.Parameters.AddWithValue("#dataPath", $"{strDataPath}{StrDBName}.mdf");
command.Parameters.AddWithValue("#logPath", $"{strLogPath}{StrDBName}_log.ldf");
I´ve also read Here that this should be possible with dynamic SQL, but sadly all my attempts either ended in Syntax errors or the parameters not being replaced by the actual values.
Am I missing something here or is this just not as trivial as I initially thought?

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints. C# Windows forms

I was working on Firebird Server and SQL Server to update database from the Firebird database to the SQL server database. This update was done using a tool called Updater Tool. I have created this tool using C# Windows Application, it was successfully running.
This database contains financial data. The client has provided a Firebird database backup file with data up to 2016, and it was successfully updating the database.
I have restored the backup file successfully on my system, so I have created a setup file and installed it on the client system and I started updating the database. The client has the latest data, it was working and updating SQL database.
It was updating some tables and then got an error "Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints." and operation was cancelled.
What I need is, whenever I get this type of error, I want to skip or ignore the error and the remaining part should update the database. How I have created the update tool means,
I have created arrays that store all table columns. This is done because only selected columns from Firebird database table columns were updated in the SQL Server database.
Each table contains 2 primary key columns with this I have created a comparison of the two databases to find which data is not present in the SQL Server database. The compared table rows are stored in DataTable.
The updating is done by selecting a date. In updater tool, I have provided a datetimepicker, the client can select the date and update his database. What client has done means that the SQL Server database was updated up to 2015 and client wants to update data from 2017 that means client left 2016 data, so in database comparison it gets the entire data above 2017. Here is a link, based on this I have created comparison method Database Comparison.
Below is the code how I update the database
public void UpdateToDatabse(DataTable table, string selectQuery, ArrayList columnNames, string tableName)
{
string fbSelectStatementQuery;
int insertedCount = 0;
int notInsertedCount = 0;
listBox1.Items.Add("Total Rows to update " + table.Rows.Count);
using (FbConnection fbconn = getFbConnection(textBox1.Text))
{
FbCommand fbcmd = new FbCommand();
fbcmd.Connection = fbconn;
for (int i = 0; i < table.Rows.Count; i++)
{
if (tableName == "COMPDATA" || tableName == "COMPMAS")
{
fbSelectStatementQuery = #"" + selectQuery
+ " Where \"" + table.Columns[0].ColumnName + "\"='" + table.Rows[i][0] + "'";
fbcmd.CommandText = fbSelectStatementQuery;
}
else if (tableName == "DLYPRICEBSE" || tableName == "DLYPRICENSE")
{
fbSelectStatementQuery = #"" + selectQuery
+ " Where \"" + table.Columns[0].ColumnName + "\"='" + table.Rows[i][0] + "' and \""
+ table.Columns[1].ColumnName + "\"='" + Convert.ToDateTime(table.Rows[i][1]).ToShortDateString() + "' and \""
+ table.Columns[2].ColumnName + "\"='" + table.Rows[i][2] + "' and \""
+ table.Columns[3].ColumnName + "\"='" + table.Rows[i][3] + "' and \""
+ table.Columns[4].ColumnName + "\"='" + table.Rows[i][4] + "' and \""
+ table.Columns[5].ColumnName + "\"='" + table.Rows[i][5] + "' and \""
+ table.Columns[6].ColumnName + "\"='" + table.Rows[i][6] + "' and \""
+ table.Columns[7].ColumnName + "\"='" + table.Rows[i][7] + "' and \""
+ table.Columns[8].ColumnName + "\"='" + table.Rows[i][8] + "' and \""
+ table.Columns[9].ColumnName + "\"='" + table.Rows[i][9] + "' and \""
+ table.Columns[10].ColumnName + "\"='" + table.Rows[i][10] + "' and \""
+ table.Columns[11].ColumnName + "\"='" + table.Rows[i][11] + "' and \""
+ table.Columns[12].ColumnName + "\"='" + table.Rows[i][12] + "' and \""
+ table.Columns[13].ColumnName + "\"='" + table.Rows[i][13] + "' and \""
+ table.Columns[14].ColumnName + "\"='" + table.Rows[i][14] + "' and \""
+ table.Columns[15].ColumnName + "\"='" + table.Rows[i][15] + "'";
fbcmd.CommandText = fbSelectStatementQuery;
}
else if (tableName == "EQTYHIS")
{
fbSelectStatementQuery = #"" + selectQuery
+ " Where \"" + table.Columns[0].ColumnName + "\"='" + table.Rows[i][0] + "' and \""
+ table.Columns[1].ColumnName + "\"='" + Convert.ToDateTime(table.Rows[i][1]).ToShortDateString() + "' ";
fbcmd.CommandText = fbSelectStatementQuery;
}
else
{
fbSelectStatementQuery = #"" + selectQuery
+ " Where \"" + table.Columns[0].ColumnName + "\"='" + table.Rows[i][0] + "' and \""
+ table.Columns[1].ColumnName + "\"='" + table.Rows[i][1] + "' ";
fbcmd.CommandText = fbSelectStatementQuery;
}
using (FbDataReader fbreader = fbcmd.ExecuteReader())
{
while (fbreader.Read())
{
string colValues = #"( ";
string columns = #"";
int j = 0;
while (j < columnNames.Count)
{
if (j < columnNames.Count - 1)
{
columns += "\"" + columnNames[j] + "\"" + ", ";
colValues += "'" + ((Object)fbreader[columnNames[j].ToString()]) + "', ";
}
else
{
columns += "\"" + columnNames[j] + "\"";
colValues += "'" + fbreader[columnNames[j].ToString()] + "' )";
}
j++;
}
string insertQuery = "INSERT INTO Data." + tableName + " (" + columns + ") VALUES " + colValues;
using (SqlConnection sqlconn = getSqlConncetion())
{
try
{
SqlCommand sqlcmd = new SqlCommand(insertQuery, sqlconn);
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
insertedCount++;
}
catch (Exception ex)
{
notInsertedCount++;
//MessageBox.Show("Not Inserted-->" + ex.Message);
//listBox1.Items.Add(fbreader["CO_CODE"] + ex.Message);
}
}
}
fbreader.Close();
}
}
listBox1.Items.Add(insertedCount + " Rows are Updated....");
if (notInsertedCount > 0)
{
listBox1.Items.Add(notInsertedCount + " Rows are not Updated....");
listBox1.Items.Add("....");
}
else
{
listBox1.Items.Add("....");
}
//MessageBox.Show(insertedCount + " Rows are Updated in IBDMaster table " + tableName);
fbconn.Close();
}
return;
}
First, I want to skip or ignore the error I'm getting.
Second, the database code is performing slowly, is there any method to do a fast update to the database.

SqlDataAdapter does not fill up datatable but SQL statement works fine in SQL Server Management Studio

I have trouble understanding why this doesn't work as it works for some of my SQL statements.
I am trying to populate a dataset using a SqlDataAdpter to store the select result and then use it to populate my result page
string sqlStr = "SELECT IRSwapId, " +
"i.InventoryName ," +
"Notional ," +
"TradeDate," +
"effectiveDate," +
"MaturityDate," +
"settleDate," +
"FixedRate," +
"ltrim(rtrim(cp.CounterParty))," +
"MurexReference," +
"case when PayReceiveFlag = -1 then 'Pay' else 'Receive' " +
"end as PayReceiveFlag," +
"ltrim(rtrim(c.currency)) ," +
"fixedValue," +
"floatValue," +
"comments," +
"CASE MurexUploadFlag WHEN 0 THEN 'N' WHEN 1 THEN 'Y' END " +
"FROM IRSwaps irs, Currency c, CounterParty cp, Inventory i " +
"WHERE i.InventoryID = irs.InventoryID AND cp.CounterPartyId = irs.CounterPartyId AND c.CurrencyID = irs.Currency " +
"AND IRSTypeId = '2' " +
(criteria == "" ? "" : " AND " + criteria + " ");
return Strucfin.Instance.Query(sqlStr).Tables[0].Rows;
public DataSet Query(string sqlStr)
{
DataSet ds = new DataSet();
lock (m_sfConn)
{
m_sqlDa = new SqlDataAdapter(sqlStr, m_sfConn);
m_sqlDa.Fill(ds);
}
return ds;
}
But when I enter ds.Tables[0].Rows in the immediate table, it shows me nothing, the sqlStr that I took from the local windows works in SQL Server Management Studio.
Thank you so much.

crystal report are not displaying my records

I have sap Crystal Report 13 in my application, It is working fine in simple tables, But in specific scenario like: I have a table which loaded via store procedure when i load this table, then report going to be called and after showing the report i clean the table by using delete query. If i comment that query report show record otherwise empty report appears. Please see my code:
private void btnPreview_Click(System.Object sender, System.EventArgs e)
{
if (IsErrorFound() == false)
{
MyResources.WaitDialogCreate("Loading....");
string FormulaString = "";
string Parameters = "";
//***** Insert Data in table naamed tblReportTrialBalanceWith (With and Without Of Opening Bal) FROM Store Procedure
string Qry = "INSERT INTO tblReportTrialBalanceWithOpening EXEC [spTrialBalance] #MinFY = '" + GlobalVriables.FYearDateStart.Year.ToString() + "'," +
"#MaxFY = '" + GlobalVriables.FYearDateEnd.Year.ToString() + "'," +
"#DateFrom = '" + MyResources.getDateForDB(dteFromDate.Text.Trim()) + "'," +
"#DateTo = '" + MyResources.getDateForDB(dteToDate.Text.Trim()) + "'," +
"#FromCode = '" + lkpFromCode.Text.Trim() + "'," +
"#ToCode = '" + lkpToCode.Text.Trim() + "'," +
"#Category = '" + rdoAccCategory.Text.Trim() + "'";
DatabaseHelper.ExecuteNonQuery(Qry);
if (chkWithOutOB.Checked == true)
{
//************* Parameters
Parameters = "CompanyName=" + GlobalVriables.CompanyName +
"&StartingDate=" + dteFromDate.Text +
"&EndingDate=" + dteToDate.Text +
"&Category=" + (rdoAccCategory.SelectedIndex == 0 ? "All Categories" : rdoAccCategory.Text.Trim()) +
"&FYear=[" + GlobalVriables.FYearDateStart.Year + "-" + GlobalVriables.FYearDateEnd.Year + "]";
switch (rdoAccCategory.SelectedIndex)
{
case 0:
Parameters = Parameters + "&ReportCase=0";
break;
case 2:
Parameters = Parameters + "&ReportCase=2";
break;
default:
Parameters = Parameters + "&ReportCase=1";
break;
}
MyResources.ViewReport("RptTrialBalanceWithOutOB.rpt", FormulaString, Parameters);
////***** Clean up tblReportTrialBalanceWithOpening for Future use.
//Qry = "DELETE FROM tblReportTrialBalanceWithOpening";
//DatabaseHelper.ExecuteNonQuery(Qry);
}
else
{
//************* Parameters
Parameters = "CompanyName=" + GlobalVriables.CompanyName +
"&StartingDate=" + dteFromDate.Text.Trim() +
"&EndingDate=" + dteToDate.Text +
"&Category=" + (rdoAccCategory.SelectedIndex == 0 ? "All Categories" : rdoAccCategory.EditValue.ToString()) +
"&FYear=[" + GlobalVriables.FYearDateStart.Year + "-" + GlobalVriables.FYearDateEnd.Year + "]";
switch (rdoAccCategory.SelectedIndex)
{
case 0:
Parameters = Parameters + "&ReportCase=0";
break;
case 2:
Parameters = Parameters + "&ReportCase=2";
break;
default:
Parameters = Parameters + "&ReportCase=1";
break;
}
MyResources.ViewReport("RptTrialBalance.rpt", FormulaString, Parameters);
////***** Clean up tblReportTrialBalanceWithOpening for Future use.
//Qry = "DELETE FROM tblReportTrialBalanceWithOpening";
//DatabaseHelper.ExecuteNonQuery(Qry);
}
MyResources.WaitDialogDispose();
//***** Clean up tblReportTrialBalanceWithOpening for Future use.
Qry = "DELETE FROM tblReportTrialBalanceWithOpening";
DatabaseHelper.ExecuteNonQuery(Qry);
}
}
you can see my delete query if i comment it. My report shows record. delete query is must in my case. So please help me i am total scattered. One more thing remember my app was upgraded from 2010 to 2012 visual studio successfully expect this problem.

Categories