private void LoginButton_Click(object sender, EventArgs e)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginUrl);
IAsyncResult result = request.BeginGetResponse(
new AsyncCallback(DeleResponse), request);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
And here is the method which called to on button click event
private void DeleResponse(IAsyncResult result)
{
byte[] PostData = Encoding.UTF8.GetBytes("username=" + userInp.Text + "&password=" + passInp.Text + extraLoginPostString);
LoginButton.Text = "Logging in...";
LoginButton.Enabled = false;
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
request.Method = "Post";
request.CookieContainer = authCookie;
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = false;
postWriter = request.GetRequestStream();
postWriter.Write(PostData, 0, PostData.Length);
postWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
string serverData = new StreamReader(response.GetResponseStream()).ReadToEnd();
string loginValidateString = response.GetResponseHeader(loginValidateStringHolder);
if (loginValidateString.Contains(LoggedKeyword))
{
some process here:
}
else if( FAILKEYWORDCHECK HERE)
{
login page process here;
}
}
The problem is when I check this with fiddler I can see only following header properties.
Connection: Keep-Alive;
Host: www.example.com
What would be the reason that I can't set properties in the request header?
Edit: Added synchronous request method which I already achieved without any errors.
private void LoginButton_Click(object sender, EventArgs e)
{
try
{
LoginButton.Text = "Logging in...";
LoginButton.Enabled = false;
byte[] PostData = Encoding.UTF8.GetBytes("username=" + userInp.Text + "&password=" + passInp.Text + extraLoginPostString);
request = (HttpWebRequest)WebRequest.Create(loginUrl);
request.Method = "Post";
request.CookieContainer = authCookie;
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = false;
postWriter = request.GetRequestStream();
postWriter.Write(PostData, 0, PostData.Length);
postWriter.Close();
response = (HttpWebResponse)request.GetResponse();
string serverData = new StreamReader(response.GetResponseStream()).ReadToEnd();
string loginValidateString = response.GetResponseHeader(loginValidateStringHolder);
if (loginValidateString.Contains(LoggedKeyword))
{
MessageBox.Show("Logged in Successfully");
foreach (Cookie cookieReader in response.Cookies)
{
authCookie.Add(cookieReader);
}
Success method continues..
}
else if (loginValidateString.Contains(failedLogKeyword))
{
Failed process
}
}
catch
{
Catchblock
}
}
Means, I just know how to set properties for normal requests.
You're trying to set properties of the request when the response is available. You need to set the request properties before you make the request to the server - so you should be setting them in LoginButton_Click, not in the response handling code. Likewise you can't use GetRequestStream in a callback for BeginGetResponse. Roughly speaking, you want:
In the initial event handler:
Create the request
Set simple properties
Call BeginGetRequestStream
In the callback handler for BeginGetRequestStream
Write out the body data
Call BeginGetResponse
In the callback handler for BeginGetResponse
Handle the response data
Alternatively, unless you have to use the asynchronous calls, you could just create a separate thread and use the synchronous versions instead. Until the language support in C# 5, that would be simpler.
Related
I'm writing an app that will authenticate user from a MySQL database.
I have written it in Java (android) but am now porting to Windows phone.
the PHP file uses $get and then echoes the response:
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['username'];
$query_search = "select * from users where user = '".$username."'";
//$query_search = "select * from users where username = '".$username."' AND password = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo "No Such User Found";
} else {
echo "User Found";
}
How can I pass the username variable to PHP and then receive the result?
YOUR CODE IS VULNERABLE TO SQL-INJECTION METHOD USE PDO/MYSQLi to AVOID THIS
Create loaded event handler:
using System;
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
System.Uri myUri = new System.Uri("Your php page url");
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(myUri);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback),myRequest);
}
creating "POST" data stream:
void GetRequestStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
// End the stream request operation
Stream postStream = myRequest.EndGetRequestStream(callbackResult);
// Create the post data
string postData = "username=value";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
}
receive response:
void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
string result = httpWebStreamReader.ReadToEnd();
//For debug: show results
Debug.WriteLine(result);
}
}
use a in-linky stuff like I have a script in my server and you just write: "example.com/save.php?username=textbox1.text&score=points"
I'm making a project to log into a website than instantly log out and do it all over again. Well my problem is cookies I'm quite unsure how to log out correctly and than resend. Closing the app and restarting it logs the user back in again so its obvious cookies are being cleared then.
private void Form1_Load(object sender, EventArgs e)
{
WebRequest request;
string postData;
byte[] byteArray;
Stream dataStream;
while (true)
{
try
{
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("http://www.********/index.php");
ASCIIEncoding encoding = new ASCIIEncoding();
postData = "param=example¶m=0¶m=bigboy";
byte[] data = encoding.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
httpWReq.KeepAlive = false;
httpWReq.CookieContainer = new CookieContainer();
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
stream.Close();
}
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
}
}
What can be done to achieve such a looping process?
Something like the following psuedocode should work for you.
Note the reuse of the same CookieContainer object on the login AND the logout requests.
static void Main(string[] args)
{
while (true)
{
try
{
CookieContainer cookies = new CookieContainer();
HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create("http://www.********/index.php");
loginRequest.CookieContainer = cookies;
// Configure login request headers and data, write to request stream, etc.
HttpWebResponse loginResponse = (HttpWebResponse)loginRequest.GetResponse();
HttpWebRequest logoutRequest = (HttpWebRequest)WebRequest.Create("http://www.********/logout.php");
logoutRequest.CookieContainer = cookies;
// Configure logout request headers and data, write to request stream, etc.
HttpWebResponse logoutResponse = (HttpWebResponse)logoutRequest.GetResponse();
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
}
}
Give something like this a try and let me know how it goes.
Also: Try debugging the response objects' Cookie property. It's a CookieCollection, not a CookieContainer as per the request. But it should still provide useful debug information if you need to take a closer look at exactly what's going on. Example here: http://goo.gl/L2MMrj
How to access the login authentication by the POST DATA in the below and it get from the httpFox to login the website. In other time i try to testing whether the GetRequestStreamCallback() operation will work and i found that the operation are not working and it end on the DoWork(). Why it not continue do the GetRequestStreamCallback() operation. Thanks For Helping me.
POST DATA
Parameter value
__EVENTTARGET
__EVENTARGUMENT
__VIEWSTATE /wEPDwUIMTQwOTY1MTgPZBYCAgMPZBYEAgEPZBYCZg9kFgICAQ9kFgJmD2QWAgINDxAPFgIeB0NoZWNrZWRoZGRkZAIFDzwrAAgCAA8WBB4PRGF0YVNvdXJjZUJvdW5kZx4OXyFVc2VWaWV3U3RhdGVnZAYPFgIeCklzU2F2ZWRBbGxnDxQrAAkUKwABFgIeDlJ1bnRpbWVDcmVhdGVkZxQrAAEWAh8EZxQrAAEWAh8EZxQrAAEWAh8EZxQrAAEWAh8EZxQrAAEWAh8EZxQrAAEWAh8EZxQrAAEWAh8EZxQrAAEWAh8EZ2QWAmYPZBYCAgEPZBYCZg9kFgJmD2QWAmYPZBYCZg9kFgICAg9kFgJmD2QWAmYPZBYCZg9kFgZmD2QWBmYPZBYCZg9kFgJmD2QWCAIBDw8WAh4ISW1hZ2VVcmwFG34vcHJvZHVjdGltYWdlL0NBRDAwNTQ3LmpwZ2RkAgMPDxYCHgRUZXh0BQhDQU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gVEVTSU5HIEFORCBUUkFJTklORyBPTlNJVEUgMSBEQVlkZAIHDw8WAh8GBQhTRU5USU5BTGRkGAIFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYCBRxMb2dpblZpZXcxJExvZ2luMSRSZW1lbWJlck1lBQ1BU1B4RGF0YVZpZXcxBQ1BU1B4RGF0YVZpZXcxDxQrAAdkZmYCA2YCFGdkMBSkuj/XQpQVVL41154MjHTriF3AqkB5ahYmcD10itw=
__EVENTVALIDATION /wEWBgLiiri0BQKRyKzhAgKUxtegDAKi77CUBwKd6MPGBALNx9K3CuAiLP9Qxn4q+Nwy4Hl2t5zaXX+GadHLKCF8sJn6YTar
LoginView1$Login1$UserName USERNAME
LoginView1$Login1$Password PASSWORD
LoginView1$Login1$LoginButton Log In
ASPxDataView1 0;3;3
DXScript 1_141,1_79,1_123,1_82
The below code is my work so far.
public void DoWork()
{
var url = "xxxxxxxx";
// Create the web request object
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
// Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
// Create the post data
// Demo POST data
string postData =
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
// Error treatment
// ...
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
DoWork();
}
I need to send some data from windows phone 7 to php page through POST method, I have the following code at wp7 side
public void SendPost()
{
var url = "http://localhost/HelpFello/profile.php";
// Create the web request object
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
// Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
MessageBox.Show("data sent");
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
// Create the post data
// Demo POST data
string postData = "user_id=3&name=danish&email_id=mdsiddiquiufo&password=12345&phone_Number=0213&about_me=IRuel2&rating=5";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
MessageBox.Show(e.ToString());
}
}
and following on my localhost, to send the data to database
<?php
require_once("constants.php");
$user_id = $_POST['user_id'];
$name = $_POST['name'];
$email_id = $_POST['email_id'];
$password = $_POST['password'];
$phone_number = $_POST['phone_number'];
$about_me = $_POST['about_me'];
$rating = $_POST['rating'];
$query="INSERT INTO profile(User_ID,Name,Email_ID,password,Phone_Number,About_Me,Rating) VALUES ({$user_id},'{$name}','{$email_id}','{$password}',{$phone_number}, '{$about_me}' , {$rating})";
mysql_query($query,$connection);
mysql_close($connection);
?>
When I run the code I have no errors it means code is working fine, but no data is inserted in the database.
I think there is a better way than HttpWebRequest. That is WebClient. You can change the method there and append data like you do in get string. key=value&key2=value then when you invoke that request and get the response try debugging and getting the output from VS or if that is difficult simply assign he string to a textblock in the code. You will get to know if that page has been ever executed or not.
A sample code :
WebClient wc = new WebClient();
wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
wc.Encoding = Encoding.UTF8;
Parameters prms = new Parameters();
prms.AddPair("email", email);
prms.AddPair("password", password);
wc.UploadStringAsync(new Uri(loginUrl), "POST", prms.FormPostData(), null);
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
// e.Result will contain the page's output
}
// This is my Parameters and Parameter Object classes
public class Parameters
{
public List<ParameterObject> prms;
public Parameters()
{
prms = new List<ParameterObject>();
}
public void AddPair(string id, string val)
{
prms.Add(new ParameterObject(id, val));
}
public String FormPostData()
{
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < prms.Count; i++)
{
if (i == 0)
{
buffer.Append(System.Net.HttpUtility.UrlEncode(prms[i].id) + "=" + System.Net.HttpUtility.UrlEncode(prms[i].value));
}
else
{
buffer.Append("&" + System.Net.HttpUtility.UrlEncode(prms[i].id) + "=" + System.Net.HttpUtility.UrlEncode(prms[i].value));
}
}
return buffer.ToString();
}
}
public class ParameterObject
{
public string id;
public string value;
public ParameterObject(string id, string val)
{
this.id = id;
this.value = val;
}
}
First error: assuming that no error messages means success
Second error: gaping SQL injection holes
first fix: always assume queries will fail, and check for that condition:
$result = mysql_query($query) or die(mysql_error());
second fix: ditch the mysql_() functions and switch to PDO using prepared statements with placeholders. Boom. No more injection problems, and your code won't stop working on you when mysql_() is removed in a future PHP version.
ps..
3rd error: no quotes on your phone number value. So someone submits 867-5309, and you end up inserting -4442 because mysql saw it as two numbers being subtracted, not a string.
I cant really seem to find this anywhere so I was wondering if you could help. I am trying to create a script which automatically logins to a HTTPS link via C#.
So essentially - I have a URL that contains a report I need to run daily but its behind a HTTPS login with username/password.
I am trying to create a script in C# which runs at X time, logins with username/password ? Any ideas?
Will love you long time!:)
Edit:---
OK now what if I want to save the *.txt file automatically to a database?
Here's some sample code that I wrote that logs into a website to send an SMS message:
private void sendMessage(SmsMessage message)
{
HttpWebRequest request;
HttpWebResponse response;
CookieContainer cookies;
string url = "http://www.xyzwebsite.com/";
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = true;
request.CookieContainer = new CookieContainer();
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
cookies = request.CookieContainer;
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
String postData = "emailfrom="+credentials.Username+"&npa="+message.DestinationPhoneNumber.Substring(0,3)+"&exchange="+message.DestinationPhoneNumber.Substring(3,3)+"&number="+message.DestinationPhoneNumber.Substring(6)+"&body="+HttpUtility.UrlEncode(message.MessageText)+"&submitted=1&submit=Send";
byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(postData);
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
request.CookieContainer = cookies;
stream.Close();
response = (HttpWebResponse)request.GetResponse();
response.Close();
}
else
{
Console.WriteLine("Client was unable to connect!");
}
}
catch (System.Exception e)
{
throw new SMSDeliveryException("Unable to deliver SMS message because " + e.Message, e);
}
}
WebClient and NetworkCredential shoudl solve that for you, examples:
https://web.archive.org/web/20211020134945/https://www.4guysfromrolla.com/articles/102605-1.aspx