crystal report are not displaying my records - c#

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.

Related

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.

ASP.NET Core issues with DB2 queries in IIS

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.

Can I use SQLCLR stored procedure to update a column of a database table ( using some compiled dll)

I wanted to update the values of a few columns of a database table, using queries or stored procedure, but wanted to use my C# library to alter the value.
For eg, I want the columns A,B,C of table T to be replaced with Encrypt(A), Encrypt(B) and Encrypt(C) where Encrypt is a part of a C# library. I could have done it in a simple console application, but I have to do this process for a lot of columns in lot of tables.
Could I use a SQLCLR stored procedure / query to do this process in SQL Server Management Studio? It will be really great if someone could assist in this.
public class SP
{
[Microsoft.SqlServer.Server.SqlFunction()]
public static void Enc()
{
using (SqlConnection connection = new SqlConnection("context connection=true"))
{
connection.Open();
SqlCommand command;
SqlCommand command1;
for (int i = 0; i < 1; i++)
{
command = new SqlCommand("SELECT " + tableFieldArray[i, 1].ToString() + " FROM " + tableFieldArray[i, 0].ToString(), connection);
SqlDataReader reader = command.ExecuteReader();
using (reader)
{
while (reader.Read())
{
if (!reader.IsDBNull(0) && !String.IsNullOrEmpty(reader.GetString(0)))
{
//SqlContext.Pipe.Send("Data = " + reader.GetString(0) + "; Encrypted = " + Encrypt(reader.GetString(0)));
SqlContext.Pipe.Send("UPDATE " + tableFieldArray[i, 0].ToString() + " SET "
+ tableFieldArray[i, 1].ToString() + " = '" + Encrypt(reader.GetString(0)) + "' "
+ "WHERE " + tableFieldArray[i, 1].ToString() + " = '" + reader.GetString(0) + "'");
//query = "UPDATE " + tableFieldArray[i, 0].ToString() + " SET "
// + tableFieldArray[i, 1].ToString() + " = '" + Encrypt(reader.GetString(0)) + "' "
// + "WHERE " + tableFieldArray[i, 1].ToString() + " = '" + reader.GetString(0) + "'";
command1 = new SqlCommand("UPDATE " + tableFieldArray[i, 0].ToString() + " SET "
+ tableFieldArray[i, 1].ToString() + " = '" + Encrypt(reader.GetString(0)) + "' "
+ "WHERE " + tableFieldArray[i, 1].ToString() + " = '" + reader.GetString(0) + "'",connection);
}
}
}
SqlCommand command1 = new SqlCommand(query , connection);
command1.ExecuteNonQuery();
}
connection.Close();
}
}
public static string Encrypt(string TextFromForm)
{
//implementation
}
}
}
You can use SQLCLR to call encryption from C#, though this is the wrong approach. If you need to do a custom algorithm, you should encapsulate that into a SQLCLR function so that it can be used in an UPDATE statement or even an INSERT or SELECT or anywhere. Something like:
public class SP
{
[Microsoft.SqlServer.Server.SqlFunction(IsDeterministic = true)]
public static SqlString EncryptByAES(SqlString TextToEncrypt)
{
return DoSomething(TextToEncrypt.Value);
}
}
Then you can use that function as follows:
UPDATE tb
SET tb.FieldA = EncryptByAES(tb.FieldA)
FROM dbo.TableName tb
WHERE tb.FieldA some_test_to_determine_that_FieldA_is_not_alreay_encrypted;
BUT, before you write a custom encryption algorithm, you might want to check out the several built-in paired ENCRYPTBY / DECRYPTBY functions that might do exactly what you need:
ENCRYPTBYASYMKEY / DECRYPTBYASYMKEY
ENCRYPTBYCERT / DECRYPTBYCERT
ENCRYPTBYKEY / DECRYPTBYKEY
ENCRYPTBYPASSPHRASE / DECRYPTBYPASSPHRASE

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.

clear a textbox values when i select a last index value from dropdown in asp.net c# but i didnt get this

I'm working on my collage project i have a bill generate form in asp.net c# , my problem is that when i select a last value from database and enter a new data for bill . and then when i save that record that will be store in database and genrate a new index value for dropdown box . so when i select a last value from dropdown i get all clear field in all text boxes.
but right now when i select a last value fromj dropdown then i get a record from last inserted values in textbox .
so please can anyone help me..
thank you in advance.
have a nice day.![enter image description here][1]
here is a screen short of my bill genration.
and i select a trans. no from dropdown.
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
string qry1 = "select trans_id from purchase";
if (qry1 == ddltansid.SelectedValue)
{
string qry2 = "update purchase set bill_no=" + txtbillno.Text + ",date = '" + txtdate.Text + "',comp_name='" + ddlcompname.SelectedValue + "',add1='" + txtadd.Text + "',phno=" + txtbxphno.Text + ",cst=" + txtbxcst.Text + ",add_tax=" + txtbxaddtax.Text + ",discount=" + txtbxdisc.Text + ",sub_total=" + txtbxsubtotal.Text + ",g_total=" + txtbxgtotal.Text + ",net_amt=" + txtbxamt.Text + "";
c.Execute(qry2);
MessageBox.Show("update successfully";
}
else
{
str = "Insert into purchase(bill_no,date,comp_name,add1,phno,cst,add_tax,discount,sub_total,g_total,net_amt) values(" + txtbillno.Text + ",'" + txtdate.Text + "','" + ddlcompname.SelectedItem + "','" + txtadd.Text + "'," + txtbxphno.Text + "," + txtbxcst.Text + ",'" + txtbxaddtax.Text + "'," + txtbxdisc.Text + "," + txtbxsubtotal.Text + "," + txtbxgtotal.Text + "," + txtbxnetamt.Text + "";
c.Execute(str);
MessageBox.Show("insert successfully";
}
str1 = "select medicin_name from pur_tans where name='" + ddlmedicine.SelectedValue + "'";
str2 = "select item_name from stock_master";
a = (String.Compare(str1, str2));
if (a > 0)
{
string str3 = "update stock_master set item_qty = (item_qty + '" + txtbxqty.Text + "') where item_name='" + ddlmedicine.SelectedValue + "'";
c.Execute(str3);
MessageBox.Show("update successfully";
}
else
{
string str4 = "insert into stock_master (item_name,item_qty) values('" + ddlmedicine.SelectedValue + "'," + txtbxqty.Text + "";
c.Execute(str4);
MessageBox.Show("insert successfully";
}
if (ddltansid.SelectedValue == "Add New "
{
ddltansid.SelectedIndex = ddltansid.SelectedIndex - 1;
ddltansid.SelectedValue = ddltansid.SelectedValue + 1;
string last = ddltansid.SelectedValue;
if (IsPostBack == true)
{
ddltansid.SelectedValue = last.ToString();
str = "Insert into purchase(bill_no,date,comp_name,add1,phno,cst,add_tax,discount,sub_total,g_total,net_amt) values('' ,'',' ','','','','','','','','')";
c.Execute(str);
}
}
}
above is code for insert a value in database
Where ddltansid.SelectedValue == "Add New " is executed, i would also set the Text property of your textbox to String.Empty.
A little side node: As far as i understand your code, you put userinput directly into your sql query. You should aviod this since it makes your application wounerable to sql insertion attacks.
e.g. if i write in your textbox:
; drop database --;
i can delet your database.
Have a look at perpared statements in SQL. You might also be able to score some extra points ;)

Categories