Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solving Magento Enterprise edition/.NET integration rest #11

Closed
78fede78 opened this issue Jan 30, 2014 · 22 comments
Closed

Solving Magento Enterprise edition/.NET integration rest #11

78fede78 opened this issue Jan 30, 2014 · 22 comments

Comments

@78fede78
Copy link

I'm trying to make a request HTTP from .NET to Magento 1.8 Enterprise edition,
but apparently I don't have any response.

OAuth Authentication is working and reply also correct token

Dou you have any suggestion to resolve this problem?

Any idea why I don't receive a response?

Here following the code I'm using:

var client = new MagentoApi().Initialize("http://test.xxxxxxxxx.nl", "xxxxxxxxxxxxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx").AuthenticateAdmin("xxx", "xxxxxxx");
var response = client.GetProductById(1).Result;


I tried to debug your code but it stops here:

  var response = await Client.ExecuteTaskAsync(request);

Can you please help me out?
Thank you
Regards

@Maxhodges
Copy link

it's asynchronous so you need a handler for the event in the drop down.
something like executeTaskComplete maybe (not at a computer at the moment)

declare the client withevents at the too of your class then look for the
event int the

On Jan 31, 2014, at 12:14 AM, 78fede78 notifications@github.com wrote:

I'm trying to make a request HTTP from .NET to Magento 1.8 Enterprise
edition,
but apparently I don't have any response.

OAuth Authentication is working and reply also correct token

Dou you have any suggestion to resolve this problem?

Any idea why I don't receive a response?

Here following the code I'm using:

var client = new MagentoApi().Initialize("http://test.xxxxxxxxx.nl",
"xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx").AuthenticateAdmin("xxx",
"xxxxxxx");
var response = client.GetProductById(1).Result;

I tried to debug your code but it stops here:

var response = await Client.ExecuteTaskAsync(request);

Can you please help me out?
Thank you
Regards

Reply to this email directly or view it on
GitHubhttps://github.com//issues/11
.

@78fede78
Copy link
Author

// in an async method
this code is that of the home page and in my case is still pending.

var response = await client.GetProductBySku("123456");
// not async
response = client.GetProductBySku("123456").Result;
// The response contains the result or errors
if (!response.HasErrors)
{
var product = response.Result;
}

@nickvane
Copy link
Owner

Note that this library has not been tested yet against Magento 1.8
On the other hand, it should give you an error.
Have you tried the sync version?

response = client.GetProductBySku("123456").Result;

@78fede78
Copy link
Author

unfortunately yes, the result does not change.

Does not work....

We are on Magento Enterprise 1.13 - might there be an issue there?

@78fede78
Copy link
Author

78fede78 commented Feb 3, 2014

CallbackUrl is not important?

InitializeRestClient();
_client.Authenticator = OAuth1Authenticator.ForRequestToken(
_consumerKey,
_consumerSecret,
"http://localhost:8888" // Value for the oauth_callback parameter, we provide a value, but it won't be used.
);

@nickvane
Copy link
Owner

nickvane commented Feb 3, 2014

Not in this implementation because we are user and server in 1 implementation (which actually is contradictory to what openauth is trying to accomplish).
We mimick the openauth implementation. In a scenario where a user uses oauth to authenticate, the callback goes to the server, but in our scenario we handle it without the need for the callback.

In step 5 from https://github.com/nickvane/Magento-RestApi/wiki/Authentication-steps
an url is received that contains the callback url, but we just need to extract the values from that url and do not have to make a call to that url.

To respond to your issue: I have no access to an enterprise edition so can't test this for you. You could however try to debug the requests with http://fiddler2.com/ and see what the server is returning as response.

@78fede78
Copy link
Author

78fede78 commented Feb 3, 2014

I have done debugging my application with fiddler.
Everything is correct!!!!!
I get the desired response.!!!

It was just a matter of reading.

How do I know that the request has been completed?

Where am I doing wrong?

using System;
using System.IO;
using System.Net;
using System.Web;
using System.Web.UI;
using Magento.RestApi;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var client = new MagentoApi().Initialize("http://test.xxxxxxx.nl", "xxxxxxxxx", "xxxxxxxx").AuthenticateAdmin("xxx", "xxxxxxxx");
            var response = client.GetProductBySku("xxxxxxx").Result;
            if (!response.HasErrors)
            {
                //here never goes out
                var product = response.Result;              
            }
        }
    }
}

@78fede78
Copy link
Author

78fede78 commented Feb 3, 2014

I also made ​​a small change to the source code.

response.ContentType.ToUpperInvariant() =   "APPLICATION/JSON; CHARSET=UTF-8"

MagentoApi.cs Line 338

Instead of:

             if (response.ContentType.ToUpperInvariant (). == "APPLICATION/JSON")

I corrected

             if (response.ContentType.ToUpperInvariant (). Contains ("APPLICATION/JSON"))

@nickvane
Copy link
Owner

nickvane commented Feb 3, 2014

Yes, I already had this one as local change, but haven't pushed yet.
On Feb 3, 2014 5:31 PM, "78fede78" notifications@github.com wrote:

I also made a small change to the source code.

response.ContentType.ToUpperInvariant() = "APPLICATION/JSON; CHARSET=UTF-8"

MagentoApi.cs Line 338
...
Instead of:

     if (response.ContentType.ToUpperInvariant (). == "application / json")

I corrected

     if (response.ContentType.ToUpperInvariant (). Contains ("application / json"))

....

Reply to this email directly or view it on GitHubhttps://github.com//issues/11#issuecomment-33971859
.

@78fede78
Copy link
Author

78fede78 commented Feb 3, 2014

In console application works perfectly:

         var client = new MagentoApi().Initialize("http://test.xxxxx.nl", "xxxxxx", "xxxx").AuthenticateAdmin("xxxx", "xxxxxx");
            var response = client.GetProductBySku("xxxxx");

            while (true)
            {
                if (response.IsCompleted)
                {
                    Console.Write(response.ToString());
                    Product provaGomma = response.Result.Result;
                    provaGomma.name = "asdfsad";
                    provaGomma.price = 77;
                    client.UpdateProduct(provaGomma);

                    break;
                }
            }

you can get the same result in web application?

@jnb1
Copy link

jnb1 commented Feb 12, 2014

I am having the same problem. It doesn't give an error, it just freezes. It works in a console application but not in a winform application. Fiddler returns the correct result. I have tried Magento community 1.7 and 1.8.

@primico
Copy link

primico commented Apr 29, 2014

Hi, your Magento REST API client looks interesting and I thought I would test it out. I see this thread is similar to what I am trying and I don't know if I have the same problem as other people here.

I created an ASP.NET Razor project and tried calling this from a webpage:

var client = new MagentoApi().Initialize("http://localhost:8080", "key", "secret").AuthenticateAdmin("user", "password");

In Web Services -> REST Roles, I created a new Admin role and assigned a user to this role. I passed this user and password into AuthenticateAdmin above.
In Web Services -> oAuth Consumers, I created a new consumer and I passed the key and secret into Initialize above.

My Magento website is running locally at localhost:8080 on a PC using WAMPSERVER

When I run the code I get this error:

The remote server returned an error: (404) Not Found.

Any ideas what I'm doing wrong?

Thanks!!!

@primico
Copy link

primico commented Apr 30, 2014

I changed the URL parameter from "http://localhost:8080" to "http://localhost:8080/index.php" and now it gets past the previous error. Now I get this error:

Additional information: The provided consumer secret was rejected by the server at url 'http://localhost:8080/index.php/oauth/initiate' for consumer key 'xxxxxxxxxxxxxxxx'.

@primico
Copy link

primico commented May 1, 2014

Just to follow up, the oAuth Magento code was stripping out my port number so I made a temporary change to the code and now I get past the error above. Now I have the exact error as the original poster, my code just hangs on this line:

var response = await Client.ExecuteTaskAsync(request);

If anyone has any solution, I would love to hear. Thanks!

@dylanyoung-dev
Copy link

Hey primico,
I've been following this actually because I was in a very similar situation when I tried to setup this in my development environment running on Wamp Server. Any chance you can specify where it was stripping out the port number, and what change you made? I originally ran into this, and just decided it was too much hassle and was going to try adding directly into the MySQL database, but I'd rather get the API to work, since that's a safer way to go.

But I think I'll have to explore going this direction again. So thanks for all the comments, they are helpful, especially knowing it wasn't just me with the issue.

Dylan

@primico
Copy link

primico commented May 1, 2014

In the Magento code:
app > code > core > Mage > Oauth > Model > Server.php
Change this:
getHttpHost()
to:
getHttpHost(false)
I think there are 2 locations.
I hope it works for you.

Let me know if you get everything working. My code won't get past ExecuteTaskAsync. I tried to see if I can use ExecuteAsync instead, but I get a different error. Oh well...

@dylanyoung-dev
Copy link

Alright, I made those changes and they worked perfectly. After that getting past authentication works fine (no more errors). But now I'm stuck exactly where you are.

I did find that atleast in my installation that the .htaccess was missing a line:

RewriteRule ^api/rest api.php?type=rest [QSA,L]

Now if I go to: http://localhost:8080/api/rest/products within a browser and I turn on full access for Guests, I see an XML response.

But it still won't work and hangs at that exact line. Very frustrating, but I'll spend maybe a few more hours with it this weekend, hopefully we figure this out!

@dylanyoung-dev
Copy link

Hey,

Okay seems to be working if we call the different API calls using Async. I did find one more issue in the source (MagentoApi.cs) at line 337:

Change:

if (response.ContentType.ToUpperInvariant() = "APPLICATION/JSON")

To:

if (response.ContentType.ToUpperInvariant().Contains("APPLICATION/JSON"))

Basically my code was adding additional values to the ContentType, so using a contains will still match if that's the case.

Seems the rest is now working correctly now!

@nickvane
Copy link
Owner

nickvane commented May 8, 2014

I think I may have to take a look at that async code to make it work synchronously.
I haven't tried to connect to Magento Enterprise version yet because I don't have it at available.
I'll incorporate the above change too.
I'm glad you guys got it working!

@nickvane nickvane closed this as completed May 8, 2014
@dylanyoung-dev
Copy link

Hey,

I should clarify, this wasn't an enterprise issue, atleast for me, it had the problem in the community edition. I think the big issue with it, was that we were both using our local wamp server, and just so happen to both be using a different port than the standard 80. I can assume that's because we both had IIS running on 80.

Since I'm just about done with the project, I have two suggestions, and wasn't sure of where to put them.

  1. Need more code examples. I would be willing to provide code examples if requested. It would've saved me a lot of time if I had some deeper examples to work off of. Especially when dealing with uploading images, and dealing with multi-select attributes.

  2. I did find an issue with the dictionary<string, string> you used for Attributes. If you are using a multi-select attribute, which I was, it won't let you pass multiple values to Magento. I was about to hack up Magento, when I found in it's source if you pass it as an array, it will add multiple items. Unfortunately dictionary<string, string> won't work. It needs to be dictionary<string, object> so I can pass in an array if needed.

~ Dylan

@Scotty79
Copy link

Scotty79 commented Aug 5, 2014

Huge thanks to Nick and Micah for sharing their code with the community...

Had this exact problem with Enterprise v1.12.0.0 trying to call methods from an asp.net webform. I imagine this also applies to Magento community.

As mentioned in the posts above, I updated line 339 inside MagentoApi.cs to...

if (response.ContentType.ToUpperInvariant().Contains("APPLICATION/JSON"))

But the code below (line 337 inside MagentoApi.cs) would still hang no matter what I tried...
var response = await Client.ExecuteTaskAsync(request);

After some trial and error I found you need to change the way you call the API methods if you're calling them from a web form or any web UI for that matter.

This will work fine (does not hang) from a console app or unit test...

var response = client.GetProductBySku("123456").Result;

.. but doesn't work from an aspx page.

What you need to do is stick the API call in a new aync task and then register it with the page....e.g. from a button click or Page_Load...

e.g.

protected void btnFindProd_Click(object sender, EventArgs e)
{
RegisterAsyncTask(new PageAsyncTask(GetProductInfo));
}

private async Task GetProductInfo()
{
var pResponse = await client.GetProductBySku(txtSku.Text.Trim());
Product p = pResponse.Result;
// you've now got the product (if the sku exists)
}

For this to work, you need to add Async="true" to the page directive
e.g.
<%@ Page Title="Async" Language="C#" CodeBehind="Async.aspx.cs" Inherits="Whatever" Async="true" %>

Some good reading here:
http://www.hanselman.com/blog/TheMagicOfUsingAsynchronousMethodsInASPNET45PlusAnImportantGotcha.aspx

Hope that saves someone a few hours :)

@carlosptt
Copy link

Hi, a have a problem

I need, get to cateries description whit API REST

please Help

I used Magento 1.9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants