asp.net Post & Submit Form to another site - javascript

I am tring send data to another website's form from my 'Web Form' and submit it. But I couldn't achive it so far. I tried add id's bodyContent_ tag but still no progress. Can you detect where I am doing it wrong ? Thank You
protected void btnSend_Click(object sender, System.EventArgs e)
{
Response.Write(PostForm().ToString());
this.PostScript(Page);
}
public string PostForm()
{
string PostUrl = "http://www.teknobilsoft.com/Contact.aspx";
string Method = "post";
string name = "John";
string email = "john#doe.com";
string subject = "Mesaj";
string message = "some messages";
StringBuilder ppForm = new StringBuilder();
ppForm.AppendFormat("<form id='form1' action='{0}' method='{1}'>", PostUrl, Method);
ppForm.AppendFormat("<input id='txtName' value='{0}'>", name);
ppForm.AppendFormat("<input id='txtEmail' value='{0}'>", email);
ppForm.AppendFormat("<input id='ddlSubject' value='{0}'>", subject);
ppForm.AppendFormat("<textarea id='txtMessage' value='{0}'></textarea>", message);
ppForm.Append("</form>");
return ppForm.ToString();
}
private void PostScript(System.Web.UI.Page Page)
{
StringBuilder strScript = new StringBuilder();
strScript.Append("<script language='javascript'>");
strScript.Append("var ctlForm = document.getElementById('form1');");
strScript.Append("ctlForm.submit();");
strScript.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "btnSendMessage", strScript.ToString());
}

What's the error message do you get?
Also, is there a reason why you use JavaScript to post the data? You can post using HttpWebRequest in C#:
http://www.stickler.de/information/code-snippets/httpwebrequest-post-data.aspx

Related

How to submit form values in JSON format to a servlet using AJAX?

I am trying to send login data in JSON format to a servlet using AJAX, but for some reason the servlet is getting null values. My servlet works fine when I send the data without AJAX, but when I use it it seems that my script is not getting any values.
Login form:
<form>
<input class="input-container" type="text" placeholder="Enter Email"
name="email" required><br>
<input class="input-container" type="password" placeholder="Enter Password"
name="paswd" required><br>
<input class="login-button" type="button" value="Log in"
onclick="loginAjax(this.form)">
</form>
AJAX:
function loginAjax(form) {
var user = new Object();
user.email = form.email.value;
user.paswd = form.paswd.value;
var jsonUser = JSON.stringify(user);
console.log(user.email);
console.log(user.paswd);
console.log(jsonUser);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
//Empty form fields
form.email.value = "";
form.paswd.value = "";
}
};
xmlhttp.open("POST", "./login", true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send(jsonUser);
}
Servlet:
# WebServlet(name = "login", urlPatterns = { "/login" })
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.sendRedirect("index.html");
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType(MediaType.APPLICATION_JSON);
response.setCharacterEncoding("UTF-8");
Dao dao = new Dao();
// return values as string.
String email = request.getParameter("email");
String password = request.getParameter("paswd");
System.out.println("Your email: " + email );// Delete Later!!
System.out.println("Your password: " + password);// Delete Later!!
System.out.println("Test passed0");
// Read reference values from DB
String salt = dao.getUserSalt(email);
String hashpw = dao.getUserpasswordHash(email);
System.out.println("Test 1 passed");
dao.checkemail(email);
try {
System.out.println("Test 2 passed");
if (SecurityUtils.isPasswordOk(hashpw, password, salt)) {
System.out.println("Test 3 passed");
String data = email;
HttpSession session = request.getSession();
User user = dao.readUserInfo(data);
dao.close();
System.out.println("Test 4 passed");
session.setAttribute("LoggedUser", user);
System.out.println("Session: " + request.getSession(false));
session.setMaxInactiveInterval(30 * 60);
System.out.println("Test 5 passed");
String encodedURL = response.encodeRedirectURL("/userInfo?email=" + data);
System.out.println("Final Test 6 passed");
try {
response.sendRedirect(encodedURL);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
dao.close();
RequestDispatcher rd = getServletContext().getRequestDispatcher("./index.html");
try {
rd.include(request, response);
} catch (ServletException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The output I get on the console:
Your email: null
Your password: null
java.lang.NullPointerException
at security.SecurityUtils.getPasswordHashed(SecurityUtils.java:32)
at security.SecurityUtils.isPasswordOk(SecurityUtils.java:57)
at app.Login.doPost(Login.java:54)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:526)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:593)
at org.eclipse.jetty.servlet.ServletHolder$NotAsync.service(ServletHolder.java:1459)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:799)
at org.eclipse.jetty.servlet.ServletHandler$ChainEnd.doFilter(ServletHandler.java:1631)
at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:148)
at org.eclipse.jetty.servlet.FilterHolder.doFilter(FilterHolder.java:193)
at org.eclipse.jetty.servlet.ServletHandler$Chain.doFilter(ServletHandler.java:1601)
at ..Error continues...
I tried to switch the input type to submit and then added return false next to the onclick as the following onclick="loginAjax(this.form); return false" but that didn't help. I previously used similar ajax function with a form to send data to PHP and it worked fine. Any help would be much appreciated!
From the Documentation of XMLHttpRequest
XMLHttpRequest send() accepts an optional parameter which lets you specify the request's body; this is primarily used for requests such as PUT. If the request method is GET or HEAD, the body parameter is ignored and the request body is set to null.
Apparently you are sending JSON data into your request body whereas you are expecting your data in request Parameter
String email = request.getParameter("email");
String password = request.getParameter("paswd");
Certainly it will return NULL
In this case you need to read request body from request.getInputStream()
Check this answer
try
xmlhttp.open("POST","./login?email=" + user.email + "&paswd=" + user.paswd,false);
xmlhttp.send();
instead of
xmlhttp.open('POST', './login', false);
xmlhttp.send(jsonUser);
OR YOU CAN USE JQUERY AJAX
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
function loginAjax(form) {
var user = new Object();
user.email = form.email.value;
user.paswd = form.paswd.value;
var jsonUser = JSON.stringify(user);
$.ajax({type: "POST",
url:"./login",
data:jsonUser,
success:function(result){
alert("Success");
}
});
}
</script>

asp.net Dropdownlist not refreshing after being removed

I have a 2 drop down lists with company name and company addresses and a remove button linked to a stored procedure. Addresses is not being refreshed even though I am calling databind() on that address drop down List. Can anyone point me out in the right direction?
//Button to remove Company
protected void btnremovecompany_2(object sender, EventArgs e)
{
if (ddlcompanyaddress2.SelectedIndex != 0) /*checked to see if an address is Selected first*/
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")/* if yes is clicked then procedd to deactivate that company address*/
{
String strConnString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_update_company_active";
cmd.Parameters.Add("#companyname", SqlDbType.VarChar).Value = ddlcompany2.SelectedItem.Text.Trim();
cmd.Parameters.Add("#address", SqlDbType.VarChar).Value = ddlcompanyaddress2.SelectedItem.Text.Trim();
cmd.Parameters.Add("#category", SqlDbType.VarChar).Value = ddlTrades2.SelectedItem.Text.Trim();
cmd.Connection = con;
**ddlcompanyaddress2.DataBind();**
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
/*Display message saying company is deactivated*/
string message = "Company has been removed";
string script = "window.onload = function(){ alert('";
script += message;
script += "')};";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
con.Close();
con.Dispose();
}
}
else
{
/*if canceled is clicked then display no changes*/
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('No Changes were made!')", true);
}
}
else
{
string message = "Please pick an address first.";
string script = "window.onload = function(){ alert('";
script += message;
script += "')};";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
}
}
You might be missing the datasource for your dropdown list. I am unable to find datasource in your code. You have just called databind method.
Can you please bind the datasource?
added this code to the try{} area and it resets all the dropdowns with fresh data.
ddlgettrades2();
getcompany2(ddlTrades2.SelectedItem.Text);
getaddress2(ddlcompany2.SelectedItem.Text);

remove element from master page on button click

So here is the deal I am working on a simple project, with a log in form and a sign up form. In the beginning you will see this which is displayed in the picture.
After you sign up or log in, then you will get what is displayed in the picture below
When I click on a new page for example: like on the home page, videos, contact, then it will just return back to its original state in the first picture. I want to prevent that and keep it the way it is in the second picture until you click on log out. I have been looking everywhere for answers and can't seem to find exactly what I am looking for.
Here is a little code from what I have used to try and accomplish this
HTML code, which is located in the master page
<a id ="LogIn" runat="server" href="../LogIn.aspx">Log In:</a>
<a id ="SignUp" runat="server" href="../SignUp.aspx">Sign Up:</a>
<a id ="LogOut" href="../LogIn.aspx">Log Out:</a>
CSS code in the master page as well.
#LogIn
{
margin-top: 10px;
font-size: 25px;
position: absolute;
margin-left: 767px;
}
#SignUp
{
margin-top: 10px;
font-size: 25px;
position: absolute;
margin-left: 867px;
}
#LogOut
{
margin-top: 30px;
font-size: 20px;
position: absolute;
margin-left: 880px;
display: none;
}
Okay I have tried doing it in javascript, which is in the master page
function showAlert() {
$(".SignUp").slideUp("25000");
$(".LogIn").slideUp("25000");
$(".CreateAccount").hide();
$(".AccountLogIn").hide();
$("h1").remove();
$("#LogIn").remove();
$("#SignUp").remove();
$("#LogOut").show();
}
the showalert function is being called from the button click event in C# for the LogIn form and SignUp form
SqlConnection connection = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
connection.ConnectionString = #"Data Source=184.168.47.13;Initial Catalog=portfoliobrown;User ID=*******;Password=**************";
connection.Open();
}
public void CheckEmail()
{
SqlCommand Comm = new SqlCommand("select count(*) from SignUp where Email ='" + Email.Text + "'", connection);
Comm.Parameters.AddWithValue("#Email", Email.Text);
Comm.Connection = connection;
int count = Convert.ToInt32(Comm.ExecuteScalar());
if (count > 0)
{
Thread.Sleep(3000);
VerifyEmail.Visible = true;
}
else
{
Thread.Sleep(5000);
InsertData();
VerifyEmail.Visible = false;
Message.Visible = true;
LogInAs.Visible = true;
LogInAs.Text = "Loged in as " + FirstName.Text + " " + LastName.Text + ":";
this.Controls.Add(new LiteralControl("<script type='text/javascript'>showAlert();</script>"));
}
}
public void InsertData()
{
SqlCommand Command = new SqlCommand("Insert into SignUp" + "(FirstName, LastName, Password, Email)values(#FirstName, #LastName, #Password, #Email)", connection);
Command.Parameters.AddWithValue("#FirstName", FirstName.Text);
Command.Parameters.AddWithValue("#LastName", LastName.Text);
Command.Parameters.AddWithValue("#Password", Password.Text);
Command.Parameters.AddWithValue("#Email", Email.Text);
HtmlAnchor LogIn = (HtmlAnchor)Master.FindControl("LogIn");
HtmlAnchor SignUp = (HtmlAnchor)Master.FindControl("SignUp");
LogIn.Visible = false;
SignUp.Visible = false;
Command.ExecuteNonQuery();
}
protected void SignUp_Click(object sender, EventArgs e)
{
CheckEmail();
connection.Close();
//ScriptManager.RegisterStartupScript(Page, Page.GetType(), "showAlert", "showAlert()", true);
//Response.Write("<script language=JavaScript> alert('You have Successfully created an Account'); </script>");
//Response.Redirect("~//Default.aspx");
}
I also tried doing it in the back end code as well shown above. It also shows how the user is being loged in and saved in the database. That is being called in the button click event, when you click to create an account or click to log into an account.
LogIn.aspx.cs
SqlConnection conn = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
conn.ConnectionString = #"Data Source=184.168.47.13;Initial Catalog=portfoliobrown;User ID=*******;Password=*******";
conn.Open();
}
private bool CompareStrings(string string1, string string2)
{
return String.Compare(string1, string2, true, System.Globalization.CultureInfo.InvariantCulture) == 0 ? true : false;
}
public void ExecuteLogIn()
{
SqlCommand Command = new SqlCommand("select ISNULL(Email, '') As Email, ISNULL(Password, '') As Password from SignUp where Email='" + Email.Text + "'", conn);
SqlCommand Command2 = new SqlCommand("select * from SignUp where FirstName= #FirstName", conn);
Command2.Parameters.AddWithValue("#FirsName", FirstName.Text);
SqlDataReader dr = Command.ExecuteReader();
string UserEmail = Email.Text;
string UserPassword = Password.Text;
HtmlAnchor LogIn = (HtmlAnchor)Master.FindControl("LogIn");
HtmlAnchor SignUp = (HtmlAnchor)Master.FindControl("SignUp");
while (dr.Read())
{
if (this.CompareStrings(dr["Email"].ToString(), UserEmail) &&
this.CompareStrings(dr["Password"].ToString(), UserPassword))
{
InvalidLogIn.Visible = false;
Message.Visible = true;
LogInAs.Visible = true;
//LogInAs.Text = "Loged in as " + FirstName.Text + " " + LastName.Text + ":";
this.Controls.Add(new LiteralControl("<script type='text/javascript'>showAlert();</script>"));
LogIn.Visible = false;
SignUp.Visible = false;
}
else
{
InvalidLogIn.Visible = true;
}
}
//Command.Parameters.AddWithValue("#Password", Password.Text);
//Command.Parameters.AddWithValue("#Email", Email.Text);
conn.Close();
}
protected void LogIn_Click(object sender, EventArgs e)
{
ExecuteLogIn();
}
Any help would be greatly appreciated thanks so much
The code is missing too many pieces. I could only give you a direction. If you have specific question about FormAuthentication, please create a new question.
CheckEmail method is prone to SQL Injection attack. You want to consider using Parameterized Query.
We normally need both username*(or email)* and password to validate an account. Easiest way to implement authentication in ASP.NET Web Form is to use FormAuthentication.
The following is the sample code. I also created a sample project at GitHub, so that you can test it.
Sign-In method inside Login.aspx.cs
protected void SubmitButton_Click(object sender, EventArgs e)
{
string username = UsernameTextBox.Text,
password = PasswordTextBox.Text;
bool rememberMe = RememberMeCheckBox.Checked;
// Retrieve username and hashed password from database, and validate them
if (username.Equals("johndoe", StringComparison.InvariantCultureIgnoreCase) &&
password.Equals("123456", StringComparison.InvariantCultureIgnoreCase))
{
FormsAuthentication.RedirectFromLoginPage(username, rememberMe);
}
MessageLabel.Text = "Invalid username or password";
}
Global.asax.cs
We then retrieve username from cookie, and save it in Principal Object.
public class Global : HttpApplication
{
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie decryptedCookie =
Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (decryptedCookie != null)
{
FormsAuthenticationTicket ticket =
FormsAuthentication.Decrypt(decryptedCookie.Value);
var identity = new GenericIdentity(ticket.Name);
var principal = new GenericPrincipal(identity, null);
HttpContext.Current.User = principal;
Thread.CurrentPrincipal = HttpContext.Current.User;
}
}
}
web.config
Please ensure authentication tag is in web.config.
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" />
</authentication>
Usage
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
string username = User.Identity.Name;
}
}

Show message only on first access to the web page in c#

With this code I show JavaScript alert message box in ASP.Net from server side using C#.
But I need show the message only on first access to the web page, how to do resolve this ?
Please help me.
My code below, thank you in advance.
protected void Page_Load(object sender, EventArgs e)
{
string message = "Hello!";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
You need to check that the page is not posting back before you display your alert:
if (!IsPostBack)
{
string message = "Hello!";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
Updates:
You can create a cookie to track the alert so it does not display after displaying during the initial page load:
private bool Alerted()
{
if (Request.Cookies["alerted"] != null)
return Server.HtmlEncode(Request.Cookies["alerted"].Value) == "true";
else
{
Response.Cookies["alerted"].Value = "true";
Response.Cookies["alerted"].Expires = DateTime.Now.AddDays(10);
return false;
}
}
Usage:
if(!Alerted())
{
// alert script here
}

How to access and perform CRUD to SQL Server Database from a Windows 8 app written in Javascript/HTML through WCF Service?

I have added a new SQL Server Database to the App_Data folder from the sample project below.
http://code.msdn.microsoft.com/How-to-consume-JSON-Web-5db0174b#content
I have added 2 new textbox, 1 button in the HTML for user to enter name, address and a click button to save in database.
But I don't know how to pass the value entered from the HTML text box, button using WinJS.xhr to the WCF and then perform CRUD from SQL Server database and will display the output in the app.
default.html
<input id="txtName" type="text" />
<input id="txtAddress" type="text" />
<button id="insertbtn">insert</button>
JSONWCFService.svc.cs
public void Insert(int name, int address)
{
string connectionString = System.Configuration.ConfigurationManager.
ConnectionStrings["Database1ConnectionString1"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
string sql = "INSERT INTO Table1(Name, Address) VALUES (#Name, #Address)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#Name", name);
cmd.Parameters.AddWithValue("#Address", address);
try
{
con.Open();
int numAff = cmd.ExecuteNonQuery();
}
catch (SqlException exc)
{
}
finally
{
con.Close();
}
}
IAddService.cs
public interface IAddService{
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
void Insert(string name, string address);}
default.js
function insertButtonClick() {
var baseURI2 = "http://localhost:45573/AddService.svc/Insert";
var name = document.getElementById('txtName').value;
var address = document.getElementById('txtAddress').value;
WinJS.xhr({
type: "POST",
url: baseURI2,
headers: { "Content-type": "application/json" },
data: JSON.stringify(txtName+ txtAddress)
}).then(function complete(request) {
var resdata = request.responseText;
}, function error(er) {
var err = er.statusText;
})
}
Please help to correct my code or share me some correct sample code (WinJS.xhr and JSONWCFService).
Thank you very much!

Categories

Resources