crystal report print and export not working - crystal-reports

I'm .net developer. now I'm working with crystal report. when I'm printing or exporting crystal report then print dialog open when I press Print, then no print operation occurs. This Print and Export not working at fire fox. only chrome support this functions. Is there extra code required for do this job.
---------------------------updated-----------------------------------------
at class declaration :
public partial class EndUser_FS_File_History : System.Web.UI.Page
{
ReportDocument reportdocument = null;
..........
at load crystal report:
reportdocument = new ReportDocument();
string connectionString = ConfigurationManager.ConnectionStrings["FileSystemConnectionString"].ConnectionString;
SqlConnectionStringBuilder SConn = new SqlConnectionStringBuilder(connectionString);
reportdocument.Load(Server.MapPath(#"~/Admin/UserReport.rpt"));
reportdocument.SetDataSource(myDataSet);
reportdocument.DataSourceConnections[0].SetConnection(SConn.DataSource, SConn.InitialCatalog, SConn.UserID, SConn.Password);
CrystalReportViewer1.ReportSource = reportdocument;
and at Page_Unload event:
protected void Page_Unload(object sender, EventArgs e)
{
if (reportdocument != null)
{
reportdocument.Close();
reportdocument.Dispose();
}
GC.Collect();
}
still problem occurs with large no of records:
The maximum report processing jobs limit configured by your system administrator has been reached.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Runtime.InteropServices.COMException: The maximum report processing jobs limit configured by your system administrator has been reached.
Source Error:
Line 782: string connectionString = ConfigurationManager.ConnectionStrings["FileSystemConnectionString"].ConnectionString;
Line 783: SqlConnectionStringBuilder SConn = new SqlConnectionStringBuilder(connectionString);
Line 784: reportdocument.Load(Server.MapPath(#"~/Admin/UserReport.rpt"));
Line 785: reportdocument.SetDataSource(myDataSet);
Line 786: reportdocument.DataSourceConnections[0].SetConnection(SConn.DataSource, SConn.InitialCatalog, SConn.UserID, SConn.Password);
Source File: f:\EasyWeb\Admin\User_Management.aspx.cs Line: 784
Stack Trace:
[COMException (0x80041016): The maximum report processing jobs limit configured by your system administrator has been reached.]
CrystalDecisions.ReportAppServer.ClientDoc.ReportClientDocumentClass.Open(Object& DocumentPath, Int32 Options) +0
CrystalDecisions.ReportAppServer.ReportClientDocumentWrapper.Open(Object& DocumentPath, Int32 Options) +144
CrystalDecisions.ReportAppServer.ReportClientDocumentWrapper.EnsureDocumentIsOpened() +526
[CrystalReportsException: Load report failed.]
CrystalDecisions.ReportAppServer.ReportClientDocumentWrapper.EnsureDocumentIsOpened() +621
CrystalDecisions.CrystalReports.Engine.ReportDocument.Load(String filename, OpenReportMethod openMethod, Int16 parentJob) +1969
CrystalDecisions.CrystalReports.Engine.ReportDocument.Load(String filename) +186
Admin_User_Management.lbut_print_Click(Object sender, EventArgs e) in f:\EasyWeb\Admin\User_Management.aspx.cs:784
System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) +111
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +79
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +175
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

There are few steps:
Before Pageload, declare the report as
ReportDocument rpt = null;
protected void Page_Load(object sender, EventArgs e)
{
try
{
rpt= new ReportName; //this is the name of your report
// do all the logic here
}
catch()
{
}
}
protected void Page_Unload(object sender, EventArgs e)
{
if(rpt!=null)
{
rpt.Close();
rpt.Dispose();
}
GC.Collect();
}

Related

How to dynamically and correctly change a query in Command Table for Crystal Reports file?

I have many rpt files. I want to change the query for each report using C#. There are several ways to do this changes.
First way:
private void button_Test_Click(object sender, EventArgs e)
{
ReportDocument rptDoc = new ReportDocument();
rptDoc.Load("D:\\Temp_01\\Report1_Test.rpt");
rptDoc.SetDatabaseLogon("User", "Password", "ServName", "DBName");
CrystalDecisions.Shared.ConnectionInfo ConnInf;
ConnInf = rptDoc.Database.Tables[0].LogOnInfo.ConnectionInfo;
String strSQLQuery = "SELECT TOP(123) * FROM sys.all_objects";
String strTableName = rptDoc.Database.Tables[0].Name;
try
{
rptDoc.SetSQLCommandTable(ConnInf, strTableName, strSQLQuery);
rptDoc.VerifyDatabase();
}
catch (Exception ex) { rptDoc.Close(); }
rptDoc.SaveAs("D:\\Temp_02\\Report2_Test.rpt");
rptDoc.Close();
}
It is not the best way. The method SetSQLCommand does not work when the query has any parameters. Even if you set value for each parameter, SetSQLCommand does not work. The example with a parameter which does not work:
private void button_Test_Click(object sender, EventArgs e)
{
ReportDocument rptDoc = new ReportDocument();
rptDoc.Load("D:\\Temp_01\\Report1_Test.rpt");
rptDoc.SetDatabaseLogon("User", "Password", "ServName", "DBName");
CrystalDecisions.Shared.ConnectionInfo ConnInf;
ConnInf = rptDoc.Database.Tables[0].LogOnInfo.ConnectionInfo;
String strSQLQuery = "SELECT TOP(1) * FROM sys.all_objects WHERE name = {?strName}";
String strTableName = rptDoc.Database.Tables[0].Name;
try
{
rptDoc.SetParameterValue("strName", "Text");
rptDoc.SetSQLCommandTable(ConnInf, strTableName, strSQLQuery);
rptDoc.VerifyDatabase();
}
catch (Exception ex) { rptDoc.Close(); }
rptDoc.SaveAs("D:\\Temp_02\\Report2_Test.rpt");
rptDoc.Close();
}
It returns an error. This method does not work with parameters!
Second way:
private void button_Test_Click(object sender, EventArgs e)
{
ReportDocument rptDoc = new ReportDocument();
rptDoc.Load("D:\\Temp_01\\Report1_Test.rpt");
rptDoc.SetDatabaseLogon("User", "Password", "ServName", "DBName");
ISCDReportClientDocument rcd = null;
rcd = rptDoc.ReportClientDocument as ISCDReportClientDocument;
CommandTable rTblOld;
CommandTable rTblNew;
rTblOld = rcd.Database.Tables[0] as CommandTable;
rTblNew = rcd.Database.Tables[0].Clone(true) as CommandTable;
rTblNew.CommandText = "SELECT TOP(1) * FROM sys.all_objects";
try
{
rcd.DatabaseController.SetTableLocationEx(rTblOld, rTblNew);
rcd.VerifyDatabase();
}
catch (Exception ex) { rcd.Close(); }
rcd.SaveAs(rcd.DisplayName, "D:\\Temp_02\\", 1);
rcd.Close();
}
This is also not the best way. The method SetLocalTableEx does a struct of the report is bad. After run SetLocalTableEx, attribute ConnectionInf.UserId have value NULL also the Name of connection
After SetTableLocationEx:
rcd.DatabaseController.SetTableLocationEx(rTblOld, rTblNew);
String UserID;
UserID = rptDoc.Database.Tables[0].LogOnInfo.ConnectionInfo.UserID;
if (UserID == null) MessageBox.Show("UserID has NULL");
UserId has value NULL
Also, before run SetTableLocationEx, Connection Name is MSODBCSQL11
enter image description here
After run SetTableLocationEx, Connection Name is Command
enter image description here
So,
how do dynamic and correctly to change the query in CommandTable for Crystal Reports file?
Thanks,
Artem
You are using command in Crystal Report which is the best way when doing and displaying a data from database to crystal report but unfortunately you do it in Code Behind.
My Question is:
Why don't you do it in Command of Crystal Report itself?
see this link for more info.

C# namedpipes server/client

I am trying to learn how named pipes work so i can connect two c# applications.
I wrote two basic C# applications for testing but it doesn't work.
When i start the connection the first application freezes waiting for input and after i sent input from application 2 it defreezes and button1 shows. But nothing appears in the textbox, any ideas why?
Application1:
private void button1_Click(object sender, EventArgs e)
{
button1.Hide();
NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe");
pipeServer.WaitForConnection();
StreamReader s = new StreamReader(pipeServer);
textBox1.Text = s.ReadToEnd();
pipeServer.Close();
button1.Show();
}
Application 2:
private void button1_Click(object sender, EventArgs e)
{
NamedPipeClientStream pipeClient = new NamedPipeClientStream("testpipe");
if (pipeClient.IsConnected != true) pipeClient.Connect();
StreamWriter sw = new StreamWriter(pipeClient);
sw.WriteLine("%s", textBox1.Text);
pipeClient.Close();
}
You're closing the NamedPipeClientStream before the StreamWriter has flushed any data to it. Therefore when you read data from the server stream, there's no data to read before the connection is closed, so you get an empty string.
You can fix this by properly disposing of the StreamWriter, as so:
private void button1_Click(object sender, EventArgs e)
{
using (var pipeClient = new NamedPipeClientStream("testpipe"))
{
if (pipeClient.IsConnected != true) pipeClient.Connect();
using (var sw = new StreamWriter(pipeClient))
{
sw.WriteLine("%s", textBox1.Text);
}
}
}
Alternatively, you can set AutoFlush to true on the StreamWriter.

Can't upload to Azure Media Services - File Not Found

When I run the website locally, the video will upload to azure and I get a publish url. No problem. However, when I publish the website and then try to upload from there, I get this error:
Server Error in '/' Application.
--------------------------------------------------------------------------------
c:\V1.mp4
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.FileNotFoundException: c:\V1.mp4
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[FileNotFoundException: c:\V1.mp4]
Microsoft.WindowsAzure.MediaServices.Client.AssetFileData.UploadAsync(String path, BlobTransferClient blobTransferClient, ILocator locator, CancellationToken token) +499
Microsoft.WindowsAzure.MediaServices.Client.<>c__DisplayClass1c.<UploadAsync>b__14(Task`1 t) +347
System.Threading.Tasks.ContinuationTaskFromResultTask`1.InnerInvoke() +80
System.Threading.Tasks.Task.Execute() +49
[AggregateException: One or more errors occurred.]
System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) +3548265
System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken) +10487717
System.Threading.Tasks.Task.Wait() +10
Microsoft.WindowsAzure.MediaServices.Client.AssetFileData.Upload(String path) +90
UploadTest.Upload.UploadVideoButton_Click(Object sender, EventArgs e) +101
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9553594
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +103
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724`enter code here`
Upload.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Upload.aspx.cs" Inherits="UploadTest.Upload" %>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="server">
<asp:Button ID="UploadVideoButton" runat="server" Text="Upload The Video" OnClick="UploadVideoButton_Click" />
</asp:Content>
Upload.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.WindowsAzure.MediaServices.Client;
namespace UploadTest
{
public partial class Upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void UploadVideoButton_Click(object sender, EventArgs e)
{
CloudMediaContext context = new CloudMediaContext("<accountname>", "<accountkey>");
var asset = context.Assets.Create("V1.mp4", AssetCreationOptions.None);
var file = asset.AssetFiles.Create("V1.mp4");
file.Upload(#"c:\V1.mp4");
}
}
}
I think you should use this to upload file by uploading the stream
public void UploadFileToAzure(Stream stream, string fileName, string contentType,
EContextType contextType) {
if (stream == null)
throw new ArgumentNullException("stream");
if (fileName == null)
throw new ArgumentNullException("fileName");
CloudBlobContainer blobContainer = null;
switch (contextType)
{
case EContextType.CloudStorage:
blobContainer = AzureBlobUtil.InitializeBlob(Settings.AzureBlobStorageFileStorage, Settings.GetAzureDataConnectionString);
break;
default:
blobContainer = AzureBlobUtil.InitializeBlob(Settings.AzureBlobStorageDocument, Settings.GetAzureDataConnectionString);
break;
}
var blob = blobContainer.GetBlockBlobReference(fileName);
blob.UploadFromStream(stream);
blob.Metadata["FileName"] = fileName;
blob.Metadata["IsArchived"] = false.ToString();
blob.SetMetadata();
// Set the properties
blob.Properties.ContentType = contentType;
blob.SetProperties();
}

iReport Barcode - local class incompatible: stream classdesc serialVersionUID

I'm working with one problematic report and it always throws the same exception when client JRE is not the same as server's. This is an RMI app and the exception only occours with this report.
Report
It's a simple report, however it has an barcode component, and I've used 2 implementations offered by iReport 5.0.1 (Barbecue and Barcode4j) and both thrown the same exception:
java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
java.io.InvalidClassException: javax.swing.JComponent;
local class incompatible:
stream classdesc serialVersionUID = -2790168081368361182,
local class serialVersionUID = 5670834184508236790
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:191)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:194)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:148)
at $Proxy17.geraRelatorio(Unknown Source)
at base.gui.reports.ReportsPrinter.showReport(ReportsPrinter.java:151)
at base.gui.reports.ReportsPrinter.showReport(ReportsPrinter.java:139)
at jacad.gui.cadastros.curso.FrameCadastroPeriodoLetivo$30.executaAtividade(FrameCadastroPeriodoLetivo.java:1499)
at jdaap.gui.components.loader.Loader$1.doInBackground(Loader.java:70)
at jdaap.gui.components.loader.Loader$1.doInBackground(Loader.java:1)
at javax.swing.SwingWorker$1.call(SwingWorker.java:296)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at javax.swing.SwingWorker.run(SwingWorker.java:335)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.io.InvalidClassException: javax.swing.JComponent;
local class incompatible:
stream classdesc serialVersionUID = -2790168081368361182,
ocal class serialVersionUID = 5670834184508236790
at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:604)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1601)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1514)
I don't know what do now, I've tried everything I could to fix this, I don't believe that error was caused by Java code because this app have +- 300 reports, and only this one has a barcode. Here's a sample of Java code to call this report by RMI:
public JasperPrint executeReport(String reportFile, Map parameters) throws GenericException {
FileInputStream is = (FileInputStream) getReportFile(reportFile);
Connection conn = getConnection();
JasperPrint print = null;
try {
parameters.put("P_REPORTS_PATH", Application.getInstance().getReportsPath());
parameters.put(JRParameter.REPORT_LOCALE, new Locale("pt", "BR"));
print = JasperFillManager.fillReport(Application.getInstance().getReportsPath() + reportFile, parameters, conn);
} catch (JRException e1) {
e1.printStackTrace();
throw new GenericException(e1);
}
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return print;
}
Client side:
public static void view(final JasperPrint print) throws GenericException {
if (print == null) {
throw new GenericException("Nenhuma visualização do relatório foi informada.");
}
new SwingWorker() {
#Override
protected Void doInBackground() throws Exception {
JFrame viewer = new JFrame("Visualização do Relatório"); //$NON-NLS-1$
viewer.setPreferredSize(new Dimension(800, 600));
viewer.setLocationRelativeTo(null);
JasperViewer jrViewer = new JasperViewer(print, true);
viewer.getContentPane().add(jrViewer.getContentPane());
new FrameConfig(viewer);
return null;
}
}.execute();
}
public void showReport(String reportFile, Map parameters) throws GenericException {
if (reportFile == null)
throw new GenericException("Report file não pode ser nulo.");
ReportsManager rm;
try {
rm = (ReportsManager) FacadeFactoryLocal.newInstance(ReportsManager.class);
JasperPrint jasperPrint = rm.geraRelatorio(reportFile, parameters);
view(jasperPrint);
} catch (RemoteException e1) {
e1.printStackTrace();
throw new GenericException("Erro ao acessar o servidor para gerar o relatório.", e1.getStackTrace());
}
}
Does anyone have a solution for this?
Thanks in advance.
Don't serialize Swing components. There is a warning about that at the head of the Javadoc of every one of them. Serialized the underlying model.

Listen to msmq queue

Following the is the code I have for listening to messages from Windows form.
I have noticed that when I click on send it sends a message to MyQueue but at that time I was hoping the event mq_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e) should get called but it is not, in other words I am trying to subscribe to MyQueue from Windows form. Just wondering if I am missing something in the code:
public class Form1 : System.Windows.Forms.Form
{
public System.Messaging.MessageQueue mq;
public static Int32 j=0;
public Form1()
{
// Required for Windows Form Designer support
InitializeComponent();
// Queue Creation
if(MessageQueue.Exists(#".\Private$\MyQueue"))
mq = new System.Messaging.MessageQueue(#".\Private$\MyQueue");
else
mq = MessageQueue.Create(#".\Private$\MyQueue");
mq.ReceiveCompleted += new ReceiveCompletedEventHandler(mq_ReceiveCompleted);
mq.BeginReceive();
}
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void btnMsg_Click(object sender, System.EventArgs e)
{
// SendMessage(Handle, 1, 0, IntPtr.Zero);
System.Messaging.Message mm = new System.Messaging.Message();
mm.Body = txtMsg.Text;
mm.Label = "Msg" + j.ToString();
j++;
mq.Send(mm);
}
void mq_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
{
//throw new NotImplementedException();
}
private void btnRcv_Click(object sender, System.EventArgs e)
{
System.Messaging.Message mes;
string m;
try
{
mes = mq.Receive(new TimeSpan(0, 0, 3));
mes.Formatter = new XmlMessageFormatter(new String[] {"System.String,mscorlib"});
m = mes.Body.ToString();
}
catch
{
m = "No Message";
}
MsgBox.Items.Add(m.ToString());
}
}
See MSDN's example on how to use the ReceiveCompletedEventHandler .
They have a console app where the Main() does the same as your Form1(), but your handler doesn't have any code. You've said it doesn't call back into your event delegate, but perhaps check your queue name is correct on the constructor.
Consider using MSDN's sample code in a new console app to test your environment first, then go back to your WinForms code with any lessons learned.
private static void MyReceiveCompleted(Object source,
ReceiveCompletedEventArgs asyncResult)
{
MessageQueue mq = (MessageQueue)source;
Message m = mq.EndReceive(asyncResult.AsyncResult);
Console.WriteLine("Message: " + (string)m.Body);
mq.BeginReceive();
return;
}
If you want to inspect the queue and get a message on the click of a button, you can simply move the statement mq.BeginReceive(); to the btnRcv_Click() in place of .Receive();