StreamWritter UTF8 Encoding Error - c#

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;
}

Related

C# API POST similar to CURL

I'm trying to use the vultr.com API that utilizes CURL. I have successfully completed a POST call to their API with several different calls, but one in particular will not work. Here is their documentation on the API https://www.vultr.com/api/ .
I am able to get their server/create and firewall/rule_create to work properly with pretty much the same exact code, but it will not work for their server/reboot command. Now here is code for a post to their API that I have successfully gotten to work.
public static void AddIpToFirewall(string ip,string fireWallGroupId)
{
string Data = "FIREWALLGROUPID=" + fireWallGroupId + "&direction=in&ip_type=v4&protocol=tcp&subnet=" + ip + "&subnet_size=32&port=80";
string Reponse = String.Empty;
StreamWriter Sw = null;
StreamReader Sr = null;
try
{
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create("https://api.vultr.com/v1/firewall/rule_create");
Req.Method = "POST";
Req.ContentType = "application/x-www-form-urlencoded";
Req.ContentLength = Data.Length;
Req.Headers.Add(ApiKey);
using (var sw = new StreamWriter(Req.GetRequestStream()))
{
sw.Write(Data);
}
Sr = new
StreamReader(((HttpWebResponse)Req.GetResponse()).GetResponseStream());
Reponse = Sr.ReadToEnd();
Sr.Close();
}
catch (Exception ex)
{
if (Sw != null)
Sw.Close();
if (Sr != null)
Sr.Close();
Console.WriteLine(ex.Message + "\r\n\r\n'error with vultr...");
}
}
Now here is the code that will not work. It's pretty much identical to the firewall POST command.
public static void RebootCommand(string subId)
{
string Data = "SUBID=" + subId;
string Reponse = String.Empty;
StreamWriter Sw = null;
StreamReader Sr = null;
try
{
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create("https://api.vultr.com/v1/server/reboot");
Req.Method = "POST";
Req.ContentType = "application/x-www-form-urlencoded";
Req.ContentLength = Data.Length;
Req.Headers.Add(ApiKey);
using (var sw = new StreamWriter(Req.GetRequestStream()))
{
sw.Write(Data);
}
Sr = new
StreamReader(((HttpWebResponse)Req.GetResponse()).GetResponseStream());
Reponse = Sr.ReadToEnd();
Sr.Close();
}
catch (Exception ex)
{
if (Sw != null)
Sw.Close();
if (Sr != null)
Sr.Close();
Console.WriteLine(ex.Message + " error with vultr...");
}
}
It does not receive an error, but fails to reboot the VM. I've contacted their support and they say that their reboot command is working without any issues. Is there anyone out there that has had this issue before? Thanks.
I figured it out. With all of the other POST requests that I have done from their API the line Req.ContentLength = Data.Length was required. But for whatever reason that line had to be removed to get the reboot command to work.

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

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?

Problems with PayPal API Http call

I've integrated an option for users to pay via PayPal their online shopping on the web shop that I'm creating. The problem came up suddenly when I started to get this error:
You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
And the code for the Http call is as following:
public string HttpCall(string NvpRequest)
{
string url = pEndPointURL;
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode(BNCode);
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost.ToString());
}
}
catch (Exception e)
{
}
//Retrieve the Response returned from the NVP API call to PayPal.
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse(); // this is the line where the exception occurs...
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
return result;
}
Can someone help me out with this? It worked fine a day ago, now its giving me this error?
Okay so if anyone is interested, I was able to fix the error by adding the following line before creating the web request (I was able to fix it by going down to Tls12 like this):
`ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12`;
Cheers :-)
Edit try this:
public string HttpCall(string NvpRequest)
{
string url = pEndPointURL;
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode(BNCode);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
// Try using Tls11 if it doesnt works for you with Tls
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = WebRequestMethods.Http.Post;
objRequest.ContentLength = strPost.Length;
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost.ToString());
}
}
catch (Exception e)
{
}
//Retrieve the Response returned from the NVP API call to PayPal.
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
return result;
}
public string HttpCall(string NvpRequest) //CallNvpServer
{
string url = pendpointurl;
//To Add the credentials from the profile
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode( BNCode );
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost);
}
}
catch (Exception e)
{
/*
if (log.IsFatalEnabled)
{
log.Fatal(e.Message, this);
}*/
}
//Retrieve the Response returned from the NVP API call to PayPal
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
//Logging the response of the transaction
/* if (log.IsInfoEnabled)
{
log.Info("Result :" +
" Elapsed Time : " + (DateTime.Now - startDate).Milliseconds + " ms" +
result);
}
*/
return result;
}
After a number of hours wasted, it turned out to be the Tls protocol version.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Google Cloud Messaging - Using "delay_while_idle" - App Server C#

First of all, I'm feeling bad asking this question because I think that the error it's something simple.
I'm using GCM on android and I wrote an app server in C#. Everything works fine but I have a doubt trying to specify delay_while_idle parameter. I put it in true but I doesn't work, I mean, if I have the device locked, the gcm messaging arrives immediately.
Here is my code
private string SendNotification( )
{
string result = string.Empty;
String GCM_URL = #"https://gcm-http.googleapis.com/gcm/send";
string collapseKey = DateTime.Now.ToString();
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("data.title", HttpUtility.UrlEncode("title"));
data.Add("data.description", HttpUtility.UrlEncode("description"));
StringBuilder sb = new StringBuilder();
sb.AppendFormat("registration_id={0}&collapse_key={1}", REGISTRATION_ID, collapseKey);
sb.AppendFormat("&delay_while_idle=true");
foreach (string item in data.Keys)
{
if (item.Contains("data."))
sb.AppendFormat("&{0}={1}", item, data[item]);
}
string msg = sb.ToString();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(GCM_URL);
req.Method = "POST";
req.Headers.Add("Authorization:key=" + API_KEY);
req.ContentType = "application/x-www-form-urlencoded;;charset=UTF-8";
req.ContentLength = msg.Length;
using (System.IO.StreamWriter oWriter = new System.IO.StreamWriter(req.GetRequestStream()))
{
oWriter.Write(msg);
}
using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
{
string respData = sr.ReadToEnd();
if (resp.StatusCode == HttpStatusCode.OK) // OK = 200
{
if (respData.StartsWith("id="))
{
result = "ok";
}
else
result = respData.ToString();
}
else if (resp.StatusCode == HttpStatusCode.InternalServerError || resp.StatusCode == HttpStatusCode.BadGateway ) // 500
result = "Internal server error";
else if (resp.StatusCode == HttpStatusCode.ServiceUnavailable || resp.StatusCode == HttpStatusCode.BadGateway ) // 503
result = "Server unavailable";
else if (resp.StatusCode == HttpStatusCode.Unauthorized) // 401
result = "invalid api key";
else
result = "Error: " + resp.StatusCode;
}
}
return result;
}
It's correct the way that I'm using the parameter "delay_while_idle"? (I tried with "delay_while_idle=1" but was the same)
Probably, I'm using a wrong format
[UPDATE]
Reading the GCM Documentation, I saw that I must put it in JSON format
The default value for delay_while_idle have to be false, and it must be a JSON boolean.

getting 403 error in release version and work fine in debug version

I working in project that connect to appannie.com API and get result and it is working fine in debug but when I publish it and try to test it I get this page :
and here is the code used for this page in C#:
protected void Button1_Click(object sender, EventArgs e)
{
string url = "https://api.appannie.com/v1/accounts?page_index=0";
string id="",temp="";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UseDefaultCredentials = true;
request.Proxy = WebProxy.GetDefaultProxy();
request.Credentials = new NetworkCredential("username", "password");
request.ContentType = "Accept: application/xml";
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
request.Referer = "http://stackoverflow.com";
request.Headers.Add("Authorization", "bearer **************");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
temp = readStream.ReadToEnd();
//TextArea1.InnerText = temp + "\n";
string[] id_arr = temp.Split(',');
int count = 0;
while (count != id_arr.Length)
{
if (id_arr[count].Contains("account_id"))
{
id = id_arr[count];
count = id_arr.Length;
break;
}
count++;
}
id = id.Substring(id.IndexOf("account_id") + 13);
//TextArea1.InnerText += id;
//Console.Write(readStream.ReadToEnd());
//response.Close();
response = null;
//readStream.Close();
request = null;
string date = Calendar1.SelectedDate.ToString("yyyy-MM-dd");
string url2 = "https://api.appannie.com/v1/accounts/" + id + "/sales?break_down=application+date" +
"&start_date="+date+
"&end_date="+date+
"&currency=USD" +
"&countries=" +
"&page_index=0";
TextArea1.InnerText = url2;
request = (HttpWebRequest)WebRequest.Create(url2);
request.Proxy = WebProxy.GetDefaultProxy();
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
request.Referer = "http://stackoverflow.com";
request.Headers.Add("Authorization", "bearer **************");
response = (HttpWebResponse)request.GetResponse();
receiveStream = response.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
readStream = new StreamReader(receiveStream, Encoding.UTF8);
temp = "";
temp = readStream.ReadToEnd();
//TextArea1.InnerText = temp;
string[] id_arr2 = temp.Split(',');
int count2 = 0;
string down = "";
string update = "";
while (count2 != id_arr2.Length)
{
if (id_arr2[count2].Contains("downloads"))
{
down = id_arr2[count2];
count2 = id_arr2.Length;
break;
}
count2++;
}
count2 = 0;
while (count2 != id_arr2.Length)
{
if (id_arr2[count2].Contains("update"))
{
update = id_arr2[count2];
count2 = id_arr2.Length;
break;
}
count2++;
}
down = down.Substring(down.IndexOf("downloads") + 12);
update = update.Substring(update.IndexOf("update") + 9);
//TextArea1.InnerText = "downloads : "+down+ "----- update :" + update;
TextBox1.Text = down;
TextBox2.Text = update;
}
}
Once you publish it, one of the following is not taking effect:
Credentials
Proxy Settings.
Hence the remote api is giving back a 403. 2 ways to torubleshoot this further:
Run fiddler trace on the working request/response and compare it with the non-working request/response. Typically a good API has more details in the response body as to why it is a 403 error.. (token invalid, invalid credentials etc.)
You can also catch a WebException in code, and try to get the exception body if any. The same will also be visible in Fiddler.
<< code formatting refuses to work on my browser. please bear with unformatted code below >>
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
// breakpoint and see what this is.
string errorDetails = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
}

Categories

Resources