consuming a soap webservice-getting 500 - c#

I have a 500 error when trying to consume a soap WS .
code below :
main function :
public void Main()
{
var action = "XXXXXX";
string result = SendSOAPRequest("http://XXXXXXXX:80/XXXX", action, new Dictionary<string, string>() , false);
}
sendrequest method :
public void Main()
{
var action = "XXXXXX";
string result = SendSOAPRequest("http://XXXXXXXX:80/XXXX", action, new Dictionary<string, string>() , false);
}
public static string SendSOAPRequest(string url, string action,Dictionary<string, string> parameters, bool useSOAP12 = false)
{
try{
XmlDocument soapEnvelopeXml = new XmlDocument();
var xmlStr = (useSOAP12)
? #"XXXXXX";
string parms = string.Join(string.Empty, parameters.Select(kv => String.Format("<{0}>{1}</{0}>", kv.Key, kv.Value)).ToArray());
var s = String.Format(xmlStr, action, new Uri(url).GetLeftPart(UriPartial.Authority) + "/", parms);
soapEnvelopeXml.LoadXml(s);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url + "/" + action));
webRequest.Headers.Add("SOAPAction", url);
webRequest.Headers.Add("XXXXXX", "AG6YUTGV6");
webRequest.ContentType = (useSOAP12) ? "application/soap+xml;charset=\"utf-8\"" : "text/xml;charset=\"utf-8\"";
webRequest.Accept = (useSOAP12) ? "application/soap+xml" : "text/xml";
webRequest.Method = "GET";
string usernamePassword = "username" + ":" + "pass";
usernamePassword = Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword));
CredentialCache mycache = new CredentialCache();
webRequest.Credentials = mycache;
webRequest.Headers.Add("Authorization", "Basic " + usernamePassword);
using (WebResponse response = webRequest.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
XmlTextReader reader = new XmlTextReader(stream);
}
}
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
string result;
using (WebResponse response = webRequest.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
result = rd.ReadToEnd();
}
}
return result;
}
catch (WebException ex)
{
string message = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
}
return "";
}

Related

Best way to POST and GET Response from REST API'S

I am doing post and get response using HttpClient to communicate with REST API as below:
public static string PostToAPI( string value)
{
var payload = new APIModel
{
CommandText = value
};
var stringPayload = JsonConvert.SerializeObject(payload);
var httpContent = new StringContent(stringPayload,Encoding.UTF8,"application/json");
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
HttpResponseMessage message=client.PostAsync("https://testAPI/test",httpContent).Result if (message.IsSuccessStatusCode)
{
string result = message.Content.ReadAsStringAsync().Result;
return result;
}
return string.Empty;
}
is there any other alternative or best way do it?
You can always use HttpWebRequest and HttpWebResponse. Try Below
try
{
var webAddr = "URL";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application";
httpWebRequest.Method = "POST";
string str = "request string";
httpWebRequest.Headers["Authorization"] = "";
httpWebRequest.Headers["TenantId"] = "";
httpWebRequest.Headers["Client-Type"] = "";
httpWebRequest.Headers["Protocol"] = "";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
Console.WriteLine(str);
streamWriter.Write(str);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine("result=" + result);
}
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
}

Why this method is called twice and at the first time the return doesn't work?

A flash application uses AMF message format to call the method SyncAddressBook (c#),and in this method ,it calls other two WebApis using HttpWebRequest (post and get ).
But only when calling WebApi (the method SyncAddressBook ), the method can return to flash well, when calling WebApi (the method SyncAddressBook ), the method SyncAddressBook can not return to the one which called it (i didnot write this method here) ,instead, it return itself. and for the second time, the method SyncAddressBook returned with error to flash .
here is the method (I omit something)
public AMFGreetoAddressBookResult SyncAddressBook(AMFGreetoLogin loginArgs, AMFGreetoAddressBook addressBook)
{
var result = new ........
this.PostReceiversGroups(addressBook, accessKey);
this.GetReceivers(accessKey, out receivers);
result.ResultCode = true;
return result;
}
private Boolean PostReceiversGroups(AMFGreetoAddressBook addressBook, string accessKey)
{
Uri theUri = new Uri(athenaSiteUrl + "/api/receivers");
var httpWebRequest = (HttpWebRequest)WebRequest.Create(theUri);
httpWebRequest.KeepAlive = false;
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add(AuthenticationServiceCodeHeaderKey, AddressServiceAccessCode);
httpWebRequest.Headers.Add(uthenticationServiceAccessKeyHeaderKey, AddressServiceAccessKey);
httpWebRequest.Headers.Add(AuthenticationUserAccessKey, accessKey);
httpWebRequest.Host = theUri.Host;
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(addressBook);
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(json);
httpWebRequest.ContentLength = bytes.Length;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
}
try
{
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Account acc = JsonConvert.DeserializeObject<Account>(result);
}
}
catch (Exception e)
{
throw new Exception("住所管理サービスの更新処理でエラーが発生しました。[PostReceiversGroups] :" + e);
}
return true;
}
private Boolean GetReceivers(string accessKey, out AMFGreetoReceiver[] receivers)
{
Uri theUri = new Uri(athenaSiteUrl + "/api/receivers");
var httpWebRequest = (HttpWebRequest)WebRequest.Create(theUri);
httpWebRequest.KeepAlive = false;
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
httpWebRequest.Headers.Add(AuthenticationServiceCodeHeaderKey, AddressServiceAccessCode);
httpWebRequest.Headers.Add(uthenticationServiceAccessKeyHeaderKey, AddressServiceAccessKey);
httpWebRequest.Headers.Add(AuthenticationUserAccessKey, accessKey);
httpWebRequest.Host = theUri.Host;
receivers = null;
try
{
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
var ser = new JavaScriptSerializer();
receivers = ser.Deserialize<AMFGreetoReceiver[]>(result);
streamReader.Close();
httpResponse.Close();
}
}
catch (Exception e)
{
throw new Exception("Receivers取得処理でエラーが発生しました。[GetReceivers] :" + e);
}
return true;
}

oauth/token returns empty body

I am encountering a problem getting the access_token in client application using oauth.
The returned response has empty body though in API I can see the response is not empty.
tokenresponse = {
"access_token":"[ACCESSTOKENVALUE]",
"token_type":"bearer",
"expires_in":"1200",
"refresh_token":"[REFRESHTOKENVALUE]",
"scope":"[SCOPEVALUE]"
}
The method from API that returns the token http://api.sample.com/OAuth/Token:
public ActionResult Token()
{
OutgoingWebResponse response =
this.AuthorizationServer.HandleTokenRequest(this.Request);
string tokenresponse = string.Format("Token({0})", response!=null?response.Body:""));
return response.AsActionResult();
}
The client method that requests the token is:
public string GetAuthorizationToken(string code)
{
string Url = ServerPath + "OAuth/Token";
string redirect_uri_encode = UrlEncode(ClientPath);
string param = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",code, ClientId, ClientSecret, redirect_uri_encode);
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
request.Headers.Remove(HttpRequestHeader.Cookie);
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
if (!string.IsNullOrEmpty(result))
{
TokenData tokendata = JsonConvert.DeserializeObject<TokenData>(result);
return UpdateAuthorizotionFromToken(tokendata);
}
return null;
}
The result variable is empty.
Please let me know if you have any idea what could cause this. Initially I assumed is because of the cookies so I tried to remove them from request.
Thanks in advance.
Dear just create webclient using following code and you will get json info in tokeninfo.I used it and simply its working perfect.
WebClient client = new WebClient();
string postData = "client_id=" + ""
+ "&client_secret=" + ""
+ "&grant_type=password&username=" + "" //your username
+ "&password=" + "";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
You can then use substring that contains only token from tokeninfo.
To upload tracks on sound cloud.
private void TestSoundCloudupload()
{
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
//some default headers
request.Accept = "*/*";
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");
//file array
var files = new UploadFile[] { new UploadFile(Server.MapPath("Downloads//0.mp3"), "track[asset_data]", "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "Some title");
form.Add("track[sharing]", "public");
form.Add("oauth_token", "");
form.Add("format", "json");
form.Add("Filename", "0.mp3");
form.Add("Upload", "Submit Query");
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
Response.Write(reader.ReadToEnd());
}
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}

Uploading a file to a web service using POST in C#

The problem with this code is that the file, once it is uploaded, is not the correct format. I'm trying to upload a .zip file.
public string HttpPost(string uri, string parameter)
{
WebRequest webRequest = WebRequest.Create(uri);
NetworkCredential credentials = new NetworkCredential("username", "password");
webRequest.Credentials = credentials;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameter);
Stream os = null;
try
{ // send the Post
webRequest.ContentLength = bytes.Length; //Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Send it
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Request error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (os != null)
{
os.Close();
}
}
try
{ // get the response
WebResponse webResponse = webRequest.GetResponse();
if (webResponse == null)
{ return null; }
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
return sr.ReadToEnd().Trim();
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Response error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return null;
}
This example how to upload file in MyBucket
private const string KeyId = "Your KeyId";
private const string AccessKey = "Your AccessKey";
private const string S3Url = "https://s3.amazonaws.com/";
private static void UploadFile()
{
var fileData = File.ReadAllBytes(#"C:\123.zip");
string timeStamp = string.Format("{0:r}", DateTime.UtcNow);
string stringToConvert = "PUT\n" + //Http verb
"\n" + //content-md5
"application/octet-stream\n" + //content-type
"\n" + //date
"x-amz-acl:public-read"+"\n" + //date
"x-amz-date:" + timeStamp + "\n" + //optionall
"/MyBucket/123.zip"; //resource
var ae = new UTF8Encoding();
var signature = new HMACSHA1 {Key = ae.GetBytes(AccessKey)};
var bytes = ae.GetBytes(stringToConvert);
var moreBytes = signature.ComputeHash(bytes);
var encodedCanonical = Convert.ToBase64String(moreBytes);
var url = "https://MyBucket.s3.amazonaws.com/123.zip";
var request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "PUT";
request.Headers["x-amz-date"] = timeStamp;
request.Headers["x-amz-acl"] = "public-read";
request.ContentType = "application/octet-stream";
request.ContentLength = fileData.Length;
request.Headers["Authorization"] = "AWS " + KeyId + ":" + encodedCanonical;
var requestStream = request.GetRequestStream();
requestStream.Write(fileData, 0, fileData.Length);
requestStream.Close();
using (var response = request.GetResponse() as HttpWebResponse)
{
var reader = new StreamReader(response.GetResponseStream());
var data = reader.ReadToEnd();
}
}
Take a look on Amazon S3 REST API

How to use Magento REST API from C#

Where can I find samples that show how to connect to the Magento REST API using C#?
I found was a php one which I could not figure out except a little.
Using a Dropbox OAuth sample I found on the net I tried to make it work for Magento:
private void button1_Click(object sender, RoutedEventArgs e)
{
var consumerKey = “xxxxxxxxxxxxx”;
var consumerSecret = “xxxxxxxxxxxxxxxx”;
var uri = new Uri("http://www.MagentoWebsite.com/oauth/token");
// Generate a signature
OAuthBase oAuth = new OAuthBase();
string nonce = oAuth.GenerateNonce();
string timeStamp = oAuth.GenerateTimeStamp();
string parameters;
string normalizedUrl;
string signature = oAuth.GenerateSignature(uri, consumerKey, consumerSecret,
String.Empty, String.Empty, “GET”, timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1,
out normalizedUrl, out parameters);
signature = HttpUtility.UrlEncode(signature);
StringBuilder requestUri = new StringBuilder(uri.ToString());
requestUri.AppendFormat("?oauth_consumer_key={0}&", consumerKey);
requestUri.AppendFormat("oauth_nonce={0}&", nonce);
requestUri.AppendFormat("oauth_timestamp={0}&", timeStamp);
requestUri.AppendFormat("oauth_signature_method={0}&", “HMAC-SHA1");
requestUri.AppendFormat("oauth_version={0}&", “1.0");
requestUri.AppendFormat("oauth_signature={0}", signature);
var request = (HttpWebRequest)WebRequest.Create(new Uri(requestUri.ToString()));
request.Method = WebRequestMethods.Http.Get;
var response = request.GetResponse();
var queryString = new StreamReader(response.GetResponseStream()).ReadToEnd();
var parts = queryString.Split(’&’);
var token = parts[1].Substring(parts[1].IndexOf(’=’) + 1);
var tokenSecret = parts[0].Substring(parts[0].IndexOf(’=’) + 1);
queryString = String.Format("oauth_token={0}", token);
var authorizeUrl = “http://www.MagentoWebsite.com/admin/oauth_authorize?”+queryString;
Process.Start(authorizeUrl);
}
Unfortunately this returns a BAD REQUEST response.
I recently started a project for a C# REST API client for Magento that might help you out:
https://github.com/nickvane/Magento-RestApi
It's not yet feature complete, but the oauth authentication is implemented.
The code uses restsharp which has support for oauth authentication.
I had the same question but couldn't find the answer hence I spent a day to make it work. I share my code here and I hope it will help other people in the feature.
use the following code in an aspx page to get oAuth access
protected void Page_Load(object sender, EventArgs e)
{
string oauth_token = Request.QueryString["oauth_token"];
string oauth_verifier = Request.QueryString["oauth_verifier"];
if (string.IsNullOrEmpty(oauth_token) || string.IsNullOrEmpty(oauth_verifier))
{
BeginAuthorization();
}
else
{
Authorize(oauth_token,oauth_verifier);
}
}
private void Authorize(string oauth_token, string oauth_verifier)
{
var uri = new Uri(MagentoServer + "/oauth/token");
string oauth_token_secret = (string)Session["oauth_token_secret"];
OAuthBase oAuth = new OAuthBase();
string nonce = oAuth.GenerateNonce();
string timeStamp = oAuth.GenerateTimeStamp();
string parameters;
string normalizedUrl;
string signature = oAuth.GenerateSignature(uri, ConsumerKey, ConsumerSecret,
oauth_token,oauth_token_secret, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.PLAINTEXT,
out normalizedUrl, out parameters);
StringBuilder sb = new StringBuilder("OAuth ");
sb.AppendFormat("oauth_verifier=\"{0}\",", oauth_verifier);
sb.AppendFormat("oauth_token=\"{0}\",", oauth_token);
sb.AppendFormat("oauth_version=\"{0}\",", "1.0");
sb.AppendFormat("oauth_signature_method=\"{0}\",", "PLAINTEXT");
sb.AppendFormat("oauth_nonce=\"{0}\",", nonce);
sb.AppendFormat("oauth_timestamp=\"{0}\",", timeStamp);
sb.AppendFormat("oauth_consumer_key=\"{0}\",", ConsumerKey);
sb.AppendFormat("oauth_signature=\"{0}\"", signature);
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Headers[HttpRequestHeader.Authorization] = sb.ToString();
request.ContentType = "text/xml";
request.Accept = "text/xml";
request.KeepAlive = true;
request.Method = "POST";
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
string text = responseReader.ReadToEnd();
try
{
Dictionary<String, string> responseDic = GetDictionaryFromQueryString(text);
string token = responseDic.First(q => q.Key == "oauth_token").Value;
string secret = responseDic.First(q => q.Key == "oauth_token_secret").Value;
Configuration objConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
//Edit
if (objAppsettings != null)
{
objAppsettings.Settings["Magento.Token"].Value = token;
objAppsettings.Settings["Magento.TokenSecret"].Value = secret;
objConfig.Save();
}
errorLabel.Text = "Done";
errorLabel.ForeColor = System.Drawing.Color.Green;
}
catch (Exception ex)
{
errorLabel.Text = "Exchanging token failed.<br>Response text = " + text + "<br>Exception = " + ex.Message;
}
}
}
catch (WebException ex)
{
var responseStream = ex.Response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
string resp = responseReader.ReadToEnd();
errorLabel.Text = resp;
}
}
private void BeginAuthorization()
{
string CallbackUrl = Server.UrlEncode(Request.Url.AbsoluteUri);
var uri = new Uri(MagentoServer + "/oauth/initiate?oauth_callback=" + CallbackUrl);
OAuthBase oAuth = new OAuthBase();
string nonce = oAuth.GenerateNonce();
string timeStamp = oAuth.GenerateTimeStamp();
string parameters;
string normalizedUrl;
string signature = oAuth.GenerateSignature(uri, ConsumerKey, ConsumerSecret,
String.Empty, String.Empty, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.PLAINTEXT,
out normalizedUrl, out parameters);
StringBuilder sb = new StringBuilder("OAuth ");
sb.AppendFormat("oauth_callback=\"{0}\",", CallbackUrl);
sb.AppendFormat("oauth_version=\"{0}\",", "1.0");
sb.AppendFormat("oauth_signature_method=\"{0}\",", "PLAINTEXT");
sb.AppendFormat("oauth_nonce=\"{0}\",", nonce);
sb.AppendFormat("oauth_timestamp=\"{0}\",", timeStamp);
sb.AppendFormat("oauth_consumer_key=\"{0}\",", ConsumerKey);
sb.AppendFormat("oauth_signature=\"{0}\"", signature);
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Headers[HttpRequestHeader.Authorization] = sb.ToString();
request.ContentType = "text/xml";
request.Accept = "text/xml";
request.KeepAlive = true;
request.Method = "GET";
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
string text = responseReader.ReadToEnd();
try
{
Dictionary<String, string> dic = GetDictionaryFromQueryString(text);
string oauth_token = dic.First(q => q.Key == "oauth_token").Value;
string oauth_token_secret = dic.First(q => q.Key == "oauth_token_secret").Value;
Session["oauth_token_secret"] = oauth_token_secret;
string redirectUrl = MagentoServer + "/index.php/admin/oauth_authorize?oauth_token=" + oauth_token + "&oauth_verifier=" +
oauth_token_secret;
Response.Redirect(redirectUrl);
}
catch (Exception ex)
{
errorLabel.Text = "Parsing request token failed.<br>Response text = " + text + "<br>Exception = " + ex.Message;
}
}
}
catch (WebException ex)
{
var responseStream = ex.Response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
string resp = responseReader.ReadToEnd();
errorLabel.Text = resp;
}
}
private static Dictionary<string, string> GetDictionaryFromQueryString(string queryString)
{
string[] parts = queryString.Split('&');
Dictionary<String, string> dic = new Dictionary<string, string>();
foreach (var part in parts)
{
dic.Add(part.Split('=')[0], part.Split('=')[1]);
}
return dic;
}
#region Settings
string MagentoServer
{
get
{
return ConfigurationManager.AppSettings["Magento.Server"];
}
}
string ConsumerKey
{
get
{
return ConfigurationManager.AppSettings["Magento.ConsumerKey"];
}
}
string ConsumerSecret
{
get
{
return ConfigurationManager.AppSettings["Magento.ConsumerSecret"];
}
}
#endregion
}
add the following code in a class file
public class ApiClient
{
public ApiClient(string magentoServer, string consumerKey, string consumerSecret, string accessToken, string accessTokenSeccret)
{
MagentoServer = magentoServer;
ConsumerKey = consumerKey;
ConsumerSecret = consumerSecret;
AccessToken = accessToken;
AccessTokenSecret = accessTokenSeccret;
}
#region Request
HttpWebRequest CreateAuthorizedRequest(string url, string requestMethod,ApiFilter filter)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + filter.ToString());
OAuthBase oAuth = new OAuthBase();
string nonce = oAuth.GenerateNonce();
string timeStamp = oAuth.GenerateTimeStamp();
string parameters;
string normalizedUrl;
string signature = oAuth.GenerateSignature(new Uri(url), ConsumerKey, ConsumerSecret,
AccessToken, AccessTokenSecret, requestMethod, timeStamp, nonce, OAuthBase.SignatureTypes.PLAINTEXT,
out normalizedUrl, out parameters);
StringBuilder sb = new StringBuilder("OAuth ");
sb.AppendFormat("oauth_token=\"{0}\",", AccessToken);
sb.AppendFormat("oauth_version=\"{0}\",", "1.0");
sb.AppendFormat("oauth_signature_method=\"{0}\",", "PLAINTEXT");
sb.AppendFormat("oauth_nonce=\"{0}\",", nonce);
sb.AppendFormat("oauth_timestamp=\"{0}\",", timeStamp);
sb.AppendFormat("oauth_consumer_key=\"{0}\",", ConsumerKey);
sb.AppendFormat("oauth_signature=\"{0}\"", signature);
request.Headers[HttpRequestHeader.Authorization] = sb.ToString();
request.Method = requestMethod;
//request.ContentType = "application/json";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";//application/json,
request.KeepAlive = true;
return request;
}
string FetchRequest(HttpWebRequest request)
{
try
{
string responseText = string.Empty;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader responseReader = new StreamReader(responseStream))
{
responseText = responseReader.ReadToEnd();
return responseText;
}
}
}
return responseText;
}
catch (WebException ex)
{
var responseStream = ex.Response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
string responseText = responseReader.ReadToEnd();
throw new MagentoApiException(responseText,ex.Status);
}
}
#endregion
#region Public properties
string MagentoServer { get; set; }
string ConsumerKey { get; set; }
string ConsumerSecret { get; set; }
string AccessToken { get; set; }
string AccessTokenSecret { get; set; }
#endregion
}
public class ApiFilter
{
public ApiFilter()
{
filterDescriptions = new List<FilterDescription>();
}
public int? Page { get; set; }
public int? Limit { get; set; }
public List<FilterDescription> filterDescriptions;
public const string Type = "rest";
public void AddFilter(string column, FilterType filterType, string value)
{
filterDescriptions.Add(new FilterDescription()
{
Column = column,
FilterType = filterType,
Value = value
});
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("type={0}", Type);
if (Page.HasValue)
sb.AppendFormat("&page={0}", Page.Value);
if (Limit.HasValue)
sb.AppendFormat("&limit={0}", Limit.Value);
int counter = 1;
foreach (var filter in filterDescriptions)
{
sb.AppendFormat("&filter[{0}][attribute]={1}&filter[{2}][{3}]={4}", counter, filter.Column, counter, filter.FilterType, filter.Value);
counter++;
}
return sb.ToString();
}
}
public class FilterDescription
{
public string Column { get; set; }
public FilterType FilterType { get; set; }
public string Value { get; set; }
}
public enum FilterType
{
/// <summary>
/// Not Equal To
/// </summary>
neq,
/// <summary>
/// equals any of
/// </summary>
#in,
/// <summary>
/// not equals any of
/// </summary>
nin,
/// <summary>
/// greater than
/// </summary>
gt,
/// <summary>
/// less than
/// </summary>
lt
}
public class MagentoApiException : Exception
{
public MagentoApiException(string responseText, WebExceptionStatus status)
{
ResponseText = responseText;
Status = status;
}
public string ResponseText { get; set; }
public WebExceptionStatus Status { get; set; }
}
also don't forget to add the https://oauth.googlecode.com/svn/code/csharp/OAuthBase.cs to the project
it's ready to use. to read from api :
var request = CreateAuthorizedRequest(MagentoServer + "/api/rest/products", "get", new ApiFilter() {Page = 1 });
var responseText = FetchRequest(request);
Magento REST Api documantion can be found here
you can quickly create a client REST API using Spring.NET Social :
http://www.springframework.net/social/
Magento uses OAuth 1.0a authentication like Twitter. You can take a look to the Twitter implementation here:
http://www.springframework.net/social-twitter/
And the related documentation with step by step instructions:
http://www.springframework.net/social/refdoc/implementing.html
I'm not sure if this helps or not, but once I was able to get the oauth_token and oauth_token_secret from Magento (I used a PHP Magento sample to get it) I was able to query the REST API by putting everything in your requestUri into the header.
Your example helped me get most of the code correct, and just modified it a little (here's a little snippet):
StringBuilder sb = new StringBuilder("OAuth ");
sb.AppendFormat("oauth_version={0},", "1.0");
sb.AppendFormat("oauth_signature_method={0},", "HMAC-SHA1");
sb.AppendFormat("oauth_nonce={0},", nonce);
sb.AppendFormat("oauth_timestamp={0},", timeStamp);
sb.AppendFormat("oauth_consumer_key={0},", consumerKey);
sb.AppendFormat("oauth_token={0},", oauth_token);
sb.AppendFormat("oauth_signature={0}", sig);
Debug.WriteLine(sb.ToString());
var request = (HttpWebRequest)WebRequest.Create((resourceUrl));
request.Headers[HttpRequestHeader.Authorization] = sb.ToString();
request.ContentType = "text/xml";
request.Accept = "text/xml";
request.KeepAlive = true;
//request.Method = WebRequestMethods.Http.Get;
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Debug.WriteLine(response.StatusCode);
Debug.WriteLine(response.Server);
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(response.GetResponseStream());
Dts.Variables["User::XML_Response"].Value = xmlDoc.OuterXml.ToString();
}
Does that help?

Categories