How to connect Amazon API in c# - c#

I have tried with below stuffs to connect Amazon API but failed to connect it I am getting error as "The remote server returned an error: (400) Bad Request". How to resolve this issue. Any help would be appreciated.
Code:
protected void btnAmazonItemSerach_Click(object sender, EventArgs e)
{
string associateId = "**************";
string accessKey = "*************";
string secretKey = "**************************";
string url = "http://webservices.amazon.com/onca/xml";
HttpWebRequest oRequest = (HttpWebRequest)HttpWebRequest.Create(url);
oRequest.Method = "GET";
oRequest.ContentType = "application/xml";
oRequest.Headers.Add("AWSAccessKeyId", accessKey);
oRequest.Headers.Add("AssociateTag", associateId);
oRequest.Headers.Add("Keywords", "Blueant s4");
oRequest.Headers.Add("Operation", "ItemSearch");
oRequest.Headers.Add("Service", "AWSECommerceService");
Encoding oEncod = new UTF8Encoding();
HMACSHA1 signature = new HMACSHA1();
signature.Key = oEncod.GetBytes(secretKey);
string sign = Convert.ToBase64String(signature.Key);
oRequest.Headers.Add("Signature", sign);
oRequest.Headers.Add("SearchIndex", "All");
oRequest.Headers.Add("Version", "2011-08-01");
string dateval = DateTime.Now.ToString();
oRequest.Headers.Add("Timestamp", dateval);
HttpWebResponse oResponse =(HttpWebResponse) oRequest.GetResponse();
StreamReader oreader =new StreamReader(oResponse.GetResponseStream());
var val = oreader.ReadToEnd();
XmlDocument oxmldoc = new XmlDocument();
oxmldoc.LoadXml(val);
XmlElement oxmlelem = (XmlElement)oxmldoc.GetElementsByTagName("Items")[0];
if (oxmlelem != null)
{
List<string> olistItems = new List<string>();
XmlNodeList olist = oxmldoc.GetElementsByTagName("Item");
for (int i = 0; i < olist.Count; i++)
{
string asi = olist[i].FirstChild.InnerText;
olistItems.Add(asi);
}
}
}

Related

Send file to Trimble Connect (HTTP://connect.trimble.com/)

I will need to send a some file to service (connect.trimble.com).
I do not understand, how upload a file to the service?
I have API instruction:
and I use this code:
string result = string.Empty;
string Url = "https://app.prod.gteam.com/tc/api/2.0/auth";
string TypeContent = "application/json";
string Method = "POST";
object obj = new
{
emailAddress = "MyMail",
key = "MyKey"
};
string Header = string.Empty;
result = RequestPost(Url, TypeContent, Method, Header, obj);
var qwe = result.Split(new char[] { '"' });
Header = "Bearer " + qwe[3];
Url = "https://app.prod.gteam.com/tc/api/2.0/files";
TypeContent = "multipart/form-data";
Method = "POST";
obj = new
{
parentId = "yVWsT_jewHs"
};
result = RequestPost(Url, TypeContent, Method, Header, obj);
private static string RequestPost(string Url, string TypeContent, string Method, string Header, object obj)
{
string result = string.Empty;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(Url);
httpWebRequest.ContentType = TypeContent;
httpWebRequest.Method = Method;
if (!string.IsNullOrEmpty(Header))
{
httpWebRequest.Headers.Add("Authorization", Header);
}
if (obj != null)
{
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(obj);
streamWriter.Write(json);
}
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
This code return error:
The remote server returned an error: (400) Bad Request.
I found answer myself. This topic can be closed.
string Url = "app.prod.gteam.com/tc/api/2.0/files?parentId=bHHkdeBSizA";
bHHkdeBSizA - This ID is parent folder ID, where the file will located, in current API parentId may equals rootId.
public static void UploadFile(string url, string filePath, string Header)
{
using (var client = new WebClient())
{
if (!string.IsNullOrEmpty(Header))
{
client.Headers.Add("Authorization", Header);
}
byte[] result = client.UploadFile(url, filePath);
string responseAsString = Encoding.Default.GetString(result);
}
}

Need to login in to remote website using c#

I am trying to log in to a remote website via a login form so I can access a sub page via iFrame so I have to pass the validation to set a cookie or a session so I can get to the sub page with the iFrame Maybe there is a better way to do this I am not 100% sure if anyone has any suggestions please let me know. I am getting access denied error:
<script type="text/javascript">
function submitEstimoteLogin() {
setTimeout(function () {
var ifr = document.getElementById("iFrameLogin");
var ifrDoc = ifr.contentDocument || ifr.contentWindow.document;
var theForm = ifrDoc.forms[0];
var username = theform.getElementById("username");
username.value = "email";
var password = theform.getElementById("password");
password.value = "password";
var sbutton = thefrom.getElementById("");
}, 5000);
}
</script>
<iframe id="iFrameLogin" src="http://cloud.estimote.com" onload="submitEstimoteLogin();" ></iframe>
I have also tried it via code behind I am getting a 404 error:
public String GetWebContent(String username, String password)
{
String urlSignin = "https://cloud.estimote.com/";
String urlLogin = "https://cloud.estimote.com/";
Uri uriSignin = new Uri(urlSignin);
Uri uriLogin = new Uri(urlLogin);
Hashtable formData = new Hashtable();
formData.Add("username", new Hashtable());
formData.Add("password", new Hashtable());
((Hashtable)formData["username"])["value"] = username;
((Hashtable)formData["password"])["value"] = password;
String postData = "";
foreach (string name in formData.Keys)
{
postData += "&" + name + "=" + ((Hashtable)formData[name])["value"];
}
postData = postData.Substring(1);
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
HttpWebRequest webReq;
HttpWebResponse webResp;
CookieContainer cookies = new CookieContainer();
String responseString = "";
try
{
webReq = (HttpWebRequest)WebRequest.Create(urlSignin);
webResp = (HttpWebResponse)webReq.GetResponse();
for (int i = 0; i < webResp.Headers.Count; i++)
{
string name = webResp.Headers.GetKey(i);
if (name != "Set-Cookie")
continue;
string value = webResp.Headers.Get(i);
foreach (var singleCookie in value.Split(','))
{
Match match = Regex.Match(singleCookie, "(.+?)=(.+?);");
if (match.Captures.Count == 0)
continue;
webResp.Cookies.Add(
new Cookie(
match.Groups[1].ToString(),
match.Groups[2].ToString(),
"/",
webReq.Host.Split(':')[0]));
}
}
cookies.Add(webResp.Cookies);
string sessionCookie = webResp.Headers["Set-Cookie"];
responseString = new StreamReader(webResp.GetResponseStream()).ReadToEnd();
string respCookie = sessionCookie.Substring(0, sessionCookie.IndexOf(';'));
char[] separator = { '=' };
string[] cookieValues = respCookie.Split(separator);
string part1 = HttpUtility.UrlEncode(cookieValues[1]);
cookies.Add(new Cookie(cookieValues[0], part1 , "/", "cloud.estimote.com"));
webReq = (HttpWebRequest)WebRequest.Create(urlLogin);
webReq.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
webReq.Referer = urlSignin;
webReq.KeepAlive = true;
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.ContentLength = data.Length;
webReq.AllowAutoRedirect = false;
webReq.CookieContainer = cookies;
webReq.Timeout = 30000;
webReq.ReadWriteTimeout = 60000;
webReq.GetRequestStream().Write(data, 0, data.Length);
webReq.GetRequestStream().Close();
webResp = (HttpWebResponse)webReq.GetResponse();
responseString = new StreamReader(webResp.GetResponseStream()).ReadToEnd();
webResp.Close();
return responseString;
}
catch (Exception ex)
{
throw ex;
}
}

Toggl API v8 with .NET

I'm trying to use the new Toggl API (v8) with .NET C#. I've based my code on the example from litemedia (http://litemedia.info/connect-to-toggl-api-with-net), but it was originally created for version 1 of the API.
private const string TogglTasksUrl = "https://www.toggl.com/api/v8/tasks.json";
private const string TogglAuthUrl = "https://www.toggl.com/api/v8/me"; //sessions.json";
private const string AuthenticationType = "Basic";
private const string ApiToken = "user token goes here";
private const string Password = "api_token";
public static void Main(string[] args)
{
CookieContainer container = new CookieContainer();
var authRequest = (HttpWebRequest)HttpWebRequest.Create(TogglAuthUrl);
authRequest.Credentials = CredentialCache.DefaultCredentials;
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded";
authRequest.CookieContainer = container;
string value = ApiToken; //= Convert.ToBase64String(Encoding.Unicode.GetBytes(ApiToken));
value = string.Format("{1}:{0}", Password, value);
//value = Convert.ToBase64String(Encoding.Unicode.GetBytes(value));
authRequest.ContentLength = value.Length;
using (StreamWriter writer = new StreamWriter(authRequest.GetRequestStream(), Encoding.ASCII))
{
writer.Write(value);
}
try
{
var authResponse = (HttpWebResponse)authRequest.GetResponse();
using (var reader = new StreamReader(authResponse.GetResponseStream(), Encoding.UTF8))
{
string content = reader.ReadToEnd();
}
HttpWebRequest tasksRequest = (HttpWebRequest)HttpWebRequest.Create(TogglTasksUrl);
tasksRequest.CookieContainer = container;
//var jsonResult = string.Empty;
var tasksResponse = (HttpWebResponse)tasksRequest.GetResponse();
MemoryStream ms = new MemoryStream();
tasksResponse.GetResponseStream().CopyTo(ms);
//using (var reader = new StreamReader(tasksResponse.GetResponseStream(), Encoding.UTF8))
//{
// jsonResult = reader.ReadToEnd();
//}
ms.Seek(0, SeekOrigin.Begin);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Task));
var tasks = ser.ReadObject(ms) as List<Task>;
ms.Close();
//var tasks = DataContractJsonConvert.DeserializeObject<Task[]>(jsonResult);
foreach (var task in tasks)
{
Console.WriteLine(
"{0} - {1}: {2} starting {3:yyyy-MM-dd HH:mm}",
task.Project.Name,
task.Description,
TimeSpan.FromSeconds(task.Duration),
task.Start);
}
}
catch (System.Exception ex)
{
throw;
}
}
The following line is returning a 404 error.
var authResponse = (HttpWebResponse)authRequest.GetResponse();
Here is code that works. Since I was looking for this answer recently there might still be others as lost as me.
Notes: I used Encoding.Default.GetBytes() because Encoding.Unicode.GetBytes() did not give me a correct result on my .NET string. I hope it doesn't depend on the default setup of Visual Studio.
The content-type is "application/json".
Sorry, I haven't tried a POST version yet.
string ApiToken = "user token goes here";
string url = "https://www.toggl.com/api/v8/me";
string userpass = ApiToken + ":api_token";
string userpassB64 = Convert.ToBase64String(Encoding.Default.GetBytes(userpass.Trim()));
string authHeader = "Basic " + userpassB64;
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(url);
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Method = "GET";
authRequest.ContentType = "application/json";
//authRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
var response = (HttpWebResponse)authRequest.GetResponse();
string result = null;
using (Stream stream = response.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
result = sr.ReadToEnd();
sr.Close();
}
if (null != result)
{
System.Diagnostics.Debug.WriteLine(result.ToString());
}
// Get the headers
object headers = response.Headers;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message + "\n" + e.ToString());
}

c# - How to reply for comment in LinkedIn?

I'm trying to integrate LinkedIn in our application. I just want to know how to reply for comment in LinkedIn.
I've written this code.
protected void Page_Load(object sender, EventArgs e)
{
string data = "<comments><comment><text>Check out the Reply!</text></comment></comments>";
byte[] databytes = Encoding.UTF8.GetBytes(data);
var request = new RestRequest { Path = "comments" };
var credentials = new Hammock.Authentication.OAuth.OAuthCredentials
{
Type = OAuthType.AccessToken,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = "kmkzt9cqml1s",
ConsumerSecret = "hNiwIrZWGSMykoD2",
Token = "b3cbdca7-37a7-474f-a9a6-e21bb89917fe",
TokenSecret = "990f1b78-79de-4490-b4e3-893b4e020e45",
};
var client = new RestClient()
{
Authority = "http://api.linkedin.com/v1/posts/g-457832-S-454334",
Credentials = credentials,
Method = WebMethod.Post,
};
client.AddHeader("Content-Type", "text/xml");
client.AddPostContent(databytes);
RestResponse response = client.Request(request);
string content = response.Content;
}
I'm getting an error in content in the below format
<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>
<error>
<status>400</status>
<timestamp>1374494502579</timestamp>
<request-id>QM4MYPEKJJ</request-id>
<error-code>0</error-code>
<message>Couldn't parse message document: error: Unexpected end of file after null</message>\n</error>\n"
Any ideas? Thanks in advance.

C2DM server side C# web service Error=InvalidRegistration

I have searched everywhere and have not found an answer to my question. Let me get straight to the point. I have developed an android messaging app for the purpose of experimenting with C2DM. My app get's the registration ID and it gets displayed in my Log correctly. I then send that key through to my C# web service.
The C# Web service then applies for an auth token, which works fine. No problem so far. But, as soon as I POST my body items (registration_id, collapse_key, data.<key>, delay_while_idle) with my header(GoogleLogin auth=[AUTH_TOKEN]) I get the response: "Error=InvalidRegistration".
There is no reason for this not to work. And yes, I have tried every solution available here in stack overflow, but remained unsuccessful. Here is my main code for my server side:
WebRequest theRequest;
HttpWebResponse theResponse;
ArrayList theQueryData;
theRequest = WebRequest.Create("https://www.google.com/accounts/ClientLogin");
theRequest.Method = "POST";
theQueryData = new ArrayList();
String [] test = new String[5];
test[0] = "accountType=HOSTED_OR_GOOGLE";
test[1] = "Email=XXXXXXXXXXXXXXXXX";
test[2] = "Passwd=XXXXXXXXXXXXXXXX";
test[3] = "Source=Domokun";
test[4] = "service=ac2dm";
// Set the encoding type
theRequest.ContentType = "application/x-www-form-urlencoded";
// Build a string containing all the parameters
string Parameters = String.Join("&", (String[])test);
theRequest.ContentLength = Parameters.Length;
// We write the parameters into the request
StreamWriter sw = new StreamWriter(theRequest.GetRequestStream());
sw.Write(Parameters);
sw.Close();
// Execute the query
theResponse = (HttpWebResponse)theRequest.GetResponse();
StreamReader sr = new StreamReader(theResponse.GetResponseStream());
String value = sr.ReadToEnd();
String token = ParseForAuthTokenKey(value);
String value2 = "";
if (value != null)
{
WebRequest theRequest2;
HttpWebResponse theResponse2;
ArrayList theQueryData2;
theRequest2 = WebRequest.Create("http://android.clients.google.com/c2dm/send");
theRequest2.Method = "POST";
theQueryData2 = new ArrayList();
String[] test2 = new String[4];
test[0] = "registration_id=" + registerid;
test[1] = "collapse_key=0";
test[2] = "data.payload=Jannik was hier";
test[3] = "delay_while_idle=0";
// Set the encoding type
theRequest2.ContentType = "application/x-www-form-urlencoded";
// Build a string containing all the parameters
string Parameters2 = String.Join("&", (String[])test2);
theRequest2.ContentLength = Parameters2.Length;
theRequest2.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + token);
// We write the parameters into the request
StreamWriter sw2 = new StreamWriter(theRequest2.GetRequestStream());
sw2.Write(Parameters2);
sw2.Close();
// Execute the query
theResponse2 = (HttpWebResponse)theRequest2.GetResponse();
StreamReader sr2= new StreamReader(theResponse2.GetResponseStream());
value2 = sr2.ReadToEnd();
public static bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
private static string ParseForAuthTokenKey(string webResponse)
{
string tokenKey = String.Empty;
if (webResponse.Contains(AuthTokenHeader))
{
tokenKey = webResponse.Substring(webResponse.IndexOf(AuthTokenHeader) + AuthTokenHeader.Length);
if (tokenKey.Contains(Environment.NewLine))
{
tokenKey.Substring(0, tokenKey.IndexOf(Environment.NewLine));
}
}
return tokenKey.Trim();
}
All I can think is that my C2DM account isn't registered correctly. Could this be it? Or are there an error in my code that I'm missing?
OK. I've found the solution.
string requestBody = string.Format("registration_id={0}&collapse_key{1}&data.key=value",
HttpUtility.UrlEncode(registrationId), "collapse");
string responseBody = null;
WebHeaderCollection requestHeaders = new WebHeaderCollection();
WebHeaderCollection responseHeaders = null;
requestHeaders.Add(HttpRequestHeader.Authorization, string.Format("GoogleLogin auth={0}", authToken));
httpClient.DoPostWithHeaders(c2dmPushUrl,
requestBody,
"application/x-www-form-urlencoded",
out responseBody,
out responseHeaders,
requestHeaders);
public bool DoPostWithHeaders(string url,
string requestBody,
string contextType,
out string responseBody,
out WebHeaderCollection responseHeaders,
WebHeaderCollection requestHeaders = null)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// FIRST SET REQUEST HEADERS
httpWebRequest.Headers = requestHeaders;
httpWebRequest.Method = "POST";
// THEN SET CONTENT TYPE - THE ORDER IS IMPORTANT
httpWebRequest.ContentType = contextType;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(requestBody);
httpWebRequest.ContentLength = data.Length;
stream = httpWebRequest.GetRequestStream();
stream.Write(data, 0, data.Length);
....
....
....
}

Categories

Resources