Why is my connection object null? - servlets

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)

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.

Unable to update DB by form data

please give me advice! I get form data in servlet and try to update the database, but it doesn't works. There is connection with database (without servlet code any data is properly added in db), but no any exception are thrown. The servlet get parameters - they are available in JSP by EL-expressions. I tried to update the db simply by statement, without using preparedStatement but it didn't help. Here it is the code:
public class ServletClass extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
DBConn dbConn = new DBConn();
String number = req.getParameter("number");
String amount = req.getParameter("amount");
String date = req.getParameter("date");
ArrayList list = dbConn.returnList(number, amount, date);
req.setAttribute("attr", list);
RequestDispatcher requestDispatcher = req.getRequestDispatcher("index.jsp");
requestDispatcher.forward(req, resp);
}
}
public class DBConn {
public ArrayList<InvoicesBean> returnList(String number, String amount, String date) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
ArrayList<InvoicesBean> beanList = new ArrayList<InvoicesBean>();
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ved", "root", "1111");
statement = connection.createStatement();
preparedStatement = connection.prepareStatement("insert into invoices values(?, ?, ?);");
preparedStatement.setString(1, number);
preparedStatement.setString(2, amount);
preparedStatement.setString(3, date);
preparedStatement.executeUpdate();
resultSet = statement.executeQuery("SELECT * FROM invoices;");
while (resultSet.next()){
InvoicesBean invoicesBean = new InvoicesBean();
invoicesBean.setNumber(resultSet.getString("number"));
invoicesBean.setAmount(resultSet.getString("amount"));
invoicesBean.setDate(resultSet.getString("date"));
beanList.add(invoicesBean);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return beanList;
}
}
InvoiceBean-class is just a standard bean class with getters/setters
invoicesBean.setNumber(resultSet.getString("number"));
invoicesBean.setAmount(resultSet.getString("amount"));
invoicesBean.setDate(resultSet.getString("date"));
You can not have the database column names as 'number' or 'date'. they are reserved.
check the column names again.
for checking if this is the error, you can replace the column names by column numbers 1,2,3.

SQLException : Missing defines in servlet

I am working on a web application using jsp and servlet using oracle.jdbc.OracleDriver.This code,working fine on my PC,but when trying to deploy build of application on other server,i am getting Exception like this.
java.sql.SQLException: Missing defines
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:158)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:305)
at oracle.jdbc.driver.OracleStatement.prepareAccessors(OracleStatement.java:793)
at oracle.jdbc.driver.T4CResultSetAccessor.getCursor(T4CResultSetAccessor.java:235)
at oracle.jdbc.driver.ResultSetAccessor.getObject(ResultSetAccessor.java:95)
at oracle.jdbc.driver.OracleCallableStatement.getObject(OracleCallableStatement.java:1947)
at org.apache.tomcat.dbcp.dbcp.DelegatingCallableStatement.getObject(DelegatingCallableStatement.java:143)
at cwep.Login.processRequest(Login.java:127)
at cwep.Login.doPost(Login.java:198)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:852)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:584)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1508)
at java.lang.Thread.run(Unknown Source)
After debugging my application,i found that when I am calling database(Oracle 10g) procedure on server side and getting cursor using callableStatement.registerOutParameter(1,OracleTypes.CURSOR), I am getting above Exception at
callableStatement.execute(); statement.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
static String CNPOOL = "cnpool";//Getting CNPOOL correctly for database connection
CallableStatement cs = null;
static DataSource dataSource;//Declared as global
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
CallableStatement cs = null;
String str = conectionPool;
System.out.println(str);
try {
InitialContext initContext = new InitialContext();
Context context = (Context) initContext.lookup("java:/comp/env");
dataSource = (DataSource) context.lookup(str);
System.out.println(" CxN Pool " + str);
String username = request.getParameter("username");
String password = request.getParameter("password");
ecode = Integer.parseInt(username);
System.out.println(" eCode " + ecode);
try {
con = ConnectionBean.getConnection(dataSource);
System.out.println(" CxN " + con.toString());
} catch (Exception e) {
System.out.println(" Opening the Cxn 1st Time" + e);
}
if(con!=null)
{
System.out.println(" Before Calling proc_user_login " + ecode);
cs = con.prepareCall("{call proc_user_login(?,?,?,?,?)}");
cs.setInt(1, empcode);
cs.setString(2, password);
cs.registerOutParameter(3, Types.NUMERIC);
cs.registerOutParameter(4, Types.NUMERIC);
cs.registerOutParameter(5, Types.VARCHAR);
try {
cs.execute();
} catch (Exception e) {
System.out.println("--------------------After executing first proc----------------------- ");
}
int message = cs.getInt(3);
if (message == 0) {
cs = con.prepareCall("{call proc_get_XXXlist(?,?)}");
cs.setInt(1, empcode);
cs.registerOutParameter(2, OracleTypes.CURSOR);
try {
System.out.println("Before executing XXXList proc ");
cs.execute(); //GETTING EXCEPTION AT THIS STATEMENT
System.out.println("After executing XXXList");
} catch (Exception e) {
System.out.println("exception in After executing secod proc ");
}
ResultSet rset = (ResultSet) cs.getObject(2);
Vector v1 = new Vector();
Vector v2 = new Vector();
Vector v3 = new Vector();
while (rset.next()) {
v1.addElement(rset.getString(1));
v2.addElement(rset.getString(2));
v3.addElement(rset.getString(3));
}
//rset.last();
String[] str1 = new String[v1.size()];
String[] str2 = new String[v2.size()];
String[] str3 = new String[v3.size()];
v1.copyInto(str1);
v2.copyInto(str2);
v3.copyInto(str3);
request.setAttribute("ecode", Integer.toString(ecode));
request.setAttribute("clientid", str1);
request.setAttribute("constring", str2);
request.setAttribute("URL", str3);
RequestDispatcher rd = request.getRequestDispatcher("XXX.jsp");
rd.forward(request, response);
//response.sendRedirect("XXX.jsp");
} else {
response.sendRedirect("index.jsp?val=" + message);
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("EEE---" + e);
Utility.log("FinalExceptionToServlet.namelookup:", e.toString(), "SERVER", "E");
}
}
In this code,First database login_usr procedure execute properly,but when trying to execute 2nd procedure,which returns a cursor as outparameter,i'm getting above exception.If same code working fine on my PC,then why it throws exception when trying to execute callablestatement after Serverside deployment.Here I'm using Ojdbc14.jar and classes12.jar.Is there is any .jar missmatch..???
Thanks in advance.
As you have mentioned that the code was running earlier, Here the culprit could be OracleTypes. As its abstract class you need correct and concrete implementation of it which is your Driver.
Verify the version of the JDBC driver and the type of JDBC driver (Thin or OCI) you
Download new jar from oracle site or from here.
Also, try using oracle.jdbc.OracleTypes before looking for drivers.
e.g. cn.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR);

How to organize Data Access Layer (DAL) in ASP.NET

I have an ASP.NET Web Forms application developed in C#.
I would like to give structure my application by separating the DAL tasks from the code behind.
I created a class in App_Code, DBUtilities that takes care of the communication with the database, in order not to have duplicated code all along the application. The class has methods to get datatables, scalar values, etc... and they accept as parameters the connection string name and the query command as string.
The problem is that I have still all the queries' commands in my code behind. Many of them are duplicated all around the pages and this cause maintanance problems.
I was wondering if it is a good practice to create a (static) class QueryRepository that contains many string properties and associate to each of them a specific query command. Everytime I want to execute the query command MyCommand I pass to the DBUtilities class the QueryRepository.MyCommand property instaed of the string. Morevoer if I need to change a query command I do it just on the QueryRepository class.
Is it a good way to organize my DAL?
For ASP.NET web forms implementing Model-View-Presenter (MVP) pattern can be one good approach to separate your logic and database queries from the UI code behind. You have to write a Presenter class that has a generic reference to a view interface and has a model in it which has database queries, logic etc. The presenter will call functions of the generic view interface in all its functions. Then you can write the actual ASP.net view. In the view you instantiates and reference this presenter and while instantiating the presenter you inject the self object i.e the ASP view itself (using "this" keyword) to the Presenter. You can design proper inheritance for your presenter classes based on your need so that they are reusabe and can be unit tested.
Addition in response to CiccioMiami's query:
Here are couple of links to start
http://www.codeproject.com/KB/aspnet/AspNet_MVP.aspx
http://wiki.asp.net/page.aspx/340/mvp-pattern/
The difference in the MVC and MVP pattern is explained here: http://www.codeproject.com/KB/architecture/DotNetMVPFramework_Part1.aspx
To add to this, for ASP.net Web form architecture, the Requests are tightly coupled with the page life cycle. You have series of page life cycle events and developers write code in each of these events. Thus the business logic becomes tightly coupled to the UI view. Over the period of time this is not a good situation for code maintainability and unit testing. Unit testing is difficult in ASP.net web forms as it is difficult to simulate the requests and page life cycle events. In MVC the requests first comes to a controller. The controller uses the model for business logic and passes the model to view. The view renders using the model data and is returned back as the response to the user. The controller has greater control on the work-flow. You can test the model, DTO transfers etc. as you could do in a standalone app. With web forms there is no controller the request directly comes to ASP.net page which is a view. There is nothing much user can do. Good that Microsoft realized this problem and we have ASP.net MVC. The MVP pattern for ASP.net webforms will solve the code separation problem to some extent. The best option is to use ASP.net MVC if not then you can use MVP with Webforms.
Long term answer: I can really recommend you read Professional Enterprise .NET
The ASP.NET website has a good example of the repository pattern which is worth looking at.
I'm no expert, but if your DAL can conform to a best-practise patterns it's more likely to be a good way for it to be organised.
I'm struggling to follow your DAL design without a concrete example, so not sure I can help there.
Few steps to follow:
It is good practice to separate the DAL, BLL code from presentation(UI) layer, however to go accordingly below steps would be helpful.
Create DTO (Data Transfer Object) or Entity
Fill the DTO/Entity from presentation layer
Pass it to a public method to your BLL layer and validate Business Logic
Then pass the DTO/Entity to DAL layer (at DAL layer, create a method which return Command, then put your CommandText, CommandType and then Set value, data type and size to all the parameters, also create execute method which get Command and return results).
Finally, execute your desired execute method ( created at DAL layer)
namespace DAL
{
public class DBAccess
{
private IDbCommand cmd = new SqlCommand();
private string strConnectionString = "";
private bool handleErrors = false;
private string strLastError = "";
public DBAccess()
{
ConnectionStringSettings objConnectionStringSettings = ConfigurationManager.ConnectionStrings["connectionString"];
strConnectionString = objConnectionStringSettings.ConnectionString;
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = strConnectionString;
cmd.Connection = cnn;
cmd.CommandType = CommandType.StoredProcedure;
}
public SqlConnection OpenSqlConnection()
{
try {
SqlConnection Conn = new SqlConnection(strConnectionString);
Conn.Open();
return Conn;
} catch (SqlException e) {
throw e;
} catch (Exception ex) {
throw ex;
}
}
public IDataReader ExecuteReader()
{
IDataReader reader = null;
try {
this.Open();
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
} catch (Exception ex) {
if (handleErrors) {
strLastError = ex.Message;
} else {
throw;
}
}
return reader;
}
public IDataReader ExecuteReader(string commandtext)
{
IDataReader reader = null;
try {
cmd.CommandText = commandtext;
reader = this.ExecuteReader();
} catch (Exception ex) {
if ((handleErrors)) {
strLastError = ex.Message;
} else {
throw;
}
}
return reader;
}
public object ExecuteScalar()
{
object obj = null;
try {
this.Open();
obj = cmd.ExecuteScalar();
this.Close();
} catch (Exception ex) {
if (handleErrors) {
strLastError = ex.Message;
} else {
throw;
}
}
return obj;
}
public object ExecuteScalar(string commandtext)
{
object obj = null;
try {
cmd.CommandText = commandtext;
obj = this.ExecuteScalar();
} catch (Exception ex) {
if ((handleErrors)) {
strLastError = ex.Message;
} else {
throw;
}
}
return obj;
}
public int ExecuteNonQuery(SqlConnection DBConnection, SqlTransaction DBTransaction, bool IsTransRequired)
{
int i = -1;
try {
if ((DBTransaction != null)) {
cmd.Transaction = DBTransaction;
}
i = cmd.ExecuteNonQuery();
} catch (Exception ex) {
if (handleErrors) {
strLastError = ex.Message;
} else {
throw;
}
}
return i;
}
public int ExecuteNonQuery(string commandtext, bool IsTransRequired)
{
SqlConnection DBConnection = null;
SqlTransaction DBTransaction = null;
int i = -1;
try {
cmd.CommandText = commandtext;
if (((DBConnection == null))) {
this.Open();
DBConnection = (SqlConnection)this.cmd.Connection;
if (IsTransRequired == true) {
if (((DBTransaction == null))) {
DBTransaction = DBConnection.BeginTransaction();
}
}
i = this.ExecuteNonQuery(DBConnection, DBTransaction, IsTransRequired);
if ((DBTransaction != null)) {
DBTransaction.Commit();
}
}
} catch (Exception ex) {
if ((DBTransaction != null)) {
DBTransaction.Rollback();
}
if (handleErrors) {
strLastError = ex.Message;
} else {
throw;
}
} finally {
this.Close();
}
return i;
}
public DataSet ExecuteDataSet()
{
SqlDataAdapter da = null;
DataSet ds = null;
try {
da = new SqlDataAdapter();
da.SelectCommand = (SqlCommand)cmd;
ds = new DataSet();
da.Fill(ds);
} catch (Exception ex) {
if ((handleErrors)) {
strLastError = ex.Message;
} else {
throw;
}
}
return ds;
}
public DataSet ExecuteDataSet(string commandtext)
{
DataSet ds = null;
try {
cmd.CommandText = commandtext;
ds = this.ExecuteDataSet();
} catch (Exception ex) {
if (handleErrors) {
strLastError = ex.Message;
} else {
throw;
}
}
return ds;
}
public string CommandText{
get {
return cmd.CommandText;
}
set {
cmd.CommandText = value;
cmd.Parameters.Clear();
}
}
public IDataParameterCollection Parameters{
get {return cmd.Parameters;}
}
public void AddParameter(string paramname, object paramvalue)
{
SqlParameter param = new SqlParameter(paramname, paramvalue);
cmd.Parameters.Add(param);
}
public void AddParameter(IDataParameter param)
{
cmd.Parameters.Add(param);
}
public string ConnectionString {
get { return strConnectionString; }
set { strConnectionString = value; }
}
private void Open()
{
cmd.Connection.Open();
}
private void Close()
{
cmd.Connection.Close();
}
public bool HandleExceptions{
get {return handleErrors;}
set {handleErrors = value;}
}
public string LastError{
get {return strLastError;}
}
public void Dispose()
{
cmd.Dispose();
}
}
}

Connection.State Issue

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?)

Resources