How do I use C# to post to this form grammatically? - c#

I am trying to check my gift card balance, (I have many) on the following website and I want to automate via a C# program.
https://www.fivebackgift.com/
It is form1 in the source code im interested in. This is my code:
class Program
{
public static string HttpPost(string url, params object[] postData)
{
StringBuilder post = new StringBuilder();
for (int i = 0; i < postData.Length; i += 2)
post.Append(string.Format("{0}{1}={2}", i == 0 ? "" : "&", postData[i], postData[i + 1]));
return HttpPost(url, post.ToString());
}
public static string HttpPost(string url, string postData)
{
postData = postData.Replace("\r\n", "");
try
{
WebRequest req = WebRequest.Create(url);
byte[] send = Encoding.Default.GetBytes(postData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = send.Length;
Stream sout = req.GetRequestStream();
sout.Write(send, 0, send.Length);
sout.Flush();
sout.Close();
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
return returnvalue;
}
catch (Exception ex)
{
Debug.WriteLine("POST Error on {0}\n {1}", url, ex.Message);
return "";
}
}
static void Main(string[] args)
{
HttpPost("https://www.fivebackgift.com/Card/_Login?returnUrl=Transactions",
"CardNumber", "CREDIT NUMBER",
"ExpirationMonth", "MONTH",
"ExpirationYear", "YEAR",
"SecurityCode", "CODE");
}
}
I just want to see if the website would give me a response. The following error is what I get:
POST Error on https://www.fivebackgift.com/Card/_Login?returnUrl=Transactions
The remote server returned an error: (404) Not Found.
How do I figure out what the real URL should be?

Related

I am trying to Access the private Poloniex trading API in Unity C# but am getting the error "invalid command"

I am trying to Access the private Poloniex trading API in Unity C# but am getting the error "invalid command" I have my API Key and Secret authorized on Poloniex for the Trading API but can't seem to get access with my current code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Security.Cryptography;
public class PolonScript : MonoBehaviour {
public TextMesh OutputText;
const string _apiKey = "---Key---";
const string _apiSecret = "---secret---";
void Start () {
string nonce = DateTime.Now.ToString("HHmmss");
string myParam = "command=returnBalances&nonce=" + nonce;
const string WEBSERVICE_URL = "https://poloniex.com/tradingApi";
try
{
var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.Timeout = 12000;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Headers.Add("Key", _apiKey);
webRequest.Headers.Add("Sign", genHMAC(myParam));
webRequest.Headers.Add("command", "returnBalances");
webRequest.Headers.Add("nonce", nonce.ToString());
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
OutputText.text = jsonResponse.ToString();
}
}
}
}
catch (Exception ex)
{
OutputText.text = ex.ToString();
}
} //end-of-start()
Here is my current signing method which I am quite sure has a mistake (Human error) within, am I doing something wrong obliviously here?
private string genHMAC(string message)
{
byte [] APISecret_Bytes = System.Text.Encoding.UTF8.GetBytes(_apiSecret);
byte [] MESSAGE_Bytes = System.Text.Encoding.UTF8.GetBytes(message);
var hmac = new HMACSHA512(APISecret_Bytes);
var hashmessage = hmac.ComputeHash(MESSAGE_Bytes);
var sign = BitConverter.ToString(hashmessage).Replace("-", "").ToLower();
return sign;
}
}
Poloniex Command should not be sent in the header, you should send it as a POST parameter, that's why it's responding "invalid command". Take a look at this answer to see how you send POST parameters in c#:How to add parameters into a WebRequest?
Here's an example of how your Start method should look like:
void Start()
{
string nonce = DateTime.Now.ToString("HHmmss");
string myParam = "command=returnBalances&nonce=" + nonce;
const string WEBSERVICE_URL = "https://poloniex.com/tradingApi";
try
{
var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.Timeout = 12000;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Headers.Add("Key", _apiKey);
webRequest.Headers.Add("Sign", genHMAC(myParam));
byte[] dataStream = Encoding.UTF8.GetBytes($"command=returnBalances&nonce={nonce.ToString()}");
webRequest.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
OutputText.text = jsonResponse.ToString();
}
}
}
}
catch (Exception ex)
{
OutputText.text = ex.ToString();
}
}

How to create Journal entry in QuickBooks Online

I am trying to use C# to create a Journal entry in Quickbooks Online V3 API.
Things I have done:
Check JSON Values and format
Checked Header and accept.
Header info:
Accept : application/json
Authorization : OAuth oauth_token="************",oauth_nonce="cfc36792-8f9a-4202-9fec-be0a610eed8e",oauth_consumer_key="************",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1435189421",oauth_version="1.0",oauth_signature="***"
Content-Length : 642
Content-Type : application/json
Host : qb.sbfinance.intuit.com
//till here everything is fine not sure about last two lines..
//not sure should i add this to my header or not..
X-NewRelic-ID : UQMAU15RGwcAUllSDwc=
X-NewRelic-Transaction : PxQAVVRUCgMIUiRXdHMBICETGlUDChAHHEAPVgoPBgILU3xUciMFJCEUG0MDUwFVAV1WVBVs
My code:
public static void Main()
{
// JournalEndPoint lnew = new JournalEndPoint();
// string Json=lnew.CreateJournal();
string consumerKey = "***";
string consec = "***";
string appkeysec1 = "***";
string appkey1 = "***";
string returnvalue = ExecuteV3Query(consumerKey, consec, appkey1, appkeysec1, "1397754725", "select * from employee where active=TRUE");
}
public static string ExecuteV3Query(string consumerKey, string consumerSecret, string accessToken, string accessTokenSecret, string CompanyId, string query)
{
string encodedQuery = RestSharp.Contrib.HttpUtility.UrlEncode(query);
string uri = string.Format("https://quickbooks.api.intuit.com/v3/company/{0}/journalentry", CompanyId, encodedQuery);
HttpWebRequest httpWebRequest = WebRequest.Create(uri) as HttpWebRequest;
httpWebRequest.Method = "POST";
string JSonvalue = CreateUserJson();
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "application/json";
httpWebRequest.Headers.Add("Authorization", GetDevDefinedOAuthHeader(consumerKey, consumerSecret, accessToken, accessTokenSecret, httpWebRequest, null));
//HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
/*
* using (Stream data = httpWebResponse.GetResponseStream())
{
//return XML response
return new StreamReader(data).ReadToEnd();
}
*/
var result = "";
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
catch (WebException e)
{
Console.WriteLine("This program is expected to throw WebException on successful run." +
"\n\nException Message :" + e.Message);
if (e.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
using (Stream data = e.Response.GetResponseStream())
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
Console.WriteLine(text);
result = text;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return result;
}
GetDevDefineHeader() will create header and return type is string.
In your url, I do not see the use of encoded query and why are you passing it?
Please check the docs for correct endpoints for CRUD and query operations-
https://developer.intuit.com/docs/api/accounting/JournalEntry
See this example for GET using dev defined-
https://gist.github.com/IntuitDeveloperRelations/0913b4c224de758fde0a
Similarly there is a post example here, you can write similarly for JE-
//string res = CreateV3Customer(consumerKey, consumerSecret, accessToken, accessTokenSecret, realmId);
public string CreateV3Customer(string consumerKey, string consumerSecret, string accessToken, string accessTokenSecret, string realmId)
{
StringBuilder request = new StringBuilder();
StringBuilder response = new StringBuilder();
var requestBody = "{\"FamilyName\":\"Jack\"}";
HttpWebRequest httpWebRequest = WebRequest.Create("https://quickbooks.api.intuit.com/v3/company/"+realmId+"/customer") as HttpWebRequest;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Authorization", GetDevDefinedOAuthHeader(consumerKey, consumerSecret, accessToken,accessTokenSecret,httpWebRequest, requestBody));
request.Append(requestBody);
UTF8Encoding encoding = new UTF8Encoding();
byte[] content = encoding.GetBytes(request.ToString());
using (var stream = httpWebRequest.GetRequestStream())
{
stream.Write(content, 0, content.Length);
}
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (Stream data = httpWebResponse.GetResponseStream())
{
string customerr = new StreamReader(data).ReadToEnd();
return customerr;
}
}

How to call add account method for tempoplugin with post in C#

At this url there is a description how to call tempoplugin with usage of post. In order to achieve it, I created following string:
also created following code for posting data:
public static string HTTP_POST(string Url, string Data, string userName = "", string password = "")
{
string Out = String.Empty;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url);
try
{
if (userName != null && password != null)
{
req.ContentType = "application/json";
req.Method = "POST";
req.ProtocolVersion = HttpVersion.Version11;
string base64Credentials = GetEncodedCredentials(userName, password);
req.Headers.Add("Authorization", "Basic " + base64Credentials);
}
req.Timeout = 100000;
byte[] sentData = Encoding.UTF8.GetBytes(Data);
req.ContentLength = sentData.Length;
using (System.IO.Stream sendStream = req.GetRequestStream())
{
sendStream.Write(sentData, 0, sentData.Length);
sendStream.Close();
}
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
System.IO.Stream ReceiveStream = res.GetResponseStream();
using (System.IO.StreamReader sr = new System.IO.StreamReader(ReceiveStream, Encoding.UTF8))
{
Char[] read = new Char[256];
int count = sr.Read(read, 0, 256);
while (count > 0)
{
String str = new String(read, 0, count);
Out += str;
count = sr.Read(read, 0, 256);
}
}
}
catch (ArgumentException ex)
{
Out = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message);
}
catch (WebException ex)
{
Out = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message);
}
catch (Exception ex)
{
Out = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message);
}
return Out;
}
But still I receive response "The remote server returned an error: (404) Not Found". Does anybody knows what I missed?
I fount the solution. The problem lied in permissions on Jira. After double checking with admins my code worked perfectly.

StreamWritter UTF8 Encoding Error

We are developing an android,wp &iOS application using File Linking strategy of Xamarin.
We have written WCF REST Service to input/output as JSON format data.
In database class we have used ASCII format and it works fine, but we tried to change UTF8 format to support for multiple languages. While changing we are getting error as "The remote server returned an error: (400) Bad Request" in HttpWebResponse line.
Please find the sample database function for sending data to WCF REST Service with UTF-8. Kindly suggest to resolve.
public async Task<String> GetString<T>(T item, String ServiceAddress, String FunctionName, String[] Parameters, object[] ParameterValues) where T : BusinessLayer.Contracts.IBusinessEntity, new()
{
string ParameterString = string.Empty;
try
{
var request = HttpWebRequest.Create(ServiceAddress);
request.ContentType = "application/json";
request.Method = "POST";
request.Headers["Authorization"] = GlobalVariables.glbtoken;
if (Parameters.Length > 0)
ParameterString = "{";
for (int i = 0; i < Parameters.Length; i++)
{
ParameterString = ParameterString + "\"" + Parameters[i] + "\":\"" + ParameterValues[i] + "\"" + ",";
}
if (Parameters.Length > 0)
{
ParameterString = ParameterString.Remove(ParameterString.Length - 1, 1);
ParameterString += "}";
}
// var sw = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
var sw = new StreamWriter(request.GetRequestStream(), Encoding.UTF8);
sw.Write(ParameterString); **//This string is not passed to server and shows null**
sw.Close();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) // Here the line breaks and returned to catch with no parameters passed.
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
if (content != "")
OutputString = (string)Newtonsoft.Json.JsonConvert.DeserializeObject(content);
}
}
}
catch (Exception e) { }
return OutputString;
}

programatically send a form with POST

I need to programatically send a form over POST. I have 4 fields, one checkbox and a submit button. how can i go about it?
I use these functions assuming your question is about a forms application.
You can call
HttpPost(
post_url,
"field_name_1", value_1,
"field_name_2", value_2,
...);
Here they are:
public static string HttpPost(string url, params object[] postData)
{
StringBuilder post = new StringBuilder();
for (int i = 0; i < postData.Length; i += 2)
post.Append(string.Format("{0}{1}={2}", i == 0 ? "" : "&", postData[i], postData[i + 1]));
return HttpPost(url, post.ToString());
}
public static string HttpPost(string url, string postData)
{
postData = postData.Replace("\r\n", "");
try
{
WebRequest req = WebRequest.Create(url);
byte[] send = Encoding.Default.GetBytes(postData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = send.Length;
Stream sout = req.GetRequestStream();
sout.Write(send, 0, send.Length);
sout.Flush();
sout.Close();
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
return returnvalue;
}
catch (Exception ex)
{
Debug.WriteLine("POST Error on {0}\n {1}", url, ex.Message);
return "";
}
}
This should do the trick:
NameValueCollection formData = new NameValueCollection();
formData.Add("field1", "value1");
formData.Add("field2", "value2");
// ... and so on ...
WebClient client = new WebClient();
byte[] result = client.UploadValues("http://www.example.com", formData);
The information, that you have checkboxes or submit buttons is not transferred. It's always name and value.
JQuery $.Post() does exactly that.

Categories

Resources