How to design Crystal report with Dynamic Data - asp.net

Good Afternoon Developers,
This is my function to generate the crystal Report,This will take the Report Name and ReportQuery as a input parameter and will generate a dataset , With this dataset how can i design my Report??Because this is Generated at the runtime , How can i access that to generate my ReportDesign??
public void fnLoadDataToReport(string rptName, string rptQuery)
{
try
{
DataSet myDS=new DataSet();
// crReportDocument.Load(Server.MapPath("Reports\" & RptName), OpenReportMethod.OpenReportByTempCopy);
crReportDocument.Load(Server.MapPath("Reports\\" + rptName ));
SqlConnection myConnection=new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ConnectionString);
SqlCommand myCommand=new SqlCommand(rptQuery,myConnection);
SqlDataAdapter MyDA=new SqlDataAdapter(myCommand);
MyDA.Fill(myDS,"ReportTable");
crReportDocument.SetDataSource(myDS);
crvReportGeneration.ReportSource=crReportDocument;
crvReportGeneration.ShowFirstPage();
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}
Any help is appreciable....!

All you need is an XML schema definition of the Dataset to be able to design the report. this can be achieved by the following code.
private void WriteSchemaToFile(DataSet thisDataSet){
// Set the file path and name. Modify this for your purposes.
string filename="mySchema.xml";
// Write the schema to the file.
thisDataSet.WriteXmlSchema(filename);
}
now add the above created file to your project.
Now while designing the report select Database expert and select the xml file under Project. and add it (just like you add tables or views).
Now you are good to go. The rest of the steps are same.
Just make sure the name of the XSD schema and the table name in your Dataset match exactly.

Why are using DataSet as the source for the report. Instead of that if you use a stored procedure as the source, it will solve your problem and also maintenance will be much more easier

Related

Creating Reports in ASP.Net with Entity Framework

We are looking to add Microsoft Reports - SSRS to one of our internal websites.
The database has all the reporting features installed.
The website is using Entity Framework 4 for all data.
I have been able to create a report using the old fashioned way of creating a DataSet (*.XSD) and this works well.
My question though, is it possible to utilise the existing Entity Framework in the site for the data required by the reports? Rather than having to re-invent the wheel and make a whole DataSet, along with relationships etc..
It's a website and not application, so this (http://weblogs.asp.net/rajbk/archive/2010/05/09/creating-an-asp-net-report-using-visual-studio-2010-part-1.aspx) doesn't seem to apply; I don't see the DataSource (in part 2 of the tutorial)
Update
As a side-note, we would like to steer clear of expensive third-party controls etc.
Also, another way to look at the issue might be to generate the *.XSD from the entity framework entity model; is this possible? It's not ideal though would get us up and running..
Below is a quick sample of how i set the report datasource in one of my .NET winForms applications.
public void getMyReportData()
{
using (myEntityDataModel v = new myEntityDataModel())
{
var reportQuery = (from r in v.myTable
select new
{
l.ID,
l.LeaveApplicationDate,
l.EmployeeNumber,
l.EmployeeName,
l.StartDate,
l.EndDate,
l.Supervisor,
l.Department,
l.Col1,
l.Col2,
.......,
.......,
l.Address
}).ToList();
reportViewer1.LocalReport.DataSources.Clear();
ReportDataSource datasource = new ReportDataSource("nameOfReportDataset", reportQuery);
reportViewer1.LocalReport.DataSources.Add(datasource);
Stream rpt = loadEmbededReportDefinition("Report1.rdlc");
reportViewer1.LocalReport.LoadReportDefinition(rpt);
reportViewer1.RefreshReport();
//Another way of setting the reportViewer report source
string exeFolder = Path.GetDirectoryName(Application.ExecutablePath);
string reportPath = Path.Combine(exeFolder, #"rdlcReports\Report1.rdlc");
reportViewer1.LocalReport.ReportPath = reportPath;
reportParameter p = new ReportParameter("DeptID", deptID.ToString());
reportViewer1.LocalReport.SetParameters(new[] { p });
}
}
public static Stream loadEmbededReportDefinition(string reportName)
{
Assembly _assembly = Assembly.GetExecutingAssembly();
Stream _reportStream = _assembly.GetManifestResourceStream("ProjectNamespace.rdlcReportsFolder." + reportName);
return _reportStream;
}
My approach has always been to use RDLC files with object data sources and run them in 'local' mode. These data sources are ... my entities! This way, I'm using all of the same business logic, string formatting, culture awareness, etc. that I use for my web apps. There are a some quirks, but I've been able to live with them:
RDLC files don't like to live in web projects. We create a separate dummy winform project and add the RDLC files there.
I don't show reports in a viewer. I let the user download a PDF, Word, or Excel file and choose to save or open in the native viewer. This saves a bunch of headaches, but can put some folks off, depending on requirements. For mobile devices, it's pretty nice.
Since you are not using SSRS, you don't get the nice subscription feature. You are going to build that, if required. In many ways, though, I prefer this.
However, the benefits are really nice:
I'm using all of the same business logic goodness that I've already written for my views.
I have a custom ReportActionResult and DownloadReport controller method that allows me to essentially run any report via a single URL. This can be VERY handy. It sure makes a custom subscription component easier.
Report development seems to go pretty quick, now that I only need to adjust entity partial classes to tweak a little something here or there. Also - If I need to shape the data just a bit differently, I have LINQ.
We too use SSRS as "local" reports. We create Views in SQL server, then create that Object in our application along with the other EF Domain Models, and query that object using our DbContext. We use an ASPX page and use the code behind (Page_Load) to get the data passed to the report.
Here is an example of how we query it in the Page_Load Event:
var person = MyDbContext
.Query<ReportModel>()
.Where(x => x.PersonId == personId)
.Where(x => x.Year == year)
.Select(x =>
{
PersonId = x.PersonId,
Year = x.Year,
Name = x.Name
});
var datasource = new ReportDataSource("DataSet1", person.ToList());
if (!Page.IsPostBack)
{
myReport.Visible = true;
myReport.ProcessingMode = ProcessingMode.Local;
myReport.LocalReport.ReportPath = #"Areas\Person\Reports\PersonReport.rdlc";
}
myReport.LocalReport.DataSources.Clear();
myReport.LocalReport.DataSources.Add(datasource);
myReport.LocalReport.Refresh();
The trick is to create a report (.rdlc) with a blank data source connection string, a blank query block and a blank DataSetInfo (I had to modify the xml manually). They must exist in file and be blank as follows:
SomeReport.rdlc (viewing as xml)
...
<DataSources>
<DataSource Name="conx">
<ConnectionProperties>
<DataProvider />
<ConnectString />
</ConnectionProperties>
<rd:DataSourceID>19f59849-cdff-4f18-8611-3c2d78c44269</rd:DataSourceID>
</DataSource>
</DataSources>
...
<Query>
<DataSourceName>conx</DataSourceName>
<CommandText />
<rd:UseGenericDesigner>true</rd:UseGenericDesigner>
</Query>
<rd:DataSetInfo>
<rd:DataSetName>SomeDataSetName</rd:DataSetName>
</rd:DataSetInfo>
now in a page event, I use a SelectedIndexChanged on a DropDownList, bind the report datasource as follows:
protected void theDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
if (theDropDownList.SelectedIndex == 0)
return;
var ds = DataTranslator.GetRosterReport(Int64.Parse(theDropDownList.SelectedValue));
_rvReport.LocalReport.ReportPath = "SomePathToThe\\Report.rdlc";
_rvReport.LocalReport.DataSources.Add(new ReportDataSource("SomeDataSetName", ds));
_rvReport.Visible = true;
_rvReport.LocalReport.Refresh();
}
You can use a WCF-Service as Datasource and so re-use your application data and logic for your report. This requires a SQL-server standard edition at least i believe. So no can do with the free SQL-express edition.
You can use LINQ with RDLC Report which is quite easy to use
LinqNewDataContext db = new LinqNewDataContext();
var query = from c in db.tbl_Temperatures
where c.Device_Id == "Tlog1"
select c;
var datasource = new ReportDataSource("DataSet1", query.ToList());
ReportViewer1.Visible = true;
ReportViewer1.ProcessingMode = ProcessingMode.Local;
ReportViewer1.LocalReport.ReportPath = #"Report6.rdlc";
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(datasource);
ReportViewer1.LocalReport.Refresh();

Retrieve data tables from database with stored procedure

Let me explain you in details the scenario that I am having and the solution I am looking for.
Firstfully, I created a stored procedure that outputs simple things such as 2 tables and a message 'don't stop here'"
T-SQL:
USE [mydb]
GO
/****** Object: StoredProcedure [dbo].[BackupDatabase] Script Date: 2/26/2013 11:29:10 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[testing]
AS
BEGIN
select 'A' firstname, 'B' lastname;
print 'dont stop here'
select 1 final
END
Up until now I used to retriew the tables in a single manner by using datarowcollection class, and my static method looked like this:
C#:
public static class DataMan
{
public static DataRowCollection SelectData(string sql)
{
SqlDataSource DS = new SqlDataSource(CS, sql);
return ((DataView)DS.Select(DataSourceSelectArguments.Empty)).ToTable().Rows;
}
public static string CS = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
}
where I can easily get what i needed like here, and locate what evver row I wanted:
DataRowCollection people = Util.SelectData("Select * from students")
But now I am planning to create a stored procedure Like I mentioned above and do somthing like this, for instance:
**DataTableCollection** people = Util.SelectData("exec dbo.Testing")
UPDATE:
so I can locate the specific table from my storedprocedure.
I have tried to use DataTable, DataSet, DataTableCollections but no success.I can't use them in proper way.
Please help me
Thank You
Although it can be used in code-behind as you're illustrating here, the SqlDataSource is more typically used in a declarative manner on an ASP.NET markup page. However, given what you've started, when calling a stored procedure, you should set the SqlCommandType to StoredProcedure, supply the name of the procedure to SelectCommand, and return a DataReader. The DataReader, in turn, supports a NextResult() method that you can call to retrieve each discrete result set your procedure provides. Here is a framework of pseudo code that tries to illustrate how you might leverage this:
// pseudo code
void stub()
{
SqlDataSource d = new SqlDataSource(*connection string*);
d.DataSourceMode = SqlDataSourceMode.DataReader;
d.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
d.SelectCommand = "dbo.Testing";
// set some parameters
d.SelectParameters.Add("Parameter1Name","Parameter1Value"); // must be tailored to your proc!!
d.SelectParameters.Add("Parameter2Name","Parameter2Value"); // must be tailored to SqlDataReader r = (SqlDataReader) d.Select();
while (r.HasRows)
{
while (r.Read())
{
// do something with each row
}
// advance to next result set
r.NextResult();
}
r.Close();
}

Merging xml Data with Infopath Form Design

hi we all know how the infopath is working. when we give details in infopath form the data is stored as XML File. And when we open it the data from XML are merged with infopath form design(template).
I need to show the data which is present in XML with my own designed(template) form in the runtime. My question is how can i read the fields which is in Infopath Form(in .xml). Then only i can design my own form in the runtime.
i dont know if i understood your question correctly, but if you want to display xml data in another form you have to transform the xml or at least include it as a datasource in your own designed form.
public void SaveXML(string filePath, string sourceXpath)
{
XPathNavigator myRoot = MainDataSource.CreateNavigator();
XPathNavigator node = myRoot.SelectSingleNode(sourceXpath, NamespaceManager);
using (StreamWriter sw = new StreamWriter(filePath))
{
sw.Write(node.OuterXml.ToString());
sw.Flush();
sw.Close();
}
}
//usage: make sure you understand reading a bit about xpath first, and you will easily know what to put here in param2. you can right click on on any node in the datasource tree of your infopath and select "copy xpath" string to clipboard.
SaveXML(_AuditsFolder + "\\" + fname, "/my:AuditForm/my:Audit");

programmatically change table names in .net strong typed dataset

hi
I've developed an application using strong-typed dataset with .net framework 3.5.
is there a way to change the source table for a tableadapter programmatically?
thnx
There are a couple of ways that you can do this. First you could just add a new query that pulls from the different table, and then execute the method for that query, as long as the columns match it will work.
If you need to dynamically change the one of the statements you can access the command collection of the table adapter, it is protected though, so the easiest way to do this is to create a partial class to extend the one generated by the designer. Once you do this you can add your own method to return the data. You can use adapter.CommandCollection[0].CommandText to get and set the SQL for the the default GetData command that is created.
Once you do this you can change it, clear out the parameters, add new parameters or whatever you want to do, then you set the CommandText with the altered SQL, and call GetData or whatever you named the command and it will execute and return as usual.
Here is a code example:
using System.Data.SqlClient;
namespace DataTableAdapters
{
public partial class Data_ItemTableAdapter
{
public Data.Data_ItemDataTable GetDynamicExample(string SearchValue)
{
using (Data_ItemTableAdapter a = new Data_ItemTableAdapter())
{
SqlCommand cmd = a.CommandCollection[0];
cmd.Parameters.Clear();
string SQL = #"Select Data_Item_ID, Data from Data_Item where
SearchValue = #SearchValue";
cmd.CommandText = SQL;
cmd.Parameters.AddWithValue("#SearchValue", SearchValue);
return a.GetData();
}
}
}
}

Storing XSLT in SQL Server 2005 with xml type?

I have a lot of XSL files in my ASP.NET web app. A lot. I generate a bunch of AJAX HTML responses using this kind of generic transform method:
public void Transform(XmlDocument xml, string xslPath)
{
...
XslTransform myXslTrans = new XslTransform();
myXslTrans.Load(xslPath);
myXslTrans.Transform(xml,null, HttpContext.Current.Response.Output);
}
I'd like to move the XSL definitions into SQL Server, using a column of type xml.
I would store an entire XSL file in a single row in SQL, and each XSL is self-contained (no imports). I would read out the XSL definition from SQL into my XslTransform object.
Something like this:
public void Transform(XmlDocument xml, string xslKey)
{
...
SqlCommand cmd = new SqlCommand("GetXslDefinition");
cmd.AddParameter("#xslKey", SqlDbType.VarChar).Value = xslKey;
// where the result set has a single column of XSL: "<xslt:stylesheet>..."
...
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read()) {
SqlXml xsl = dr.GetSqlXml(0);
XslTransform myXslTrans = new XslTransform();
myXslTrans.Load(xsl.CreateReader());
myXslTrans.Transform(xml,null, HttpContext.Current.Response.Output);
}
}
It seems like a straightforward way to:
add metadata to each XSL, like lastUsed, useCount, etc.
bulk update/search capabilities
prevent lots of disk access
avoid referencing relative paths and organizing files
allow XSL changes without redeploying (I could even write an admin page that selects/updates the XSL in the database)
Has anyone tried this before? Are there any caveats?
EDIT
Caveats that responders have listed:
disk access isn't guaranteed to diminish
this will break xsl:includes
The two big issues I can see are:
We use a lot of includes to ensure that we only do things once, storing the XSLT in the database would stop us from doing that.
It makes updating XSLs more interesting - we've been quite happy to dump new .xsl files into deployed sites without doing a full update of the site. For that matter we've got bits of code that look for client specific xsl in a folder and those bits of code can reach back up to common code (templates) in the root - so I'm not sure about the redeploy thing at all, but this will depend very much on the particular use case, yours is certainly different to ours.
In terms of disk access, hmm... the db still has to go access the disk to pull the data and if you're talking about caching then the db isn't a requirement for enabling caching.
Have to agree about the update/search options - you can do stuff with Powershell but that needs to be run on the server and that's not always a good idea.
Technically I can see no reason why not (excepting the wish to do includes as above) but practically it seems to be fairly balanced with good arguments either way.
I store XSLTs in a database in my application dbscript. (However I keep them in an NVARCHAR column, since it also runs on SQL Server 2000)
Since users are able to edit their XSLTs, I needed to write a custom validator which loads the text of TextBox in a .Net XslCompiledTransform object like this:
args.IsValid = true;
if (args.Value.Trim() == "")
return;
try
{
System.IO.TextReader rd = new System.IO.StringReader(args.Value);
System.Xml.XmlReader xrd = System.Xml.XmlReader.Create(rd);
System.Xml.Xsl.XslCompiledTransform xslt = new System.Xml.Xsl.XslCompiledTransform();
System.Xml.Xsl.XsltSettings xslts = new System.Xml.Xsl.XsltSettings(false, false);
xslt.Load(xrd, xslts, new System.Xml.XmlUrlResolver());
xrd.Close();
}
catch (Exception ex)
{
this.ErrorMessage = (string.IsNullOrEmpty(sErrorMessage) ? "" : (sErrorMessage + "<br/>") +
ex.Message);
if (ex.InnerException != null)
{
ex = ex.InnerException;
this.ErrorMessage += "<br />" + ex.Message;
}
args.IsValid = false;
}
As for your points:
file I/O will be replaced by database-generated disk I/O, so no gains there
deployment changes to providing an INSERT/UPDATE script containing the new data

Resources