Connection.State Issue - asp.net

I've published my new website , In my computer it works fine and no problem , But in the Server I when some user connect at the same time it crash .
I found out There is a error at this Method :
public static DbDataReader ExecuteReader(DbCommand dbCommand, CommandBehavior commandBehavior)
{
if (dbConnection.State != ConnectionState.Open)
dbConnection.Open();
return dbCommand.ExecuteReader(commandBehavior);
}
When i trace it , It says ConnectionState is not open , and it's doing opening . Here are my questions :
1- Is it a problem if while ConnectionState is doing opening , we Open the connection again ?
2- What I've missed , that i receive this error ?
Edit
For more information I past some part of my code here :
public class DbProviderHelper
{
private static DbProviderFactory dbProviderFactory;
private static DbConnection dbConnection;
#region dbConnexion
public static DbConnection GetConnection()
{
if (dbConnection == null)
{
ConnectionStringsSection connectionStringsSection = GetConnectionStringsSection();
dbProviderFactory = DbProviderFactories.GetFactory(connectionStringsSection.ConnectionStrings[1].ProviderName);
dbConnection = dbProviderFactory.CreateConnection();
dbConnection.ConnectionString = connectionStringsSection.ConnectionStrings[1].ConnectionString;
}
return dbConnection;
}
public static ConnectionStringsSection GetConnectionStringsSection()
{
return ConfigurationManager.GetSection("connectionStrings") as ConnectionStringsSection;
}
#endregion dbConnexion
#region dbCommand
public static DbCommand CreateCommand(String commandText, CommandType commandType)
{
DbCommand dbCommand = dbProviderFactory.CreateCommand();
dbCommand.Connection = dbConnection;
dbCommand.CommandType = commandType;
dbCommand.CommandText = commandText;
return dbCommand;
}
#endregion dbCommand
#region dbParameter
public static DbParameter CreateParameter(string parameterName, DbType dbType, object value)
{
DbParameter oDbParameter = dbProviderFactory.CreateParameter();
oDbParameter.ParameterName = parameterName;
oDbParameter.DbType = dbType;
oDbParameter.Value = value;
return oDbParameter;
}
#endregion dbParameter
#region Operations
public static DbDataReader ExecuteReader(DbCommand dbCommand)
{
if (dbConnection.State != ConnectionState.Open)
dbConnection.Open();
return dbCommand.ExecuteReader(CommandBehavior.CloseConnection);
}
public static int ExecuteNonQuery(DbCommand dbCommand)
{
try
{
if (dbConnection.State != ConnectionState.Open)
dbConnection.Open();
return dbCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
dbConnection.Close();
}
}
#endregion Operations
}
And i invote that like :
public class Configuration
{
public Configuration()
{
DbProviderHelper.GetConnection();
}
public DbDataReader GetTabsParent(int tabId)
{
DbCommand oDbCommand = DbProviderHelper.CreateCommand("Portal_TabsGetParent", CommandType.StoredProcedure);
oDbCommand.Parameters.Add(DbProviderHelper.CreateParameter("#TabID", DbType.Int32, tabId));
DbDataReader oDbDataReader = DbProviderHelper.ExecuteReader(oDbCommand);
return oDbDataReader;
}
}

Is it a problem if while ConnectionState is doing opening , we Open the connection again?
Yes, it can throw an exception.
Straight from MSDN: SqlConnection.Open method
InvalidOperationException:
Cannot open a connection without specifying a data source or server.
or
The connection is already open
(are you executing the method on different threads with a single shared connection?)

Related

Spring MVC returns 405 for api call made from my android client

I have an android app which is making api requests to my server running Spring MVC. The RestController works fine when I make a request from the browser but it responds with 404 when I am making requests from android. Not sure why
Here is code snippet from Android app making requests
public class AsyncFetch extends AsyncTask<Pair<String, String>, String, String> {
public ProgressDialog pdLoading;
private HttpURLConnection conn;
private String urlStr;
private String requestMethod = "GET";
public AsyncFetch(String endpoint, Context ctx)
{
pdLoading = new ProgressDialog(ctx);
Properties reader = PropertiesReader.getInstance().getProperties(ctx, "app.properties");
String host = reader.getProperty("host", "10.0.2.2");
String port = reader.getProperty("port", "8080");
String protocol = reader.getProperty("protocol", "http");
String context = reader.getProperty("context", "");
this.urlStr = protocol+"://"+host+":"+port+context+endpoint;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(Pair<String, String>... params) {
URL url;
try {
url = new URL(urlStr);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod(requestMethod);
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made`enter code here`
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
Spring MVC Controller
#RestController
public class ApiController {
#RequestMapping(value = "homefeed", method=RequestMethod.GET)
public String homefeed(#RequestParam(value="userId", required = false) Integer id, #RequestParam(value="search", required = false) String search, #RequestParam(value="page", required = false, defaultValue = "0") Integer page) { ... }
}
localhost:8080/api/homefeed -- works
127.0.0.1:8080/api/homefeed -- works
My Public IP:8080/api/homefeed -- does not works
10.0.2.2:8080/api/homefeed -- android emulator to localhost -- does not work
10.0.2.2:8080/Some resource other than the api endpoint -- works
Any help is highly appreciable, have wasted quiet some time in debugging.

C# & Asp.Net : transfer files from SQL Server to browser client, without save on application server

I have an application that persists big files with more 2,5 Gb. When client request to download this file, I want that the file goes to the client browser without save on application server as I do today.
I'm using SQL Server 2008 R2, Asp.Net 3.5, and the column that stores the file is of datatype Varbinary.
I went through the same situation and got the solution in this post. You will use the VarbinaryStream class as follows:
Original Post here.
VarbinaryStream filestream = new VarbinaryStream(
DbContext.Database.Connection.ConnectionString,
"FileContents",
"Content",
"ID",
(int)filepost.ID,
true);
Code:
public class VarbinaryStream : Stream
{
private SqlConnection _Connection;
private string _TableName;
private string _BinaryColumn;
private string _KeyColumn;
private int _KeyValue;
private long _Offset;
private SqlDataReader _SQLReader;
private long _SQLReadPosition;
private bool _AllowedToRead = false;
public VarbinaryStream(
string ConnectionString,
string TableName,
string BinaryColumn,
string KeyColumn,
int KeyValue,
bool AllowRead = false)
{
// create own connection with the connection string.
_Connection = new SqlConnection(ConnectionString);
_TableName = TableName;
_BinaryColumn = BinaryColumn;
_KeyColumn = KeyColumn;
_KeyValue = KeyValue;
// only query the database for a result if we are going to be reading, otherwise skip.
_AllowedToRead = AllowRead;
if (_AllowedToRead == true)
{
try
{
if (_Connection.State != ConnectionState.Open)
_Connection.Open();
SqlCommand cmd = new SqlCommand(
#"SELECT TOP 1 [" + _BinaryColumn + #"]
FROM [dbo].[" + _TableName + #"]
WHERE [" + _KeyColumn + "] = #id",
_Connection);
cmd.Parameters.Add(new SqlParameter("#id", _KeyValue));
_SQLReader = cmd.ExecuteReader(
CommandBehavior.SequentialAccess |
CommandBehavior.SingleResult |
CommandBehavior.SingleRow |
CommandBehavior.CloseConnection);
_SQLReader.Read();
}
catch (Exception e)
{
// log errors here
}
}
}
// this method will be called as part of the Stream ímplementation when we try to write to our VarbinaryStream class.
public override void Write(byte[] buffer, int index, int count)
{
try
{
if (_Connection.State != ConnectionState.Open)
_Connection.Open();
if (_Offset == 0)
{
// for the first write we just send the bytes to the Column
SqlCommand cmd = new SqlCommand(
#"UPDATE [dbo].[" + _TableName + #"]
SET [" + _BinaryColumn + #"] = #firstchunk
WHERE [" + _KeyColumn + "] = #id",
_Connection);
cmd.Parameters.Add(new SqlParameter("#firstchunk", buffer));
cmd.Parameters.Add(new SqlParameter("#id", _KeyValue));
cmd.ExecuteNonQuery();
_Offset = count;
}
else
{
// for all updates after the first one we use the TSQL command .WRITE() to append the data in the database
SqlCommand cmd = new SqlCommand(
#"UPDATE [dbo].[" + _TableName + #"]
SET [" + _BinaryColumn + #"].WRITE(#chunk, NULL, #length)
WHERE [" + _KeyColumn + "] = #id",
_Connection);
cmd.Parameters.Add(new SqlParameter("#chunk", buffer));
cmd.Parameters.Add(new SqlParameter("#length", count));
cmd.Parameters.Add(new SqlParameter("#id", _KeyValue));
cmd.ExecuteNonQuery();
_Offset += count;
}
}
catch (Exception e)
{
// log errors here
}
}
// this method will be called as part of the Stream ímplementation when we try to read from our VarbinaryStream class.
public override int Read(byte[] buffer, int offset, int count)
{
try
{
long bytesRead = _SQLReader.GetBytes(0, _SQLReadPosition, buffer, offset, count);
_SQLReadPosition += bytesRead;
return (int)bytesRead;
}
catch (Exception e)
{
// log errors here
}
return -1;
}
public override bool CanRead
{
get { return _AllowedToRead; }
}
#region unimplemented methods
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return true; }
}
public override void Flush()
{
throw new NotImplementedException();
}
public override long Length
{
get { throw new NotImplementedException(); }
}
public override long Position
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
#endregion unimplemented methods
}

Why is my connection object null?

private static final String DB_URL = "jdbc:derby://localhost:1527/ShopDB";
private static final String DB_CLOSE = DB_URL + ";shutdown=true";
private static final String DB_DRIVER = "org.apache.derby.jdbc.ClientDriver";
private static Connection con = null;
public WebshopDAO() {
try {
Class.forName(DB_DRIVER).newInstance();
con = DriverManager.getConnection(DB_CLOSE);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
}
I created a WebshopDAO object in another class. After that, I called a method in the WebDAO:
public CatalogDTO createCatalogDTO() {
String query = "SELECT * FROM Catalog";
CatalogDTO catalog = new CatalogDTO();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
Catalog c = new Catalog();
c.setCName(rs.getString("CName"));
c.setCategoryNr(rs.getInt("CategoryNr"));
c.setSupercategoryNr(rs.getInt("SupercategoryNr"));
catalog.addCatalog(c);
}
} catch (SQLException e) {
e.getMessage();
}
return catalog;
}
So when I call the createCatalogDTO method, I get a NullPointerException. I don't know why. I checked the driver url and the db url and they are correct. I am using servlets for the first time. The class that uses this WebshopDAO is a servlet and I have a bit of a problem using the debugger.
Can you guys tell me the possible mistakes? I am looking for hours but I just can't find it.
EDIT:
Here is what I get:
java.lang.NullPointerException
WebshopDAO.createCatalogDTO(WebshopDAO.java:96)
Navigation.doGet(Navigation.java:28)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Arithmetic operation resulted in an overflow

After updating my website on ii7 on window server 2008 from framework 3.5 to work with framework 4
i got my c# base database class stop working copmlitly with this error: "Arithmetic operation resulted in an overflow".
I am working with mysql server from different server.
I did not find any solution on this so i had very sadness to role bakce to framework 3.5
here is some of my logs for this error in the event viewr on my server:
Process information:
Process ID: 3680
Process name: w3wp.exe
Account name: NT AUTHORITY\NETWORK SERVICE
Exception information:
Exception type: OverflowException
Exception message: Arithmetic operation resulted in an overflow.
at DataAccess.ExecuteStringQuery(String strSQL) in d:\webSites\s2s\App_Code\DB\DataAccess.cs:line 214
at DataSelect.generalString(String rowName, String tableName, String idName, String ID) in d:\webSites\s2s\App_Code\DB\DataSelect.cs:line 48
at camsBaseShowWeb.OnPreInit(EventArgs e) in d:\webSites\s2s\App_Code\Bases\camsBaseShowWeb.cs:line 134
at System.Web.UI.Page.PerformPreInit()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
big thanks for any halp
i got this error - no matter wich function i try to call from this code
here is my code:
using System;
using System.Data;
//using Microsoft.Data.Odbc;
using System.Data.Odbc;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public class DataAccess
{
#region Private Variables
private static DataAccess _DataAccess = null;
private static object _SyncLock = new object();
private string _strCon = "Driver={MySQL ODBC 5.1 Driver};Server=theIP;Database=theDatabase; UID=root;Password=thePassword;Option=3;";
private OdbcConnection myConnection = null;
#endregion
#region Instance Method
public static DataAccess Instance
{
get
{
lock (_SyncLock)
{
if (_DataAccess == null)
_DataAccess = new DataAccess();
return _DataAccess;
}
}
}
#endregion
#region Constractors
public DataAccess()
{
myConnection = new OdbcConnection(_strCon);
myConnection.Open();
}
#endregion
#region Public Functions
public OdbcDataReader ExecuteQueryReader(string strSQL)
{
try
{
OdbcCommand myCommand = new OdbcCommand(strSQL, myConnection);
return myCommand.ExecuteReader();
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteQueryReader SQL s2s", strSQL, ex);
}
throw ex;
}
}
public DataTable ExecuteQuery(string strSQL)
{
DataTable dt = new DataTable();
OdbcDataAdapter objDataAdapter = null;
try
{
objDataAdapter = new OdbcDataAdapter(strSQL, myConnection);
objDataAdapter.Fill(dt);
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (objDataAdapter != null) objDataAdapter.Dispose();
}
return dt;
}
public DataView ExecuteQueryDV(string strSQL)
{
DataTable dt = new DataTable();
OdbcDataAdapter objDataAdapter = null;
try
{
objDataAdapter = new OdbcDataAdapter(strSQL, myConnection);
objDataAdapter.Fill(dt);
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (objDataAdapter != null) objDataAdapter.Dispose();
}
return new DataView(dt);
}
public DataTable ExecuteLimitedQuery(string strSQL, int startRow, int rowNum)
{
DataTable dt;
DataSet ds = new DataSet();
OdbcDataAdapter objDataAdapter = null;
try
{
objDataAdapter = new OdbcDataAdapter(strSQL, myConnection);
objDataAdapter.Fill(ds, startRow, rowNum, "rowTable");
dt = (DataTable)ds.Tables["rowTable"];
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteLimitedQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (objDataAdapter != null) objDataAdapter.Dispose();
}
return dt;
}
public object ExecuteScalarQuery(string strSQL)
{
OdbcCommand myCommand = null;
object obj = null;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
obj = myCommand.ExecuteScalar();
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteScalarQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return obj;
}
public string ExecuteStringQuery(string strSQL)
{
OdbcCommand myCommand = null;
object obj = null;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
obj = myCommand.ExecuteScalar();
}
catch (Exception ex)
{
if (myConnection.State != ConnectionState.Open)
{
myConnection.Open();
if (myCommand != null) myCommand.Dispose();
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
obj = myCommand.ExecuteScalar();
}
catch (Exception ex2)
{
if (Dict.IsRemote == true)
{
sendMail("error - לאחר ניסיון שני ExecuteStringQuery SQL s2s", strSQL, ex2);
}
throw ex2;
}
}
else
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteStringQuery SQL s2s", strSQL, ex);
}
throw ex;
}
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return obj != null ? obj.ToString() : string.Empty;
}
public int ExecuteNoneQuery(string strSQL)
{
OdbcCommand myCommand = null;
int i;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
i = myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteNoneQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return i;
}
public int InsertGetLastID(string strSQL)
{
OdbcCommand myCommand = null;
int LastID = 0;
object objID = null;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
if (myCommand.ExecuteNonQuery() == 1)
{
myCommand = new OdbcCommand("SELECT LAST_INSERT_ID()", myConnection);
objID = myCommand.ExecuteScalar();
if (objID != null)
{
LastID = int.Parse(objID.ToString());
}
}
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error InsertGetLastID SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return LastID;
}
private void sendMail(string title, string sql, Exception ex)
{
string body = string.Empty +
"SQL:\n\n" + sql + "\n\n" +
"Exeption:\n\n" + ex.Message + "\n\n" +
"Stack Trace:\n\n" + ex.StackTrace + "\n\n" +
"Source:\n\n" + ex.Source + "\n\n";
mailSend mailS = new mailSend("theMail", "mailTo", title, body);
}
#endregion
}
I was getting this too since the upgrade to .Net 4.0
System.OverflowException: Arithmetic operation resulted in an overflow.
at System.Data.Odbc.OdbcDataReader.GetSqlType(Int32 i)
at System.Data.Odbc.OdbcDataReader.GetValue(Int32 i)
at System.Data.Odbc.OdbcCommand.ExecuteScalar()
at Server.Engines.MyRunUO.DatabaseCommandQueue.Thread_Start() in d:\RunUO\Sec
ondAge\Scripts\Engines\MyRunUO\DatabaseCommandQueue.cs:line 117
OdbcConnection version is System.Data.dll, v4.0.30319
Using "{MySQL ODBC 5.1 Driver}" (actually 5.01.06.00) against MySQL 5.1.40-community via TCP/IP on localhost.
The query was any variation of:
SELECT COUNT(*) FROM myrunuo_timestamps WHERE time_type='chardb'
The (apparently) offending lines:
command.CommandText = string.Format("SELECT COUNT(*) FROM myrunuo_timestamps WHERE time_type='{0}'", m_timeStampName); // Line 116
object result = command.ExecuteScalar(); // Line 117
This occurred with an x64 compile only, i.e. using the x64 mySQL driver.
This was fixed by upgrading from mySQL ODBC driver 5.01.06.00 to 5.01.08.00
conver to boolean function does not work when
1. Development is done on 32 bit OS
2. Implementation is done on 64 bit OS
When I altered the code for Convert.ToBoolean function, It worked normally.

Quickest way to setup this asp.net page against MS Access DB . .

I have an access database with 3 tables.
People
Gifts
PeopleGifts
Using VS 2008, what is the quickest way to get a page up and running which allows me to run queries against these tables and do basic inserts.
I want to have comboboxs bound to fields in the table so a user can click on a person and click on a gift and they click "Add".
The quickest way? Iron Speed
try using an oleDBDataAdapter and a formview
public interface IOleDbDataGateway
{
void ExecuteNonQuery(string sql, params object[] args);
object ExecuteScalar(string sql, params object[] args);
DataTable FillDataTable(string sql, params object[] args);
}
public class OleDbDataGateway : IOleDbDataGateway
{
private readonly string connectionString;
public OleDbDataGateway(string connectionString)
{
this.connectionString = connectionString;
}
public void ExecuteNonQuery(string sql, params object[] args)
{
if (args != null)
{
sql = string.Format(sql, args);
}
var connection = new OleDbConnection(connectionString);
var command = new OleDbCommand(sql, connection);
connection.Open();
try
{
command.ExecuteNonQuery();
}
finally
{
connection.Close();
}
}
public object ExecuteScalar(string sql, params object[] args)
{
if (args != null)
{
sql = string.Format(sql, args);
}
var connection = new OleDbConnection(connectionString);
var command = new OleDbCommand(sql, connection);
connection.Open();
try
{
return command.ExecuteScalar();
}
finally
{
connection.Close();
}
}
public DataTable FillDataTable(string sql, params object[] args)
{
if (args != null)
{
sql = string.Format(sql, args);
}
var connection = new OleDbConnection(connectionString);
var adapter = new OleDbDataAdapter(sql, connection);
var table = new DataTable();
connection.Open();
try
{
adapter.Fill(table);
}
finally
{
connection.Close();
}
return table;
}
}

Resources