Exception of type 'System.OutOfMemoryException' was thrown while Export to Excel using EPPlus in C# windows application - export-to-excel

I am getting error while export to excel large amount of data using EPPLUS library in C# windows application.
Dataset contains one table with 120 columns and more than 200k rows.
It is throwing 'System.OutOfMemoryException'.
protected void GetDailyTransactionDump_New()
{
try
{
DataSet dsGetData = new DataSet();
Hashtable ht = new Hashtable();
string Date = "";
string filename = "Transaction_Dump.xlsx";
ht.Add("#report_date", Date);
bll.GetDataset("Usp_Get_TransactionDump", ht, CommandType.StoredProcedure, out dsGetData);
//dsGetData retruns 120 cols and 200k rows
ExcelPackage package = new ExcelPackage();
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");
worksheet.Cells["A1"].LoadFromDataTable(dsGetData.Tables[0], true); //getting exception here
package.SaveAs(new FileInfo(filename));
}
catch (Exception ex)
{
throw;
}
}

Related

How do i convert OracleDataReader to a List object that i can store in my model MVC

I have managed to connect to the OracleDb and use the OracleDataReader to retrieve the data from the DB. The problem i have is that i now want to insert the retrieved data in my model (Invoice). The problem right now is that i cant convert the retrieved data to a type that is accepted by the model. Is there a way to convert the OracleDataReader reader to a type that is accepted by the model so i can fil the model (IEnumerable) with data?
public ViewResult search_btn(object sender, EventArgs e, string docno){
OracleConnection OC = new OracleConnection("SOMECONNECTIONSTRING");
OracleCommand getBlobRecord = new OracleCommand("select * from xx where invoice_no=:invoiceId", OC);
getBlobRecord.Parameters.Add(new OracleParameter("invoiceId", docno));
OC.Open();
using (OracleDataReader reader = getBlobRecord.ExecuteReader(CommandBehavior.SequentialAccess))
{
try
{
while (reader.Read())
{
var x = reader["invoice_no"];
var y = reader["supplier_id"];
new Invoice
{
Invoice_No = (int)x,
Supplier_Id = (int)y
};
}
reader.Close();
reader.Dispose();
return View("Index");
}
finally
{
reader.Close();
OC.Close();
}
}}

Crystal Report ExportToStream Failing with Object Reference not set to an instance

I have a very simple app that takes in No parameters in the attempt to return PDF.
The crystal Reports were authored using CR IX and I had to update the web service code to use Crystal Report for Visual studio 13. I am able to set parameters, as well as being able to login and verify that login credentials are correct.
public string TestReport()
{
try
{
var p = new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>("Product", "03R95-01"),
new KeyValuePair<string, string>("Product_Rev", "E-V001")
};
var reportParameters = new ParameterField[2];
var rpt = InitializeReport("testReport", p);
var s = rpt.ExportToStream(ExportFormatType.PortableDocFormat);
return "Stream exists";
}
catch (Exception ex)
{
return $"{ex.Message}|{ex.StackTrace}";
}
}
The Initialize Report method is:
private ReportDocument InitializeReport(string svrId, string reportName, List<KeyValuePair<string, string>> parameters)
{
var uid = "userId";
var pwd = "pwd";
var svr = "serverId";
var db = "DBNAME";
var reportFolder = "c:\\CrystalTest\\ReportFolder";
var reportFile = Path.Combine(reportFolder, $"{reportName}.rpt");
var rpt = new ReportDocument
{
FileName = reportFile
};
rpt.Load(reportFile);
var conInfo = new ConnectionInfo
{
UserID = uid,
Password = pwd,
ServerName = svr,
DatabaseName = db
};
foreach (Table t in rpt.Database.Tables)
{
try
{
var loginInfo = t.LogOnInfo;
loginInfo.ConnectionInfo = conInfo;
t.ApplyLogOnInfo(loginInfo);
if(!t.TestConnectivity())
{
throw new Exception($"{t.Name} failed login");
}
}
catch (Exception ex)
{
throw;
}
}
rpt.VerifyDatabase();
return rpt;
}
I have verified that an error is thrown when userid/pass combinations are incorrect.
I get the following error when I run this.
Object reference not set to an instance of an object.| 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 ICEWS4.maintenance.TestReport() in
C:\CrystalTest.cs:line 724
I learned of the fix.
I had CR for VS 13 SP 29.
The Runtime installed on the server was 13 SP 23
I was told by SAP to update to SP 30.
After updating my code, and installing the runtime, I was able to export to PDF as desired.

Oracle database over ODBC converts non-english characters to question marks

I am working on retrieving data from an Oracle data source, however I am having issues with non-english characters being replaced with question marks. Some background:
I am pulling data from an Oracle view whose columns are defined as VARCHAR2
When accessing said view through Oracle SQL Developer, the results display properly
I have attempted to update my System.Web.Odbc to the latest version to no avail
I am aware that the console does not properly display certain Unicode characters, but even viewing the raw data using breakpoints shows said characters replaced with '?'
Here is a runnable example with some specific implementation details removed:
using System;
using System.Data;
using System.Data.Odbc;
namespace OdbcTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Trying ODBC Connection");
DataTable odbcData = GetData("SELECT NAME as name FROM SYSADM.[ViewName] WHERE TRUNC(sysdate) - to_date(HIRE_DT) BETWEEN 0 AND 20");
Console.WriteLine(odbcData.Rows.Count.ToString() + "rows extracted.");
foreach (DataRow dataRow in odbcData.Rows)
{
foreach (var item in dataRow.ItemArray)
{
Console.WriteLine(item);
}
}
Console.ReadKey();
}
public static DataTable GetData(string SQLStatement)
{
try
{
using (System.Data.Odbc.OdbcConnection connection = new OdbcConnection([DSN Details]))
{
DataSet ds = new DataSet();
OdbcCommand command = new OdbcCommand(SQLStatement, connection);
OdbcDataAdapter adapter = new OdbcDataAdapter(command);
command.CommandTimeout = 600;
connection.Open();
adapter.Fill(ds);
connection.Close();
return ds.Tables[0];
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}

How to store BMP image (which is in base64 string format) into oracle 11g database using spring's jdbctemplate class?

I want to store base64 string (BMP image) into oracle 11g database.
few links i have gone through-
http://forums.asp.net/t/1061466.aspx?how+to+save+image+in+oracle+blob+field+
http://www.dba-oracle.com/t_storing_insert_photo_pictures_tables.htm
But I am not getting it how to do this? I have written a code with using this link -
http://www.technicalkeeda.com/spring-tutorials/insert-image-using-spring-jdbctemplate
My Table:
CREATE TABLE profile_image (img_title VARCHAR2(20) NOT NULL, img_data blob,);
My code with db Query:
File file = new File("Picture.bmp");
if (file.exists())
{
file.delete();
}
OutputStream stream;
try (stream = new FileOutputStream(file))
{
stream.write(data);//data is byte array converted from base64 string
}
catch (IOException e)
{
e.printStackTrace();
}
final String UPDATE_USER_PROFILE_PICTURE = "UPDATE profile_image SET img_data = ? WHERE img_title = ?";
final Object[] replacementObjectList = new Object[]
{ new SqlLobValue(stream, (int) file.length(), lobHandler), image_title };
final int count = jdbcTemplate.update(UPDATE_USER_PROFILE_PICTURE, replacementObjectList, new int[]
{ Types.BLOB, Types.VARCHAR });
if(count>0)
{return success;}
else
{return failure;}
But this query is not updating blob image data and returning failure. Any help?

Exception Devart.Data.Linq on a server "Devart.Data.Oracle.Linq.Provider"

I am trying to deploy my application on Windows server 2007 32 Bit.
My application gave me this Exception
Error on opening DbConnection. bei Devart.Data.Linq.LinqCommandExecutionException.CanThrowLinqCommandExecutionException
(String message, Exception e)
bei Devart.Data.Linq.Provider.k.a.g()
bei Devart.Data.Linq.Provider.k.a.b(IConnectionUser A_0)
bei Devart.Data.Linq.Provider.k.b(IConnectionUser A_0)
bei Devart.Data.Linq.Provider.DataProvider.ExecuteQuery(CompiledQuery compiledQuery, Object[] parentArgs, Object[] userArgs, Object lastResult)
bei Devart.Data.Linq.Provider.DataProvider.ExecuteAllQueries(CompiledQuery compiledQuery, Object[] userArguments)
bei Devart.Data.Linq.Provider.DataProvider.CompiledQuery.Devart.Data.Linq.Provider.ICompiledQuery.Execute(IProvider provider, Object[] userArgs)
bei Devart.Data.Linq.DataQuery`1.i()
bei System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
bei System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
while executing this line in my program
var list = clientCustomers.ToList();
Code
public Repository(String Connection, String EventPackageName, String EventScopeName)
{
this.connectionDict = this.getConnectionInfo(Connection);
//this.context = new DataContext(connection);//old way
this.context = new DataContext(Connection, new Devart.Data.Oracle.Linq.Provider.OracleDataProvider());
this.eventContext = new EventPacDataContext(Connection);
this.eContext = new Context.EventPacDataContext(Connection, new Devart.Data.Oracle.Linq.Provider.OracleDataProvider());
this.eventPackageName = EventPackageName;
this.eventScopeName = EventScopeName;
this.clientUserName = this.connectionDict["User Id"];
}
/// <summary>
/// Collect all Customers from VIEW
/// </summary>
/// <returns>IQueryable<Customer></returns>
public IQueryable<Customer> GetCustomers()
{
try
{
var result = from p in this.context.YDEVQUALIBASICs
join extended in this.context.YDEVQUALIBASICEXTENDEDs on
p.ACCOUNTID equals extended.ACCOUNTID
select
new Customer
{
Base = new Customer
{
CustomerId = p.CUSTOMERID.ToString(),
CustomerNo = p.CUSTOMERNO.ToString(),
Geburtsdatum = p.DETGEBURTSDATUM.GetValueOrDefault(new DateTime(1900, 1, 1)),
Email = p.DETEMAIL,
BusinessArea = p.ACCBUSINESSAREA,
ContractType = p.ACCCONTRACTTYPE,
ContractTariff = p.ACCCONTRACTARIFF,
SubscribeChannel = p.DETANMELDEKANAL,
PaymentMethod = p.CUSCOLLECTIONIDENT,
CustomerAddress = new Address
{
City = p.CUSCITY,
Street = p.CUSSTREET,
ExtendedInfo = p.CUSEHNR,
StreetNumber = p.CUSHNR,
LCountry = p.CUSCOUNTRYL,
SCountry = p.CUSCOUNTRYS,
ZipCode = p.CUSZIPCODE
},
AccountPerson = new Person
{
Salutation = p.ACCANREDE,
Title = p.ACCAKADEM,
Branche = p.ACCBRANCHE,
Lastname = p.ACCTOMERNAME1,
Firstname = p.ACCTOMERNAME2,
Name3 = p.ACCTOMERNAME3
}
},
CustomerPerson = new Person
{
Salutation = p.CUSANREDE,
Title = p.CUSAKADEM,
Branche = p.CUSBRANCHE,
Lastname = p.CUSTOMERNAME1,
Firstname = p.CUSTOMERNAME2,
Name3 = p.CUSTOMERNAME3
},
InternGeolocChecked = extended.DETINTERNGEOLOCCHECKED,
InternGeolocStatus = extended.DETINTERNGEOLOCSTATUS,
};
return result;
}
catch (ReflectionTypeLoadException ex)
{
StringBuilder sb = new StringBuilder();
foreach (Exception exSub in ex.LoaderExceptions)
{
sb.AppendLine(exSub.Message);
if (exSub is FileNotFoundException)
{
FileNotFoundException exFileNotFound = exSub as FileNotFoundException;
if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
{
sb.AppendLine("Fusion Log:");
sb.AppendLine(exFileNotFound.FusionLog);
}
}
sb.AppendLine();
}
string errorMessage = sb.ToString();
//Display or log the error based on your application.
logger.Fatal("Aha: " + errorMessage);
return null;
}
catch (Exception ex)
{
logger.Fatal("Customer failed: " + ex.Message + ex.StackTrace);
throw new DataAccessException("Customer failed", ex);
}
}
When deploying applications written with the help of LinqConnect you should register run-time assemblies Devart.Data.Oracle.dll, Devart.Data.dll, Devart.Data.Oracle.Linq.dll and Devart.Data.Linq.dll at Global Assembly Cache (GAC) or place them in the folder of your application.
When deploying ASP.NET applications it is also necessary to have Devart.Data.Oracle.Web.dll and App_Licenses.dll assemblies available.
If all required assemblies are available for your project, please perform the following steps:
Make sure that Oracle Client Software is installed on your computer;
Specify the name of Oracle Home explicitly in the Home connection string parameter.
Place the content of the ORACLE_HOME variable on the first position in the PATH variable of your operating system;
Make sure that capacity (x86 or x64) of your application and the capacity of your Oracle Client are the same.
If after these steps the issue still persists, please contact us with more details for this issue, e.g.:
the full stack trace of the exception;
the connection string;
the version of the Oracle Client;
the version of the Oracle server;
the definitions of the database tables and corresponding entity classes, etc.

Resources