I have a class in the Dashboard.App_code
The functions in this class can be called without problem from the web form (bugs.aspx) to populate object data sources
But when I try to call a function from bugs.aspx.cs, I get the follwoing error message
Compiler Error CS0103 The name 'Clmysql' does not exist in the current context
bugs.aspx.cs
using System;
using System.Data;
using System.Linq;
using System.Web.UI.WebControls;
namespace Dashboard
{
public partial class _Bugs : System.Web.UI.Page
{
protected void Calendar2_SelectionChanged(object sender, EventArgs e)
{
txtdate2.Text = Calendar2.SelectedDate.ToString("dd-MM-yyyy");
if (txtdate1.Text != "" && txtdate2.Text != "")
{
GridView1.DataBind();
GridView2.DataBind();
txtjson.Text = **Clmysql.GettreatedBugsdetails**(Calendar1.SelectedDate, Calendar2.SelectedDate);
}
}
}
app_codes\Clmysql.cs
using System.Data;
using MySql.Data.MySqlClient;
using System;
using System.Configuration;
using Newtonsoft.Json;
namespace Dashboard.App_code
{
public static class Clmysql
{
public static string GettreatedBugsdetails(DateTime Mydate1, DateTime Mydate2)
{
var conn = new MySql.Data.MySqlClient.MySqlConnection(ConfigurationManager.ConnectionStrings["mantis"].ConnectionString);
conn.Open();
string StrQuery = "select *****mysql code here" max(date(FROM_UNIXTIME(date_modified))),realname";
MySqlCommand Command = new MySqlCommand(StrQuery, conn);
DataTable dt = new DataTable();
using (MySqlDataAdapter da = new MySqlDataAdapter(Command))
{
da.Fill(dt);
}
conn.Close();
conn.Dispose();
return JsonConvert.SerializeObject(dt);
}
}
}
ASP.NET C# Web Forms Visual Studio 2019
After searching, I found the solution
Right-click on the class file "ClMysql.cs" => properties=>Build action: compile instead of content
Related
I'm trying to create a Data Framework in the form of a .dll so that I can reference it when creating new projects, as opposed to reinventing the wheel with each project I create.
I have an app.config in which I store my SQL connections, a class that uses the app.config to build my SQL ConnectionString (ConnectionStrings.cs) and a Logic class (Logic.cs) that'll build whatever objects I require from the SQL Server.
Here's the classes in the .dll:
ConnectionStrings.cs:
using System.Configuration;
using System.Data.SqlClient;
namespace DataFramework
{
public static class ConnectionStrings
{
static string _liveConnectionString = ConfigurationManager.ConnectionStrings["LiveDataSource"].ConnectionString;
static string _liveMISConnectionString = ConfigurationManager.ConnectionStrings["LiveDataSource_MIS"].ConnectionString;
static string _devConnectionString = ConfigurationManager.ConnectionStrings["DevDataSource"].ConnectionString;
static string _devMISConnectionString = ConfigurationManager.ConnectionStrings["DevDataSource_MIS"].ConnectionString;
public static SqlConnection CreateLiveConnection
{
get { return new SqlConnection(_liveConnectionString); }
}
public static SqlConnection CreateLiveMISConnection
{
get { return new SqlConnection(_liveMISConnectionString); }
}
public static SqlConnection CreateDevConnection
{
get { return new SqlConnection(_devConnectionString); }
}
public static SqlConnection CreateDevMISConnection
{
get { return new SqlConnection(_devMISConnectionString); }
}
}
}
Logic.cs:
using System;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace DataFramework
{
public class Logic
{
SqlConnection liveConnection = ConnectionStrings.CreateLiveMISConnection;
SqlConnection devMISConnection = ConnectionStrings.CreateDevMISConnection;
public bool IsConnecting { get; set; }
public string ConnectionMessage { get; set; }
public async Task<DataTable> ResultDataTable(bool connectToLive, string commandText, CommandType commandType)
{
DataTable dt = new DataTable();
using (SqlCommand command = new SqlCommand())
{
try
{
command.CommandType = commandType;
command.CommandTimeout = 360000000;
switch (connectToLive)
{
case true:
command.CommandText = commandText;
command.Connection = liveConnection;
if (liveConnection.State == ConnectionState.Connecting)
{
IsConnecting = true;
ConnectionMessage = "Connecting to Data Source...";
}
if (liveConnection.State != ConnectionState.Closed)
liveConnection.Close();
if (liveConnection.State != ConnectionState.Open)
{
liveConnection.Open();
IsConnecting = false;
ConnectionMessage = "";
}
break;
case false:
command.CommandType = commandType;
command.CommandText = "";
command.Connection = devMISConnection;
if (devMISConnection.State == ConnectionState.Connecting)
{
IsConnecting = true;
ConnectionMessage = commandText;
}
if (devMISConnection.State != ConnectionState.Closed)
devMISConnection.Close();
if (devMISConnection.State != ConnectionState.Open)
{
devMISConnection.Open();
IsConnecting = false;
ConnectionMessage = "";
}
break;
}
using (SqlDataReader reader = await command.ExecuteReaderAsync())
{
dt.Load(reader);
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message, "An Error Has Occured", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
}
finally
{
if (devMISConnection.State != ConnectionState.Closed)
devMISConnection.Close();
if (liveConnection.State != ConnectionState.Closed)
liveConnection.Close();
}
}
return dt;
}
}
}
I include this dll as a reference in the app that I'm writing:
using System.Data;
using System.Threading.Tasks;
using System.Windows.Forms;
using DataFramework;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
DataTable dt = new DataTable();
DataFramework.Logic logic = new Logic();
public Form1()
{
InitializeComponent();
}
private async void Form1_Load(object sender, EventArgs e)
{
dt = await Task.Run(() => logic.ResultDataTable(true, "SELECT * FROM MIS.dbo.ETL_Table", CommandType.StoredProcedure));
}
}
}
The code throws the exception here:
SqlConnection liveConnection = ConnectionStrings.CreateLiveMISConnection;
So why, when I'm initializing the class, do I get this issue?
When you reference a DLL (or project) from another project, the app.config from the top most project is used. So, if you have your DataFramework being called from your WinformsApp, then your WinformsApp needs to have the right config settings in it. By default, it will ignore any app.config in the DataFramework. A bit frustrating at times! Copy your settings from your DataFramework app.config in to the WinformsApp app.config and it will work.
Another unrelated observation is that you have the following:
"SELECT * FROM MIS.dbo.ETL_Table", CommandType.StoredProcedure
The command type should be text and not a stored procedure.
I'm getting error like
An object reference is required for the non-static field, method, or
property 'System.Web.UI.Page.Session.get'
Can you suggest me to recover from this problem in session.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.SessionState;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//Onclick Submit Button
[WebMethod(EnableSession = true)]
//[System.Web.Services.WebMethod(EnableSession = true)]
public static string Login(string email, string password)
{
var con = new SqlConnection(ConfigurationManager.ConnectionStrings["blogConnString"].ConnectionString);
con.Open();
string res = "0";
SqlDataReader reader;
string sql = "select uid,username from personal where email='" + email + "' and password='" + password + "'";
SqlCommand cmd1 = new SqlCommand(sql, con);
reader = cmd1.ExecuteReader();
while (reader.Read())
{
res = "1";
Session["UID"] = reader["uid"].ToString(); //error line here
Session["UNAME"] = reader["username"].ToString(); //error line here
}
return res;
con.Close();
}
}
Try this code and please be-ware of SQL Injection - to prevent it, use a Parametrized Query as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.SessionState;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//Onclick Submit Button
[WebMethod(EnableSession = true)]
//[System.Web.Services.WebMethod(EnableSession = true)]
public static string Login(string email, string password)
{
var con = ConfigurationManager.ConnectionStrings["blogConnString"].ConnectionString;
con.Open();
string res = "0";
SqlDataReader reader;
string sql = "select uid,username from personal where email=#Email and password=#Password";
using(SqlConnection connection = new SqlConnection(con))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#Email", SqlDbType.String);
command.Parameters["#Email"].Value = email;
command.Parameters.AddWithValue("#Password", password);
reader = command.ExecuteReader();
while (reader.Read())
{
res = "1";
HttpContext.Current.Session["UID"] = reader["uid"].ToString(); //Either Remove Static from Method Declaration or use HttpContext.Current along with session.
HttpContext.Current.Session["UNAME"] = reader["username"].ToString();
}
}
return res;
con.Close();
}
}
Don't make your method static. It doesn't need to be static and it prevents you from using any non-static properties (like Session). Make it:
public string Login(string email, string password)
{
....
}
Also, don't concatenate SQL queries, especially with the values that come from the UI. This leaves you vulnerable to SQL injection. Use SQLParameters.
can you use it for insert a variable to the session :
HttpContext.Current.Session["UID"] = reader["uid"].ToString();
and don't use static
public string Login(string email, string password)
{
}
I have got a couple of questions. I am making gym management system to submit in my university. I implemented a service based database by reading the tutorials at www.homeandlearn.co.uk. The problem is I can not update it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Gym_Management_System
{
class GMSDConnectionClass
{
public string sql_string;
public string strCon;
public string Sql
{
set { sql_string = value; }
}
public string connection_string
{
set { strCon = value; }
}
public System.Data.DataSet GetConnection
{
get { return MyDataSet(); }
}
public System.Data.DataSet MyDataSet()
{
System.Data.SqlClient.SqlConnection con = new
System.Data.SqlClient.SqlConnection(strCon);
con.Open();
System.Data.SqlClient.SqlDataAdapter da_1 = new
System.Data.SqlClient.SqlDataAdapter(sql_string, con);
System.Data.DataSet dat_set = new System.Data.DataSet();
da_1.Fill(dat_set, "Table_data_1");
con.Close();
return dat_set;
}
public void UpdateDatabase(System.Data.DataSet ds)
{
System.Data.SqlClient.SqlCommandBuilder cb = new
System.Data.SqlClient.SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
}
}
The problem is that I can not access da_1 in UpdateDatabase() method.
What's wrong there? I have tried couple of things but I couldn't get it. It may be a simple problem but I am totally new to database and this stuff.
Note:
I have to submit this project on 23rd January 2014.
Variables cannot be accessed outside of their declaring scope. There are various scoping rules.. the one you're most concerned with here is method-scope. This might help explain:
public System.Data.DataSet MyDataSet()
{
// da_1 is delcared in this method.. it is only available here
...
System.Data.SqlClient.SqlDataAdapter da_1 = new
System.Data.SqlClient.SqlDataAdapter(sql_string, con);
...
}
public void UpdateDatabase(System.Data.DataSet ds)
{
// not available here
}
In order to access it across methods within a class.. you must declare it at class level:
class GMSDConnectionClass
{
System.Data.SqlClient.SqlDataAdapter da_1;
Then you can assign it like this in your other method:
da_1 = new System.Data.SqlClient.SqlDataAdapter(sql_string, con);
I don't see why I have to create a DbCommand object every time I need to call a stored procedure. So I'm trying to come up with a way to do that. I have tested my code (see below). But I would like to check with the community in case there is something I have missed. I would be using it with in an ASP.NET app. Is this code thread safe?
SharedDbCommand - wraps up the creation and storage of the DbCommand object
Db - the wrapper for the database, uses the SharedDbCommand via a static field and the ThreadStatic attribute
Program - the console app that starts threads and uses the Db object which
// SharedDbCommand.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data;
namespace TestCmdPrepare {
public class SharedDbCommand {
[ThreadStatic]
static DbCommand cmd;
public SharedDbCommand(string procedureName, ConnectionStringSettings dbConfig) {
var factory = DbProviderFactories.GetFactory(dbConfig.ProviderName);
cmd = factory.CreateCommand();
cmd.Connection = factory.CreateConnection();
cmd.Connection.ConnectionString = dbConfig.ConnectionString;
cmd.CommandText = procedureName;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
if (cmd is SqlCommand) {
try {
cmd.Connection.Open();
SqlCommandBuilder.DeriveParameters(cmd as SqlCommand);
} finally {
if (cmd != null && cmd.Connection != null)
cmd.Connection.Close();
}
}
}
public DbParameter this[string name] {
get {
return cmd.Parameters[name];
}
}
public IDataReader ExecuteReader() {
try {
cmd.Connection.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
} finally {
cmd.Connection.Close();
}
}
public void ExecuteNonQuery() {
try {
cmd.Connection.Open();
cmd.ExecuteNonQuery();
} finally {
cmd.Connection.Close();
}
}
}
}
// Db.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.Common;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Diagnostics;
namespace TestCmdPrepare {
public class Db {
ConnectionStringSettings dbSettings;
DbProviderFactory factory;
public Db() {
dbSettings = ConfigurationManager.ConnectionStrings["db"];
factory = DbProviderFactories.GetFactory(dbSettings.ProviderName);
}
IDataReader ExecuteReader(DbCommand cmd) {
cmd.Connection.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
private DbConnection CreateConnection() {
var c = factory.CreateConnection();
c.ConnectionString = dbSettings.ConnectionString;
return c;
}
DbCommand CreateCommand(string procedureName) {
var cmd = factory.CreateCommand();
cmd.Connection = CreateConnection();
cmd.CommandText = "get_stuff";
cmd.CommandType = CommandType.StoredProcedure;
if (cmd is SqlCommand) {
try {
cmd.Connection.Open();
SqlCommandBuilder.DeriveParameters(cmd as SqlCommand);
} finally {
cmd.Connection.Close();
}
}
return cmd;
}
[ThreadStatic]
static DbCommand get_stuff;
DbCommand GetStuffCmd {
get {
if (get_stuff == null)
get_stuff = CreateCommand("get_stuff");
return get_stuff;
}
}
public string GetStuff(int id) {
GetStuffCmd.Parameters["#id"].Value = id;
using (var reader = ExecuteReader(GetStuffCmd)) {
if (reader.Read()) {
return reader.GetString(reader.GetOrdinal("bar"));
}
}
return null;
}
[ThreadStatic]
static SharedDbCommand get_stuff2;
public string GetStuff2(int id) {
if (get_stuff2 == null)
get_stuff2 = new SharedDbCommand("get_stuff", dbSettings);
get_stuff2["#id"].Value = id;
using (var reader = get_stuff2.ExecuteReader()) {
if (reader.Read()) {
Thread.Sleep(1000);
return reader.GetString(reader.GetOrdinal("bar"));
}
}
return null;
}
}
}
// Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Configuration;
using System.Data.SqlClient;
using System.Threading;
namespace TestCmdPrepare {
class Program {
static void Main(string[] args) {
var db = new Db();
var threads = new List<Thread>();
for (int i = 0; i < 4; i++) {
var one = new Thread(Run2);
var two = new Thread(Run1);
threads.Add(one);
threads.Add(two);
one.Start();
two.Start();
Write(db, 1);
Write(db, 2);
}
Console.WriteLine("Joining");
foreach (var thread in threads) {
thread.Join();
}
Console.WriteLine();
Console.WriteLine("DONE");
Console.ReadLine();
return;
}
static void Write(Db db, int id) {
Console.WriteLine("2:{0}:{1}", Thread.CurrentThread.ManagedThreadId, db.GetStuff2(id));
Console.WriteLine("1:{0}:{1}", Thread.CurrentThread.ManagedThreadId, db.GetStuff(id));
}
static void Run1() {
var db = new Db();
Write(db, 1);
}
static void Run2() {
var db = new Db();
Write(db, 2);
}
}
}
Bad idea for lots of reasons. Others have mentioned some of them, but I'll give you one specific to your implementation: using ThreadStatic in ASP.NET will bite you eventually (see here). You don't control the pipeline, so it's possible for multiple threads to end up servicing one request (think between event handlers on a page, etc- how much code is running that isn't yours?). It's also easy to orphan data on a request thread you don't own due to unhandled exceptions. Might not be a showstopping problem, but best case you're looking at a memory leak and increased server resource usage while your connection just sits there...
I'd recommend you just let the ConnectionPool do its job- it has some warts, but performance isn't one of them compared to what else is going on in the ASP.NET pipeline. If you really want to do this, at least consider storing the connection object in HttpContext.Current.Items. You can probably make this work in limited circumstances, but there will always be gotchas, especially if you ever start writing parallel code.
Just $0.02 from a guy who's been there. :)
This is not a good practice to keep DbCommand created. Also, this makes your application very complex because of thread handling logic.
As Microsoft suggests you should create and dispose connection and command objects right after you have executed your query. They are very lightweight to create. No need to keep memory used with them - dispose them when your query execution is complete and you have fetched all of the results.
How to pass a class into another class to a codebehind?
When I debug and check the myCategoryObj in the Default.aspx page, I can see the object is in the debug. What am I doing wrong?
I know I could create the object in the Default.aspx but I should not have to I should be able to call the Business Logic Layer and ask for an object back and then fill the object and pass it back to the Business Logic Layer to be saved (insert or update).
I hope this makes sense.
Default.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SC1.Models.OBJ;
using SC1.Models.BLL;
using SC1.Models.DAL;
namespace SC1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(Object sender, EventArgs e)
{
// I know I could do this but I don't want to unless I have too.
//Category categoryObj = new Category();
CategoryBLL myCategoryBLL = new CategoryBLL();
Object myCategoryObj = myCategoryBLL.CategoryNew();
// How do I make the code below work or what am I doing wrong.
myCategoryObj.Name = "test";
string test = "";
}
}
}
CategoryBLL.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using SC1.Models.DAL;
using SC1.Models.OBJ;
namespace SC1.Models.BLL
{
public class CategoryBLL
{
// Create a page object
Category myCategoryObject = new Category();
// Create a Data Acces Layer Object
CategoryDAL myCategoryDAL = new CategoryDAL();
public CategoryBLL()
{
}
public DataSet Select()
{
return (myCategoryDAL.Select());
}
public Object CategoryNew()
{
return myCategoryObject;
}
}
}
CategoryDAL.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace SC1.Models.DAL
{
public class CategoryDAL
{
public CategoryDAL()
{
}
string connStr = ConfigurationManager.ConnectionStrings["staceys_cakesConnectionString"].ConnectionString;
// select all
public DataSet Select()
{
SqlConnection sqlConnection1 = new SqlConnection();
string SqlString = "select * from Categories";
SqlDataAdapter da = new SqlDataAdapter(SqlString, connStr);
DataSet ds = new DataSet();
da.Fill(ds, "Categories");
return (ds);
}
// save
// insert
// update
// delete
}
}
Category.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SC1.Models.OBJ
{
public class Category
{
public int CategoryID { get; set; }
public int ParentID { get; set; }
public string Name { get; set; }
public int DisplayOrder { get; set; }
public bool Active { get; set; }
public Category(){
}
}
}
change
Object myCategoryObj = myCategoryBLL.CategoryNew()
to
Category myCategoryObj = myCategoryBLL.CategoryNew()
and also
public Object CategoryNew()
{
return myCategoryObject;
}
to
public Category CategoryNew()
{
return myCategoryObject;
}