Intermittent Issue - OleDbConnection.Open() throws System.Data.OleDb.OleDbException: Unspecified error - asp.net

A production application in our organization uses Excel 2003 files to handle user submitted data through a web application. This application works reliably most of the time. Recently, the application has begun intermittently throwing "System.Data.OleDb.OleDbException: Unspecified error" when the OleDbConnection.Open() method is called. The error continues until the application pool is recycled, at which time everything functions as expected again. No errors are captured within the Windows Application event log.
The ASP.NET web application is hosted within web parts in WSS 3.0 on a Windows Server 2003 32 bit machine. The application is designed to prevent any concurrency issues. The system functional id is the only account with access to the temporary file store and there are mechanisms built in to ensure that the file cannot be overwritten by another upload during processing using a unique naming convention and upload tracking sub-system.
Any insight would be much appreciated.
We are using the following code to retrieve data from an Excel 2003 file:
public static DataTable GetWorksheetData(string filePath)
{
OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder { DataSource = filePath };
builder.Provider = "Microsoft.Jet.OLEDB.4.0";
builder["Extended Properties"] = "Excel 8.0;IMEX=1;HDR=YES";
DataTable table = new DataTable();
try
{
// Creates an OleDbConnection for the excel file
using (OleDbConnection connection = new OleDbConnection(builder.ConnectionString))
{
connection.Open();
string sheetName = GetWorksheet(connection, "Template");
if (!string.IsNullOrEmpty(sheetName))
{
using (OleDbCommand command = connection.CreateCommand())
{
try
{
command.CommandText = string.Format("SELECT * FROM [{0}]", sheetName);
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
using (DataSet dataSet = new DataSet())
{
adapter.Fill(dataSet);
table = dataSet.Tables[0];
}
}
finally
{
connection.Close();
}
}
}
else
{
throw new InvalidWorksheetException();
}
}
}
catch (Exception ex)
{
Logger.Write(LogMsgSeverity.Error, ex);
throw;
}
return table;
}
private static string GetWorksheet(OleDbConnection connection, string sheetName)
{
string validSheetName = string.Empty;
using (DataTable tables = connection.GetSchema("Tables"))
{
DataRowCollection rows = tables.Rows;
if (rows.Count > 0)
{
foreach (DataRow row in rows)
{
if (row["Table_Name"].ToString().Contains(sheetName))
{
validSheetName = sheetName;
}
}
}
}
return validSheetName;
}

Related

Asp.net async db connection not reusing connections

I have a .net mvc / sql server website for a high-traffic application. I'm using async database connections.
Prior to launch I ran a load test, and it blew up pretty quickly under load. The connection pool quickly ran out of connections.
Running sp_who at the database level shows a pile of connections sleeping awaiting command. If I switch to non-async, this does not happen.
So, it appears that new database calls are not using connections sitting in the connection pool, instead they are opening their own new connection. This quickly exhausts the connection pool limit, and begins timing out queries.
The following is the helper I'm using to execute an async datareader. Does anyone see any issue here?
private async Task<List<T>> ExecuteReaderAsync<T>(SqlCommand command, Func<SqlDataReader, T> rowConverter)
{
List<T> ret = new List<T>();
using (SqlConnection connection = new SqlConnection(this.ConnectionString))
{
command.Connection = connection;
await connection.OpenAsync();
using (SqlDataReader reader = await command.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
ret.Add(rowConverter(reader));
}
reader.Close();
}
connection.Close();
}
return ret;
}
I'm calling the code like the datareader helper like the following:
public async Task<Content> FindContentAsync(int id)
{
Content content = null;
using (SqlCommand command = CreateProcedure("dbo.FindContent"))
{
AddParam(command, "Id", SqlDbType.Int, id);
List<Content> items = await ExecuteReaderAsync<Content>(command, x => BindContent(x));
if (items.Count > 0)
{
content = items[0];
}
}
return content;
}
And calling that from a helper:
public async Task<Content> FindAsync(int id)
{
var db = new DataAccess();
var content = await db.FindContentAsync(id);
return content;
}

Static function of database in Asp .net

I have a class that gets tables from Sql Server. the class is static, but the variables are not. I want to know if it is OK in Asp net, because I had read not to use static at database in Asp net.
My Class: (There are more functions in the class, I put here one for example)
public static class DataBase
{
public static bool TableChange(string sqlCreate)
{
using (SqlConnection connection = new SqlConnection(Global.ConnectionString))
{
using (var cmd = new SqlCommand(sqlCreate, connection))
{
try
{
connection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Log.WriteLog(ex.Message + "\n" + sqlCreate, ex, HttpContext.Current.Request);
return false;
}
}
}
return true;
}
}
Thanks in advance
What you have read is most probably something to do with this approach:
public static EntityContext Database = new EntityContext();
// or
public static SqlConnection Database = new SqlConnection("...");
Here you store the database connection in a static variable and thus all parallel requests would want to use the same connection which is a very bad approach if it even works at all (it will probably work sort of fine until the page is under load).
You do not have this problem, because in your case only the methods are static, not the variables. Your code follows the recommended path - open connection (retrieve it from the pool), execute query, close the connection (return it to the pool).

Accessing SSRS server report from local application

I have deployed my SSRS reports in the server. Is it possible for me to access that report from my local web application. I have given the server's credentials in the web.config. But still its not displaying the report and it shows some error like Cannot create a connection to data source 'DataSource1'. (rsErrorOpeningConnection).
When I hosted the same application in the server it is working absolutely fine.
Can anyone tell me why am not able to access the reports from my local system?
This is not my code, but ideally is all you have to do. I remember using it successfully in one of previous projects some time back
private void ShowReport()
{
try
{
string urlReportServer = "http://sqlDBServer//Reportserver";
rptViewer.ProcessingMode = ProcessingMode.Remote; // ProcessingMode will be Either Remote or Local
rptViewer.ServerReport.ReportServerUrl = new Uri(urlReportServer); //Set the ReportServer Url
rptViewer.ServerReport.ReportPath = "/ReportName"; //Passing the Report Path
//Creating an ArrayList for combine the Parameters which will be passed into SSRS Report
ArrayList reportParam = new ArrayList();
reportParam = ReportDefaultPatam();
ReportParameter[] param = new ReportParameter[reportParam.Count];
for (int k = 0; k < reportParam.Count; k++)
{
param[k] = (ReportParameter)reportParam[k];
}
// pass crendentitilas
//rptViewer.ServerReport.ReportServerCredentials =
// new ReportServerCredentials("uName", "PassWORD", "doMain");
//pass parmeters to report
rptViewer.ServerReport.SetParameters(param); //Set Report Parameters
rptViewer.ServerReport.Refresh();
}
catch (Exception ex)
{
throw ex;
}
}
Ref: http://www.codeproject.com/Articles/675762/Call-SSRS-Reports-by-using-Csharp

Backup of the database in entity framework

i working with entity famework i need to transfer that code
RESTORE DATABASE [showing8-5-2013] FROM DISK = N'C:\Program Files (x86)\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\Backup\Company.bak' WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 10
to code Entity frame work
any help thanks
EF is a DB neutral provider concept. Such commands are by their nature DB specific. EF exposes a way to execute an SQL command:
MyContext.Database.ExecuteSqlCommand();
But you may as well just do it directly.
Pass your SQL command into a custom routine eg:
private static bool ExecuteSqlStatement(string connectionString, string statement) {
int rowsAffected;
using (var sqlConnection = new SqlConnection(connectionString)) {
using (var sqlCommand = new SqlCommand(statement, sqlConnection)) {
try {
sqlConnection.Open();
rowsAffected = sqlCommand.ExecuteNonQuery();
}
catch (Exception ex) {
// your handler or re-throw....
return false;
}
}
}
return rowsAffected == -1;
// see http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx
}

Reading from HttpContext.Current.Session fails on multi server environment

Environment: IIS 7.5, .Net 4.0
I have a problem reading from HttpContext.Current.Session on a multi server environment.
First in my code I store an object in HttpContext.Current.Session an later try to read it again. The read (performed a number of times) fails randomly and I suspect it has something to do with what server the call hits. The storing and reading of the object is done through ajax calls and a colleague told me to store the object in Page_Load. I was fairly skeptic and as it turns out the problem has not been solved using this approach.
Storing:
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public Stream GetHierarchy(string invId, string zoomLevel)
{
Hierarchy hierarchy = new Hierarchy();
try
{
hierarchy = businessLogic.GetHierarchy(invId);
HttpContext.Current.Session["hierarchy"] = hierarchy;
}
catch (Exception ex)
{
throw ex;
}
return new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(hierarchy)));
}
Reading:
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public Stream GetCustomer(string invId, string includeDetails, string zoomLevel)
{
Hierarchy hierarchy = (Hierarchy)HttpContext.Current.Session["hierarchy"];
Customers customers = null;
Customer customer = null;
if (hierarchy != null) {
customers = hierarchy.Customers;
if (customers != null)
{
try
{
customer = (from e in customers.DiagramCustomers where e.InvId == invId select e).ToList()[0];
}
catch (Exception ex)
{
}
}
}
return new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(customer)));
}
Everything is working just fine in a single server environment...
Can anyone shed some light over what kind of problem it is I'm facing here? And preferably how to solve it :-)
./CJ
Use Sql Server to Store Asp.NET Session State
http://support.microsoft.com/kb/317604

Resources