how to link to ssrs report from asp.net webpage - asp.net

I'm having trouble linking to an ssrs report from my asp.net webpage.
the direct link is
server/Reports/Pages/Report.aspx?ItemPath=%2fRig+Dashboard%2fRig+Status+Report
I also need to pass in two parameters which is FileTypeID and Date
Please help...
ReportViewer1.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote;
ReportViewer1.ServerReport.ReportServerUrl = new Uri("http://server/Reports"); // Report Server URL
ReportViewer1.ServerReport.ReportPath = "/Rig Dashboard/Rig Status Report"; // Report Name
ReportViewer1.ShowParameterPrompts = false;
ReportViewer1.ShowPrintButton = true;
ReportViewer1.ServerReport.Refresh();
The attempt to connect to the report server failed. Check your connection information and that the report server is a compatible version.
The request failed with HTTP status 404: Not Found.

Your doing it wrong. You are trying to call the 'landing page' : /Reports NOT THE SERVICE: /ReportServer. Yuriy gave you a good place to get started. I can give you an example of how I do it in some local code I use in WPF calling a Windows Form(blech!):
private void ResetReportViewer(ProcessingMode mode)
{
this.reportViewer.Clear();
this.reportViewer.LocalReport.DataSources.Clear();
this.reportViewer.ProcessingMode = mode;
}
private void ReportViewerRemote_Load(object sender, EventArgs e)
{
ResetReportViewer(ProcessingMode.Remote);
reportViewer.ServerReport.ReportServerUrl = new Uri(#"http://server/ReportServer");
reportViewer.ServerReport.ReportPath = "/Folder/ReportName";
reportViewer.RefreshReport();
}
private void ReportViewerRemoteWithCred_Load(object sender, EventArgs e)
{
ResetReportViewer(ProcessingMode.Remote);
reportViewer.ServerReport.ReportServerUrl = new Uri(#"http://server/ReportServer");
reportViewer.ServerReport.ReportPath = "/Folder/ReportName";
DataSourceCredentials dsCrendtials = new DataSourceCredentials();
dsCrendtials.Name = "DataSource1";
dsCrendtials.UserId = "DedicatedUser";
dsCrendtials.Password = "P#ssword(jk)";
reportViewer.ServerReport.SetDataSourceCredentials(new DataSourceCredentials[] { dsCrendtials });
reportViewer.RefreshReport();
}

Related

SqlDependency with signalR not firing dependency_OnChange consistently

Setup
•Visual Studio 2010
•IIS 8.5
•.NET Framework 4.6
•Microsoft SQL Server 2014
•AppPool Account on IIS is domain\web
I have a web page that monitors changes in a database table. I am using dependency_OnChange to monitor the database and pass the data to the user via signalR. I set a breakpoint in the dependency_OnChange method and it is only getting hit a few times out of thousands of database updates.
In web.config... I am using Integrated Security=True.
My user is a sysadmin on the sql box. (This is just for proof of concept)
In Global.asax... specifying a queuename and stopping and starting sqldependency
void Application_Start(object sender, EventArgs e)
{
var queuename = "Q_Name";
var sConn = ConfigurationManager.ConnectionStrings["singalR_ConnString"].ConnectionString;
SqlDependency.Stop(sConn, queuename);
SqlDependency.Start(sConn, queuename);
}
void Application_End(object sender, EventArgs e)
{
var queuename = "Q_Name";
var sConn = ConfigurationManager.ConnectionStrings["singalR_ConnString"].ConnectionString;
SqlDependency.Stop(sConn, queuename);
}
In code behind...
public void SendNotifications()
{
//Identify Current User and Row No
string CurrentUser = GetNTName();
string message = string.Empty;
string conStr = ConfigurationManager.ConnectionStrings["singalR_ConnString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conStr))
{
string query = "SELECT [RowNo] FROM [dbo].[Test] WHERE [User] = #User";
string SERVICE_NAME = "Serv_Name";
using (SqlCommand command = new SqlCommand(query, connection))
{
// Add parameters and set values.
command.Parameters.Add("#User", SqlDbType.VarChar).Value = CurrentUser;
//Need to clear notification object
command.Notification = null;
//Create new instance of sql dependency eventlistener (re-register for change events)
SqlDependency dependency = new SqlDependency(command, "Service=" + SERVICE_NAME + ";", 0);
//SqlDependency dependency = new SqlDependency(command);
//Attach the change event handler which is responsible for calling the same SendNotifications() method once a change occurs.
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
message = reader[0].ToString();
}
}
}
//If query returns rows, read the first result and pass that to hub method - NotifyAllClients.
NotificationsHub nHub = new NotificationsHub();
nHub.NotifyAllClients(message);
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
//Check type to make sure a data change is occurring
if (e.Type == SqlNotificationType.Change)
{
// Re-register for query notification SqlDependency Change events.
SendNotifications();
}
}
NotificationsHub.cs page...
//Create the Hub
//To create a Hub, create a class that derives from Microsoft.Aspnet.Signalr.Hub.
//Alias that can call class from javascript. - i.e. var hub = con.createHubProxy('DisplayMessage');
[HubName("DisplayMessage")]
public class NotificationsHub : Hub //Adding [:Hub] let c# know that this is a Hub
{
//In this example, a connected client can call the NotifyAllClients method, and when it does, the data received is broadcasted to all connected clients.
//Create NotifyAllClients Method
//public means accessible to other classes
//void means its not returning any data
public void NotifyAllClients(string msg)
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>();
//When this method gets called, every single client has a function displayNotification() that is going to be executed
//msg is the data that is going to be displayed to all clients.
context.Clients.All.displayNotification(msg);
}
}
The first thing I would do here is refactor the Sql Dependency setup out to a stand alone method and call it from your send notification. (SoC and DRY) because if you are creating other SqlDependencies in other places they are going to trip each other up. Secondly your are creating a new NotificationsHub, You should be getting the currently active hub.
DefaultHubManager hubManager = new DefaultHubManager();
hub = hubManager.ResolveHub("NotificationsHub");
hub.NotifyAllClients(message);
There is also an older way to get the hub but I am not sure it will still work
GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>()
I also have an example of a simpler version in this answer.
Polling for database changes: SqlDependency, SignalR is Good
Let me know if you have any questions.

System.Net.Sockets.SocketException: A system call has failed

I have the following code snippet that run with IIS Express of VS2012. It is able to send out email and working fine with smtp server.
Then deployed it as New Application on IIS 7. When I run it, I am getting the error “System.Net.Sockets.SocketException: A system call has failed 11.29.83.49:25” .
Do you have any idea what causing the error?
Do I miss something to configure IIS server to work with smtp server?
protected void Page_Load(object sender, EventArgs e)
{
System.Net.Mail.MailMessage _message = new System.Net.Mail.MailMessage();
_message.Subject = "Hi Testing";
_message.SubjectEncoding = System.Text.Encoding.UTF8;
_message.From = new System.Net.Mail.MailAddress("sender#gmail.com","Test");
_message.To.Add(new System.Net.Mail.MailAddress("receiver#gmail.com", "Test"));
System.Net.Mail.AlternateView _content_view = System.Net.Mail.AlternateView.CreateAlternateViewFromString("Message Body");
_message.AlternateViews.Add(_content_view);
sendEmailMessage(_message);
}
public void sendEmailMessage(System.Net.Mail.MailMessage message)
{
getClientFromConfig().Send(message);
}
private static System.Net.Mail.SmtpClient getClientFromConfig()
{
System.Net.Mail.SmtpClient _client = new System.Net.Mail.SmtpClient();
_client.Host = "host name/ip here";
_client.Port = 25;
return _client;
}
Could anyone please suggest to get it work?
I think the reason is firewall.
Open IIS Manager ->Application Pool and select your pool then click advanced settings.
Change your Identity as
Network Service
-below the process model

Push Sharp Within Asp.Net Web Service

This is more of a general Asp.Net / .Net lifecycle question.
I'm looking at using PushSharp within a Asp.Net Web Service to send notifications using APNS.
Given the nature of PushSharp using a queue to async send messages and then event callbacks to notify of 'OnNotificationSent' / 'OnServiceException' etc.. how would this work within Asp.net?
The Web Service exposes a method that instantiates PushSharp, registers for the various callback events and queues Notification Messages.
The consumer calls the web service
Once The Web service method returns, does that method continue to receive the event callbacks or is it disposed and the events will not be called?
Thanks
for your help.
Not highly recommended in Asp.net, due to application pool interfering in the process (PushSharp author says notifications in the queue but not get sent). I have implemented this though in an Asp.net website and it works.
I have moved this to a Windows service since.
Global.asax.cs file:
using PushSharp;
using PushSharp.Core;
public class Global : System.Web.HttpApplication
{
private static PushBroker myPushBroker;
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
myPushBroker = new PushBroker();
myPushBroker.OnNotificationSent += NotificationSent;
myPushBroker.OnChannelException += ChannelException;
myPushBroker.OnServiceException += ServiceException;
myPushBroker.OnNotificationFailed += NotificationFailed;
myPushBroker.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
myPushBroker.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
myPushBroker.OnChannelCreated += ChannelCreated;
myPushBroker.OnChannelDestroyed += ChannelDestroyed;
HttpContext.Current.Application["MyPushBroker"] = myPushBroker;
}
//IMPLEMENT PUSHBROKER DELEGATES HERE
}
aspx.cs file (example Notifications.aspx.cs):
using PushSharp;
using PushSharp.Apple;
using PushSharp.Core;
public partial class Notifications : System.Web.UI.Page {
private PushBroker myPushBroker = HttpContext.Current.Application["MyPushBroker"] as PushBroker;
//SO I CAN SWITCH FROM DEVELOPMENT TO PRODUCTION EASILY I SET THIS IN THE DATABASE
private string pushCertificate = "";
private string certPass = "";
private bool isProduction = false;
protected void btnSendNotification_Click(object sender, EventArgs e)
{
bool hasError = false;
lblError.Text = "";
if (!string.IsNullOrEmpty(txtMessage.Text))
{
try
{
GetCertificate();
//GET DEVICE TOKENS TO SEND MESSAGES TO
//NOT THE BEST WAY TO SEND MESSAGES IF YOU HAVE HUNDREDS IF NOT THOUSANDS OF TOKENS. THAT'S WHY A WINDOWS SERVICE IS RECOMMENDED.
string storedProcUser = "sp_Token_GetAll";
string userTableName = "User_Table";
DataSet dsUser = new DataSet();
UserID = new Guid(ID.Text);
dsUser = srvData.GetDeviceToken(UserID, storedProcUser, userTableName, dataConn);
DataTable userTable = new DataTable();
userTable = dsUser.Tables[0];
if (userTable.Rows.Count != 0)
{
string p12FileName = Server.MapPath(pushCertificate); //SET IN THE GET CERTIFICATE
var appleCert = File.ReadAllBytes(p12FileName);
string p12Password = certPass;
//REGISTER SERVICE
myPushBroker.RegisterAppleService(new ApplePushChannelSettings(isProduction, appleCert, p12Password));
DataRow[] drDataRow;
drDataRow = userTable.Select();
string savedDeviceToken = "";
for (int i = 0; i < userTable.Rows.Count; i++)
{
if (drDataRow[i]["DeviceToken"] is DBNull == false)
{
savedDeviceToken = drDataRow[i]["DeviceToken"].ToString();
myPushBroker.QueueNotification(new AppleNotification()
.ForDeviceToken(savedDeviceToken)
.WithAlert(txtMessage.Text)
.WithBadge(1)
.WithSound("sound.caf"));
//NOTHING TO DO ANYMORE. CAPTURE IN THE PUSH NOTIFICATION DELEGATE OF GLOBAL ASCX FILE WHAT HAPPENED TO THE SENT MESSAGE.
}
}
}
}
catch(Exception ex)
{
}
finally
{
}
}
}
}
Check out EasyServices it allows you to easily push notifications to various push servers using PushSharp without having to take care of un-received notifications even when using ASP.NET
var _pushNotificationService = EngineContext.Current.Resolve<IPushNotificationService>();
_pushNotificationService.InsertNotification(NotificationType type, string title, string message, int subscriberId, PushPriority Priority = PushPriority.Normal);
https://easyservices.codeplex.com

Crystal Report 2011 Login prompt in asp.net

We are using Crystal Reports 2011 & SQL Server 2008 (Windows 7 64 bit). Whenever I try to deploy the crystal reports in the IIS it is always prompting enter the database login information. I have tried the below options
Set the login information in the code
Set IIS app pool to LocalService
Nothing works. Here is the code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ConfigureCrystalReports();
}
else
{
ReportDocument doc = Session["Report"] as ReportDocument;
SetLogon(doc);
CrystalReportViewer1.ReportSource = doc;
CrystalReportViewer1.RefreshReport();
}
}
private void ConfigureCrystalReports()
{
ReportDocument reportDoc;
if (!IsPostBack)
{
reportDoc = new ReportDocument();
reportDoc.Load(Server.MapPath("~/Sample.rpt"));
Session.Add("Report", reportDoc);
}
else
{
reportDoc = Session["Report"] as ReportDocument;
}
SetLogon(reportDoc);
CrystalReportViewer1.ReportSource = reportDoc;
CrystalReportViewer1.RefreshReport();
}
private void SetLogon(ReportDocument reportDoc)
{
var connectionInfo1 = new ConnectionInfo()
{
ServerName = #"ODBCDSN",
DatabaseName = "hrdw_old",
IntegratedSecurity = true
};
SetDBLogonForReport(connectionInfo1, reportDoc);
}
private void SetDBLogonForReport(ConnectionInfo connectionInfo1, ReportDocument reportDocument)
{
Tables tables = reportDocument.Database.Tables;
foreach (CrystalDecisions.CrystalReports.Engine.Table table in tables)
{
TableLogOnInfo tableLogonInfo = table.LogOnInfo;
tableLogonInfo.ConnectionInfo = connectionInfo1;
tableLogonInfo.ConnectionInfo.Type = ConnectionInfoType.SQL;
table.ApplyLogOnInfo(tableLogonInfo);
}
reportDocument.SetDatabaseLogon(connectionInfo1.UserID, connectionInfo1.Password);
}
}
Steps tried in IIS:
Application pool: ASP.NET 4.0 Default app pool
Also enabled Windows Authentication in IIS & disabled anonymous authentication.
Tried anonymous authentication only.
SQL Server has both windows and sql server authentication.
I will not be able to use dataset since the crystal reports will be developed by someone using command objects. It works perfectly good in the Visual studio 2010 environment. But doesnt work in IIS.
Am I missing something basic? Any help is appreciated.
Thanks
Shankar.
Here is how this was solved. It was a bit of workaround
CrystalDecisions.ReportAppServer.ClientDoc.ISCDReportClientDocument rptClientDoc = doc.ReportClientDocument;
CrystalDecisions.ReportAppServer.ClientDoc.ISCDReportClientDocument rcd = rptClientDoc;
string server = #"<SERVER>";
string db = "<DATABASE>";
string user = "<USER>";
string pass = "PASSWORD";
rptClientDoc.DatabaseController.LogonEx(server, db, user, pass);
//Create the logon propertybag for the connection we wish to use
CrystalDecisions.ReportAppServer.DataDefModel.PropertyBag logonDetails = new CrystalDecisions.ReportAppServer.DataDefModel.PropertyBag();
logonDetails.Add("Auto Translate", -1);
logonDetails.Add("Connect Timeout", 15);
logonDetails.Add("Data Source", server);
logonDetails.Add("General Timeout", 0);
logonDetails.Add("Initial Catalog", db);
logonDetails.Add("Integrated Security", "false");
logonDetails.Add("Locale Identifier", 1033);
logonDetails.Add("OLE DB Services", -5);
logonDetails.Add("Provider", "SQLOLEDB");
logonDetails.Add("Use Encryption for Data", 0);
//Create the QE (query engine) propertybag with the provider details and logon property bag.
CrystalDecisions.ReportAppServer.DataDefModel.PropertyBag QE_Details = new CrystalDecisions.ReportAppServer.DataDefModel.PropertyBag();
QE_Details.Add("Database DLL", "crdb_ado.dll");
QE_Details.Add("QE_DatabaseName", db);
QE_Details.Add("QE_DatabaseType", "OLE DB (ADO)");
QE_Details.Add("QE_LogonProperties", logonDetails);
QE_Details.Add("QE_ServerDescription", server);
QE_Details.Add("QE_SQLDB", "True");
QE_Details.Add("SSO Enabled", "False");
CrystalDecisions.ReportAppServer.DataDefModel.ConnectionInfo newConnInfo = new CrystalDecisions.ReportAppServer.DataDefModel.ConnectionInfo();
CrystalDecisions.ReportAppServer.DataDefModel.ConnectionInfo oldConnInfo;
CrystalDecisions.ReportAppServer.DataDefModel.ConnectionInfos oldConnInfos;
oldConnInfos = rcd.DatabaseController.GetConnectionInfos(null);
for (int I = 0; I < oldConnInfos.Count; I++)
{
oldConnInfo = oldConnInfos[I];
newConnInfo.Attributes = QE_Details;
newConnInfo.Kind = CrystalDecisions.ReportAppServer.DataDefModel.CrConnectionInfoKindEnum.crConnectionInfoKindCRQE;
try
{
rcd.DatabaseController.ReplaceConnection(oldConnInfo, newConnInfo, null, CrystalDecisions.ReportAppServer.DataDefModel.CrDBOptionsEnum.crDBOptionDoNotVerifyDB);
}
catch (Exception ex)
{
Label1.Text = ex.Message;
return;
}
}
doc.SetDatabaseLogon(user, pass);
To ensure that there is no login prompt at all at first I had to login to the controller and then set all the login credentials. Ensure that login credentials are reused during post back as well. After this is done, login using the reportdocument as well. This solves the issue of login prompt coming again and again.
Thanks
Shankar

passing parameter to report viewer

I want to pass a parameter to my report view. I have a drop down list with values from database and a button for displaying the report after selecting an item from the drop down list.
here is the code I wrote for adding the parameter
protected void Button1_Click(object sender, EventArgs e)
{
RenderReport();
}
protected void RenderReport()
{
try
{
ServerReport serverReport = ReportViewer1.ServerReport;
ReportViewer1.ProcessingMode = ProcessingMode.Remote;
try
{
serverReport.ReportServerUrl = new Uri("http://hedinaily-pc/Reports_HEDI");
}
catch (Exception ex)
{
Logger.Error(ex.Message, "");
}
serverReport.ReportPath = "~/Diagrammes/PresenceTotale.rdlc";
ReportParameter employe = new ReportParameter();
employe.Name = "Employe";
employe.Values.Add(DropDownList1.SelectedValue);
ReportViewer1.ServerReport.SetParameters( new ReportParameter[] { employe });
ReportViewer1.Visible = true;
}
catch (Exception ex)
{
Logger.Error(ex.Message, "");
}
}
Here is the data set of my report
When I check my log file I find this error :
The attempt to connect to the report server failed. Check your connection information and that the report server is a compatible version.
Can anyone tell me where doe's this error come from. I spent hours searching on google I found this LINK but I couldn't resolve it.
Try it like this...
ReportViewer1.ServerReport.ReportPath = "FooReport.rdlc";
ReportParameter[] reportParameter = new ReportParameter[2];
reportParameter[0] = new ReportParameter("fooFromDate", dateFrom.ToShortDateString());
reportParameter[1] = new ReportParameter("fooDateTo", dateTo.ToShortDateString());
ReportViewer1.ServerReport.SetParameters(reportParameter);
ReportViewer1.ServerReport.Refresh();
Also .Refresh() method must be called so that...report is displayed..
You can test with this code
ReportParameter[] yourParams = new ReportParameter[1];
yourParams [0] = new ReportParameter("Employe", DropDownList1.SelectedValue);//Adjust value
this.ReportViewer1.ServerReport.SetParameters(yourParams );
One way of doing the same is by using the Report Parameters dialog box to define parameters for a report that is processed in local mode. You can define parameters to support conditional formatting or to use in expressions or code. You cannot use the Report Parameters dialog box to map report parameters to query parameters or use them in data source filters.
So you can pass the parameters to the SP as we can do it in normal operation, by usign sqlParameters. Then execute the SP bind it to report viewer datasource.
For the "The attempt to connect to the report server failed. Check your connection information and that the report server is a compatible version." error try:
serverReport.ReportPath = "/Diagrammes/PresenceTotale";
instead of:
serverReport.ReportPath = "~/Diagrammes/PresenceTotale.rdlc";

Resources