System.Data.OracleClient.OracleConnection does not contain a definition - c#

I got this error CS1061: 'System.Data.OracleClient.OracleConnection' does not contain a definition for 'searchDBSet' and no extension method 'searchDBSet' accepting a first argument of type 'System.Data.OracleClient.OracleConnection' could be found (are you missing a using directive or an assembly reference?). I'm sure I have the reference which System.Data;and I think I have the issue with the inheritance because my code is not recognized.Can anyone please help solve this issue.Thank you
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Data.OracleClient;
public partial class users_Login : System.Web.UI.Page
{
OracleConnection oc = new OracleConnection("Data Source=**;Persist Security Info=True;User ID=****;Password=****;Unicode=false");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
int flag = 0;
string user_name = loginUserName.Text;
string password = loginPassword.Text;
string qry = "select user_name,password from users where user_name='" + user_name + "' and password='" + password + "'";
DataSet set = oc.searchDBSet(qry);
foreach (DataRow dr in set.Tables[0].Rows)
{
flag = 1;
}
if (flag == 1)
{
FormsAuthentication.RedirectFromLoginPage(user_name, true);
}
else
{
lblMessage.Visible = true;
}
}
}
my class1 code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.OracleClient;
public class Oracleconection
{
string connectionString;
private System.Data.OracleClient.OracleConnection connection;
private System.Data.OracleClient.OracleDataAdapter adapter;
private System.Data.OracleClient.OracleCommand command;
public Oracleconection(string host, string dbname, string username, String password)
{
try
{
//this.connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST="+host+")(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME="+dbname+")));User Id="+username+";Password="+password+";";
this.connectionString = "Data Source=****;Persist Security Info=True;User ID=****;Password=****;Unicode=false";
this.connection = new System.Data.OracleClient.OracleConnection(this.connectionString);
this.connection.Open();
this.command = connection.CreateCommand();
Console.WriteLine("Connected");
}
catch (Exception e)
{
Console.WriteLine("Error while connecting:" + e.Message);
}
}
public DataTable searchDB(string query)
{
DataTable table = new DataTable();
try
{
this.command.CommandText = query;
this.adapter = new System.Data.OracleClient.OracleDataAdapter(command);
this.adapter.Fill(table);
}
catch (Exception e)
{
Console.Write("Error:" + e);
}
return table;
}
public DataSet searchDBSet(string query)
{
DataSet ds = new DataSet();
try
{
this.command.CommandText = query;
this.adapter = new System.Data.OracleClient.OracleDataAdapter(command);
this.adapter.Fill(ds);
}
catch (Exception e)
{
Console.Write("Error:" + e);
}
return ds;
}
public int updateDB(string query)
{
try
{
this.command.CommandText = query;
return this.command.ExecuteNonQuery();
}
catch (Exception e)
{
Console.Write("Error:" + e);
return -1;
}
}
public void close()
{
connection.Close();
}
}

The class name is wrong.
You are doing this:
OracleConnection oc = new OracleConnection(...);
Change to your class:
Oracleconnection oc = new Oracleconnection(...);

Related

Unable to access functions from another class (C# Windows Form, SQL Server Management Studio)

I'm learning database connectivity using C# Windows Form Application in Visual Studio and SQL Server Management Studio.
The problem I'm having is I'm unable to access the AddParams() and sqlQueryCmd() functions from the SQLConn.cs Class.
I've tried changing the access modifiers from private to public but it didn't work. Can anyone guide me here? I don't know what I'm doing wrong.
SQLConn.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Microsoft.Data.SqlClient;
namespace dbConnectivityTest1
{
public class SQLConn
{
public static void Main1(string[] args)
{
using (SqlConnection connString = new SqlConnection("Server=ServerName;Database=DatabaseName;User Id=UserID;\r\nPassword=Password;"))
{
List<SqlParameter> paramList = new List<SqlParameter>();
string AddParams(string tableName, object insVal)
{
SqlParameter sqlparams = new SqlParameter(tableName, insVal);
paramList.Add(sqlparams);
}
SqlCommand sqlCmd = new SqlCommand();
string sqlQueryCmd(string sqlQuery)
{
int recordCount = 0;
string excptnShow = "";
try
{
connString.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, connString);
paramList.ForEach(p => { sqlCmd.Parameters.Add(p); });
paramList.Clear();
DataTable sqlDT = new DataTable();
SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCmd);
recordCount = sqlDA.Fill(sqlDT);
}
catch(Exception ex)
{
excptnShow = "Error: \r\n" + ex.Message;
}
finally
{
if (connString.State == ConnectionState.Open)
{
connString.Close();
}
}
}
}
}
}
}
Form1.cs
namespace dbConnectivityTest1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private SQLConn sqlDB = new SQLConn();
private void enterNametextBox_Click(object sender, EventArgs e)
{
enterNametextBox.Clear();
}
private void submitButton_Click(object sender, EventArgs e)
{
while(fullNameTextBox.Text.Length <= 0)
{
MessageBox.Show("Please enter your Full Name!", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
}
while(contactTextBox.Text.Length <= 0)
{
MessageBox.Show("Please enter your Contact Number!", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
}
while(ageTextBox.Text.Length <= 0)
{
MessageBox.Show("Please enter your Age!", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
}
while(emailTextBox.Text.Length <= 0)
{
MessageBox.Show("Please enter your E-mail!", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
}
System.Text.RegularExpressions.Regex emailRegex = new System.Text.RegularExpressions.Regex(#"^[a-zA-Z0-9+_.-]+#[a-zA-Z0-9.-]+$");
while(!emailRegex.IsMatch(emailTextBox.Text))
{
MessageBox.Show("Please enter a valid E-mail!", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
}
InsVal();
}
public void InsVal()
{
**I am trying to call the SQLConn.cs Functions here**
}
}
}
Movint addParam method/function would not solve the problem since the SqlParam variable is not available in sqlConn class.
the better approach for your goal is to to this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace dbConnectivityTest1
{
public class SQLConn
{
private readonly string _connectionString;
private List<SqlParameter> _paramList;
public SQLConn()
{
_connectionString="Server=ServerName;Database=DatabaseName;User Id=UserID;\r\nPassword=Password;";
_paramList = new List<SqlParameter>();
}
public void AddParams(string tableName, object insVal)
{
SqlParameter sqlparams = new SqlParameter(tableName, insVal);
_paramList.Add(sqlparams);
}
public void sqlQueryCmd(string sqlQuery)
{
using (var sqlConn = new SqlConnection(_connectionString))
{
int recordCount = 0;
string excptnShow = "";
try
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
_paramList.ForEach(p => { sqlCmd.Parameters.Add(p); });
_paramList.Clear();
DataTable sqlDT = new DataTable();
SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCmd);
recordCount = sqlDA.Fill(sqlDT);
}
catch (Exception ex)
{
excptnShow = "Error: \r\n" + ex.Message;
}
finally
{
if (sqlConn.State == ConnectionState.Open)
{
sqlConn.Close();
}
}
}
}
}
}
in this scenario there is no need for Main method since every application can have only one Main method and winForms by default already have one Main method.
secondly, the SQLConn class can have private field of type List,
and a public method called AddParam which its responsibility is to add new params to it.
Lastly, a public SqlQueryCmd method is added to do the rest of the job.
you can now use this class to execute your query like this:
private void button1_Click(object sender, EventArgs e)
{
var sqlConn = new SQLConn();
sqlConn.AddParams("tableName","your Object");
sqlConn.AddParams("tableName","your Object");
sqlConn.AddParams("tableName","your Object");
sqlConn.sqlQueryCmd("Query");
}

How to enter item from datatable into textbox

First C# form app for me. I can write it in POSH, but I'm trying to graduate and understand C#. I know I have a long way to go, but if someone could help explain this, I would be grateful.
I have a simple SQL table with the following: CLIENT, INPATH, OUTPATH, LIMITERS (PK)
LIMITERS have Unique Values
For each CLIENT, INPATH and OUTPATH are the same.
I am trying to create a form that does the following:
Display a listbox with distinct CLIENT -Working
--- The rest is not working ---
On ListBox Click:
Fill TextBox with INPATH for selected CLIENT
Fill TextBox with OUTPATH for selected CLIENT
Fill ListBox with LIMITERS for selected CLIENT
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 Microsoft.Data.SqlClient;
namespace DSI_SFTP_FrontEnd
{
public partial class ClientMain : Form
{
private SqlDbConnect con;
public ClientMain()
{
InitializeComponent();
con = new SqlDbConnect();
con.SqlQuery("Select Distinct CLIENT from Client_Inf");
clientListBoxValues.Items.Clear();
foreach (DataRow dr in con.QueryEx().Rows)
{
clientListBoxValues.Items.Add(dr[0].ToString());
}
}
private void clientListBoxValues_SelectedIndexChanged(object sender, EventArgs e)
{
string text = clientListBoxValues.GetItemText(clientListBoxValues.SelectedItem);
if (text != null)
{
InitializeComponent();
string sql = $"Select INPATH, OUTPATH, LIMITERS from Client_Inf where CLIENT = '{text}'";
con = new SqlDbConnect();
con.SqlQuery(sql);
DataTable dataTable = con.QueryEx();
{
inPathTextBoxValue.Text = dataTable.Rows[0]["INPATH"].ToString();
outPathTextBoxValue.Text = dataTable.Rows[0]["OUTPATH"].ToString();
}
foreach (DataRow dr in dataTable.Rows)
{
limitersListBoxValues.Items.Add(dr[2].ToString());
}
}
}
private void createNewbutton_Click(object sender, EventArgs e)
{
NewClientForm frm = new NewClientForm();
frm.ShowDialog();
}
private void cancelButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
SqlDbConnect.cs
using System.Data;
namespace DSI_SFTP_FrontEnd
{
public class SqlDbConnect
{
private SqlConnection _con;
public SqlCommand _cmd;
private SqlDataAdapter _da;
private DataTable _dt;
public SqlDbConnect()
{
_con=new SqlConnection("Server=<SERVER>;Database=<DB>;Trusted_Connection=True;TrustServerCertificate=True;");
_con.Open();
}
public void SqlQuery(string queryText)
{
_cmd= new SqlCommand(queryText, _con);
}
public DataTable QueryEx()
{
_da = new SqlDataAdapter(_cmd);
_dt= new DataTable();
_da.Fill(_dt);
return _dt;
}
public void NonQueryEx()
{
_cmd.ExecuteNonQuery();
}
}
}
The problem is that you are calling InitializeComponent() in clientListBoxValues_SelectedIndexChanged. InitializeComponent() creates the controls, .i.e., the TextBoxes and ListBoxes, etc. The effect is that you are creating another set of those controls every time the selected index of the ListBox changes.
InitializeComponent() must be called once in the constructor ClientMain() and nowhere else!

Why does ap.Connect(authrequest) return a null value?

I am having a problem with my code where i run into an error when i try to click the join button. It says the ap.Connect(authrequest) is returning a null value so it cannot return a bool value. I am doing this in visual studio in a .net forms i think.
Thanks for you help.
Ps i am a student
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 SimpleWifi;
namespace desk_flat
{
public partial class formConnect : Form
{
private static Wifi wifi;
public formConnect()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
wifi = new Wifi();
List<AccessPoint> aps = wifi.GetAccessPoints();
foreach (AccessPoint ap in aps)
{
ListViewItem listobj = new ListViewItem(ap.Name);
listobj.SubItems.Add(ap.SignalStrength + "'''");
listobj.Tag = ap;
lstWifi.Items.Add(listobj);
}
}
private bool ConnectWifi(AccessPoint ap, string password)
{
AuthRequest authrequest = new AuthRequest(ap);
authrequest.Password = password;
return ap.Connect(authrequest);
}
private void btnJoin_Click(object sender, EventArgs e)
{
if (lstWifi.Items.Count > 0 && txtbPassword.Text.Length > 0)
{
ListViewItem selectedItem = lstWifi.SelectedItems[0];
AccessPoint ap = (AccessPoint)selectedItem.Tag;
if (ConnectWifi(ap, txtbPassword.Text))
{
lblStatus.Text = "You have connected to " + ap.Name;
}
else
{
lblStatus.Text = "Connection has failed";
}
}
else
{
lblStatus.Text = "Enter a password or select a network";
}
}
}
}

Display a logged in users info

I have a program where the user has to login, so they have a id and password. The database with the user login details are stored in a local .mdf file.
I would like to set it up so that whilst the user is logged in, the rest of the program shows their details in the top right corner, so for example their name and their id.
I unfortunately have no idea how to do this and all I have seen whilst I browsed around is people using the actual System login, which is not what I want.
Code for login form:
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.SqlClient;
namespace InventoryManager
{
public partial class frmLogin : Form
{
public frmLogin()
{
InitializeComponent();
}
private void frmLogin_Load(object sender, EventArgs e)
{
this.AcceptButton = btnSubmit;
}
string cs = #"Data Source= (LocalDB)\v11.0;AttachDbFilename=|DataDirectory|Users.mdf;Integrated Security = True;";
private void btnSubmit_Click(object sender, EventArgs e)
{
if (txtUserID.Text == "" || txtPassword.Text == "")
{
MessageBox.Show("Please enter a User ID and Password");
return;
}
try
{
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("SELECT * FROM tbl_Login WHERE UserID = #userid AND Password = #password", con);
cmd.Parameters.AddWithValue("#userid", txtUserID.Text);
cmd.Parameters.AddWithValue("#password", txtPassword.Text);
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapt.Fill(ds);
con.Close();
int count = ds.Tables[0].Rows.Count;
if (count == 1)
{
MessageBox.Show("Login Successful!");
this.Hide();
frmOverview fo = new frmOverview();
fo.Show();
}
else
{
MessageBox.Show("Login Failed");
txtPassword.Text = "";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
You can make some static class like this one
public static class LoggedUser
{
public static string Name { get; set; }
public static string Username { get; set; }
}
after successful login, populate that class with data (in example):
if (count == 1)
{
MessageBox.Show("Login Successful!");
LoggedUser.Name = ds.Tables[0].Rows[1].ToString();
LoggedUser.Username = ds.Tables[0].Rows[2].ToString();
this.Hide();
frmOverview fo = new frmOverview();
fo.Show();
}
later, you can use data stored in LoggedUser class on every form in your project...

How to create class in asp.net with c#

i have problem in create class
i have 1 class called "lib" :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
/// <summary>
/// Summary description for lib
/// </summary>
public class lib
{
public static SqlConnection con;
public static void constr()
{
lib.con = new SqlConnection();
lib.con.ConnectionString = "Data Source=(local);Initial Catalog=FroumDB;Persist Security Info=True;User ID=sa;Password=123";
}
//insert
public static SqlCommand cmd;
public static void insert(string TableName ,string FieldNames, string values)
{
lib.constr();
lib.cmd = new SqlCommand("insert into " + TableName + " (" + FieldNames + ") values(" + values + ")", lib.con);
lib.cmd.CommandType = CommandType.Text;
lib.con.Open();
lib.cmd.ExecuteNonQuery();
lib.con.Close();
}
}
and in webform i used:
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.Data.SqlClient;
public partial class ForumPost : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string t = "TPost";
string f = "PostTitle,PostQuestion";
string v = "#pt,#pq";
lib.insert(t, f, v);
lib.cmd.Parameters.AddWithValue("#pt", this.tbxTitle.Text);
lib.cmd.Parameters.AddWithValue("#pq", this.tbxText.Text);
lblshow.Text = "submited !!!";
}
}
but when i play debug give me this error:
Must declare the scalar variable "#pt".
from this code "lib.cmd.ExecuteNonQuery()"
and this error in browser:
Must declare the scalar variable "#pt".
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Must declare
the scalar variable "#pt".
Source Error:
Line 27: Line 28: lib.con.Open(); Line 29:
lib.cmd.ExecuteNonQuery(); Line 30: lib.con.Close(); Line 31:
}
how can i fix this error ?
Try this:
var db = Database.open(/*your database*/);
string sqlcommand = "insert into TPost (PostTitle,PostQuestion,PostAnserw) values(#0,#1,#2)";
db.Execute(sqlcommand,param0,param1,param2);
There are also some security reasons to use #0,#1 like preventing sql injections.
i found answer:
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.Data.SqlClient;
public partial class ForumPost : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string t = "TPost";
string f = "PostTitle,PostQuestion";
string v = "#pt,#pq";
lib.insert(t, f, v);
lib.cmd.Parameters.AddWithValue("#pt", this.tbxTitle.Text);
lib.cmd.Parameters.AddWithValue("#pq", this.tbxText.Text);
lib.con.Open();
lib.cmd.ExecuteNonQuery();
lib.con.Close();
lblshow.Text = "submited !!!";
}
}

Categories