ODP.Net Unable to receive OracleDependency Notifications - asp.net

I am trying to get a notification in ASP.Net console application whenever a column value changes in a specific database column using OracleDependency. Notification gets Registered and inserted in USER_CHANGE_NOTIFICATION_REGS table but onChange event is not triggered when row is updated in DB.
Additionally, I have granted following privilege to user:
grant change notification to hasan;
and my firewall is also currently disabled.
Below is the code to register query:
string constr = "User ID=hasan;Data Source=10.32.157.5:1521/iwin;Password=hasan; Min Pool Size=1; Connection Lifetime = 120;";
OracleConnection con = null;
OracleDependency dep = null;
con = new OracleConnection(constr);
OracleCommand cmd = new OracleCommand("select * from hasan.Emp", con);
con.Open();
OracleDependency.Port = 2010;
dep = new OracleDependency(cmd);
dep.OnChange +=
new OnChangeEventHandler(OnMyNotificaton);
OracleDataAdapter ad = new OracleDataAdapter(cmd);
cmd.ExecuteNonQuery();
OracleTransaction txn = con.BeginTransaction();
string updateCmdText =
"update hasan.Emp empl set empl.empId = empl.empId + 1";
OracleCommand updateCmd = new OracleCommand(updateCmdText, con);
updateCmd.ExecuteNonQuery();
txn.Commit();
Event Listener:
public static void OnMyNotificaton(object src,
OracleNotificationEventArgs arg)
{
Console.WriteLine("Notification Received");
DataTable changeDetails = arg.Details;
Console.WriteLine("Data has changed in {0}",
changeDetails.Rows[0]["ResourceName"]);
IsNotified = true;
}

Related

Using stored procedure to login Asp.net

I'm using asp.net to create a login page; in debugging I see the correct inputted data but I keep gettting the error message Invalid Username or Password even when it is valid. I have also executed the stored procedure with values and shows the correct result. I'm not sure what is happening.
protected void login_Click(object sender, EventArgs e)
{
String username = txtUserName.Text.ToString();
String password = txtPassword.Text;
string con = ConfigurationManager.ConnectionStrings["LoginConnectionString"].ToString();
SqlConnection connection = new SqlConnection(con);
connection.Open();
string passwords = encryption(password);
SqlCommand cmd1 = new SqlCommand("spLogin", connection);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#UserName", username);
cmd1.Parameters.AddWithValue("#password", passwords);
SqlDataReader sqldr = cmd1.ExecuteReader();
if (sqldr.Read())
{
Session["UserName"] = username.ToUpper();
Response.Redirect("~/Home/Welcome.aspx");
}
else
{
lblError.Text = "Invalid Username or Password";
}
connection.Close();
sqldr.Close();
}
StoredProcedure
select * from Users u where UserName=#UserName and password=#password

ASP.Net db connection issue

I'm new to ASP.Net & SQL Server and have the following code:
protected void btnShowData_Click(object sender, EventArgs e)
{
string connectionString;
SqlConnection cnn;
connectionString = #"Data Source=DESKTOP-RV7DDL4;Initial Catalog=Demodb
;User ID=DESKTOP-RV7DDL4\dbname;Password=test123";
cnn = new SqlConnection(connectionString);
SqlCommand command;
SqlDataReader dataReader;
String sql, Output = "";
sql = "Select TutorialID, TutorialName from demotb";
command = new SqlCommand(sql, cnn);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "</br>";
}
Response.Write(Output);
dataReader.Close();
command.Dispose();
cnn.Close();
lblName.Visible = false;
txtName.Visible = false;
lstLocation.Visible = false;
chkC.Visible = false;
chkASP.Visible = false;
rdMale.Visible = false;
rdFemale.Visible = false;
btnSubmit.Visible = false;
}
When I run the project I receive the following error:
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: ExecuteReader requires an open and available Connection. The connection's current state is closed.
I thought the connection was made so not sure why it says the db is closed?
Try to to explicitly open the connection via the Open method on the SQL connection class.
Perhaps a using statement is more appropriate here. Like so:
using (var cnn = new SqlConnection(connectionString))
{
// Use the connection
}
Thanks for your help. I re-jigged things around and added the .Open method and it works!
string connectionString = null;
SqlConnection cnn;
SqlCommand command;
string sql, Output = "";
connectionString = #"Data Source=DESKTOP-RV7DDL4\SQLEXPRESS;Initial Catalog=DemoDBase
;User ID=sa;Password=test1234";
cnn = new SqlConnection(connectionString);
sql = "Select TutorialID, TutorialName from demoTable";
cnn.Open();
command = new SqlCommand(sql, cnn);
SqlDataReader dataReader;
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "</br>";
}
Response.Write(Output);
dataReader.Close();
command.Dispose();
cnn.Close();

how to auto login after registration in asp.net

I want to login automatically after registration by using a session like Session["ud"] , but I don't know where should I put it.
public partial class index : System.Web.UI.Page
{
SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["dbpath"]);
protected void btnSave_Click(object sender, EventArgs e)
{
long idx;
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "Insert into tblUser (UInfo,UEmail,UName,UPass, UGender) Values (#P1,#P2,#P3,#P4,#P5) select ##Identity";
cmd.Parameters.AddWithValue("#P1", txtInfo.Text);
cmd.Parameters.AddWithValue("#P2", txtEmail.Text);
cmd.Parameters.AddWithValue("#P3", txtUserName.Text);
cmd.Parameters.AddWithValue("#P4", txtPass.Text);
cmd.Parameters.AddWithValue("#P5", rdbMale.Checked);
cnn.Open();
idx = Convert.ToInt64(cmd.ExecuteScalar()); // i think here we can do something
cnn.Close();
here we want to upload the image of user and it works correctly
string fn = "";
if (FileUpload1.HasFile == true)
{
fn = FileUpload1.FileName;
string des = Server.MapPath("\\UserImg\\") + idx.ToString() + ".jpg";
FileUpload1.PostedFile.SaveAs(des);
SqlCommand cmdUpdate = new SqlCommand();
cmdUpdate.Connection = cnn;
cmdUpdate.CommandText = "Update tblUser Set UImg=#P5 where UId=#P0";
cmdUpdate.Parameters.AddWithValue("#P5", idx.ToString() + ".jpg");
cmdUpdate.Parameters.AddWithValue("#P0", idx);
cnn.Open();
cmdUpdate.ExecuteNonQuery();
cnn.Close();
}
Response.Redirect("Profile.aspx");
}
}
once you have entered data into in sql database you will get id of new user here
idx = Convert.ToInt64(cmd.ExecuteScalar()); // i think here we can do something
Once you get the id assign it to your session
idx = Convert.ToInt64(cmd.ExecuteScalar()); // i think here we can do something
cnn.Close();
Session["ud"]=idx;
once you have assigned session ,you just have to redirect to required page and validate Session variable if it's null or not.
i hope on Profile.aspx page you are checking for same session variable.
Profile.aspx.cs--on page load
if (Session["ud"] != null)
{
//successfull login
}
else
{
//redirect to login page
}

Retrieving the image from database and displaying in web page in Asp.Net

I am trying to store the profile picture which the user uploads in a database and retrieve from the database and display in web page.I have successfully saved the image in database but I don't know how to retrieve it.I have tried to display but when I click the retrieve button nothing happens.
This is the code in Handler page and instead of retrieving the image based on Id I am trying to do it by passing the name of the user which will be on the welcome page.
public void ProcessRequest(HttpContext context)
{
//passing name here
if (context.Request.QueryString["name"] != null)
{
string csc = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(csc))
{
SqlCommand com = new SqlCommand("RetrieveImage", con);
com.CommandType = CommandType.StoredProcedure;
//passing name
SqlParameter p1 = new SqlParameter("#userName", context.Request.QueryString["name"]);
com.Parameters.Add(p1);
con.Open();
SqlDataReader dr = com.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((byte[])dr["image"]);
dr.Close();
con.Close();
}
}
else
{
context.Response.Write("No Image Found");
}
}
public bool IsReusable
{
get
{
return false;
}
}
I have created a stored procedure which accepts username and gives image.Stored procedure name is "RetrieveImage"
This is the button click event.On clicking the button "RetrieveImage" it calls handler and passes value as "name"which then calls stored procedure and displays image
protected void RetrieveImage_Click(object sender, EventArgs e)
{
string csc = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(csc))
{
SqlCommand com = new SqlCommand("RetrieveImage", con);
com.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("#userName", WelcomeUsername.Text);
com.Parameters.Add(p1);
con.Open();
SqlDataReader dr = com.ExecuteReader();
ImageDisp.ImageUrl = "~/ImagePage.ashx?name=" + WelcomeUsername.Text;
con.Close();
}
}
When I run the page I am not getting any error but when I click the button nothing happens.I am new to .Net .Please help.!! Thanks in advance

While fetching a record in asp.net from sql server it always return null

While fetching a record in asp.net from sql server it always return null..here's code-
Even if record is available in database, object oid will have null at run time.
Please help.
thanks.
protected void btnLogin_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["DBMS"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand com = new SqlCommand("select id from reg where user=#user and password=#pass", con);
com.Parameters.AddWithValue("#user", txUName.Text);
com.Parameters.AddWithValue("#pass", txPass.Text);
con.Open();
var oid = com.ExecuteScalar();
con.Close();
if (oid == null)
{
lblEr.Visible = true;
}
else
{
Session.Add("id", oid.ToString());
Session.Add("user", txUName.Text);
com = new SqlCommand("select type from dbo.reg where user=#u", con);
com.Parameters.AddWithValue("#u", txUName.Text);
con.Open();
var otype = com.ExecuteScalar();
con.Close();
var vtype = "admin";
if (vtype == otype.ToString())
{
Session.Add("admin", otype.ToString());
Response.Redirect("admin.aspx");
}
Response.Redirect("user.aspx");
}
}
It worked just by correcting following syntax-
SqlCommand com = new SqlCommand("select id from reg where [user]=#user and [password]=#pass", con);
Since 'user' is also name of a user in sql server, so when we want to use it at another place like here as column then we have to use it as [user].

Resources