Getting Connection Error Connection Must Be Valid and Open - mysql

This is my Data access layer but i don't know why i am getting connection error when multi user using and when more than 1 user access the website i checked all thing but cant fix it i am posting my code. this is updated code. it again stuck and result same as last code. i dnt know why it happened when more than 1 user try to access it login but then its not working more after 1 to 2 mints
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Configuration;
public class clsMySqlConnection
{
public MySqlConnection con = null;
protected MySqlConnection getConnection()
{
if (con == null || con.State != ConnectionState.Open)
{
con = new MySqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
con.Open();
}
return (con);
}
}
public class clsManagement : clsMySqlConnection
{
public DataTable getData(string MySql)
{
MySqlCommand cmd = new MySqlCommand();
MySqlDataAdapter da = new MySqlDataAdapter();
DataTable dt = new DataTable();
cmd.CommandText = MySql;
cmd.Connection = getConnection();
da.SelectCommand = cmd;
da.Fill(dt);
return (dt);
}
public MySqlDataReader ExecuteActionQuery(string MySql)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = MySql;
try
{
cmd.Connection = getConnection();
cmd.ExecuteNonQuery();
MySqlDataReader rdr = cmd.ExecuteReader();
return (rdr);
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
}
public int ExecuteDML(string MySql)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = MySql;
try
{
cmd.Connection = getConnection();
return cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
}
}

You can just create a new connection and return from getConnection() function.
protected MySqlConnection getConnection()
{
MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
con.Open();
}
And use con variable in local scope.

Related

system 'ArgumentException' occurred in system.data.dll

My Question is can I pass the string to MySqlConnection this way??
The Error is in this Line below in the code "MySqlConnection conn = new MySqlConnection(myconnstr);"
It worked for SQLConnection but not for MySqlConnection ... is it not possibl?
kindly help me With the right solution
thanks!
string myconnstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
//Selecting Data from databse
public DataTable Select()
{
MySqlConnection conn = new MySqlConnection(myconnstr);
DataTable dt = new DataTable();
try
{
string sql = "SELECT * FROM Member";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
conn.Open();
adapter.Fill(dt);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
return dt;
}

How do I close mysql connection after if-statement if it is true?

I'm new to ASP.NET and I'm stuck on this problem. I get the error:
Error:System.InvalidOperationException: The connection was not closed. The connection's current state is open. at System.Data.ProviderBase.DbConnectionInternal.
Here is my code, the error points towards 'while' statement. I've tried number of things but nothing worked. I know that I need to close connection when if-statement is true but don't know how. Can anyone help me on this? Thanks.
protected void loadtour()
{
try
{
conn.Open();
string strSelect = "Select * From Agents where Agent_ID='" + AgID.Text + "'";
SqlCommand cmd = new SqlCommand(strSelect, conn);
SqlDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
if (myReader["Agent_Status"].ToString() == "On Tour")
{
Label1.Text = "Assigned Tour Details:";
try
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT PackageInfo.pkg_Name, PackageInfo.pkg_Type, PackageInfo.pkg_Status, Packages.pkg_Country, Packages.pkg_Start, Packages.pkg_End, PackageInfo.Agent_ID, PackageInfo.Agent_Name FROM PackageInfo INNER JOIN Packages ON PackageInfo.pkg_ID = Packages.pkg_ID WHERE(PackageInfo.Agent_ID = '" + AgID.Text + "')", conn);
DataTable ds = new DataTable();
da.Fill(ds);
gv1.DataSource = ds;
gv1.DataBind();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
conn.Close();
}
else
{
Label1.Text = "No Tour Assigned Yet!";
}
myReader.Close();
conn.Close();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
//Do stuff with the connection
}
Wrap your connection in a using block. This guarantees it always gets closed.

Capture CheckBox list input- and assign to text area-

I am developing a web application using asp.net and MySQL. in my app, users can add recipes. It is a record that will be inserted. I have to input the ingredients in to the database as well. I am trying to capture the input ingredients ( which are in the form of checkboxes. ) Please review the GetIngredientsInput() method. I am checking which check boxes are checked, and saving the TEXT of the item checked. I want to capture the input in form of list. ( list of strings. ) I used StringBuilder for this, and assign it to a textarea control. But the code doesn't seem in effect. Thanks in advance.
protected void AddRecipe(object sender, EventArgs e)
{
GetIngredientsInput();
MySqlConnection con = new MySqlConnection("Server=localhost;Database=FreedomKitchen;Uid=root;Password=;");
con.Open();
String strcmd = "insert into Recipes(Recipe_ID,Food_Category,Meal_Category,Recipe_Name,All_Ingredients,Recipe_Description,Recipe_Instructions) values(#Recipe_ID,#Food_Category,#Meal_Category,#Recipe_Name,#All_Ingredients,#Recipe_Description,#Recipe_Instructions)";
MySqlCommand cmd = new MySqlCommand(strcmd, con);
MySqlCommand cmd_two = new MySqlCommand("select * from Recipes", con);
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = cmd_two;
DataSet ds = new DataSet();
da.Fill(ds, "Rows");
int row_count = ds.Tables["Rows"].Rows.Count;
r_id = row_count + 1;
cmd.Parameters.Add(new MySqlParameter("#Recipe_ID", r_id));
cmd.Parameters.Add(new MySqlParameter("#Food_Category", DropDownFoodCat.Text.ToString()));
cmd.Parameters.Add(new MySqlParameter("#Meal_Category", DropDownMealCat.Text));
cmd.Parameters.Add(new MySqlParameter("#Recipe_Name", txtRecipeName.Text));
cmd.Parameters.Add(new MySqlParameter("#All_Ingredients", txtAllIngredients.Text));
cmd.Parameters.Add(new MySqlParameter("#Recipe_Description", txtDescription.Text));
cmd.Parameters.Add(new MySqlParameter("#Recipe_Instructions", txtInstructions.Text));
cmd.ExecuteNonQuery();
con.Close();
}
public void GetIngredientsInput() {
foreach (ListItem li in CheckBoxListVeg.Items) {
if (li.Selected) {
String ing_name=li.Text.ToString();
str_ing_name.Append(ing_name);
str_ing_name.Append("\n");
txtAllIngredients.Text = ing_name = li.Text.ToString();
}
}
}
Try this :-
public string GetIngredientsInput()
{
StringBuilder str_ing_name = new StringBuilder();
foreach (ListItem li in CheckBoxListVeg.Items)
{
if (li.Selected)
{
String ing_name = li.Text.ToString();
str_ing_name.Append(ing_name);
str_ing_name.Append(",");
}
}
return str_ing_name.ToString();
}
protected void AddRecipe(object sender, EventArgs e)
{
txtAllIngredients.Text= GetIngredientsInput();
// Rest of code
}

How to get list of reports

How to list all the reports, that I have created in the report server? Later I would like to use this list to display them in my ReportViewer control.
Report server uses stored procedure called FindObjectsNonRecursive.
string cnxstr = "Data Source=server;Initial Catalog=ReportServer;Integrated Security=SSPI;"; //connection string
using (SqlConnection connection = new SqlConnection(cnxstr))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "FindObjectsNonRecursive";
command.Parameters.Add(new SqlParameter("#Path", "/folder_name"));
command.Parameters.Add(new SqlParameter("#AuthType", 1));
SqlDataReader reader = null;
try
{
reader = command.ExecuteReader();
while (reader.Read())
{
string path = reader["Path"].ToString();
//now you can display this path in your list, or do whatever
}
}
finally
{
if (reader != null)
reader.Close();
}
}

The index outside of the range Exception

I'm trying to fill my list on Visual Studio side with help of stored procedure.
I'm using the following stored procedure:
CREATE PROCEDURE [dbo].[GetColletcion]
AS
BEGIN
select CollectionType.Name ,GlassesCollection.Name
from GlassesCollection
inner join CollectionType
on GlassesCollection.CollectionType=CollectionType.CollTypeID
END
Here's the code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
List<GlassesCollection> list = new List<GlassesCollection>();
using (SqlConnection conn = new SqlConnection("Server=(local);DataBase=ISeeOptic;Integrated Security=SSPI"))
{
GlassesCollection gln = new GlassesCollection();
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetColletcion";
conn.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
gln.Name = (string)reader["CollectionType.Name"];
gln.CollectionType = (string)reader["GlassesCollection.Name"];
list.Add(gln);
}
reader.Close();
conn.Close();
}
}
But when it comes to this row:
gln.Name = (string)reader["CollectionType.Name"];
I get this Exception:
Exception Details: System.IndexOutOfRangeException: CollectionType.Name
The index outside of the range, although in database more than one record.
How can I solve my problem?
It would be best to use column aliases and refer to the columns by those instead.
CREATE PROCEDURE [dbo].[GetColletcion]
AS
BEGIN
select CollectionType.Name As TypeName ,GlassesCollection.Name As GlassesName
from GlassesCollection
inner join CollectionType
on GlassesCollection.CollectionType=CollectionType.CollTypeID
END
Then use
(string)reader["TypeName"];
(string)reader["GlassesName"];
If you cannot change your stored procedure, then you can use the oridinal position:
(string)reader[0]; //CollectionType.Name
(string)reader[1]; //GlassesCollection.Name
I corrected your typo, too. (GetCollection)
CREATE PROCEDURE [dbo].[GetCollection]
AS
BEGIN
select CollectionType.Name AS CollectionType_Name, GlassesCollection.Name AS GlassesCollection_Name
from GlassesCollection
inner join CollectionType
on GlassesCollection.CollectionType=CollectionType.CollTypeID
END
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
List<GlassesCollection> list = new List<GlassesCollection>();
using (SqlConnection conn = new SqlConnection("Server=(local);DataBase=ISeeOptic;Integrated Security=SSPI"))
{
GlassesCollection gln = new GlassesCollection();
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetCollection";
conn.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
gln.Name = (string)reader["GlassesCollection_Name"];
gln.CollectionType = (string)reader["CollectionType_Name"];
list.Add(gln);
}
reader.Close();
conn.Close();
}
}

Categories