How to execute an SSRS .rss script file in IIS/ASP.NET - asp.net

I need to execute a .rss SSRS script file within an ASP.NET application running in IIS 7.x. How can I do that?
Do I have to configure the IIS AppPool that is running my web application to have elevated privileges such that I can start up the rs.exe console application passing the .rss script to it the way I would otherwise execute an .rss script file outside of IIS?
Or is there another way? Does Visual Studio/.NET provide any mechanism for bootstrapping an .rss script file without needing the rs.exe console application? Is my only option to make the rs.exe console application available to my web application running in IIS?

So, I figured it out. If you're wondering how to create a History Snapshot of a report on your SSRS Reports Server using the ReportServices2010 proxy, here's one example and one way you can accomplish it (many thanks to kyzen for sharing his insight in directing me to the SOAP API):
Dim basicHttpBinding As New BasicHttpBinding()
basicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm
basicHttpBinding.SendTimeout = New TimeSpan(0, 10, 0)
Dim endPoint As New EndpointAddress("http://server/reportserver/ReportService2010.asmx")
Dim instance As New ReportingService2010SoapClient(basicHttpBinding, endPoint)
Dim itemPath As String = "/Path/to/report"
Dim warnings() As Warning
Dim historyId As String = Nothing
Dim values As ParameterValue() = Nothing
Dim credentials As DataSourceCredentials() = Nothing
Dim t As New TrustedUserHeader()
instance.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation
instance.ClientCredentials.Windows.ClientCredential = New Net.NetworkCredential("userid", "password", "domain")
instance.Open()
oServerInfoHeader = instance.CreateItemHistorySnapshot(t, itemPath, historyId, warnings)
and in C#:
BasicHttpBinding basicHttpBinding = new BasicHttpBinding();
basicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm
basicHttpBinding.SendTimeout = New TimeSpan(0, 10, 0)
EndpointAddress endPoint = new EndpointAddress("http://server/reportserver/ReportService2010.asmx");
ReportingService2010SoapClient instance = new ReportingService2010SoapClient(basicHttpBinding, endPoint);
string itemPath = "/Path/to/report"
Warning warnings[];
string historyId;
ParameterValue values[];
DataSourceCredentials credentials[];
TrustedUserHeader t = new TrustedUserHeader();
instance.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
instance.ClientCredentials.Windows.ClientCredential = New Net.NetworkCredential("userid", "password", "domain");
instance.Open();
oServerInfoHeader = instance.CreateItemHistorySnapshot(t, itemPath, historyId, warnings);

Related

is it possible for asp.net and a console application access the same semaphores?

the idea is that a process (windows application console) creates the semaphores and a memory mapped file, and an asp.net application had to modify the memory mapped file.
When i try to do this operation from visual studio (IIS EXPRESS) all works, but when i try with the same code published on local (same machine) IIS, the asp application doesn't find the semaphores. where is the problem?
this is the .net application console code:
Dim user As String = Environment.UserDomainName & "\" + Environment.UserName
Dim mSec As New SemaphoreSecurity
Dim rule As SemaphoreAccessRule = New SemaphoreAccessRule(user, SemaphoreRights.Synchronize Or SemaphoreRights.Modify, AccessControlType.Allow)
mSec.AddAccessRule(rule)
Dim emptyw = New Semaphore(0, 1, "MMF_EMPTY", True, mSec)
Dim fullw = New Semaphore(1, 1, "MMF_FULL", True, mSec)
this is the asp.net code:
Dim empty = New Semaphore(0, 1, "MMF_EMPTY")
Dim full = New Semaphore(1, 1, "MMF_FULL")

Passing datatable to SQL Server stored procedure not working

I have an ASP.NET application that passes a Datatable to a web service, then from the web service to a SQL Server stored procedure. When I publish the web application and web service to the server and run, it fails. When I run the application from the local host pointing to the web service on the server, it works fine. When I run the both the web application and web service from localhost, it works fine.
I did some troubleshooting and see that the following line is the problem but I am not sure how to solve:
cmdCommit.Parameters.AddWithValue(#SourceTable, dtSource);
When I comment the line above, everything works. When I replace the reference to the DataTable (dtSource) in the line above with a string datatype, it works.
Here is the entire web method, I am using this code within a try/catch block:
DataTable dtSource = ObjectToData(sourceTable);
dtSource.TableName = TableTypeObject;
using (SqlConnection cnn = new SqlConnection(_cnnSqlCapss))
{
SqlCommand cmdCommitChange = new SqlCommand("usp_Stored_Procedure", cnn);
cmdCommitChange.CommandType = CommandType.StoredProcedure;
cmdCommitChange.Parameters.AddWithValue("#Parm1", Value1);
cmdCommitChange.Parameters.AddWithValue("#Parm2", Value2);
cmdCommitChange.Parameters.AddWithValue("#Parm3", dtSource);
var returnParameter = cmdCommitChange .Parameters.Add("#ReturnVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
cnn.Open();
cmdCommitChange .ExecuteNonQuery();
var result = returnParameter.Value;
return (int)result;
}
The confusing part is that when I run the web application from the localhost and reference the web service on the server, it works. I don't understand why it fails when I run the web application from the server.
When I comment the line that reference the DataTable everything works.
I have tried the following and still no success:
SqlParameter tvpParam cmdCommit.Parameters.AddWithValue "#SourceTable", dtSource);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.SourceTableType";
Also, The web method is not throwing an exception.
Assumed you're already doing these:
Defining table type in User-Defined Table Types in your database (often known as TVP, see reference section below);
Adding parameter to pass DataTable to stored procedure (e.g. #SourceTable).
Then, you can use SqlDbType.Structured to pass DataTable contents as stored procedure parameter like this:
cmdCommitChange.Parameters.Add("#SourceTable", SqlDbType.Structured).Value = dtSource;
Alternative with AddWithValue:
cmdCommitChange.Parameters.AddWithValue("#SourceTable", dtSource).SqlDbType = SqlDbType.Structured;
Example usage in SqlConnection block:
using (SqlConnection cnn = new SqlConnection(_cnnSqlCapss))
{
SqlCommand cmdCommitChange = new SqlCommand("usp_Stored_Procedure", cnn);
cmdCommitChange.CommandType = CommandType.StoredProcedure;
cmdCommitChange.Parameters.AddWithValue("#Parm1", Value1);
cmdCommitChange.Parameters.AddWithValue("#Parm2", Value2);
cmdCommitChange.Parameters.AddWithValue("#Parm3", Value3);
// add this line
cmdCommitChange.Parameters.Add("#SourceTable", SqlDbType.Structured).Value = dtSource;
cmdCommitChange.Parameters.Add("#ReturnVal", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
cnn.Open();
cmdCommitChange.ExecuteNonQuery();
var result = (int)returnParameter.Value;
return result;
}
Reference:
Table-Valued Parameters (MS Docs)
I found the problem. I am passing a text value that is too large for a column on my datatable.
The web service was indeed throwing an exception but there was some code in my application's routine which was preventing me from seeing it.

ASP.NET application opening WAY too many SQL connections

I have an issue on a codebit with an ASP.NET Webforms 4 application.
I am using SQL server 2008 R2, IIS 7, the website is running on Windows Server 2008 R2 in separate Application pool (integrated mode, .NET4, with support for 32bit assemblies).
The following code is posing problems:
Dim sqlCmd = New SqlClient.SqlCommand
With sqlCmd
Using sqlConnectionToUse As SqlClient.SqlConnection = GetActiveConnexion(pstrConnectString), _
vAdaptor As New SqlClient.SqlDataAdapter
.Connection = sqlConnectionToUse
.CommandText = pstrSQL 'function parameter
vAdaptor.SelectCommand = sqlCmd
'query1: SELECT somecolumn FROM table WHERE somecolumn '' ==> opens a new connection in SQL Server
'query2: SELECT someothercolumn FROM anothertable WHERE someothercolumn 23 ==> uses my WebSite process active connection
vAdaptor.Fill(vDataSet)
End Using
End With
UPDATE: the GetActiveConnexion() method simply does the following code in my case:
Return New SqlClient.SqlConnection("my connection string obtained from the web.config file")
When I run the query2, everything goes smoothly, the ASP.NET application uses the openned connection of the application pool and I get my results in the dataset.
However, whenever I run the query1, a NEW connection is openned in SQL server (I can see it show up in the SSMS's Activity Monitor) and this one remains openned. The problem is that If I run this query1 100 times, I reach the connection pool's limit and very bad things happens. I still gets the results in the dataset, can use them etc...
The new connection is created on the call of vAdaptator.Fill().
Any idea on what's wrong ?
Thanks a lot for your time.
(PS: sorry for the bad english).
Here is the code in C# for those who prefer:
object sqlCmd = new SqlClient.SqlCommand();
using (SqlClient.SqlConnection sqlConnectionToUse = GetActiveConnexion(pstrConnectString)) {
using (SqlClient.SqlDataAdapter vAdaptor = new SqlClient.SqlDataAdapter()) {
sqlCmd.Connection = sqlConnectionToUse;
sqlCmd.CommandText = pstrSQL; //function parameter
vAdaptor.SelectCommand = sqlCmd;
//query1: SELECT F10_ID FROM FIN_MONTANT_TT_F10 WHERE F10_ID_TT_F19 = '' ==> opens a new connection in SQL Server
//query2: SELECT A48_ID FROM ADH_EPARTICIPANT_ADMIN_A48 WHERE A48_ID=23 ==> uses my WebSite process active connection
vAdaptor.Fill(vDataSet);
}
}
Your SqlCommand instance should be wrapped in a using block as it's Disposable. It's probably the source of your problems.
using (SqlClient.SqlConnection sqlConnectionToUse = GetActiveConnexion(pstrConnectString))
{
using (SqlCommand sqlCmd = sqlConnectionToUse.CreateCommand())
{
using (SqlClient.SqlDataAdapter vAdaptor = new SqlClient.SqlDataAdapter())
{
...
}
}
}
Or VB
Using sqlConnectionToUse As SqlClient.SqlConnection = GetActiveConnexion(pstrConnectString)
Using sqlCmd As SqlCommand = sqlConnectionToUse.CreateCommand()
Using vAdaptor As New SqlClient.SqlDataAdapter()
...
End Using
End Using
End Using

Crystal Report Credentials Prompt after deployment

I am Publishing crystal reports on remote server using the following code. when i try to run the crystal report page Crystal report viewer prompt me for database info. As the published crystal report were created using development server. In my crystal report i was using OLEDB ADO Connection
MyRepository _MyRepository = new MyRepository();
System.Data.SqlClient.SqlConnection myConnection = new System.Data.SqlClient.SqlConnection();
myConnection.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnStr"].ConnectionString;
System.Data.SqlClient.SqlCommand MyCommand = new System.Data.SqlClient.SqlCommand("dbo.spMySP");
MyCommand.Connection = myConnection;
MyCommand.Parameters.Add("#PositionID", SqlDbType.Int).Value = (cmbPositions.SelectedValue == "" ? 0 : Convert.ToInt32(cmbPositions.SelectedValue));
MyCommand.CommandType = System.Data.CommandType.StoredProcedure;
System.Data.SqlClient.SqlDataAdapter MyDA = new System.Data.SqlClient.SqlDataAdapter();
MyDA.SelectCommand = MyCommand;
ASale _DS = new ASale();
MyDA.Fill(_DS, "dbo.spMySP");
rptSale oRpt = new rptSale();
oRpt.SetDatabaseLogon("sa", "mypass");
oRpt.SetDataSource(_DS);
oRpt.SetParameterValue(0, "param1");
oRpt.SetParameterValue(1, "param2");
oRpt.SetParameterValue(2, "param3" );
oRpt.SetParameterValue(3, (cmbPositions.SelectedValue == "" ? 0 : Convert.ToInt32(cmbPositions.SelectedValue)));
CrystalReportViewer1.ReportSource = oRpt;
HI,
When you develop your report, do you use Windows authentication to login to the database to build the report?
Maybe you can try to open the report again and try to update your database set up on the crystal report. E.g. by using the same login information your use on your code.
What I normally do is to put the database server name and the database name on to the code as well
E.G.
_CReportDoc.SetDatabaseLogon(username, pw, ServerName, DB)
Not sure if it could help

How to pass parameters to SSRS report programmatically

I'm looking for a little help on programmatically passing parameters to a SSRS report via VB.NET and ASP.NET. This seems like it should be a relatively simple thing to do, but I haven't had much luck finding help on this.
Does anyone have any suggestions on where to go to get help with this, or perhaps even some sample code?
Thanks.
You can do the following,: (it works both on local reports as in Full Blown SSRS reports. but in full mode, use the appropriate class, the parameter part remains the same)
LocalReport myReport = new LocalReport();
myReport.ReportPath = Server.MapPath("~/Path/To/Report.rdlc");
ReportParameter myParam = new ReportParameter("ParamName", "ParamValue");
myReport.SetParameters(new ReportParameter[] { myParam });
// more code here to render report
If the Report server is directly accessible, you can pass parameters in the Querystring if you are accessing the repoort with a URL:
http://MyServer/ReportServer/?MyReport&rs:Command=Render&Param1=54321&Param2=product
You can add output formatting by adding the following on the end of the URL:
&rs:Format=Excel
or
&rs:Format=PDF
It's been a while since I did this code, but it may help:
Your web project has to be a Web Site, and not a project of type "ASP.Net Web Application", or you won't be able to add the reference mentioned below.
Right click on the project and add an ASP.Net folder - App_WebReferences. You'll have to specify the server where your SRS is; choose the .asmx.
Once it's added, the folder under that level is called RSService, and under that are 2 things: reportservice.discomap & .wsdl.
In my VB, I do Imports RSService and Imports System.Web.Services.Protocols, then...
Dim MyRS As New ReportingService
The reporting service is on a different server than the webserver the app is on, so I can't do the following: MyRS.Credentials = System.Net.CredentialCache.DefaultCredentials
Instead: MyRS.Credentials = New System.Net.NetworkCredential(rs1, rs2, rs3),
where the rs1/2/3 are the login to SRS box, password to SRS box, & domain name". (These are encrypted in my web.config.)
Then, a mass-paste:
MyRS.Credentials = New System.Net.NetworkCredential(rs1, rs2, rs3)
Dim ReportByteArray As Byte() = Nothing
Dim ReportPath As String = "/SRSSiteSubFolder/ReportNameWithoutRDLExtension"
Dim ReportFormat As String = "PDF"
Dim HistoryID As String = Nothing
Dim DevInfo As String = "<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"
'Dim x As ReportParameter - not necessary
Dim ReportParams(0) As ParameterValue
ReportParams(0) = New ParameterValue()
ReportParams(0).Name = "TheParamName"
ReportParams(0).Value = WhateverValue
Dim Credentials As DataSourceCredentials() = Nothing
Dim ShowHideToggle As String = Nothing
Dim Encoding As String
Dim MimeType As String
Dim ReportHistoryParameters As ParameterValue() = Nothing
Dim Warnings As Warning() = Nothing
Dim StreamIDs As String() = Nothing
'Dim sh As New SessionHeader() - not necessary
''MyRS.SessionHeaderValue = sh - not necessary
ReportByteArray = MyRS.Render(ReportPath, ReportFormat, HistoryID, DevInfo, ReportParams, Credentials, _
ShowHideToggle, Encoding, MimeType, ReportHistoryParameters, Warnings, StreamIDs)
'(Yay! That line was giving "HTTP error 401 - Unauthorized", until I set the credentials
' as above, as explained by http://www.odetocode.com/Articles/216.aspx.)
'Write the contents of the report to a PDF file:
Dim fs As FileStream = File.Create(FullReportPath, ReportByteArray.Length)
fs.Write(ReportByteArray, 0, ReportByteArray.Length)
fs.Close()
Call EmailTheReport(FullReportPath)
If IO.File.Exists(FullReportPath) Then
IO.File.Delete(FullReportPath)
End If
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.Reset();
Label1.Visible = false;
ReportViewer1.Visible = true;
DataSet dataSet = new DataSet();
dataSet = new ClassBLL().Load_Report_Detail(TextBox1.Text,
ddlType.SelectedValue, levelcode, fields);
ReportDataSource datasource = new ReportDataSource("DataSet_StoreprocedureName",
dataSet.Tables[0]);
if (dataSet.Tables[0].Rows.Count == 0)
{
ReportViewer1.Visible = false;
}
ReportViewer1.LocalReport.ReportPath = Server.MapPath("") + #"\Report.rdlc";
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(datasource);
string fields="name,girish,Z0117";
string[] filedName = fields.Split(',');
ReportParameter[] param = new ReportParameter[2];
//for (int i = 0; i < filedName.Length; i++)
//{
param[0] = new ReportParameter(filedName[0], filedName[0], true);
param[1] = new ReportParameter(filedName[3], filedName[3], true);
// }
ReportViewer1.LocalReport.SetParameters(param);
ReportViewer1.ServerReport.Refresh();

Resources