Convert Crystalreport's Provider from 'SQLNCLI' to 'SQLOLEDB' by code (c#) - c#

Is it possible to convert crystalreport's Provider from 'SQLNCLI' to 'SQLOLEDB' by code "c#"
I have tried with following code but did not work.
TableLogOnInfo logoninfo;
foreach (CrystalDecisions.CrystalReports.Engine.Table tbcurrent in rptH.Database.Tables)
{
logoninfo = new TableLogOnInfo();
logoninfo.ConnectionInfo.DatabaseName = connectionInfo.DatabaseName;
logoninfo.ConnectionInfo.ServerName = connectionInfo.ServerName;
logoninfo.ConnectionInfo.UserID = connectionInfo.UserID;
logoninfo.ConnectionInfo.Password = connectionInfo.Password;
tbcurrent.ApplyLogOnInfo(logoninfo);
}
rptH.SetDatabaseLogon(connectionInfo.UserID, connectionInfo.Password, connectionInfo.ServerName, connectionInfo.DatabaseName, true);
for (int i = 0; i < rptH.Subreports.Count; i++)
{
foreach (CrystalDecisions.CrystalReports.Engine.Table tbcurrent in rptH.Subreports[i].Database.Tables)
{
logoninfo = new TableLogOnInfo();
logoninfo.ConnectionInfo.DatabaseName = connectionInfo.DatabaseName;
logoninfo.ConnectionInfo.ServerName = connectionInfo.ServerName;
logoninfo.ConnectionInfo.UserID = connectionInfo.UserID;
logoninfo.ConnectionInfo.Password = connectionInfo.Password;
tbcurrent.ApplyLogOnInfo(logoninfo);
}
rptH.Subreports[i].SetDatabaseLogon(connectionInfo.UserID, connectionInfo.Password, connectionInfo.ServerName, connectionInfo.DatabaseName, true);
}

I am not sure if this can be done as the connection type seems to be stored in the .rpt file.
But you can try use native .Net API to retrieve database selection into a System.Data.DataSet / System.Data.DataTable instance and call Table.SetDataSource() to set as the table data source, so you do not need to care about TableLogOnInfo object, but please ensure the scheme matches that of the report.
Below sample codes are from Crystal Reports .NET API Guide:
private void SetDataSource
(string conn, string query, DataSet dataSet)
{
OleDbConnection oleConn = new OleDbConnection(conn);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter();
oleAdapter.SelectCommand = new OleDbCommand(query, oleConn);
oleAdapter.Fill(dataSet, "Customer");
reportDocument.Database.Tables["Customer"].SetDataSource (dataSet);
}
Besides, ReportDocument also has SetDataSource() method, so you can set the data source for the whole report.

Related

Adding uploaded by (user name or name) Automatically while uploading the Excel into SQL Server in C#

I want to upload Excel data into SQL Server with uploaded by (i.e which pick from session method)
I have created table name, country, address, uploaded by.
Normally the upload is working fine but I want to add the uploaded by value while uploading the excel bulk upload
I don't know how to insert the uploaded by value in bulk upload some one help me
This is my code:
try
{
myExcelConn.Open();
// GET DATA FROM EXCEL SHEET.
OleDbCommand objOleDB = new OleDbCommand("SELECT * FROM [Sheet1$]", myExcelConn);
// READ THE DATA EXTRACTED FROM THE EXCEL FILE.
OleDbDataReader objBulkReader = null;
objBulkReader = objOleDB.ExecuteReader();
// SET THE CONNECTION STRING.
string sCon = sqlconn;
using (SqlConnection con = new SqlConnection(sCon))
{
con.Open();
//SqlConnection p = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\jetback\source\repos\Projectstudent\webdown_up_load\App_Data\upload.mdf;Integrated Security=True");
// FINALLY, LOAD DATA INTO THE DATABASE TABLE.
oSqlBulk = new SqlBulkCopy(con);
oSqlBulk.DestinationTableName = "Table3"; // TABLE NAME.
oSqlBulk.ColumnMappings.Add("name", "name");
oSqlBulk.ColumnMappings.Add("address", "address");
oSqlBulk.ColumnMappings.Add("country", "country");
oSqlBulk.WriteToServer(objBulkReader);
}
lblConfirm.Text = "DATA IMPORTED SUCCESSFULLY.";
lblConfirm.Attributes.Add("style", "color:green");
}
catch (Exception ex)
{
lblConfirm.Text = ex.Message;
lblConfirm.Attributes.Add("style", "color:red");
}
finally
{
// CLEAR.
oSqlBulk.Close();
oSqlBulk = null;
myExcelConn.Close();
myExcelConn = null;
}
It's better to use DataTable if you want to add more col when there's already data in yr dataSet:
var results = new DataTable();
using(var myExcelConn = new OleDbConnection(excCnnStr))
{
using (var cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", myExcelConn))
{
myExcelConn.Open();
var adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
}
}
//add new col
results.Columns.Add("uploadedBy", typeof(System.Int32));
foreach (DataRow row in results.Rows)
{
row["uploadedBy"] = loggedInUserId; // set uploader
}
using (var con = new SqlConnection(sCon))
{
con.Open();
using (var oSqlBulk = new SqlBulkCopy(con))
{
oSqlBulk.DestinationTableName = "Table3";
oSqlBulk.ColumnMappings.Add("name", "name");
oSqlBulk.ColumnMappings.Add("address", "address");
oSqlBulk.ColumnMappings.Add("country", "country");
oSqlBulk.ColumnMappings.Add("uploadedBy", "uploadedBy");
oSqlBulk.WriteToServer(results);
}
}
You will have to get from Excel and then insert into SQL.
//After objBulkReader = objOleDB.ExecuteReader();
if (objBulkReader.HasRows)
{
while (objBulkReader.Read())
{ string newname = objBulkReader[0].ToString();
string address= objBulkReader[1].ToString();
string country= objBulkReader[2].ToString();
string uploadedby=Session["uploader"].ToString();
//insert these into SQL db by SQL connection
}
}
The 0,1 and 2 in objBulkReader are column positions in Excel.

Load data to a data set from data table in C#

I have a dataset called "dts_Material_Report" which is used to generate reports.In that data set I have a tableAdapter called "dt_report_Received_Materials".
Previously I have load the data to that table adapter with following code ,
private void generate_report( string qry )
{
string query, qry1;
query = qry;
int pr_id = Form_Common_PCM.pr_id;
clz_Common_SqlConnection con = new clz_Common_SqlConnection();
SqlDataAdapter sda = new SqlDataAdapter(query, con.ActiveCon());
DataSet dts = new DataSet();
sda.Fill(dts, "dt_report_Received_Materials");
rdc.SetDataSource(dts);
crystalReportViewer1.ReportSource = rdc;
crystalReportViewer1.DisplayToolbar = true;
crystalReportViewer1.Show();
}
But currently I am having all the data which I need to generate the report in one of my data table called "dt_mat_cost".
int Ref_ID_s_category;
Ref_ID_s_category = Convert.ToInt16(cbo_sub_category .SelectedValue );
int pro_id = Form_Common_PCM.pr_id;
clz_Received_Material_Summary rms = new clz_Received_Material_Summary();
DataTable dt_mat_cost = rms.Summary_Material_Cost_Filter_By_Project_By_Sub_Category(Ref_ID_s_category);
Now i want to load those data from "dt_mat_cost" to my tableAdapter "dt_report_Received_Materials" .Is there any way to do this.
Thanks in Advance.
One way to resolve this would be to put the DataTable into a DataSet and then run the crystal code as shown below. You may be able to just set the ReportSource to the datatable but I do not recall off the top of my head if that will work.
DataTable dt_matCost = rms.Summary_Material_Cost_Filter_By_Project_By_Sub_Category(Ref_ID_s_category);
DataSet dts = new DataSet();
dts.Tables.Add(dt_matCost);
//ds.Tables[0].TableName = "Whatever CR thinks it is"; // may need to set for CR
rdc.SetDataSource(dts);
crystalReportViewer1.ReportSource = rdc;
crystalReportViewer1.DisplayToolbar = true;
crystalReportViewer1.Show();

How to View Crystal report in Visual Studio 2013?

I'm working on ASP.Net with C#, and installed CrystalReport 13 for Visual Studio 2013. I wrote code to fill a Datasource and pass it into my `CrystalReport file, but my website doesn't show anything. How can I execute my report?
Here is my PageLoad:
SqlConnection cnn = new SqlConnection(connectionstring);
cnn.Open();
SqlCommand command = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
command.Connection = cnn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "STP_T00050030";
command.Parameters.Add("#F_CNTRowID", SqlDbType.Int).Value = Convert.ToInt32("20");
command.Parameters.Add("#F_CNTid", SqlDbType.Int).Value = Convert.ToInt32("45");
adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
ReportDocument crystalReport = new ReportDocument();
crystalReport.Load(Server.MapPath("~/Report1.rpt"));
crystalReport.SetDataSource(ds);
CrystalReportViewer1.ReportSource = crystalReport;
In your solution, right mouse click on each report (.rpt file) and go properties --> Build Action=Content, Copy To Output Directory=Copy Always
Here's a complete block of code for setting data source. Notice how data source must also be set for each subreport.
public static CrystalReportSource Crystal_SetDataSource(string reportName, object par1, object par2, object par3)
{
CrystalReportSource CrystalReportSource2 = new CrystalReportSource();
CrystalReportSource2.CacheDuration = 10;
CrystalReportSource2.Report.FileName = #"~\App_Pages\Secure\Reports\" + reportName;
CrystalDecisions.CrystalReports.Engine.Database crDatabase = CrystalReportSource2.ReportDocument.Database;
ConnectionInfo crConnectionInfo = new ConnectionInfo();
crConnectionInfo.ServerName = server;
crConnectionInfo.DatabaseName = db;
crConnectionInfo.UserID = crystalUser;
crConnectionInfo.Password = pwd;
crConnectionInfo.IntegratedSecurity = false;
// First we assign the connection to all tables in the main report
TableLogOnInfo crTableLogOnInfo = new TableLogOnInfo();
foreach (CrystalDecisions.CrystalReports.Engine.Table crTable in crDatabase.Tables)
{
crTableLogOnInfo = crTable.LogOnInfo;
crTableLogOnInfo.ConnectionInfo = crConnectionInfo;
crTable.ApplyLogOnInfo(crTableLogOnInfo);
}
//SET DATASOURCE FOR EACH SUBREPORT IN REPORT
foreach (CrystalDecisions.CrystalReports.Engine.Section section in CrystalReportSource2.ReportDocument.ReportDefinition.Sections)
{
// In each section we need to loop through all the reporting objects
foreach (CrystalDecisions.CrystalReports.Engine.ReportObject reportObject in section.ReportObjects)
{
if (reportObject.Kind == ReportObjectKind.SubreportObject)
{
SubreportObject subReport = (SubreportObject)reportObject;
ReportDocument subDocument = subReport.OpenSubreport(subReport.SubreportName);
foreach (CrystalDecisions.CrystalReports.Engine.Table table in subDocument.Database.Tables)
{
// Cache the logon info block
TableLogOnInfo logOnInfo = table.LogOnInfo;
// Set the connection
logOnInfo.ConnectionInfo = crConnectionInfo;
// Apply the connection to the table!
table.ApplyLogOnInfo(logOnInfo);
}
}
}
}
if (CrystalReportSource2.ReportDocument.DataSourceConnections.Count > 0)
CrystalReportSource2.ReportDocument.DataSourceConnections[0].SetConnection(server, db, crystalUser, pwd);
CrystalReportSource2.ReportDocument.SetDatabaseLogon(crystalUser, pwd, server, db);
if (par1 != null)
CrystalReportSource2.ReportDocument.SetParameterValue(0, par1);
if (par2 != null)
CrystalReportSource2.ReportDocument.SetParameterValue(1, par2);
if (par3 != null)
CrystalReportSource2.ReportDocument.SetParameterValue(2, par3);
return CrystalReportSource2;
}

How to print multiple instance of crystal report using single Crystal Report Viewer in c#

I am trying to print multiple crystal report using single Crystal Report Viewer.
I have 'n' number of items in a database and I need to print 'n' crystal reports. As it is dynamic in nature so I cannot fix number of Report Viewer, so I thought to use single Report Viewer and load crystal report using 'For loop'.
I created a new datatable in dataset and I was trying to put value from another datatable it didnt worked out so created parameter fields and is putting values in through
For Loop
Here my code(I have 3 parameter fields for ease of viewing showing only one):
private void CRVtakeout_Load(object sender, EventArgs e)
{
try
{
string sqlqry = "Select KOTNo,Time,TableNo,WaiterName,ItemCode,ItemName,Quantity,Amount,Foodtype From tblOrder Where KOTNo=#kotno";
SqlCommand cmd = new SqlCommand(sqlqry, connectionclass.con);
cmd.Parameters.AddWithValue("#kotno", NewOrderBL.KOTNo);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet1 ds = new DataSet1();
adapter.Fill(ds, "Takeout");
//adapter.Fill(ds, "Takeout");
string tableno = ds.Tables["Takeout"].Rows[i][2].ToString();
tableno = tableno.Substring(6, 1);
if (ds.Tables["Takeout"].Rows.Count == 0)
{
MessageBox.Show("No Data Found", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (tableno == "T")
{
for (int i = 0; i < ds.Tables["Takeout"].Rows.Count; i++)
{
crystalReportViewer1.RefreshReport();
ParameterFields paramFields = new ParameterFields();
ParameterField paramField = new ParameterField();
ParameterDiscreteValue paramDiscreteValue = new ParameterDiscreteValue();
paramField.Name = "Billno";
paramDiscreteValue.Value = ds.Tables["Takeout"].Rows[0][0].ToString();
paramField.CurrentValues.Add(paramDiscreteValue);
paramFields.Add(paramField);
printtakeout printtakeout = new printtakeout();
printtakeout.SetDataSource(ds);
crystalReportViewer1.ReportSource = printtakeout;
System.Drawing.Printing.PrintDocument printdocument = new System.Drawing.Printing.PrintDocument();
printtakeout.PrintOptions.PrinterName = printdocument.PrinterSettings.PrinterName;
printtakeout.PrintOptions.PrinterName = "EPSON TM-U220 Receipt";
printtakeout.PrintToPrinter(1, false, 0, 0);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally { connectionclass.disconnect(); }**strong text**
}
Each time I do it gives error :
activex control 8856f961-340a-11d0-a96b-00c04fd705a2 cannot be instantiated because the current thread is not a single-thread apartment
If I dont use parameter field theirs no error.
If any clarification needed please do tell.
Thanks .
There is an example to do queries
using (SqlConnection connection = new SqlConnection("connectionString"))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM Customers";
command.CommandType = CommandType.Text;
using (SqlDataReader objDataReader = command.ExecuteReader())
{
if (objDataReader != null)
{
while (objDataReader.Read())
{
// To get results...
// objDataReader["NameResultParam"];
}
}
}
}

Crystal REport throws error on formula field while exporting to pdf using c#

I have crystal report that is build on a view that uses 2 tables and around 47 columns. this was created in cr 2008. now I have to import this report into c# asp.net project and use dataset I have created to work as a data source for this same report. it giving error stating that a formula fields that are created using a view are throwing an error which is something like this
This field name is not known.
Details: errorKindError in File statement {C4B51C11-81BC-4D27-9886-23BE50D5A9D0}.rpt:
Error in formula Location:
'if {statements_view.DOC_TYPE} = 'RU' then
{statements_view.BUNUMBER_RU}
else {statements_view.BUNUMBER}
am I missing something here ?
here is my code so far
string connetionString = null;
OracleConnection connection;
OracleDataAdapter OracleAdapter;
DataSet ds = new DataSet();
string firstSql = null;
string secondSql = null;
connetionString = "DATA SOURCE= blah blah ";
firstSql = "select * from STATEMENT_DOMESTIC";
secondSql = "Select * from STATEMENT_DOM_DETAILS";
connection = new OracleConnection(connetionString);
connection.Open();
OracleAdapter = new OracleDataAdapter(firstSql, connection);
OracleAdapter.Fill(ds, "Tables[0]");
OracleAdapter.SelectCommand.CommandText = secondSql;
OracleAdapter.Fill(ds, "tables[1]");
OracleAdapter.Dispose();
connection.Close();
// GridView1.DataSource = ds;
// GridView1.DataBind();
ReportDocument reportDoc = new ReportDocument();
reportDoc.Load(#"c:\statement.rpt");
reportDoc.SetDataSource(ds.Tables);
ExportOptions CrExportOptions;
DiskFileDestinationOptions CrDiskFileDestinationOptions =new DiskFileDestinationOptions();
PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();
CrDiskFileDestinationOptions.DiskFileName = #"d:\Converte5_1_13.pdf";
CrExportOptions = reportDoc.ExportOptions;
{
CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
CrExportOptions.FormatOptions = CrFormatTypeOptions;
}
reportDoc.Export();
}
is there a problem with my dataset or am I missing something here..
any guidance on this issue is

Categories

Resources