The "clsDataLayer" does not exists in current context - c#

I have been trying to figure this out for hours now, I know there is some small error that I have here but I am not able to pinpoint it. Please help me.
So I created a class called "clsDataLayer.cs" and it is in the App_Code asp.net folder.
I then created a form called "frmUserActivity", but now when I post the code in it and call the class it says "The "clsDataLayer" does not exists in current context" Can anyone please help me?
code for clsDataLayer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
// Add your comments here
using System.Data.OleDb;
using System.Net;
using System.Data;
namespace ASP_PayRoll.App_Code
{
public class clsDataLayer
{
// This function gets the user activity from the tblUserActivity
public static dsUserActivity GetUserActivity(string Database)
{
// Add your comments here
dsUserActivity DS;
OleDbConnection sqlConn;
OleDbDataAdapter sqlDA;
// Add your comments here
sqlConn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
// Add your comments here
sqlDA = new OleDbDataAdapter("select * from tblUserActivity", sqlConn);
// Add your comments here
DS = new dsUserActivity();
// Add your comments here
sqlDA.Fill(DS.tblUserActivity);
// Add your comments here
return DS;
}
// This function saves the user activity
public static void SaveUserActivity(string Database, string FormAccessed)
{
// Add your comments here
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
strSQL = "Insert into tblUserActivity (UserIP, FormAccessed) values ('" +
GetIP4Address() + "', '" + FormAccessed + "')";
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
command.ExecuteNonQuery();
conn.Close();
}
// This function gets the IP Address
public static string GetIP4Address()
{
string IP4Address = string.Empty;
foreach (IPAddress IPA in
Dns.GetHostAddresses(HttpContext.Current.Request.UserHostAddress))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
if (IP4Address != string.Empty)
{
return IP4Address;
}
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}
}
}
Code for frmUserActivity.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ASP_PayRoll
{
public partial class frmUserActivity : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Declare the DataSet
dsUserActivity myDataSet = new dsUserActivity();
//Fill the dataset with what is returned from the function
myDataSet = clsDataLayer.GetUserActivity(Server.MapPath("PayrollSystem_DB.mdb"));
//Sets the DataGrip to the DataSource based on the table
grdUserActivity.DataSource = myDataSet.Tables["tblUserActivity"];
//Binds the DataGrid
grdUserActivity.DataBind();
}
}
}
}
Thanks in advance.
Ak

Use ASP_PayRoll.App_Code.clsDataLayer. Your namespace in your data layer class is ASP_PayRoll.App_Code and in your page it's ASP_PayRoll.

Add using ASP_PayRoll.App_Code; to your aspx file.
Since you declared that in a namespace other than the one of your aspx page, you have to use a using statement, or the entire path (ASP_PayRoll.App_Code.clsDataLayer) in order to be able to access that class.

Related

C# Cannot convert string to int error when im not even trying to convert it to int

Hello can someone please help me? when i am trying to get a string value from a table on my sql server database table it says that i can not convert string to int, but i dont want to convert the value to int. as the values in the table are "Admin" and "General User".
by the way i am using sql server 2014
the variable that i use to capture the string is cap and i declared it as a string.
and when i write the code.
conn.Open();
string query_inicio = "select * from usuarios where USU_Usuario = '" + txtusuario.Text + "' AND USU_Contra ='" + txtcontra.Text + "'";
SqlCommand exe_query_inicio = new SqlCommand(query_inicio, conn);
SqlDataReader leer_exe;
try
{
leer_exe = exe_query_inicio.ExecuteReader();
if (leer_exe.Read())
{
cap = leer_exe.GetString("Admin");
MessageBox.Show("CONECTADO");
if (cap.Equals("Admin"))
{
Reporte_Detallado IB = new Reporte_Detallado();
IB.Show(this);
this.Hide();
}
}
else if (leer_exe.Read() == false)
{
MessageBox.Show("Inicio Fallido, Verifique Conexion");
}
it underlines the cap = leer_exe.GetString("Admin"); and says that i can't convert string to int.
i have the same code using a mysql datbase and it works. now i am trying to do it with microsoft sql server. so the only thing i changed from the mysql version was instead of mysqlconection and those database code lines to sqlconnection and the other variations.
here is my complete code. i hope someone can help me.
by the way i am coding in c#.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace ClimateReports
{
public partial class Login : Form
{
SqlConnection conn = ConexionBD.ObtenerConexion();
string cap;
public Login()
{
InitializeComponent();
}
private void btncancelar_Click(object sender, EventArgs e)
{
this.Dispose();
}
private void btniniciar_Click(object sender, EventArgs e)
{
conn.Open();
string query_inicio = "select * from usuarios where USU_Usuario = '" + txtusuario.Text + "' AND USU_Contra ='" + txtcontra.Text + "'";
SqlCommand exe_query_inicio = new SqlCommand(query_inicio, conn);
SqlDataReader leer_exe;
try
{
leer_exe = exe_query_inicio.ExecuteReader();
if (leer_exe.Read())
{
cap = leer_exe.GetSqlString("Admin");
MessageBox.Show("CONECTADO");
if (cap.Equals("Admin"))
{
Reporte_Detallado IB = new Reporte_Detallado();
IB.Show(this);
this.Hide();
}
}
else if (leer_exe.Read() == false)
{
MessageBox.Show("Inicio Fallido, Verifique Conexion");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn.Close();
}
}
}
The problem is this line:
cap = leer_exe.GetString("Admin");
GetString takes an int32 as its argument.
If you want to access a column by its name, you should use Item instead:
cap = leer_exe["Admin"] as string;
Or, if you know what column "Admin" is, you can replace it with its position index. If it's the 4th column in the resultset, you'd use index 3 (because it's base 0):
cap = leer_exe.GetString(3);

How do I write a database driven dropdown selection to a label?

Another ASP.NET C# noobie question...
The following codebehind populates a dropdown list from a database. There are three columns in the table (ID, ItemType & BinType). I need to be able to return the correct BinType for the row selected by the user:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Data.OleDb;
public partial class _Default : System.Web.UI.Page
{
// Global variable for SqlConnection
OleDbConnection con = new OleDbConnection();
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// specifying sqlconnection string
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString_GRPAS_dev"].ConnectionString;
{
// Select rows from database where the ItemType field isn't empty. Sort them alphabetically by ItemType
using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM NF_WhatWasteWhere WHERE ItemType <>'' Order By ItemType"))
{
//Open the connection and populate the dropdown list with ID and Itemtype
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
ItemType1.DataSource = cmd.ExecuteReader();
ItemType1.DataTextField = "ItemType";
ItemType1.DataValueField = "ID";
ItemType1.DataBind();
con.Close();
}
}
// Add a non selectable "Select Item" row at the top of the dropdown list
ItemType1.Items.Insert(0, new ListItem("--Select Item--", "0"));
}
}
protected void ItemType1_SelectedIndexChanged(object sender, EventArgs e)
{
//
// *** Stuff needs to go here in order to continue with the following conditional statement ***
//
if (ItemType1.SelectedValue == "Green")
{
BinResultTest.Text = "<div class='greenBin results'><div class='arrow'></div><p>" + ItemType1.SelectedItem + " should be disposed of in a <strong>green bin</strong>.</p></div>";
}
else if (ItemType1.SelectedValue == "Black")
{
BinResultTest.Text = "<div class='blackBin results'><div class='arrow'></div><p>" + ItemType1.SelectedItem + " should be disposed of in a <strong>black bin</strong>.</p></div>";
}
else
{
BinResultTest.Text = "<div class='noBin results'><div class='arrow'></div><p>" + ItemType1.SelectedItem + " should <strong>NOT</strong> be disposed of in a green or black bin.</p></div>";
}
}
}
What do I need to do to get the conditional statement to work? I presume I need to run another database query - something like the following:
SELECT BinType FROM NF_WhatWasteWhere WHERE ID=" + ItemType1.DataValueField
However, I'm not sure how to code this to establish the connection and return the result.
Any help appreciated.
Thanks.
Edit***
Okay then in protected void ItemType1_SelectedIndexChanged(object sender, EventArgs e)
You can do something similar to what you did with your first query but use an OdbcDataReader
string binValue;
int idHolder = ItemType1.SelectedValue;
con.ConnectionString =System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString_GRPAS_dev"].ConnectionString;
{
using (OleDbCommand cmd = new OleDbCommand("SELECT BinType FROM NF_WhatWasteWhere WHERE ID = #Id;"))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Id",idHolder);
cmd.Connection = con;
con.Open();
OleDbDataReader reader = cmd.ExecuteReader();
if(reader.Read())
{
if(!DBNull.Value.Equals(reader["BinType"]))
{
binValue = Convert.ToString(reader["BinType"]);
}
}
con.Close();
//Then all your conditionals based off of binValue....
Something like this but maybe a bit more well writen.

C# how to insert data to mysql using C#?

Im very new on C#
I Only create 1 Form that Can insert Data to Mysql Database. My code not have Error, but data cant enter the Database. I m so confused.
this my code
Koneksi.cs
using System;
using System.Data;
using MySql.Data.MySqlClient;
using System.Drawing;
using System.Windows.Forms;
namespace timbangan
{
public class Koneksi
{
public MySqlConnection konek;
//string konfigKoneksi = "server=localhost; database=timbangan; uid=root; pwd=";
string konfigKoneksi = "Server=localhost;Database=timbangan;Uid=root;Pwd=";
public void bukaKoneksi()
{
konek = new MySqlConnection(konfigKoneksi);
konek.Open();
var temp = konek.State.ToString();
if (temp == "Open")
{
MessageBox.Show(#"Connection working.");
}
else {
MessageBox.Show(#"Please check connection string");
}
}
public void tutupKoneksi()
{
konek = new MySqlConnection(konfigKoneksi);
konek.Close();
}
}//end of koneksi
}//end namespace
Isidata.cs File
using System;
using System.Data;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
namespace timbangan
{
public class Isidata
{
MySqlDataAdapter adapter;
MySqlCommand komand;
Koneksi classKoneksi;
DataTable tabel;
string sql = "";
public DataTable tambahData(string berat_filter, string qty, string nama_barang, string dari, string shift)
{
classKoneksi = new Koneksi();
sql = "insert into tb_timbang(BERAT_FILTER,QTY,NAMA_BARANG,DARI,SHIFT) values (" + berat_filter + ",'" + qty + "','" + nama_barang + "','" + dari + "','" + shift + "')";
//MessageBox.Show(sql);
tabel = new DataTable();
try
{
classKoneksi.bukaKoneksi();
komand = new MySqlCommand(sql);
adapter = new MySqlDataAdapter(sql, classKoneksi.konek);
adapter.Fill(tabel);
}
catch (Exception)
{
MessageBox.Show("error");
}
return tabel;
}
}//end of issdata
}//end of timbangan
Form1.cs File
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
namespace timbangan
{
public partial class Form1 : Form
{
public DataTable tabel;
public string status = "";
public string berat_filter, qty, nama_barang, dari, shift;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Isidata isi = new Isidata();
tabel = isi.tambahData(tbBerat.Text, tbQty.Text, tbNama.Text, tbDari.Text, tbShift.Text);
MessageBox.Show("Berhasil");
}
}
}
Can Anyone Help me to Fix this? or Advice me to have more short code to Insert data?
Thanks in advance
You could redesign your classes to something like this
namespace timbangan
{
public static class Koneksi
{
public static MySqlConnection konek;
private static string konfigKoneksi = "Server=localhost;Database=timbangan;Uid=root;Pwd=";
public static MySqlConnection GetConnection()
{
konek = new MySqlConnection(konfigKoneksi);
konek.Open();
}
}//end of koneksi
public class Isidata
{
public int InsertData(string berat_filter, string qty, string nama_barang, string dari, string shift)
{
sql = #"insert into tb_timbang
(BERAT_FILTER,QTY,NAMA_BARANG,DARI,SHIFT)
values (#berat_filter,#qty,#nama_barang,#dari,#shift)";
try
{
using(MySqlConnection cnn = Koneksi.GetConnection())
using(MySqlCommand cmd = new MySqlCommand(sql, cnn))
{
cmd.Parameters.Add("#berat_filter", MySqlDbType.VarChar).Value = berat_filter;
cmd.Parameters.Add("#qty", MySqlDbType.VarChar).Value = qty;
cmd.Parameters.Add("#name_barang", MySqlDbType.VarChar).Value = nama_barang;
cmd.Parameters.Add("#dari", MySqlDbType.VarChar).Value = dari;
cmd.Parameters.Add("#shift", MySqlDbType.VarChar).Value = shift;
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("error " + ex.Message);
return -1;
}
}
}
}//end of issdata
}//end of timbangan
In this design there are no more global variables around. The same Koneski class could be totally removed and your MySqlConnection could be created on the spot (reading the connectionstring from an external source like your config file). Don't think this is less efficient than keeping a global connection object already created and always open. There is an ADO.NET Connection Pooling infrastructure (link is for Sql Server but it is the same for MySql) that runs very efficiently to handle your connections
The important thing is the Using Statement (that closes and dispose the command and the connection when no more needed freeing valuable resources) and the parameters used to fill the command sent to the server. If you need to use an Adapter for other aspect of your work you could add other methods like this to your Isidata class
As a last note, notice that all parameters are of string type. This could work but it is best to have parameters of the same type of the field type on the database (and of course your variables should be of the correct datatype). This is particularly important with datetime fields that when are treated as strings could give a good headache to let them work correctly) See MySqlDbType enum
Make a class named DBClass.cs and write the below code-
class DBClass
{
MySqlCommand odcmd = new MySqlCommand();
MySqlConnection odcon = new MySqlConnection();
MySqlDataAdapter oda = new MySqlDataAdapter();
public DBClass()
{
}
public void OpenConnection()
{
odcon.ConnectionString = "Server=localhost;Database=timbangan;Uid=root;Pwd=";
if (odcon.State == ConnectionState.Closed)
odcon.Open();
oda.SelectCommand = odcmd;
odcmd.Connection = odcon;
}
public void CloseConnection()
{
if (odcon.State == ConnectionState.Open)
odcon.Close();
}
public DataTable Select(string sql)
{
DataTable dt = new DataTable();
odcmd.CommandText = sql;
oda.Fill(dt);
return dt;
}
public int ModiFy(string sql)
{
odcmd.CommandText = sql;
return odcmd.ExecuteNonQuery();
}
}
On your form, Now you can fire your query like-
DbclassObject.Modify(Your_Insert_Update_Delete_Query);
DataTable dt= DbclassObject.Select(Your_Select_Query);

Close firefox webpage and debug

My following code has two problems.
1- It doesn't go to the next row in dataset (when I run it, it just run firefox for 2916 times). I change this it from
var test = url.Replace("<userid>", Convert.ToString(row[userID]));
to
var test = url.Replace("<userid>", Convert.ToString(row["userID"]));
but it shows an error (Column 'userid' does not belong to table).
2- I want to close the firefox webpage page at the end of each loop and for next loop it runs again(because of performance issue)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Net;
namespace test2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\hidden.accdb";
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from hidden";
DataTable dt = new DataTable();
//To read data from dataset
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = cmd;
//Store the userID
adapter.Fill(dt);
int userid=0,trackid=0;
int counter=0;
foreach(DataRow row in dt.Rows)
{
string url = "http://abcd/<userid>?groups=<userid>";
var test = url.Replace("<userid>", Convert.ToString(row[userid]));
System.Diagnostics.Process.Start(url);
string client = (new WebClient()).DownloadString("http://abcd/userid?groups=userid");
if (client.ToLower() == (Convert.ToString(trackid).ToLower()))
{
counter++;
}
int ave = counter / 2916;
MessageBox.Show("Average = " + counter);
}
conn.Close();
}
}
}
string url = "http://abcd/<userid>?groups=<userid>";
var test = url.Replace("<userid>", Convert.ToString(row["userid"])); // You need ""
System.Diagnostics.Process.Start(test); // You should use variable test, which contains your url with <userid> replaced.

Arithmetic operation resulted in an overflow error c#

Hello i'm using c# to build an application to connect to remote mysql server.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace login
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (tryLogin(textBox1.Text, textBox2.Text) == true)
{
MessageBox.Show("Authed!");
}
else
{
MessageBox.Show("Auth Failure.");
}
}
public bool tryLogin(string username, string password)
{
MySqlConnection con = new MySqlConnection("host=myhostname;user=myusername;password=mypassword;database=mydatabase;");
MySqlCommand cmd = new MySqlCommand("SELECT * FROM test WHERE username = '" + username + "' AND password = '" + password + "';");
cmd.Connection = con;
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read() != false)
{
if (reader.IsDBNull(0) == true)
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return false;
}
else
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return true;
}
}
else
{
return false;
}
}
}
}
It shows the following error:
"OverflowException was unhandled
Arithmetic operation resulted in an overflow "
I'm not using any arithmetic operations here. Any help ???
Check the test table in mysql server.
Make sure that all fields have valid values in the username and password columns.
UPDATE
try to include the option "Use Pipe=false;",with your connection string.Then it will opens the connection just fine.
I hope this will help to you.

Categories

Resources