Datareader has rows property returns false - asp.net

I am trying to check if the username exists or not . I am using XMLHTTPREqUEST object in the html page and sending user name and password values to Default aspx page.But when I exacute the code .Nothing happens.I mean There is no exception message or anyting after debugging I have noticed that connection state open but datareader's hasRows property returns false.I am sure I am able to pass query string values into variables . And What am i missing out Can you plase help
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["ka"] != null && Request.QueryString["pass"] != null)
{
string username = Request.QueryString["ka"];
string pass = Request.QueryString["pass"];
SqlConnection con = new SqlConnection("server=.\\sqlexpress;database=Projects;UID=sa;Password=1234");
if (con.State == ConnectionState.Closed) {
con.Open();
SqlCommand cmd = new SqlCommand("select * from userstable where username=#name and pass=#pass", con);
cmd.Parameters.AddWithValue("#name", username);
cmd.Parameters.AddWithValue("#pass", pass);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
Response.Write("exist");
}
else
{
Response.Write("Doesntexist");
}
con.Close();
}
}
Response.Close();
}
this is Htmlpage
<script src="Scripts/jquery-2.1.1.js"></script>
<script type="text/javascript">
function createXHR() {
var xhr;
try {
xhr = new XMLHttpRequest();
} catch (e) {
}
return xhr;
}
function signIn() {
var xhr = createXHR();
var username=$('#txtusername').val();
var pass=$('#txtpass').val()
xhr.onreadystatechange=function(){
if(xhr!=null){
if(xhr.readyState==4){
if(xhr.status>=200 && xhr.status<300){
var v = $('#result').html(xhr.responseText);
if (v == "exist") {
$('#result').html("Done");
}
else if (v == "Doesntexist") {
$('#result').html("Error");
}
else{
$('#result').html(v);
}
}
}
}
else{
$('#result').html("Error");
}
}
xhr.open("GET", "Default.aspx?ka='" + username + "&pass=" + pass, true);
xhr.send(null);
}
</script>
</head>
<body>
<input id="txtusername" type="text" name="txtusername"/><br />
<input id="txtpass" type="text" name="txtpass"/><br />
<input id="Button1" type="button" value="signin" onclick="signIn();" /><br />
<div id="result" ></div>
</body>

Related

asp.net checkbox.checked evaluation after uncheck

protected void submitLogin(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["tropicalConnectionString"].ConnectionString;
string queryString = "select * from tblUserLogin where userId='" + useridtextbox.Text
+ "' and password ='" + passwordtextbox.Text + "'";
Console.WriteLine(queryString);
conn = new OleDbConnection(connStr);
conn.Open();
cmd = new OleDbCommand(queryString, conn);
reader = cmd.ExecuteReader();
userId = "";
if (reader.HasRows && reader.Read())
{
userId = reader.GetString(reader.GetOrdinal("UserId"));
}
if (reader.HasRows)
{
Session["uid"] = userId;
Response.BufferOutput = true;
Response.Redirect("/UI/Products.aspx", false);
bool ck = remembercheckbox.Checked;
if (ck)
{
Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(7);
Response.Cookies["UserName"].Value = useridtextbox.Text.Trim();
}
else
{
HttpCookie myCookie = new HttpCookie("UserSettings");
Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(myCookie);
}
}
else
{
passwordtextbox.Text = "invalid user";
}
Here's a snippet of my login content page
<div class="login">
<asp:CheckBox ID="remembercheckbox" TextAlign="left" runat="server" text="Remember my Id" checked="false" OnCheckedChanged="clickCkbx" />
<asp:Button ID="loginButton" CssClass="loginButton" runat="server" text="Login" OnClick="submitLogin" />
</div>
I'm trying to implement a remember user id function and practicing it with cookie. The problem is that when I uncheck the box for "remembercheckbox", the value in remembercheckbox.Checked keep returning true and thus I cannot go into the else statement and destroy the cookie.
Thanks in advance!
Just solve the problem. I had this as my page_load. and when the button was clicked button, because the postback mechanism, the page got reloaded and Page_Load was called and thus remembercheckbox.Checked was set to true again.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["UserName"] != null)
{
remembercheckbox.Checked = true;
useridtextbox.Text = Request.Cookies["UserName"].Value;
}
chk = remembercheckbox.Checked;
}
solve this by checking !Page.IsPostBack and then assign the cookie

SignalR sqlDependency

I need SQL Dependency change on a gridview displaying all rows that are changed or old data. Can anybody help me?
Here is my script:
<script>
$(function () {
var notify = $.connection.notificationsHub;
notify.client.displayNotification = function (msg) {
$("#newData").html(msg);
};
$.connection.hub.start();
});
</script> </head> <body>
<form id="form1" runat="server">
<div>
<asp:GridView id="newData" runat="server" AutoGenerateColumns="False">
</asp:GridView>
public void SendNotifications()
{
string message = string.Empty;
string conStr = ConfigurationManager.ConnectionStrings["TestDB"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conStr))
{
string query = "SELECT [Message] FROM [dbo].[tb]";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
message = reader.GetString(0);
}
}
}
}
NotificationsHub nHub = new NotificationsHub();
nHub.NotifyAllClients(message);
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
SendNotifications();
}
}

MVC Contact Form with Email

I wonder if someone can please help with a MVC Contact Form which send an Email on submission? I think I have most elements setup, but for some reason the form appear to be sending (takes ages) then just returns back to the form and no email is received.
MailModels.cs:
namespace WebApplication1.Models
{
public class MailModels
{
public string Name { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
public string Message { get; set; }
}
}
Contact.cshtml:
#using (Html.BeginForm("Contact", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #id = "contact-form", role = "form" }))
{
#Html.ValidationSummary()
<fieldset>
<div class="form-div-1">
<label class="name">
#Html.TextBoxFor(m => m.Name, new { #placeholder = "Name *", #type = "text" })
</label>
</div>
<div class="form-div-2">
<label class="email">
#Html.TextBoxFor(m => m.Email, new { #placeholder = "Email Address *", #type = "email" })
</label>
</div>
<div class="form-div-3">
<label class="phone notRequired">
#Html.TextBoxFor(m => m.Telephone, new { #placeholder = "Telephone Number", #type = "text" })
</label>
</div>
<div>
<label class="message">
#Html.TextAreaFor(m => m.Message, new { #placeholder = "Message *" })
</label>
</div>
<div class="button-wrapper">
<input type="submit" value="Send" name="submit" class="button"> <input type="reset" value="Reset" name="MFReset" class="button"><span>* Required Fields</span>
</div>
</fieldset>
}
HomeController.cs:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using WebApplication1.Models;
using System.Text;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Contact()
{
ViewBag.Message = "Test Form";
return View();
}
[HttpPost]
public ActionResult Contact(MailModels e)
{
if (ModelState.IsValid)
{
StringBuilder message = new StringBuilder();
MailAddress from = new MailAddress(e.Email.ToString());
message.Append("Name: " + e.Name + "\n");
message.Append("Email: " + e.Email + "\n");
message.Append("Telephone: " + e.Telephone + "\n\n");
message.Append(e.Message);
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.mail.yahoo.com";
smtp.Port = 465;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("yahooaccount", "yahoopassword");
smtp.Credentials = credentials;
smtp.EnableSsl = true;
mail.From = from;
mail.To.Add("yahooemailaddress");
mail.Subject = "Test enquiry from "+e.Name;
mail.Body = message.ToString();
smtp.Send(mail);
}
return View();
}
Banging my head against a brickwall with this one, any help would be much appreciated :-)
Sending an email will take time. It should be a thread. Put your code in a function. And make the following changes:
public void SendEmail(string toAddress, string fromAddress,
string subject, string message)
{
try
{
using (var mail = new MailMessage())
{
const string email = "username#yahoo.com";
const string password = "password!";
var loginInfo = new NetworkCredential(email, password);
mail.From = new MailAddress(fromAddress);
mail.To.Add(new MailAddress(toAddress));
mail.Subject = subject;
mail.Body = message;
mail.IsBodyHtml = true;
try
{
using (var smtpClient = new SmtpClient(
"smtp.mail.yahoo.com", 465))
{
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(mail);
}
}
finally
{
//dispose the client
mail.Dispose();
}
}
}
catch (SmtpFailedRecipientsException ex)
{
foreach (SmtpFailedRecipientException t in ex.InnerExceptions)
{
var status = t.StatusCode;
if (status == SmtpStatusCode.MailboxBusy ||
status == SmtpStatusCode.MailboxUnavailable)
{
Response.Write("Delivery failed - retrying in 5 seconds.");
System.Threading.Thread.Sleep(5000);
//resend
//smtpClient.Send(message);
}
else
{
Response.Write("Failed to deliver message to {0}",
t.FailedRecipient);
}
}
}
catch (SmtpException Se)
{
// handle exception here
Response.Write(Se.ToString());
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
Call that function in your controller:
[HttpPost]
public ActionResult Contact(MailModels e)
{
if (ModelState.IsValid)
{
//prepare email
var toAddress = "someadress#yahoo.co.uk";
var fromAddress = e.Email.ToString();
var subject = "Test enquiry from "+ e.Name;
var message = new StringBuilder();
message.Append("Name: " + e.Name + "\n");
message.Append("Email: " + e.Email + "\n");
message.Append("Telephone: " + e.Telephone + "\n\n");
message.Append(e.Message);
//start email Thread
var tEmail = new Thread(() =>
SendEmail(toAddress, fromAddress, subject, message));
tEmail.Start();
}
return View();
}
If you dont get email, check your spam folder
You need to implement Producer Consumer pattern for this use case. You will have to have one thread running dedicated to emails. This thread will read from the queue & send emails. In the contact method, you will just add to the queue. Its not a good idea to do time consuming operations in controller methods.
C# producer/consumer
settings to web.config
<system.net>
<mailSettings>
<smtp from="you#outlook.com">
<network host="smtp-mail.outlook.com"
port="587"
userName="you#outlook.com"
password="password"
enableSsl="true" />
</smtp>
</mailSettings>
</system.net>
Port 465 or 587?
Lots of code samples for Gmail feature port 465 but most people cannot get this to work. When they revert to port 587, their email suddenly works. According to Gmail's documentation SSL is required if you specify port 465. Many people think that setting EnableSsl to true achieves this, but in fact, it means that your app must be running under https. When you set EnableSsl to true, you actually switch TLS on, which is required for port 587. Https is not supported by the SmtpClient object. For more details, read the Remarks section of the docs on MSDN.
public void SendEmail(string toAddress, string fromAddress,string subject, string message)
{
try
{
using (var mail = new MailMessage())
{
const string email = "username#yahoo.com";
const string password = "password!";
var loginInfo = new NetworkCredential(email, password);
mail.From = new MailAddress(fromAddress);
mail.To.Add(new MailAddress(toAddress));
mail.Subject = subject;
mail.Body = message;
mail.IsBodyHtml = true;
try
{
using (var smtpClient = new SmtpClient(
"smtp.mail.yahoo.com", 465))
{
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(mail);
}
}
finally
{
//dispose the client
mail.Dispose();
}
}
}
catch (SmtpFailedRecipientsException ex chor gai )
{
foreach (SmtpFailedRecipientException t in ex.InnerExceptions)
{
var status = t.StatusCode;
if (status == SmtpStatusCode.MailboxBusye ||
status == SmtpStatusCode.MailboxUnavailableee)
{
Response.Write("Delivery failed - retrying in 5 seconds.");
System.Threading.Thread.Sleep(5000);
//resend
//smtpClient.Send(message);
}
else
{
Response.Write("Failed to deliver message to {0}",
t.FailedRecipient);
}
}
}
catch (SmtpException Se)
{
// handle exception here
Response.Write(Se.ToString());
}
catch (Exception ex)
{
Response.Write(ex.Toread());
}
}

else error occur in asp.net

I am trying approving documents and below is the code in button which I did it
but here else condition error occur ..any one tell me where is the mistake occur in below code. Is there nay brackets problem or something else????
code
protected void Button1_Click(object sender, EventArgs e)
{
string connStr =
ConfigurationManager.ConnectionStrings["mydms"].ConnectionString;
SqlConnection mySQLconnection = new SqlConnection(connStr);
if (mySQLconnection.State == ConnectionState.Closed)
{
mySQLconnection.Open();
}
for (int i = 0; i < Repeater2.Items.Count; i++)
{
DropDownList DropDownListcontrol =
((DropDownList)Repeater2.Items[i].FindControl("DropDownList4"));
Label DocId = ((Label)Repeater2.Items[i].FindControl("DocId"));
SqlCommand cmd = new SqlCommand("approveddd",mySQLconnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#DocID", SqlDbType.Int).Value =
Convert.ToInt32((DocID.Text));
cmd.Parameters.Add("#ApproveID", SqlDbType.Int).Value =
Convert.ToInt32(DropDownListcontrol.SelectedValue);
cmd.Parameters.Add("#ApproveBy", SqlDbType.VarChar, 50).Value
= (Session["Login2"]);
cmd.ExecuteNonQuery();
DMSLIB.Doc myDoc = new DMSLIB.Doc();
myDoc.MarkDocAs(Convert.ToInt16(DocId.Text),
Convert.ToInt32(DropDownListcontrol.SelectedValue));
}
else
{
apfi.Text = "Error";
}
if (mySQLconnection.State == ConnectionState.Open)
{
mySQLconnection.Close();
}
}
An error occurs in the else block:
Invalid expression term 'else'
; expected
You must follow Microsoft guideline . It should be like this :
if(condition)
{
}
else
{
}
Not like this
if(condition)
{
}
for(...........)
{
}
else
{
}
You misplaced else. change your for loop. because you have
if()
{
}
for()
{
}
else// belongs to where?
{
}

how to return a datatable if a register number exists

I am trying to display a grid if the user entered register number exists in database, if the register number does not exists this means that I need to display one label also.i am a new one in asp.net,so please help me.
Here is my code below.
public DataTable madhrasaViewByRegNo(string viewByNo)
{
try
{
madhrasaInfo infomadhrasa = new madhrasaInfo();
object decobj = new object();
if (sqlcon.State == ConnectionState.Closed)
{
sqlcon.Open();
}
SqlCommand sqlcmd = new SqlCommand("madhrasaViewByRegNo", sqlcon);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.Add("#regNo", SqlDbType.VarChar).Value = viewByNo;
decobj = sqlcmd.ExecuteNonQuery();
if (decobj == null)
{
decStuId = decimal.Parse(decobj.ToString());
}
else
{
DataTable dtbClass = new DataTable();
SqlDataAdapter sqlda = new SqlDataAdapter("madhrasaViewByRegNo", sqlcon);
sqlda.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlda.SelectCommand.Parameters.Add("#regNo", SqlDbType.VarChar).Value = viewByNo;
sqlda.Fill(dtbClass);
return dtbClass;
}
}
catch (Exception)
{
throw;
}
return null;
}
public void gridfillByNo()
{
madhrasaSp spMadhrasa = new madhrasaSp();
DataTable dtbl = new DataTable();
dtbl = spMadhrasa.madhrasaViewByRegNo(TextBox2.Text);
gvstuResult.DataSource = dtbl;
gvstuResult.DataBind();
}
public void regSearch()
{
madhrasaSp spmadhrasa = new madhrasaSp();
spmadhrasa.madhrasaViewByRegNo(TextBox2.Text);
if (madhrasaSp.decStuId > 0)
{
gridfillByNo();
MultiView1.ActiveViewIndex = 1;
}
else
{
MultiView1.ActiveViewIndex = 0;
Label1.Visible = true;
Label1.Text = "Invalid Register Number";
}
}
protected void Button2_Click(object sender, EventArgs e)
{
regSearch();
}
You Dont you just set the grid view's EmptyDataText to 'Reg No Dosent exist'. It will solve your ploblem.
<asp:GridView ID="GridView1" runat="server" EmptyDataText="register number not available">
</asp:GridView>

Resources