Deploying an app with Crystal Reports in IIS - c#

I am trying to deploy an app that I used Crystal Reports in. I want to say that it works on local host as I am using IIS Express and in staging I am using IIS. This is the main difference that I can think of but just to be sure I want to write out the entire process that have done.
Build Report in Visual Studio
Create ODBC Connection on local host
Run Report in localhost - it works
publish MVC app
add ODBC connection with same name on server
copy report to correct location on IIS server
run app and report app works report doesn't.
The log that I am getting is:
FATAL 2018-08-28 03:22:30,923 37280ms Log Service GenerateReport - Exception during StringFormat: Index (zero based) must be greater than or equal to zero and less than the size of the argument list. Generate Reports at: 8/28/2018 3:22:30 AM, Exception: CrystalDecisions.CrystalReports.Engine.InternalException: Failed to open the connection.
QuoteReport 5092_4216_{0FAD9DBD-DCD7-4158-816D-56895A79B362}.rpt
Details: [Database Vendor Code: 4060 ] ---> System.Runtime.InteropServices.COMException: Failed to open the connection.
QuoteReport 5092_4216_{0FAD9DBD-DCD7-4158-816D-56895A79B362}.rpt
Details: [Database Vendor Code: 4060 ]
at CrystalDecisions.ReportAppServer.Controllers.ReportSourceClass.Export(ExportOptions pExportOptions, RequestContext pRequestContext)
at CrystalDecisions.ReportSource.EromReportSourceBase.ExportToStream(ExportRequestContext reqContext)
--- End of inner exception stack trace ---
at CrystalDecisions.ReportAppServer.ConvertDotNetToErom.ThrowDotNetException(Exception e)
at CrystalDecisions.ReportSource.EromReportSourceBase.ExportToStream(ExportRequestContext reqContext)
at CrystalDecisions.CrystalReports.Engine.FormatEngine.ExportToStream(ExportRequestContext reqContext)
at CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToStream(ExportOptions options)
at CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToStream(ExportFormatType formatType)
at QuickQuote.Controllers.ReportsController.GenerateReport(Int32 reportId, String json) in C:\Users\James\Source\Repos\QuickQuote3\QuickQuote\Controllers\ReportsController.cs:line 84{}
Can someone please tell me what my issue is? I have google this error and I don't understand what my issue is.
try
{
var stream = _reportBuilder.BuildReport(dataSet, report, filePath, parameters);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", $"Quote{report.Name}-{DateTime.Now}.pdf");
}
catch (Exception e)
{
_loggingService.FatalFormat($"Generate Reports at: {DateTime.Now}, Exception: {e}");
throw;
}
Inside reportBuilder.BuildReport is where it is breaking. I'm sure that it is this line:
var stream = reportDocument.ExportToStream(ExportFormatType.PortableDocFormat);
BuildReport method:
public Stream BuildReport(DataSet dataSet, Report report, string path, string parameters)
{
var reportDocument = new ReportDocument();
reportDocument.Load(path);
reportDocument.SetDataSource(dataSet);
AddParametersToReport(ref reportDocument, report, parameters);
return reportDocument.ExportToStream(ExportFormatType.PortableDocFormat);
}

The exception message is Failed to open the connection.
Verify if System Data Sources are set up correctly in ODBC Data Source Administrator (for both 32-bit and 64-bit).
You may get Database logon failed error, as credentials specified in .rpt file might be invalid for the database. The solution is to provide database credentials in code:
public Stream BuildReport(DataSet dataSet, Report report, string path, string parameters)
{
try
{
var reportDocument = new ReportDocument();
reportDocument.Load(path);
reportDocument.SetDataSource(dataSet);
AddParametersToReport(ref reportDocument, report, parameters);
// Set database credentials
reportDocument.SetDatabaseLogon("dbUsername", "dbPassword");
return ReportDocument.ExportToStream(ExportFormatType.PortableDocFormat);
}
catch(Exception ex)
{
_loggingService.FatalFormat($"Exception: {ex}");
throw;
}
}

Related

SAP.Middleware.Connector.RfcSerializationException: End mark of RFCID.TableContLZ not found

I have a problem. I am trying to get data from SAP using a desktop app developed. When i connect to the VPN and run the application it runs smoothly with no errors, but when a customers try to run it from his machine it receive the folowing error and the application crashes. Can someone help me with this.
2019-03-25 15:22:29,581 [9] FATAL SAP_TO_DB.Connection - SAP.Middleware.Connector.RfcSerializationException: End mark of RFCID.TableContLZ not found. at SAP.Middleware.Connector.RfcConnection.ReadRfcIDEnd(RFCID rid) at SAP.Middleware.Connector.RfcConnection.ReadUpTo(RFCGET readState, RfcFunction function, RFCID toRid) at SAP.Middleware.Connector.RfcConnection.RfcReceive(RfcFunction function) at SAP.Middleware.Connector.RfcFunction.RfcDeserialize(RfcConnection conn, IRfcIOStream stream) at SAP.Middleware.Connector.RfcFunction.RfcCallReceive(RfcConnection conn, IRfcIOStream stream, RFCID rid) at SAP.Middleware.Connector.RfcFunction.RfcCallReceive(RfcConnection conn) at SAP.Middleware.Connector.RfcFunction.Invoke(RfcDestination destination) at SAP_TO_DB.Connection.GetOnlyData(String tableName, String userName, String password, String client, String serverName, String sysNo, String optionString, Int32 rowSkips, Int32 rowCount, IRfcTable fields)
Edit: when testing on the same vpn he gets another error:
2019-03-26 14:28:16,039 [1] FATAL SAP_TO_DB.MainForm - SAP.Middleware.Connector.RfcCommunicationException: destination Custom_destination_ failed when calling RFC_METADATA_GET -- see log for details at SAP.Middleware.Connector.RfcRepository.Execute(RfcFunction function) at SAP.Middleware.Connector.RfcRepository.LookupFunctionMetadataNew(String name) at SAP.Middleware.Connector.RfcRepository.LookupFunctionMetadata(String name) at SAP.Middleware.Connector.RfcRepository.GetFunctionMetadata(String name) at SAP.Middleware.Connector.RfcRepository.CreateFunction(String name) at SAP_TO_DB.Connection.GetOnlyHeader(String tableName, String userName, String password, String client, String serverName, String sysNo, String tableFileName, Boolean isDescriptionTable) at SAP_TO_DB.MainForm.button2_Click(Object sender, EventArgs e)
There is not much about this anywhere, therefore any help is more than welcome
These are two separate problems:
First problem "End mark of RFCID.TableContLZ not found."
Most probable reason is that the data got corrupted/truncated on the network layer. If you activate RFC trace on backend side and in the .NET program, you can compare the response data that was sent by the backend and the data that was received by the .NET program. (RFC trace contains a binary network dump, if the level is high enough.)
If the traces differ, the data was modified during network transmission. If they are the same, that means the backend system already sent corrupted data. --> Open an SAP ticket in that case to have it investigated.
Second problem "Custom_destination_ failed when calling RFC_METADATA_GET"
Could it be that the parameter RfcRepository.UseRoundtripOptimization is set to true, but your customer's backend does not yet support it? (See note 1456826 for the necessary prerequisites for using this feature.)
If that is not the problem, again an RFC trace would be helpful.

Excel Automation in ASP.NET

I am aware that this approach is not recommended and should be avoid at all cost. So please do not answer me of using a third party library or any thing related
First the system creates a file and writes html inside it to display data. The system is fooling MS Excel by naming it with a .xls extension even though what it contains is html.
Aim:
I need to convert it to REAL XLS file. So i want to open it using COM and save it as xls.
Problem:
Now what happens is that it gives throws an exception that i don't know where it from. On the Development environment it is working pretty fine. but whenever we transfer it to the server. The problem occurs. I cannot debug on the server ( I know I must not) but i think i have no other choice. Here is the exception thrown
Server Error in '/' Application.
Exception from HRESULT: 0x800A03EC.
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: Exception from HRESULT: 0x800A03EC.
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:
[COMException (0x800a03ec): Exception from HRESULT: 0x800A03EC.]
PLDTGlobal.Remco.ExcelCOM.SaveFileAsXLS(String filePath, String fileName, String path)
PLDTGlobal.Remco.OtherFulfilments.BatchFiles.__InsertBDO.SaveRecord()
PLDTGlobal.Remco.OtherFulfilments.BatchFiles.__InsertBDO.cmdSave_Click(Object sender, EventArgs e)
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +108
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +57
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +18
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
System.Web.UI.Page.ProcessRequestMain() +1292
Version Information: Microsoft .NET Framework Version:1.1.4322.2032; ASP.NET Version:1.1.4322.2032.
Environment Details:
DEV
Windows XP Professional SP3,
Visual Studio 2003,
.NET 1.1,
MS EXCEL 11.0 Object Library
Server
Windows Server 2008 R2 (x64)
Here is an excerpt of the code:
public ExcelCOM()
{
try
{
excelApp = new Excel.Application();
excelApp.Visible = true;
}
catch(Exception ex)
{
ErrorLogger logger = new ErrorLogger();
logger.WriteErrorLog(ex.Message, ex.StackTrace);
throw ex;
}
}
/// <summary>
/// Opens the xml file using Excel COM library and converts it to .xls(1997-2003) format
/// </summary>
/// <param name="filePath">complete file path from target file</param>
/// <param name="fileName">filename of the target</param>
/// <param name="path">new path where to save the .xls</param>
public void SaveFileAsXLS(string filePath, string fileName, string path)
{
object missingParam = System.Reflection.Missing.Value;
string fileToCreate = path + fileName.Substring(0, fileName.Length - 4);
try
{
if(!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
excelApp.Visible = false;
Excel.Workbook workBook = excelApp.Workbooks.Open(filePath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Excel.Worksheet workSheet1 = (Excel.Worksheet) workBook.Sheets.get_Item(1);
workSheet1.Name = "Sheet1";
workSheet1.SaveAs(fileToCreate, Excel.XlFileFormat.xlExcel9795, missingParam, missingParam, false, missingParam, missingParam, missingParam, missingParam, missingParam);
workBook.Close(missingParam, missingParam, missingParam);
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.ReleaseComObject(workSheet1);
Marshal.ReleaseComObject(workBook);
}
catch(Exception ex)
{
ErrorLogger logger = new ErrorLogger();
logger.WriteErrorLog(ex.Message, ex.StackTrace);
throw ex;
}
finally
{
excelApp.Quit();
Marshal.ReleaseComObject(excelApp);
}
}
I have tried giving launch permission to NETWORK SERVICE account in dcomcnfg.
Any idea about the problem and how to solve it is much appreciated.
I'm not sure this will work. I do run a development environment on my server, for just these kinds of issues. I wrote code to automate Excel in Visual Studio 2013, code works great. When I put the code into IIS 7 (2012 server), the code stops working. From my research, this is by design by Microsoft because they do not want you doing this. I had to change a whole lot of permissions to get it to even partially work. In the end, I cannot get Excel to display and officially, Microsoft says that Excel will throw errors because this is not supported.

Does LibGit2Sharp support cloning a repository from the local file system?

I am trying to clone a git repository from the local file system:
using System;
using LibGit2Sharp;
class Program
{
static void Main()
{
var sourceUrl = #"file:///c:/work/libgit2sharp";
using (Repository.Clone(sourceUrl, "targetDir", bare: true))
{
Console.WriteLine("repository successfully cloned");
}
}
}
and I get an exception:
Unhandled Exception: LibGit2Sharp.LibGit2SharpException: An error was raised by libgit2. Category = Odb (Error).
Failed to find the memory window file to deregister
at LibGit2Sharp.Core.Ensure.Success(Int32 result, Boolean allowPositiveResult) in c:\work\libgit2sharp\LibGit2Sharp\Core\Ensure.cs:line 85
at LibGit2Sharp.Core.Proxy.git_clone_bare(String url, String workdir, git_transfer_progress_callback transfer_cb) in c:\work\libgit2sharp\LibGit2Sharp\Core\Proxy.cs:line 219
at LibGit2Sharp.Repository.Clone(String sourceUrl, String workdirPath, Boolean bare, Boolean checkout, TransferProgressHandler onTransferProgress, CheckoutProgressHandler onCheckoutProgress) in c:\work\libgit2sharp\LibGit2Sharp\Repository.cs:line 431
at Program.Main() in c:\work\ConsoleApplication1\Program.cs:line 10
I've also tried the following source url:
var sourceUrl = #"c:\work\libgit2sharp\.git\";
and got another exception:
Unhandled Exception: LibGit2Sharp.LibGit2SharpException: An error was raised by libgit2. Category = Config (Error).
Failed to parse config file: Unexpected end of file while parsing multine var (in c:/work/ConsoleApplication1/bin/Debug/targetDir/config:23, column 0)
at LibGit2Sharp.Core.Ensure.Success(Int32 result, Boolean allowPositiveResult) in c:\work\libgit2sharp\LibGit2Sharp\Core\Ensure.cs:line 85
at LibGit2Sharp.Core.Proxy.git_clone_bare(String url, String workdir, git_transfer_progress_callback transfer_cb) in c:\work\libgit2sharp\LibGit2Sharp\Core\Proxy.cs:line 219
at LibGit2Sharp.Repository.Clone(String sourceUrl, String workdirPath, Boolean bare, Boolean checkout, TransferProgressHandler onTransferProgress, CheckoutProgressHandler onCheckoutProgress) in c:\work\libgit2sharp\LibGit2Sharp\Repository.cs:line 431
at Program.Main() in c:\work\ConsoleApplication1\Program.cs:line 12
targetDir is never created.
If on the other hand I use HTTP transport, the Repository.Clone method works fine:
var sourceUrl = "https://github.com/libgit2/libgit2sharp";
So my question is if I am doing something wrong or if this is unsupported feature or a bug in the native git2.dll?
So my question is if I am doing something wrong or if this is unsupported feature or a bug in the native git2.dll?
A bit a both, actually.
The first exception is clearly a bug. This should not happen and will be troubleshot.
The second one requires a deeper analysis. Would you be so kind as to open a issue in the LibGit2Sharp project?
Good news are that a pull request from BenStraub was recently merged. This pull request implements the local fetch transport which should pretty solve the issue.
LibGit2Sharp will be updated in the following days with a new a new version of libgit2 binaries which should allow you perform a local clone/fetch. I'll update this answer as soon as it's been done.
Update
This test shows how do to a Clone and a Push over against a local repository.

The file size exceeds the limit allowed and cannot be saved on EventLog

Getting this exception The file size exceeds the limit allowed and cannot be saved when writing to event viewer using EventLog
Code used:
string cs = "LoggingService";
EventLog elog = new EventLog();
if (!EventLog.SourceExists(cs))
{
EventLog.CreateEventSource(cs, cs);
}
elog.Source = cs;
elog.EnableRaisingEvents = true;
elog.WriteEntry(message);
Stack trace:
System.ComponentModel.Win32Exception (0x80004005): The file size exceeds the limit allowed and cannot be saved
at System.Diagnostics.EventLogInternal.get_OldestEntryNumber()
at System.Diagnostics.EventLogInternal.StartRaisingEvents(String currentMachineName, String currentLogName)
at System.Diagnostics.EventLogInternal.set_EnableRaisingEvents(Boolean value)
Things tried:
http://support.microsoft.com/kb/328380#top
When I put this statement elog.Clear() before elog.EnableRaisingEvents = true;
I am getting different exception
System.ComponentModel.Win32Exception (0x80004005): Access is denied
at System.Diagnostics.EventLogInternal.Clear()
The above code is executed by a web service which runs under LocalSystem which has full permission on the computer.
OS: windows server 2008R2 and .NET 4.0
There is a method EventLog.ModifyOverflowPolicy that modifies log policy.
I believe EventLog.ModifyOverflowPolicy(OverflowAction.OverwriteAsNeeded,0) could be helpful.
Event Viewer - Properties - Maximum log size was 1028. I bumped it and it started working fine.
But the same code was working from another window service before I made the above the change.
which make me think what could have happened
The message I was trying to log was just a line (less then 255 characters)

Steps involved with getting an existing Crystal Report on a production database working in an MVC app?

I'm new to the world of Crystal Reports, and I've found a variety of articles on creating a new Crystal Report in VS 2010, but nothing about taking an existing report and using it to generate a PDF that can be exported by a user.
This is the article I found I was trying to use as a start:
Crystal Reports in ASP.NET MVC
I ran SQL Profiler when running the original report in our ERP system, and tried to use this query as my DataSource, but each time I get to the point where I am loading my report file, it throws an exception:
Exception Details: System.Runtime.InteropServices.COMException: Database logon failed.
If I debug through the code, the HasRecords
'((CrystalDecisions.CrystalReports.Engine.ReportDocument)(rptH)).HasRecords' threw an exception of type 'CrystalDecisions.CrystalReports.Engine.LogOnException'
I've also tried adding the SetDatabaseLogin method, with a username and password with DBO access to the database, but got the same results.
rptH.SetDatabaseLogon("username", "password");
So to make a long story longer, I'm wondering if anyone knows of a good article, or can give me some foolproof steps to get the report working in my code, where I can have a PDF returned (even if I hardcode the SQL first... I just want to see it working).
Thanks!
Here's an overly simplified version of how we do it where I work...
protected void btnGetReport_Click(object sender, EventArgs e)
{
System.Guid desiredGuid = System.Guid.NewGuid();
desiredGuid = createReport();
//open report in browser
Response.Redirect(#"SecureReports\" + desiredGuid + ".pdf");
}
private System.Guid createReport()
{
System.Guid desiredGuid = System.Guid.NewGuid();
string workpath = "";
ReportDocument reportDocument = new ReportDocument();
workpath = #"c:\Reports\cr_myReport.rpt";
reportDocument.FileName = workpath;
reportDocument.SetDatabaseLogon("user", "pass", "SERVER\\sql", "database");
reportDocument.SetParameterValue("#param", strParam);
//export CR to a pdf on the server
reportDocument.ExportToDisk(ExportFormatType.PortableDocFormat, #"c:\SecureReports\" + desiredGuid + ".pdf");
//send location of pdf back to calling function
return desiredGuid;
}

Categories

Resources