Error at login in Asp .Net and MySQL - asp.net

I am trying to connect to a database on an sql server in asp .net.
Here is a part of the code:
try
{
connection = new SqlConnection();
if(connection != null)
try
{
connection.ConnectionString = "Data Source=127.0.0.1,3306;Initial Catalog=MyPlace;User ID=root;Password=student";
connection.Open();
cmd = new SqlCommand(sqlQuery, connection);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
String s1 = (String)rdr["id"];
Response.Redirect(s1);
// Operate on fetched data
}
}
catch (Exception exc) { Response.Output.Write(exc.Message); }
}
catch(Exception ex)
{
Response.Output.Write(ex.Message);
}
finally
{
if (cmd != null)
cmd.Dispose();
if (connection != null)
connection.Close();
if (rdr != null)
rdr.Dispose();
}
The error I receive is :
A connection was successfully established with the server, but then an error occurred during the login process. (provider:TCP Provider, error:0 - An existing connection was forcibly closed by the remote host)
Any ideas why this might happen? I've already gone through the basic troubleshooting steps, but nothing seems to help...

Could be a number of things but start with the simplest which would be to verify that your MySql database is allowing connections. yes it seems silly, but we recently ran in to a case where an application wasn't behaving and part of the problem was the way the MySql users were configured which limited where they could connect from and what they could do once connected.
Assuming you can connect locally through the sql tools, and since you are running on the default port try this connect string instead of the one you are using
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Also make sure there aren't any conflicts with the MySql connectors on your box.

Related

Intermittent Error - The .Net Framework Data Providers require Microsoft Data Access Components

We are deploying a full-framework (.Net 4.5.1) website to an IIS server.
We are intermittently experiencing the error:
Application Error: System.AggregateException: One or more errors occurred. ---> System.Exception: SelectAllTOCBasedOnRole failed to execute. ---> System.InvalidOperationException: The .Net Framework Data Providers require Microsoft Data Access Components(MDAC). Please install Microsoft Data Access Components(MDAC) version 2.6 or later. ---> System.Runtime.InteropServices.COMException: Retrieving the COM class factory for component with CLSID {2206CDB2-19C1-11D1-89E0-00C04FD7A829} failed due to the following error: 800703fa Illegal operation attempted on a registry key that has been marked for deletion. (Exception from HRESULT: 0x800703FA).
The site is accessing a DB2 database.
MDAC 2.8.1 is installed on the server. Microsoft OLE DB Provider for DB2 Version 5.0 is also installed on all machines running the site.
If we restart the application pool the error is resolved for a while. The error will then, randomly, start again and continue until the app pool is restarted again.
The same web app is on another server that doesn't seem to exhibit this issue though I cannot see any actual differences between the servers and what components they have installed.
The piece of code that is connecting to the DB2 instance is below. Maybe there is something funky in this..?
public async Task<IList<WebTOC>> GetAllTOCAsync(string countryCode, string languageCode, string employeeNumber, string tocIdentifier)
{
IList<WebTOC> results = new List<WebTOC>();
using (OleDbConnection connection = new OleDbConnection(_connectionString))
{
// Parameter order matters with OLEDBCommands
try
{
using (OleDbCommand command = connection.CreateCommand())
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
command.CommandText = _selectAllTOCCommand;
command.Parameters.AddWithValue("?", $"{tocIdentifier}%");
command.Parameters.AddWithValue("?", countryCode);
command.Parameters.AddWithValue("?", languageCode);
command.Parameters.AddWithValue("?", employeeNumber);
command.Parameters.AddWithValue("?", DateTime.Now.ToString("yyyy-MM-dd"));
LogHelper.Log($"Prepare DB2 Command selectAllToCCommand", level: LogHelper.LogLevel.Debug);
//// FAILS HERE WHEN ATTEMPING TO OPEN THE CONNECTION ////
connection.Open();
try
{
using (INullSafeDataReader dataReader = new NullSafeDataReader(await command.ExecuteReaderAsync()))
try
{
results = dataReader.MapToList<WebTOC>(true);
}
finally
{
dataReader.Close();
}
}
catch (Exception exDR)
{
LogHelper.Log($"Failed to read data from DB2", level: LogHelper.LogLevel.Error);
throw new Exception("Failed to read data from database.", exDR);
}
}
}
catch (Exception ex)
{
/// HITS THIS CATCH ///
LogHelper.Log($"SelectAllTOCBasedOnRole failed to execute", level: LogHelper.LogLevel.Error);
throw new Exception("SelectAllTOCBasedOnRole failed to execute.", ex);
}
finally
{
if (connection.State != System.Data.ConnectionState.Closed)
connection.Close();
connection.Dispose();
}
}
return results;
}

SQL Server Database Size Increasing

I am developing a ASP.NET Web Application with real time functionality by using ASP.NET SignalR.
The problem which I'm facing is the SqlNotificationType.
If I use SqlNotificationType.Change, I can't get the change notification from my database. The SQL 'ServiceBroker' is enabled for my database.
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
NotificationHub nHub = new NotificationHub();
nHub.SendNotifications();
}
}
But if I use SqlNotificationType.Subscribe, It just start notifying me the database changes but the database size starts growing with the every change made in the database.
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Subscribe)
{
NotificationHub nHub = new NotificationHub();
nHub.SendNotifications();
}
}
Whenever a change is made in the database table, a new subscription must be created by re-executing the query after each notification is processed.
It increases the Database Size
Given below is the function to sendNotifications to all the connected clients.
public string SendNotifications()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MCNServerconnectionString"].ConnectionString))
{
const string query = "Select ID, AgentID, DiallerID, Call_Direction, Extension, Call_ID from [MCNServer].[dbo].[CallsDataRecords] where ID = 915";
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
json = JsonConvert.SerializeObject(dt, Formatting.Indented);
}
}
}
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
return context.Clients.All.RecieveNotification(json).ToString();
}
The solution I found is to decrease the database QueryNotificationTimeOut to expire the notifications.
How to Invalidate Cache Entry inorder to eliminate querynotifications?
After lot of searching and debugging my code, I figured out the problem and resolve it.
The SqlNotificationType.Change wasn't working for me and when I used SqlNotificationType.Subscribe it works for me but it increases by database size by subscribing Query Notifications and they are not getting expired due to unauthorized access of database.
So the problem due to database size was increasing while I was using Sql Dependency and enabled Service Broker for my database is unauthorized access to database with sa user.
Due to this problem, queries notifications are not getting expired and they are adding in to the database whenever a change it made in the database. That's why the database size was growing.
So to solve this problem I alter my database and set authorization to sa user and its working fine for me.
ALTER AUTHORIZATION ON DATABASE::[MCNServer] TO [sa];
Now no query notification is pending in the database as sa user is now authorized to access this database and I'm using SqlNotificationType.Change and it is working now.

How to call webservice using wifi in J2ME code for BlackBerry 5.0 and above? [duplicate]

This question already has answers here:
How to call HTTP URL using wifi in J2ME code for BlackBerry 5.0 and above?
(2 answers)
Closed 8 years ago.
I am calling a web service from BlackBerry using J2ME code. When I try to open a connection using HttpConnection, it is checking only the GPRS connection. Now, I want to check the Wi-Fi connection and call a webservice through Wi-Fi.
The following code is my connection section. How to change the code for a Wi-Fi connection?
public boolean HttpUrl()
{
HttpConnection conn = null;
OutputStream out = null;
String url = "http://www.google.com";
try
{
conn = (HttpConnection) new ConnectionFactory().getConnection(url).getConnection();
if (conn != null)
{
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Length", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
}
}
catch (Exception e)
{
return false;
}
finally
{
try
{
out.close();
}
catch (Exception e2)
{
}
}
//Only if exception occurs, we close the connection.
//Otherwise the caller should close the connection himself.
try
{
conn.close();
}
catch (Exception e1)
{
}
return true;
}
How to achieve this?
Instead of creating a new connection factory each time, create one just once and have it stored in a variable. You could create several factories as well. For instance, a factory that only makes connections via Wi-Fi would be something like this:
ConnectionFactory wifiFactory = new ConnectionFactory();
wifiFactory.setPreferredTransportTypes(new int[]{TransportInfo.TRANSPORT_TCP_WIFI});

asp.net Enterprise Library, All connections in use (closed)

im using the asp.net Enterprise Library to insert and update data to an sql database.
c# code:
Database db = DatabaseFactory.CreateDatabase();
IDbConnection connection = db.GetConnection();
connection.Open();
IDbTransaction transaction = connection.BeginTransaction();
DBCommandWrapper command;
try
{
//insert part
command = db.GetStoredProcCommandWrapper("stored_procedure1");
command.CommandTimeout = 900;
command.AddInParameter("#parameter1", DbType.Int32, 3);
db.ExecuteNonQuery(command, transaction);
//update part
command = db.GetStoredProcCommandWrapper("stored_procedure2");
command.CommandTimeout = 900;
command.AddInParameter("#param1", DbType.Int32, 5);
db.ExecuteNonQuery(command, transaction);
transaction.Commit();
}
catch (SqlException e)
{
transaction.Rollback();
throw (new ApplicationException("sql error", e));
}
catch (Exception e)
{
transaction.Rollback();
throw (new ApplicationException("error", e));
}
finally
{
connection.Close();
}
the code is on a method.
The method is executed many times and sometimes im getting error:
"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached."
My questions are: Is it ok to have the insert and update part together as it is above?
Having the insert and update part together is causing this error?
Thanks.
First you do not roll back your transaction on error.
Secondly in order to guarantee that your finally block is called you need to add the catch block.
Try {
...
}
Catch {
}
finally {
close connection
}
Read the second paragraph of the link located below
http://msdn.microsoft.com/en-us/library/zwc8s4fz(v=vs.100).aspx

ASP.NET Oracle Sessions Remain Inactive and error for maximum exceeded maximum connect time

My ASP.NET C# application is connection to an Oracle database, running a stored procedure, and returning a reader with the command behavior of CloseConnection. The reader itself is disposed but - the Oracle sessions persist as inactive in V$SESSION. In a few hours, this turns into an error when another customer uses the application and we receive the error 'ORA-02399: exceeded maximum connect time, you are being logged off'. Further attempts to connect to Oracle return 'ORA-01012: not logged on'
Here is the connection string:
User Id=UserID;Password=userPass;Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP) (HOST=IP.IP.IP.IP)(PORT=XXXX))(CONNECT_DATA=(SID=SID)));;Max Pool Size=5;Connection Timeout=60;Connection Lifetime=120;
Here is how the reader is used:
using (OracleDataReader dr = OraFunctions.ExecuteReader(input.ConnectionString,
CommandType.Text,
input.SqlStmt,
null))
{
while (dr.Read())
{
//do stuff here
}
dr.Dispose();
}
Here is the class that connects to Oracle:
public static OracleDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText, OracleParameter[] commandParameters) {
OracleConnection connection = null;
OracleCommand command = new OracleCommand();
try {
connection = new OracleConnection(connectionString);
connection.Open();
command.Connection = connection;
command.CommandType = commandType;
command.CommandText = commandText;
if (commandParameters != null) {
foreach (OracleParameter param in commandParameters) {
command.Parameters.Add(param);
}
}
//Passing CommandBehavior.CloseConnection flag to the ExecuteReader method makes the DataReader connection to be closed when the DataReader is closed.
OracleDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
command.Dispose();
return reader;
} catch {
if (connection != null) {
command.Dispose();
connection.Close();
}
throw;
}
}
I'm looking for any hints on why the connections aren't actually closing. I'm using Oracle.DataAccess.Client. My guess is that the datareader's command behavior isn't working and that I need to recode this as a dataset where I can explitictly close the connection without having to rely on the CommandBehavior.
Thoughts? Thanks!
since you have connection.Open();
why didn't proper close it?
We never could get this worked out. We ended up disabling connection pooling and the open/inactive sessions went away in Oracle. If anyone reads this and has a suggestion on what was going wrong, I would definitely appreciate your input.
The possible solution I'm evaluating right now is to set Connection Lifetime parameter below the server's value.
The idea is when connection returned to the pool after performing query, it's lifetime is checked, and connection is closed if both conditions are met:
Connection's lifetime exceeded Connection Lifetime parameter value
Number of connections opened would not be lower than Min Pool Size parameter value
Kudos to Joao Morais for ODP.NET pooling details.

Resources