How to get response from Base CRM API authentication - c#

I am trying to get a response from Base API, but i keep getting "500 Internal Server Error" error. I want to get at least 401 HTTP Response which means that authentication call has failed. Here is a description of using Base API authentication:
http://dev.futuresimple.com/api/authentication
And here is my code:
public string Authenticate()
{
string result = "";
string url = "https://sales.futuresimple.com/api/v1/";
string email = "mail#mail.com";
string password = "pass";
string postData = "email=" + email + "&password=" + password;
HttpWebRequest request = null;
Uri uri = new Uri(url + "authentication.xml");
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/xml";
request.ContentLength = postData.Length;
using (Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postData);
writeStream.Write(bytes, 0, bytes.Length);
writeStream.Close();
}
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
}
catch (WebException ex)
{
ex = ex;
}
return result;
}

You're setting the ContentType to application/xml - this is the type of the request body. The body you're sending (string postData = "email=" + email + "&password=" + password;) is form-encoded instead of xml. Just skipping the line request.ContentType = "application/xml"; should do the trick. Alternatively you can encode your request body as xml.

Related

Basic Authentication with multiple request header in HttpwebRequest in c#. Getting error 401 unauthorized

Getting 401 unauthorized error on calling external API from a console application.
through hhtpwebrequest class. Below is my code... requestBody gives me Json data to post
Please suggest to me how to do authentication.
public string InvokeRestService()
{
var serviceUrl = "http://xrmd0/api/v1.0/student/specialized/feed";
var reqData = _service.Retrieve("entityname",
new Guid("guid"), new ColumnSet("requestdata"));
var requestBody = reqData.Attributes["requestdata"].ToString();
string prefix = #"abc""";
string userName = prefix + "xyz";
string password = "pwdqawe";
try
{
var request = (HttpWebRequest)WebRequest.Create(new Uri(serviceUrl));
request.Method = "POST";
request.ContentType = "application/json";
request.Accept = "application/json";
//request.Headers["authorization"] = "Basic" + Convert.ToBase64String(Encoding.Default.GetBytes(userName + ":" + password));
request.Headers["Authorization"] = "Basic Auth" + Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(userName + ":" + password));
request.Headers["User-Id"] = "userId";
request.Headers["User-Type"] = "usertype";
if (!string.IsNullOrEmpty(requestBody))
{
byte[] data = Encoding.UTF8.GetBytes(requestBody);
var requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
}
var response = (HttpWebResponse)request.GetResponse();
var responseStream = response.GetResponseStream();
var responseStreamReader = new StreamReader(responseStream, Encoding.UTF8);
var responseString = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
return responseString;
}
catch (Exception ex)
{
}
}

ALM Rest API : site-session returns 'The remote server returned an error: (400) Bad Request.'

I am getting '(400) Bad Request.' when I try complete authenticate against an ALM REST API, the first part (authentication) is successful) and I get the LWSSO_COOKIE_KEY, but site-session always fails with a 400 error code.
What am I doing wrong please... very confused!
// Authentication XML : 0 = User, 1 = Password
private const string AuthenticationXML = #"<alm-authentication>" +
"<user>{0}</user><password>{1}</password></alm-authentication>";
baseRequestURL = settings.QualityCentreURL + "/qcbin/";
Authentication is done first (and is successful) :
string authRequest = baseRequestURL + "authentication-point/alm-authenticate";
HttpWebRequest myauthrequest = (HttpWebRequest)WebRequest.Create(authRequest);
string xml = String.Format(AuthenticationXML, qcSettings.Username, qcSettings.Password);
byte[] Requestbytes = Encoding.UTF8.GetBytes(xml);
myauthrequest.Method = "POST";
myauthrequest.ContentType = "application/xml";
myauthrequest.ContentLength = Requestbytes.Length;
myauthrequest.Accept = "application/xml";
Stream RequestStr = myauthrequest.GetRequestStream();
RequestStr.Write(Requestbytes, 0, Requestbytes.Length);
RequestStr.Close();
HttpWebResponse myauthres = (HttpWebResponse)myauthrequest.GetResponse();
authenticationCookie = myauthres.Headers.Get("Set-Cookie");
The Site-Session code is :
public void GetSiteSession()
{
// Creat the web request fore site-session.
string request = baseRequestURL + "rest/site-session";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(request);
string xml = String.Empty;
byte[] requestbytes = Encoding.UTF8.GetBytes(xml);
// Update the attributes before sending.
webRequest.Method = "POST";
webRequest.ContentType = "application/xml";
webRequest.Accept = "application/xml";
webRequest.Headers.Set(HttpRequestHeader.Cookie, authenticationCookie);
try
{
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(requestbytes, 0, requestbytes.Length);
requestStream.Close();
HttpWebResponse webRequestResponse = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = webRequestResponse.GetResponseStream();
XDocument doc = XDocument.Load(responseStream);
}
catch (System.Net.WebException except)
{
Console.WriteLine(except.Message);
}
}
I have tried cutting ;Path=/;HTTPOnly from LWSSO_COOKIE_KEY as per this question, but to no avail.
The API reference I found(here) seems to be a big vague or, possibly that I haven't understood it... :P
Apologies, it seems that with 12.53 I should have been using 'api/authentication/sign-in'
string requestURL = baseRequestURL + "api/authentication/sign-in";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);
var credentials = String.Format("{0}:{1}", qcSettings.Username, qcSettings.Password);
request.CookieContainer = authenticationCookieContainer;
request.Headers.Set(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
var authResponse = request.GetResponse();
errorString = String.Empty;
}
catch (System.Net.WebException except)
{
errorString = except.Message;
return false;
}
errorString = String.Empty;
return true;
}

How can I retrieve campaign's placements from AdWords through api(.net)

How can I retrieve campaign's placements from AdWords through api(.net)?
I'd seen this piece of code, but I can't do something similar via c#.
Also I try to get links through report PLACEMENT_PERFORMANCE_REPORT, but I can't.
public static string GetReport(AdWordsUser user, string customerId)
{
string postData = string.Format("__rdxml={0}", System.Web.HttpUtility.UrlEncode(#"<reportDefinition xmlns=""https://adwords.google.com/api/adwords/cm/v201506"">
<selector>
<fields>CampaignId</fields>
<fields>Impressions</fields>
<fields>Clicks</fields>
<fields>Cost</fields>
<fields>FinalUrls</fields>
<predicates>
<field>Impressions</field>
<operator>GREATER_THAN</operator>
<values>0</values>
</predicates>
</selector>
<reportName>Custom Campaign Performance Report</reportName>
<reportType>PLACEMENT_PERFORMANCE_REPORT</reportType>
<dateRangeType>ALL_TIME</dateRangeType>
<downloadFormat>XML</downloadFormat>
</reportDefinition>"));
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://adwords.google.com/api/adwords/reportdownload/v201506");
request.Headers.Add("Authorization", "Bearer " + user.OAuthProvider.AccessToken);
request.Headers.Add("developerToken", "MyToken");
request.Headers.Add("clientCustomerId", customerId);
request.Headers.Add("skipReportSummary", "true");
request.Headers.Add("skipReportHeader", "true");
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
var requestWriter = request.GetRequestStream();
requestWriter.Write(byteArray, 0, byteArray.Length);
requestWriter.Close();
string responseData = "";
try
{
StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
responseReader.Close();
request.GetResponse().Close();
}
catch (Exception ex)
{
Console.WriteLine(ex);
return "";
}
return responseData;
}

Call Genderize.io API From C#

I'm trying to call http://genderize.io/ , but i'm getting an error from .NET saying:
{"You must provide a request body if you set ContentLength>0 or SendChunked==true. Do this by calling [Begin]GetRequestStream before [Begin]GetResponse."}
How would I call this web service "http://api.genderize.io/?name=peter" from C# and get a JSON string back?
HttpWebRequest request;
string postData = "name=peter"
URL = "http://api.genderize.io/?"
Uri uri = new Uri(URL + postData);
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
request.AllowAutoRedirect = true;
UTF8Encoding enc = new UTF8Encoding();
string result = string.Empty;
HttpWebResponse Response;
try
{
using (Response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = Response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
return readStream.ReadToEnd();
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Error: " + ex.Message);
throw ex;
}
You are making the call to the service using POST method, reading through the comments area in http://genderize.io/ the author states that only GET method requests are allowed.
Stroemgren: Yes, this is confirmed. Only HTTP GET request are allowed.
This answer probably would be better as a comment, but I don't have enough reputation :(

Bad Request trying to retrieve Tokens from Google with C#

I'm trying to replicate the process detailed here; https://developers.google.com/accounts/docs/OAuth2WebServer#handlingtheresponse
in C#
String authorizationCode = String.Empty;
String consumerKey = String.Empty;
String consumerSecret = String.Empty;
String redirectUrl = String.Empty;
String grantType = String.Empty;
String requestContent = String.Empty;
HttpWebRequest request = null;
byte[] byteArray = null;
Stream dataStream = null;
WebResponse response = null;
StreamReader reader = null;
String serverResponse = String.Empty;
byte[] authorizationResult = null;
try
{
authorizationCode = HttpUtility.UrlEncode(context.Request.QueryString["code"]);
consumerKey = Properties.Settings.Default.GoogleConsumerKey;
consumerSecret = Properties.Settings.Default.GoogleConsumerSecret;
redirectUrl = Properties.Settings.Default.RedirectUrl;
grantType = "authorization_code";
request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
request.Method = "POST";
requestContent = String.Format("code={0}&client_id={1}&client_secret={2}&redirect_url={3}&grant_type={4}",authorizationCode,consumerKey,consumerSecret,redirectUrl,grantType);
byteArray = Encoding.UTF8.GetBytes(requestContent);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
response = request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
serverResponse = HttpUtility.UrlDecode(reader.ReadToEnd());
reader.Close();
dataStream.Close();
response.Close();
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
}
The Trouble is when calling GetResponse() I am getting Bad Request.
The ConsumerKey & Secret is the one I got from Google when I registered my application. The authorizationCode comes from Google as well.
any ideas what I am doing wrong?
Thanks in advance.
I had the same issue :
The "using" keyword solved it for me. follow the link:
https://stackoverflow.com/a/1968543/1820776

Categories