Cannot get Context.Request parameters from Paypal IPN - c#

I have a little C# snippet that is supposed to be requested by Paypal IPN, confirm the payment then get some parameters from the request. The problem is that I am unable to get those parameters.
public class ipn : IHttpHandler {
protected string paypalUrl = "https://www.sandbox.paypal.com/cgi-bin/webscr";
public void ProcessRequest (HttpContext context) {
Task.Run(() => VerifyTask(context));
context.Response.Write("");
}
private void VerifyTask(HttpContext context)
{
var verificationResponse = string.Empty;
StreamReader reader = new StreamReader(context.Request.InputStream);
string requestFromPost = reader.ReadToEnd();
// at this point I am getting the request parameters correctly
File.WriteAllText(context.Server.MapPath("request.txt"), "Request: " + requestFromPost);
context.Request.InputStream.Position = 0;
try
{
// validating request here, all fine
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var verificationRequest = (HttpWebRequest)WebRequest.Create(paypalUrl);
// set values for the verification request
verificationRequest.Method = "POST";
verificationRequest.ContentType = "application/x-www-form-urlencoded";
// add cmd=_notify-validate to the payload
var strRequest = "cmd=_notify-validate&" + requestFromPost;
verificationRequest.ContentLength = strRequest.Length;
// attach payload to the verification request
var streamOut = new StreamWriter(verificationRequest.GetRequestStream(), Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
// send the request to PayPal and get the response
var streamIn = new StreamReader(verificationRequest.GetResponse().GetResponseStream());
verificationResponse = streamIn.ReadToEnd();
streamIn.Close();
}
catch ( Exception exception)
{
// handling exception here, later
}
// sending context and response
ProcessVerificationResponse(context, verificationResponse);
}
private void ProcessVerificationResponse(HttpContext context, string verificationResponse)
{
// verifications response is VERIFIED
if (verificationResponse.Equals("VERIFIED"))
{
try {
// trying to get payment status
File.WriteAllText(context.Server.MapPath("status.txt"), "Verified: " + context.Request.QueryString["payment_status"]);
}
catch ( Exception exception)
{
// capture exception for manual investigation
File.WriteAllText(context.Server.MapPath("error.txt"), "Error: " + exception.Message);
}
}
}
}
An exception is thrown and the error.txt file is created with an "Object reference not set to an instance of an object" error. This happens no matter what I do with context.Request
context.Request.QueryString.Count.ToString() does the same
context.Request["payment_status"]
context.Request.Params.Count.ToString() triggers the same exception
so I don't know what is uninitialized and why, because context.Request.InputStream is not empty at least

Related

C# RestClient returning "Login Required" when Login Details are specified

Just started at a new company and we all use Jira, the customers are determined to not use it as they don't like it so I have decided to build a simple Windows Form when they can both Log tickets and get Updates and Comments in a nice simple UI.
Now I have never done any coding before 2 weeks ago so it has been a struggle to get my head around both C# and Rest (Have made scripts for basic IT fixes but never anything as complex as this!)
Back onto point, Set up and got a Rest API set up with a Rest Client but everytime I try pull data from a ticket on Jira I get the error:
{"errorMessages":["You do not have the permission to see the specified issue.","Login Required"],"errors":{}}
Here is the code from the Form:
private void button3_Click_1(object sender, EventArgs e)
{
var client = new RestClient("https://jira.eandl.co.uk/rest/api/2/issue/ITREQ-" + textBox1.Text
);
client.Authenticator = new SimpleAuthenticator("username", "abc", "password", "123");
var request = new RestRequest(Method.GET);
request.AddParameter("token", "saga001", ParameterType.UrlSegment);
// request.AddUrlSegment("token", "saga001");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var queryResult = client.Execute(request);
Console.WriteLine(queryResult.Content);
}
And here is the code from the Rest Client itself:
public Restclient()
{
endPoint = string.Empty;
httpMethod = httpVerb.GET;
}
private string logonAttempt;
public string makeRequest()
{
string strResponseValue = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endPoint);
request.Method = httpMethod.ToString();
String authHeader = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(userName + ":" + userPassword));
request.Headers.Add("Authorization", authType.ToString() + " " + authHeader);
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
//Process the Response Stream... (Could be JSON, XML ot HTML etc...)
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
strResponseValue = reader.ReadToEnd();
}//End of Stream Reader
}
}//end of Response Stream
}
catch (Exception ex)
{
strResponseValue = "(\"errorMessages\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
}
finally
{
if(response != null)
{
((IDisposable)response).Dispose();
}
}
return strResponseValue;
}
}
}
Now obviously I am expecting that I have missed something absolutely bigginer as like I said, I've never taken on a project like this before and had 0 experience.
Just looking for someone to bluntly tell me what I'm doing wrong
Changed to this as per answer:
private void button3_Click_1(object sender, EventArgs e)
{
var client = new
RestClient("https://jira.eandl.co.uk/rest/api/2/issue/ITREQ-" + textBox1.Text
);
client.Authenticator = new HttpBasicAuthenticator("username", "password");
var request = new RestRequest(Method.GET);
string authHeader = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("cdale!" + ":" + "Chantelle95!"));
request.AddHeader("Authorization", "Basic " + authHeader);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var queryResult = client.Execute(request);
Console.WriteLine(queryResult.Content);
}
By default with the Jira REST API, you can use Basic Authentication or OAuth2. I think that more easy way for you will be to use the Basic one.
I'm not sure why you have a class where you define your custom RestClient since the first block of code uses the RestSharp one from http://restsharp.org.
In this case, you will need to modify your authenticator:
client.Authenticator = new HttpBasicAuthenticator(userName, password);
And I think that you should remove the line where you specify a token. I don't think that it's required.
Finally, the class Restclient doesn't seem to be used, then remove it.
You could also uses what you have created in your custom RestClient and manually specify a Basic header:
string authHeader = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(userName + ":" + userPassword));
request.AddHeader("Authorization", "Basic " + authHeader);
However, it's essentially the behavior of the HttpBasicAuthenticator class.
If you don't want to encode your credentials in every request here is how to do it using cookies.
When requesting the cookie you don't need to add any authorization on the headers. This method will accept a JSON string with the user name and password and the URL. It will return the cookie values.
public async Task<JiraCookie> GetCookieAsync(string myJsonUserNamePassword, string JiraCookieEndpointUrl)
{
using (var client = new HttpClient())
{
var response = await client.PostAsync(
JiraCookieEndpointUrl,
new StringContent(myJsonUserNamePassword, Encoding.UTF8, "application/json"));
var json = response.Content.ReadAsStringAsync().Result;
var jiraCookie= JsonConvert.DeserializeObject<JiraCookie>(json);
return jArr;
}
}
public class JiraCookie
{
public Session session { get; set; }
}
public class Session
{
public string name { get; set; }
public string value { get; set; }
}
When I call it using url: http://[baseJiraUrl]/rest/auth/1/session it returns the following JSON response:
{
"session" : -{
"name" : JSESSIONID,
"value" : cookieValue
}
Keep in mind the URL above is valid in the version of JIRA I'm using and may vary depending on which version you're using. Read the JIRA API documentation for the correct URL for the version you are using. I'm using the following:
https://docs.atlassian.com/software/jira/docs/api/REST/7.6.1/#auth/1/session
Remember you'll have to store your cookie and use it on every subsequent request.
Check out this answer on how add cookies to your HttpClient request: How do I set a cookie on HttpClient's HttpRequestMessage.
Once you're done with the cookie (logging out) simply send a delete http request with the same URL as the post.
Reference: https://stackoverflow.com/a/49109192/7763903

Two consecutive httpwebRequests in c#

Is it possible to make two consecutive web requests in c#? So make the inital request and then make a request from that response. I am doing this to fill out two consecutive forms in a c# program.
string postdata = "param1=...&param2=..."
var data1 = Encoding.ASCII.GetBytes(postdata);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data1.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data1, 0, data1.Length);
}
var response = (HttpWebResponse)request.GetResponse();
So if this is my first form how would I then go and fill out the second form that the completion of this form should lead to?
This is a (very) stripped down version of some code using HttpWebRequest that can send a request either via parameters or content but assumes either (or both) are objects passed in. E.g., if you need to send parameters like login and password usage would look like;
var response = HttpUtilities.Post("http://www.someurl.com/", new { login = "user", password = "1234");
// check response data + codes, etc...
var secondResponse = HttpUtilities.Post("http://www.someurl.com/page2", new { data = "stuff" });
The code below won't necessarily compile as I had to strip it down manually and is untested in its current form but it gives a very good idea of what's needed to check the response, debug, etc.;
namespace Helpers.Web
{
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Cache;
using System.Net.Http;
using System.Reflection;
using System.Web;
using Newtonsoft.Json;
using NLog;
public class HttpUtilities
{
#region NLog instance
/// <summary>
/// The single instance of an NLog LogManager for this class.
/// </summary>
private static Logger _logger = LogManager.GetCurrentClassLogger();
#endregion
#region Public Methods
public static TResponse Post<TResponse, TContent>(string uri, object parameters = null, TContent content = null)
where TContent : class
{
return GetResponse<TResponse, TContent>(uri, SerializeToQueryString(parameters),
content, HttpMethod.Post);
}
public static HttpWebResponse GetResponse<TContent>(string uri,
string parameters,
TContent content,
HttpMethod method)
where TContent : class
{
// build the full URL if parameters have been specified
if (!string.IsNullOrEmpty(parameters))
{
uri += "?" + parameters;
}
// make the request and send back the results
HttpWebRequest webRequest = BuildWebRequest(uri, content, method);
return GetWebResponse(uri, webRequest);
}
#endregion
#region Private Methods
private static HttpWebRequest BuildWebRequest<TContent>(string uri, TContent content, HttpMethod method)
where TContent : class
{
// get the request details
_logger.Trace("Building request for [{0}]", uri);
// set the web request details
_logger.Trace("Setting request header details...");
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = method.ToString();
webRequest.ContentType = "application/json";
webRequest.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
// do we have content to insert
string serializedContent = string.Empty;
if (content != null)
{
JsonSerializerSettings jsonSettings = new JsonSerializerSettings
{
// ignore the self referencing nature of EntityFramework objects and skip
// over the self references when serializing
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
// serialize the object as json and convert it into bytes we can
// inject into the content stream of the request.
serializedContent = JsonConvert.SerializeObject(content, jsonSettings);
UTF8Encoding encoding = new UTF8Encoding();
byte[] byteContent = encoding.GetBytes(serializedContent);
webRequest.ContentLength = byteContent.Length;
// write the content
// NOTE: the act of writing out the data actually sends the request!
_logger.Trace("Sending request and getting response from [{0}]", uri);
using (var contentStream = webRequest.GetRequestStream())
{
contentStream.Write(byteContent, 0, byteContent.Length);
}
_logger.Trace("Injected content into request to [{0}]. Content: {1}", uri, serializedContent);
}
else
{
// if there's no content then we haven't actually sent the request yet. However we still
// need to set the header details.
webRequest.ContentLength = 0;
_logger.Trace("Sending request and getting response from [{0}]", uri);
}
return webRequest;
}
private static HttpWebResponse GetWebResponse(string uri, HttpWebRequest webRequest)
{
HttpWebResponse response;
try
{
_logger.Debug("Sending [{0}] request to [{1}]...", webRequest.Method, webRequest.RequestUri.AbsoluteUri);
response = (HttpWebResponse)webRequest.GetResponse();
}
catch (WebException wex)
{
// we might still have response information on the request
// if this is so, then extract it and log it as we'll need to
// find out what the server actually replied with in order to debug
// what went on
_logger.Error(wex, "There was a problem getting a response from the server");
if (wex.Response != null)
{
try
{
// NOTE: this can be caused by the server returning a YSOD. You can see the formatted result
// in debug mode by using the HTML visualizer when looking at the content of the
// wResponseContent variable.
_logger.Debug("Attempting to extract server response details from WebException...");
using (Stream wResponseStream = wex.Response.GetResponseStream())
{
if (wResponseStream != null)
{
using (StreamReader wStreamReader = new StreamReader(wResponseStream))
{
string wResponseContent = wStreamReader.ReadToEnd();
_logger.Debug(wex, "Received fault response from [{0}]. Response: {1}",
uri, wResponseContent);
}
}
}
}
catch (Exception eex)
{
// there was an issue trying to get the response content from the original error.
// There's nothing more we can do except log this exception and rethrow the
// original.
_logger.Fatal(eex, "There was a problem getting response details from a WebException raised from the server");
throw;
}
}
else
{
_logger.Debug("No response data present in the exception.");
}
throw;
}
catch (Exception ex)
{
_logger.Error(ex, "There was a problem getting a response from [{0}]", uri);
throw;
}
return response;
}
private static string SerializeToQueryString(object parameters)
{
// if we weren't given anything then there's nothing we can do
if (parameters == null)
{
return string.Empty;
}
if (parameters is string)
{
return parameters as string;
}
// iterate over the parameter properties and build the query string
Type type = parameters.GetType();
BindingFlags flags = BindingFlags.Instance
| BindingFlags.GetProperty
| BindingFlags.Public;
if (type.IsInterface)
{
// if the type is an interface, only get the interface's members
flags |= BindingFlags.FlattenHierarchy;
}
PropertyInfo[] properties = type.GetProperties(flags);
List<string> urlParameters = new List<string>();
foreach (PropertyInfo prop in properties)
{
// convert the value to a string first so that we can make it safe
// to put into the URL
_logger.Trace("Getting value from {0}.{1} [{2}]", type.FullName, prop.Name, prop.PropertyType.FullName);
object rawValue = prop.GetValue(parameters, null);
string propertyValue = string.Empty;
if (rawValue != null)
{
propertyValue = rawValue.ToString();
}
urlParameters.Add(string.Format("{0}={1}", prop.Name, HttpUtility.UrlEncode(propertyValue)));
}
return string.Join("&", urlParameters.ToArray());
}
#endregion
}
}

C# GetResponse not coming back

I have an strange problem. My .NET DataController send a response to an Java server (REST). All works fine, but when I send a response very often, suddenly the GetResponse method not coming back just hangs.
I don't know what's the problem is.
Here is my code
ServicePointManager.DefaultConnectionLimit = 20;
public string HttpGet(string url, string requestAccept)
{
if(string.IsNullOrEmpty(url))
throw new Exception("HttpGet: no REST service URL provided");
if(string.IsNullOrEmpty(requestAccept))
requestAccept = defaultRequestAccept;
if(!url.Equals("pc/alive"))
{
if(string.IsNullOrEmpty(SessionId))
{
if(string.IsNullOrEmpty(Authorization()))
throw new WebException("HttpGet: no login");
}
}
int tries = RestAccessData.MaxReconnect;
string result = string.Empty;
do
{
try
{
var request = NewWebRequest(url, "GET", false, true, requestAccept);
using(var response = request.GetResponse() as HttpWebResponse)
{
UpdateSessionId(response);
HttpStatusCode statusCode = response.StatusCode;
LOG.Debug("...StatusCode: {0} ({1})", (int) response.StatusCode, response.StatusDescription);
if((int) response.StatusCode < 500)
lastContactWithServer = DateTime.Now.Ticks;
switch(statusCode)
{
// Informational 1xx
case HttpStatusCode.Continue: // 100
case HttpStatusCode.SwitchingProtocols: // 101
throw new HttpResponseException(response);
// Successful 2xx
case HttpStatusCode.OK: // 200
result = ReadContent(response);
response.Close();
return (result);
case HttpStatusCode.NoContent: // 204 The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation.
response.Close();
return (string.Empty);
case HttpStatusCode.Created: // 201
case HttpStatusCode.NonAuthoritativeInformation: // 203
result = ReadContent(response);
throw new HttpResponseException(response, result);
case HttpStatusCode.Accepted: // 202 The request has been accepted for processing, but the processing has not been completed.
case HttpStatusCode.ResetContent: // 205 The server has fulfilled the request and the user agent SHOULD reset the document view which caused the request to be sent.
case HttpStatusCode.PartialContent: // 206 The server has fulfilled the partial GET request for the resource.
throw new HttpResponseException(response);
case HttpStatusCode.Unauthorized:
throw new HttpResponseException(response);
default:
throw new HttpResponseException(response);
}
}
}
catch(WebException ex)
{
HandleWebException(ex);
}
catch(HttpResponseException ex)
{
throw ex;
}
catch(SystemException ex)
{
LOG.Error(ex, "caused a(n) {0}", ex.GetType().Name);
}
catch(Exception ex)
{
LOG.Warn(ex, "HttpGet: An error occured while trying to contact the server. Reason: {0}", ex.Message);
throw new UserException("An error occured while trying to contact the server.", ex);
}
}
while(0 < tries--);
return (string.Empty);
}
private HttpWebRequest NewWebRequest(string urlAsString, string requestType, bool withContentType, bool applicationJson, string requestAccept)
{
urlAsString = string.Format("{0}{1}", RestAccessData.GetUrl(), EncodeUrl(urlAsString));
Uri url;
if(!Uri.TryCreate(urlAsString, UriKind.Absolute, out url))
throw new NotSupportedException("url is not compatible");
LOG.Info("RESTUrl {0}", urlAsString);
try
{
var request = HttpWebRequest.Create(url) as HttpWebRequest;
if(!string.IsNullOrEmpty(SessionId))
{
CookieContainer cookies = new CookieContainer();
Cookie cookie = new Cookie
{
Name = "JSESSIONID",
Value = SessionId,
Domain = url.Host
};
cookies.Add(cookie);
request.CookieContainer = cookies;
}
request.Timeout = RestAccessData.Timeout;
request.Method = requestType;
request.AllowAutoRedirect = true;
request.AllowWriteStreamBuffering = true;
request.KeepAlive = false;
request.ContentLength = 0;
request.Headers["Accept-Charset"] = "utf-8";
request.Accept = requestAccept;
request.UserAgent = LvsClient;
if(withContentType)
request.ContentType = applicationJson ? defaultApplicationJson : defaultApplicationWwwForm;
if(!string.IsNullOrEmpty(credential.UserName) && !string.IsNullOrEmpty(credential.Password))
request.Headers["Authorization"] = string.Format("Basic {0}", Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", credential.UserName, credential.Password))));
return (request);
}
catch(Exception ex)
{
throw new UserException(TH.Translate("NewWebRequest caused an error"), ex);
}
}
Any ideas where the problem is?
This line is making me uncomfortable:
using(var response = request.GetResponse() as HttpWebResponse)
If the response is not an HttpWebResponse then it will never be disposed - the as operator will give you `null.
I found a solution. Very useful is this MSDN article about Understanding MaxServicePointIdleTime and DefaultConnectionLimit. After I play with MaxServicePointIdleTime property and read this comment
change the connection limit at any time
I found a good balance between connection alive and connection close. My client works fine after playing with MaxServicePointIdleTime and DefaultConnectionLimit.

Trouble in fetching results from server in windows phone

I'm communicating with my server with the following code,
private void Save_Click(object sender, RoutedEventArgs e)
{
var request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.BeginGetResponse(new AsyncCallback(GotResponse), request);
}
private void GotResponse(IAsyncResult asynchronousResult)
{
try
{
string data;
HttpWebRequest myrequest = (HttpWebRequest)asynchronousResult.AsyncState;
using (HttpWebResponse response = (HttpWebResponse)myrequest.EndGetResponse(asynchronousResult))
{
System.IO.Stream responseStream = response.GetResponseStream();
using (var reader = new System.IO.StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
}
this.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(data);
});
}
catch (Exception e)
{
var we = e.InnerException as WebException;
if (we != null)
{
var resp = we.Response as HttpWebResponse;
var code = resp.StatusCode;
this.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Message :" + we.Message + " Status : " + we.Status);
});
}
else
throw;
}
}
I'm giving date and amount as my input value,it is url encoded. If all my data's are valid then everything works fine. And so my server will give the data as
{
"code":0,
"message":"Success",
"data":{
"date":xxxx,
"amount":123
}
}
But in case if give an invalid value,(For eg: abcd for 'amount'), then my server would reply as
{
"code":2,
"message":"Invalid value passed"
}
In this case, after Executing the line
using (HttpWebResponse response = (HttpWebResponse)myrequest.EndGetResponse(asynchronousResult))
It jumps to catch, and it display
Message:The remote server returned an error:NotFound. Status:UnKnown Error
Required Solution: It should fetch the result as it did in the previous case.
What sholud i do to fix it?
Well presumably the HTTP status code is 404. You're already accessing the response in your error code though - all you need to do is try to parse it as JSON, just as you are in the success case, instead of using we.Message to show an error message. You should probably be ready for the content to either be empty or not include valid JSON though, and only do this on specific status codes that you expect to still return JSON.

Sending data to php from windows phone

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.

Categories