dcsimg
Results 1 to 36 of 36
  1. #1

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Make a webrequest in asana

    We use asana for project management and I'm working on using API so I can make calls from my c# application.

    I am starting out with the simplest thing, that I cannot get to work:

    Code:
            public string GetUsers()
            {
                var req = WebRequest.Create("https://app.asana.com/api/1.0/users");
                SetBasicAuthentication(req);
                try
                {
                    return new StreamReader(req.GetResponse().GetResponseStream()).ReadToEnd();
                }
                catch (System.Net.WebException exWeb)
                {
                    return "nogood";
                }
            }
    
            void SetBasicAuthentication(WebRequest req)
            {
                var authInfo = apiKey + ":";
                var encodedAuthInfo = Convert.ToBase64String(
                    Encoding.Default.GetBytes(authInfo));
                req.Headers.Add("Authorization", "Basic " + encodedAuthInfo);
            }
    I am getting: The underlying connection was closed: An unexpected error occurred on a send, and Status=SendFailure.
    It seems the asana documentation doesn't have anything on using it from a C# program, only python, javascript, etc. But others have gotten their desired results from the calls I am trying so I believe it's just something basic I am overlooking.

    Thanks.
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  2. #2

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    Maybe I should've called this "make a request in anything"? My research has led me to figuring out how to use OAuth from a windows application which isn't anything asana-specific. At least, that is what I think I need to do. So I found OAuth for .NET desktop applications. They have a reference to RestSharp. Is this something I would need to download? I am assuming because I don't have it, that is why things lke AuthInfo, RestClient, RestRequest, etc. are not defined.
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  3. #3
    Superbly Moderated NeedSomeAnswers's Avatar
    Join Date
    Jun 2002
    Location
    Manchester uk
    Posts
    2,440

    Re: Make a webrequest in asana

    I dont know much about Asana but here is my web request method i use to talk to my own web service which may help.

    In my case i am returning JSON but this method doesn't actually convert it into JSON so the return string can by XML or any other string based data

    Code:
     private string MakeRequest(string uri)
            {
                HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
                req.KeepAlive = false;
    
                try
                {
                    using (HttpWebResponse response = req.GetResponse() as HttpWebResponse)
                    {
                        using (var sr = new StreamReader(response.GetResponseStream()))
                        {
                            json = sr.ReadToEnd();
                        }
                        return json;
                    }
                }
                catch (WebException e)
                {
                    error = e.Message;
                    Console.WriteLine(error);
                    return "";
                }
            }
    Please Mark your Thread "Resolved", if the query is solved & Rate those who have helped you



  4. #4
    Superbly Moderated NeedSomeAnswers's Avatar
    Join Date
    Jun 2002
    Location
    Manchester uk
    Posts
    2,440

    Re: Make a webrequest in asana

    I use another method when i need the data Async using HttpClient which i can also share with you if you want?
    Please Mark your Thread "Resolved", if the query is solved & Rate those who have helped you



  5. #5

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    Probably not but thanks for the offer.
    I've generated a client id and client secret for use with OAuth. Now I just have to figure out how to use them.
    And this error is still haunting me: The underlying connection was closed: An unexpected error occurred on a send.
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  6. #6
    Superbly Moderated NeedSomeAnswers's Avatar
    Join Date
    Jun 2002
    Location
    Manchester uk
    Posts
    2,440

    Re: Make a webrequest in asana

    I had a quick look at Asana and your example uses an APIKey which is deprecated.

    it sound like you just need to add a header like this -

    Code:
    private string MakeRequest(string uri)
            {
                HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
                req.KeepAlive = false;
                SetBasicAuthentication(req);
                try
                {
                    using (HttpWebResponse response = req.GetResponse() as HttpWebResponse)
                    {
                        using (var sr = new StreamReader(response.GetResponseStream()))
                        {
                            json = sr.ReadToEnd();
                        }
                        return json;
                    }
                }
                catch (WebException e)
                {
                    error = e.Message;
                    Console.WriteLine(error);
                    return "";
                }
            }
    
            void SetBasicAuthentication(HttpWebRequest req)
            {
                req.PreAuthenticate = true;
                req.Headers.Add("Authorization",  "AccessToken");   // replace AccessToken with your actual generated Access Token
            }
    Please Mark your Thread "Resolved", if the query is solved & Rate those who have helped you



  7. #7

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    I have to run out for an hour but I will try what you suggested upon my return and thank you for researching asana for me.
    I will say that I'm not optimistic it will work. Even though I called the variable "apikey" it is actually a PAT - personal access token.
    If I enter a request in a browser data is returned, because I am logged into asana as a user. (I will log out and see what happens).
    If I run the same request in my code, I get the "underlying connection" error.
    If my request is to https://www.microsoft.com/en-us/, I get a response from that, so I believe my basic code is good. It's just when I'm trying to talk to asana some kind of authentication/credentials is missing, I believe.
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  8. #8

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    As soon as I execute response = req.GetResponse(), I get: "The underlying connection was closed: An unexpected error occurred on a send."
    I think that is asana's way of telling me it doesn't want to talk to me, but a more clear error message would be appreciated.

    I logged out of asana, and when I do this "https://app.asana.com/api/1.0/users" now in a browser, it says
    {"errors":[{"message":"Not Authorized","help":"For more information on API status codes and how to handle them, read the docs on errors: https://asana.com/developers/documentation/getting-started/errors"}]}
    So that is a clear message of what is wrong. I still am not sure what is wrong with my code nor, therefore, how to fix it. Any ideas, without having to become an asana expert yourself?
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  9. #9
    Superbly Moderated NeedSomeAnswers's Avatar
    Join Date
    Jun 2002
    Location
    Manchester uk
    Posts
    2,440

    Re: Make a webrequest in asana

    I have taken a look and i would suggest you read this page of the documentation - https://asana.com/developers/documen...g-started/auth

    when you get to the section titled - User Authorization Endpoint you will see that it says that there is an authentication URL -
    Code:
    https://app.asana.com/-/oauth_authorize
    which you need to pass the required parameters and it will return an auth code which i think you then pass in for each subsequent call to the original URL in your initial posts

    For the API each authorisation code you generate lasts for 1 hour.
    Please Mark your Thread "Resolved", if the query is solved & Rate those who have helped you



  10. #10

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    Hi. Yes, I have read *all* of the documentation, a couple times over. I am having trouble picturing how all this is going to flow.
    So I have two problems. 1) Proof of concept, where I test and just make sure I can issue asana commands, getting data back which I would display and sending data to update an asana task, for example. (To give you a little background, my application is a customer service application. Whenever our technicians service a customer, we have a case which consists of one or more tasks. These are tracked in asana. So we'd like a direct interface where I can display users comments so far and add to them. I believe these are called stories in asana).
    2) Then, implementing the API calls on behalf of the user. So maybe he would click a button saying Update Asana Task and type some text. From what you and the doc say, he will then be "interrupted" by asana chiming in: The user then sees a screen giving them the opportunity to accept or reject the request for authorization. In either case, the user will be redirected back to the redirect_uri And that last part - redirected back to the redirect_uri - I still don't understand what that means in light of it being a Windows App.

    Sorry...I know this isn't your problem and you are doing a lot of research on my behalf. I have a discussion about this topic also in StackOverflow and the asana community.
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  11. #11
    Superbly Moderated NeedSomeAnswers's Avatar
    Join Date
    Jun 2002
    Location
    Manchester uk
    Posts
    2,440

    Re: Make a webrequest in asana

    Code:
    Hi. Yes, I have read *all* of the documentation, a couple times over. I am having trouble picturing how all this is going to flow.
    Ah ok, so i have read a bit more and i missed something. This is how i see it now anyway.

    Firstly you need to authenticate your App in Asana for the specific User, you can probably do this inside Asana somehow, but you can also do it via the API.

    You do that by calling the Auth URL (https://app.asana.com/-/oauth_authorize) and passing the necessary param's (most of these params are what you will have used to register your app with Asana)

    client_id required The Client ID uniquely identifies the application making the request.
    redirect_uri required The URI to redirect to on success or error. This must match the Redirect URL specified in the application settings.
    response_type required Must be one of either code (if using the Authorization Code Grant flow) or token (if using the Implicit Grant flow). Other flows are currently not supported.
    state required Encodes state of the app, which will be returned verbatim in the response and can be used to match the response up to a given request.

    When you do this the User will see a request for your app access in there Asana (each users it seems as far as i can tell has to allow or disallow apps that can access there profile), and they have to click accept or reject. Once the user does this you will receive a reply on the redirect URL giving you the Access Code you need.

    What i would say here is this sounds quite tricky to do nicely in a desktop app, and if you can do the "authorise my app" bit directly in Asana, then you can skip the authorise bit in your app which would be good.

    They do say this about the Redirect URL for native apps -
    Native or command line applications should use the special redirect URL
    Code:
    urn:ietf:wg:oauth:2.0:oob
    but they fail to tell you what that means in terms of getting a response. Maybe if you use properly Asynch await http get methods then you code will wait, and once the user accepts then you will get a response returned, but i dont know and you would have to test this.

    I have an Asynch Await http get example, but it might just be easier to avoid this step by authenticating inside Asana. Let me know if you want the example.


    Once you are authorised (and therefore have an access code) you can make a call to the Token exchange web URL - passing the neccessary parameters

    grant_type required One of authorization_code or refresh_token. See below for more details.
    client_id required The Client ID uniquely identifies the application making the request.
    client_secret required The Client Secret belonging to the app, found in the details pane of the developer console.
    redirect_uri required Must match the redirect_uri specified in the original request.
    code sometimes required If grant_type=authorization_code this is the code you are exchanging for an authorization token.
    refresh_token sometimes required If grant_type=refresh_token this is the refresh token you are using to be granted a new access token.
    The token exchange URL is used to exchange your Access Code for a refresh token for a time limited access token which you then pass in the header of each subsequent call you make to the main URL like this one -The Header record should be added like this -

    Code:
    void SetBasicAuthentication(HttpWebRequest req)
            {
                req.PreAuthenticate = true;
                req.Headers.Add("Authorization",  "AccessToken");   // replace AccessToken with your actual generated Access Token
            }
    At this point if you have your token you should be able to make calls to get and post data to Asana.

    You will need to get a new token each time you do a new session of calls, as the token times out after 1 hour i think.
    Last edited by NeedSomeAnswers; Jun 8th, 2018 at 06:46 AM.
    Please Mark your Thread "Resolved", if the query is solved & Rate those who have helped you



  12. #12

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    OK! I will get back on this now.
    Regarding Native or command line applications should use the special redirect URL, I honestly didn't know if my app was "native". I looked up what native app is and believed it to be a phone or tablet app. And what the heck is a command line application? (Rhetorical question, perhaps).
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  13. #13
    Superbly Moderated NeedSomeAnswers's Avatar
    Join Date
    Jun 2002
    Location
    Manchester uk
    Posts
    2,440

    Re: Make a webrequest in asana

    Yes a Native app normally means a native mobile/Tablet app (one that runs directly on the mobile O/S, rather than a JavaScript based web app), but they might just be saying a non-web app its not completely clear.

    A command line app is a windows app without a front end, and is a project type you can use in VS. Your app essentially runs in a kind of command prompt window.
    Please Mark your Thread "Resolved", if the query is solved & Rate those who have helped you



  14. #14

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    So I am starting here.

    Quote Originally Posted by NeedSomeAnswers View Post
    [CODE]
    Firstly you need to authenticate your App in Asana for the specific User, you can probably do this inside Asana somehow, but you can also do it via the API.

    You do that by calling the Auth URL (https://app.asana.com/-/oauth_authorize) and passing the necessary param's (most of these params are what you will have used to register your app with Asana)
    Right now I am a logged in asana user; I have it open in a web browser. This has nothing to do with my code yet.
    I go to My Profile Settings. There is a link to "Manage Developer Apps".
    Under "Apps You Own" I say Add New Application
    A form comes up and is asking me for: APP NAME, APP URL, REDIRECT URL.
    I enter "test asana api", the website for my company (not 100% sure about that?) and for redirect url I am trying "urn:ietf:wgauth:2.0ob" (sorry, the forum is putting emojis here) which got generated because I checked "this is a native or command line app".
    It gives me a client id and a client secret.
    On the same form, it then it wants to know if authorization endpoint is Authorization Code Grant or Implicit Grant. I chose the former and it generates for me that oauth_authorize string. It looks like I'm done, so now I'm coding.

    The first thing I do is try to make an authorization request. I've copied the string it gave me above: MakeRequest("https://app.asana.com/-/oauth_authorize?response_type=code&client_id=<the generated client id>&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&state=<STATE_PARAM>");
    I was not sure what STATE_PARAM should be. I tried putting my name in here, I tried leaving it STATE_PARAM.

    MakeRequest() is the code you gave me above:
    Code:
    private string MakeRequest(string uri)
            {
                string json;
                string error;
    
                HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
                req.KeepAlive = false;
    
                try
                {
                    using (HttpWebResponse response = req.GetResponse() as HttpWebResponse)
                    {
                        using (var sr = new StreamReader(response.GetResponseStream()))
                        {
                            json = sr.ReadToEnd();
                        }
                        return json;
                    }
                }
                catch (WebException e)
                {
                    error = e.Message;
                    Console.WriteLine(error);
                    return "";
                }
            }
    I exception on the "response =" line with The underlying connection was closed: An unexpected error occurred on a send.
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  15. #15

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    Interesting! I just took the uri I am passing to MakeRequest() and put it in a web browser, and I got the form that says Grant Permission! This is the form you and I have discussed a bit, based on what the asana doc said would happen
    So, it looks like this string is fine. The trouble is when it comes from my app.
    Then...I logged out of asana. Now when I run that uri, I get a screen to login.
    So...I am not sure what that means in light of my application issuing the request.
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  16. #16

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    THEN...I logged in and the next form was that Grant Permission form, so I said grant and this plain text page came up:
    Please copy this code, switch to your application, and paste it there:
    0/<followed by a 32 digit string>
    It is the same format as the token I generated previously.
    Paste it *where* into my application?
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  17. #17

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    OMG! This was in StackOverflow. What is a CertificateCheck? I am looking this up now.
    Code:
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CertificateCheck);
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
                //Must use Tls12 or else exception: "The underlying connection was closed: An unexpected error occurred on a send." InnerException = {"Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."}
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  18. #18

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    Oh, I was able to comment-out CertificateCheck.

    This is much better! "The remote server returned an error: (401) Unauthorized."

    I will get authorized and test again!
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  19. #19

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    I can't get authorized. You said
    Once the user does this you will receive a reply on the redirect URL giving you the Access Code you need.
    I am wondering if this is buried somewhere in the html I am finally successfully receiving in our MakeRequest() function:

    Code:
            private string MakeRequest(string uri)
            {
                string json;
                string error;
    
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
                req.KeepAlive = false;
                SetBasicAuthentication(req);
                try
                {
                    using (HttpWebResponse response = req.GetResponse() as HttpWebResponse)
                    {
                        using (var sr = new StreamReader(response.GetResponseStream()))
                        {
                            // Oh, is there a token somewhere in here???
                            json = sr.ReadToEnd();
                        }
                        return json;
                    }
                }
                catch (WebException e)
                {
                    error = e.Message;
                    Console.WriteLine(error);
                    return "";
                }
            }
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  20. #20
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    31,621

    Re: Make a webrequest in asana

    I'm not sure how html is coming into this. Usually when you're accessing a web-based api that you need to first authenticate against, you get the user's login credentials, and send them to the login api... and get back a token. From then on, you send the token when making further requests. That's really the only way it can work in a desktop app... if it was a web app, then yeah, I could see there being a url redirect, but from the desktop, or a non-web interface, that's not going to work.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  21. #21

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    I didn't know if the token was buried somewhere in the html. You may have noticed the comment in the code I posted: // Oh, is there a token somewhere in here??? (LOL!)
    The html comes back from the instruction: json = sr.ReadToEnd();
    I know it's called json but that's just the name of a string variable, and this is what I am getting:
    ? json
    "<!DOCTYPE html>\n<html>\n<head>\n<title>Asana - Log In</title><script>__FILE__=\"(none)\";var config = {\"CLUSTER\":\"prod\"};

    etc...it's quite long!
    This is so frustrating why how to use this API isn't better documented!
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  22. #22
    Superbly Moderated NeedSomeAnswers's Avatar
    Join Date
    Jun 2002
    Location
    Manchester uk
    Posts
    2,440

    Re: Make a webrequest in asana

    If you have authorised your app inside Asana you dont need to do it through code aswell ! The Authorise URL does the same thing as authorising your app inside Asana.

    If you re-read my last post, you just need to do the part that talks about the Token exchange

    (follow my last post form this line on-wards - Once you are authorised (and therefore have an access code) you can make a call to the Token exchange web URL)

    You need to use the oauth_authorize string that was generated for you when you authorised your app inside Asana and use that against the Token exchange web URL -

    Last edited by NeedSomeAnswers; Jun 11th, 2018 at 03:35 AM.
    Please Mark your Thread "Resolved", if the query is solved & Rate those who have helped you



  23. #23

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    OK...I'm trying. I am now getting an error "no route found". I found this same error on StackOverflow. What exactly is this person saying how s/he fixed it?
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  24. #24

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    In my research (I think I've read every post to stackoverlfow regarding asana issues), I found contact information for asana support so I've emailed them.

    Here is the state of my code in case, in the meantime, you see anything glaring I am doing wrong. I did go back and look at the post you had cited.

    Code:
                StringBuilder sbRequest = new StringBuilder();
                sbRequest.Append("https://app.asana.com/-/oauth_token");
                sbRequest.Append("?grant_type=refresh_token");
                sbRequest.Append("&refresh_token=x/xxxxxxxxxxxxxxxxxxxxxxxxxx");
                sbRequest.Append("&client_id=xxclientIDxx");
                sbRequest.Append("&client_secret=xxxclientSecretxxx");
               MakeRequest(sbRequest.ToString());
    Code:
            private string MakeRequest(string uri)
            {
                string json;
                string error;
    
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
                req.KeepAlive = false;
                SetBasicAuthentication(req);
                try
                {
                    using (HttpWebResponse response = req.GetResponse() as HttpWebResponse)
                    {
                        using (var sr = new StreamReader(response.GetResponseStream()))
                        {
                            // Oh, is there a token somewhere in here???
                            json = sr.ReadToEnd();
                        }
                        return json;
                    }
                }
                catch (WebException e)
                {
                    error = e.Message;
                    Console.WriteLine(error);
                    return "";
                }
            }
    
            void SetBasicAuthentication(HttpWebRequest req)
            {
                req.PreAuthenticate = true;
                req.Headers.Add("Authorization", "x/xxxxxxxxxxxxxxxxxxxxxxxxxx");   // replace AccessToken with your actual generated Access Token
            }
    Iíve received unauthorized errors, bad request, no route found, and occasionally HTML that I canít make heads or tails of, based on different things I am trying.
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  25. #25
    Superbly Moderated NeedSomeAnswers's Avatar
    Join Date
    Jun 2002
    Location
    Manchester uk
    Posts
    2,440

    Re: Make a webrequest in asana

    Basically the method above is a Get command when you need to do a Post command that is what the error is saying.

    Very simply a Get command Gets a resource or data , Post is more like a save. It posts data, but can also give return data (much like a stored procedure can)

    Try this method instead, you will need to replace the bookmarks i have left in the json string like this one - [granttype] with actual values

    Code:
    using (var httpclient = new HttpClient())
                    {
                        var url = "https://app.asana.com/-/oauth_token";
    
                        var json = "{\"grant_type\": [granttype] \"\",\"client_id \": [clientid] \"\",\"client_secret  \": [clientsecret]\"\",\"redirect_uri \": [redirecturi]\"\",\"code  \": [code ] }";
    
                        var content = new StringContent(json, Encoding.UTF8, "application/json");
    
                        var response = httpclient.PostAsync(url, content).Result;
    
                       
                    }
    if this is successful you should get data returned in the response variable, probably json data and then we can move on to the next step.
    Please Mark your Thread "Resolved", if the query is solved & Rate those who have helped you



  26. #26

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    Thanks. So, I think I had to reformat that a bit to make it valid json:
    Code:
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                using (var httpclient = new System.Net.Http.HttpClient())
                {
                    var url = "https://app.asana.com/-/oauth_token";
    
                    var json = "{\"grant_type\": \"authorization_code\",\"client_id\": \"xxIDxx\",\"client_secret\": \"xxSecretxx\",\"redirect_uri\": \"urn:ietf:wg:oauth:2.0:oob\",\"code\": \"xxAccessTokenxx\" }";
    
                    var content = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
    
                    var response = httpclient.PostAsync(url, content).Result;
    
    
                }
    I am not exceptioning which I guess is progress, but in the rather long response back I have things like:
    {StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
    and
    IsSuccessStatusCode: false
    ReasonPhrase: "Bad Request"
    RequestMessage: {Method: POST, RequestUri: 'https://app.asana.com/-/oauth_token', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
    {
    Content-Type: application/json; charset=utf-8
    Content-Length: 209
    }}
    StatusCode: BadRequest
    Version: {1.1}
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  27. #27

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    Wow! I found something that worked! Unfortunately, it's in VB.NET

    I copied this person's code from this post

    I modified it with my specific API_KEY, and I added ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 to take care of the "underlying connection was closed" error.

    There must be something subtle in this code that I didn't have in any of mine.

    Here it all is:
    Code:
    Imports System.Net
    Imports System.IO
    Imports System.Text
    
    ' https://stackoverflow.com/questions/16588038/connecting-to-asana-using-webrequests
    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
        End Sub
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim response As String  ' = GetResponse("https://app.asana.com/0/taskIDhere")
            response = GetResponse("https://app.asana.com/api/1.0/users/me")
            MsgBox(response)
        End Sub
    
        Public Function GetResponse(uri As String, Optional data As String = "", Optional method As String = "GET") As String
            System.Diagnostics.Trace.WriteLine(uri)
    
            ' ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
    
            ' create request
            Dim request As HttpWebRequest = DirectCast(WebRequest.Create(uri), HttpWebRequest)
            request.PreAuthenticate = True
            request.Method = method
            request.ContentType = "application/x-www-form-urlencoded"
    
            ' log in
            Dim authInfo As String = "MMOCK_API_KEY" & ":" & ""
            ' blank password
            authInfo = Convert.ToBase64String(Encoding.[Default].GetBytes(authInfo))
            request.Headers("Authorization") = "Basic " & authInfo
    
            ' send data
            If data <> "" Then
                Dim paramBytes As Byte() = Encoding.ASCII.GetBytes(data)
                request.ContentLength = paramBytes.Length
                Dim reqStream As Stream = request.GetRequestStream()
                reqStream.Write(paramBytes, 0, paramBytes.Length)
                reqStream.Close()
            End If
    
            ' get response
            Try
                Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
                Return New StreamReader(response.GetResponseStream()).ReadToEnd()
            Catch ex As WebException
                Dim response As HttpWebResponse = DirectCast(ex.Response, HttpWebResponse)
                Throw New Exception((uri & " caused a " & CInt(response.StatusCode) & " error." & vbLf) + response.StatusDescription)
            End Try
    
        End Function
    End Class
    I get JSON back with my email, name, workspaces... This is amazing!
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  28. #28

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    *** IMPORTANT DISCOVERY ***

    That VB.NET code that worked...I rewrote it in C#, it does not work! How can that be? Is there something inherent in the VB.NET code that I must explicitly put in the C#? Same code is giving me a 401 unauthorized error in C#.
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  29. #29

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    I am perfectly fine with having one of my projects in my application solution be VB.NET, if that's what it takes. It's just odd.

    @NeedSomeAnswers, you've probably given up on me...
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  30. #30
    Superbly Moderated NeedSomeAnswers's Avatar
    Join Date
    Jun 2002
    Location
    Manchester uk
    Posts
    2,440

    Re: Make a webrequest in asana

    Hi MMock,

    no i have not given up, as i live in the UK my time zone will be a bit different then yours

    Whats difficult is as i am not registered with Asana i cant test any code myself, but web services and the like are my area and the whole oauth stuff is interesting so i will Persevere

    It's 9pm in the evening over here now though so it will probably be tomorrow before i get a chance to look at that VB.Net code but once i have had a look i will post a reply.
    Please Mark your Thread "Resolved", if the query is solved & Rate those who have helped you



  31. #31

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    I just meant that I am a pain in the neck, not that you weren't answering.
    I know it's hard not being able to run it yourself!
    By the way, nothing to do with VB.NET vs C#. I had a typo on C#.
    Here is my discussion on the asana forum. I assume it is for public consumption: asana forum It was there the typo was pointed out.
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  32. #32
    Superbly Moderated NeedSomeAnswers's Avatar
    Join Date
    Jun 2002
    Location
    Manchester uk
    Posts
    2,440

    Re: Make a webrequest in asana

    I just meant that I am a pain in the neck, not that you weren't answering.
    Not at all, if i didn't want to help i wouldn't have involved myself in the first place

    So does you C# code work now then?

    could you post it so we can see it?

    I have now had a chance to look at the VB.Net code now and its very similar to my original makeRequest code apart from they set the content type and the the header is added slightly differently.

    are you just hitting the main URL straight away - "https://app.asana.com/api/1.0/users/me"

    or are you hitting the token exchange first?
    Please Mark your Thread "Resolved", if the query is solved & Rate those who have helped you



  33. #33

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    Yes here is my C# code

    Code:
    using System;
    using System.Text;
    using System.Net;
    using System.Windows.Forms;
    using System.IO;
    
    namespace WindowsApplication2
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                string response;
                response = GetResponse("https://app.asana.com/api/1.0/users/me");
            }
    
            public string GetResponse(string uri, string data = "", string method = "GET")
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    
                // Create Request
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                request.PreAuthenticate = true;
                request.Method = method;
                request.ContentType = "application/x-www-form-urlencoded";
    
                // Log In
                string authInfo = "x/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + ":" + "";
                authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
                request.Headers["Authorization"] = "Basic " + authInfo;
    
                // send data if supplied
                if (data != "")
                {
    
                }
    
                // receive response
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                return new StreamReader(response.GetResponseStream()).ReadToEnd();
    
            }
        }
    }
    authInfo is the personal access token I created from "Developer App Management" within asana.

    web services and the like are my area and the whole oauth stuff is interesting
    I believe after all this you are qualified to add asana API to your resume!
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  34. #34
    Superbly Moderated NeedSomeAnswers's Avatar
    Join Date
    Jun 2002
    Location
    Manchester uk
    Posts
    2,440

    Re: Make a webrequest in asana

    Ok so yes that code really is not far off my code, and i think it was probably the way the header is added that is the big difference.

    I have 2 questions though;

    1, When your logged out of Asana does that Asana request run then? and do you get data returned?

    2, If the answer to 1 is yes, what the hell is the point of the token exchange ?? (the second question is rhetorical )
    Please Mark your Thread "Resolved", if the query is solved & Rate those who have helped you



  35. #35

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    Sitting in an empty room trying to forget the past
    Posts
    4,007

    Re: Make a webrequest in asana

    Ah yes, I meant to test not being logged into asana...So I just logged off, issued the users/me request and yes I got back data. However, I would like to try this from a "fresh" machine because I am skeptical. But, I guess that would be preferable so I don't have to worry about users being logged in, in order for the interface to work?

    I don't know if you read the thread on the asana forum, but there was this about security:
    In your code use are using what is called Basic Auth. The downside of this method is that you need to hard code (or provide) login + password inside your code. It means, that if your code is going to be stolen by someone, they will have a full access to your account.

    Another method is oAuth : you donít need login and password (and you donít send them via open protocols as in Basic Auth and e.g. main-in-the-middle attack cannot be done to reveal your credentials). You just have a temporary token (together with secret to be able to verify that this is the correct client) which allows you to access only to resources that this token is authorized for. It means, that this method is much more secure and now widely used.

    However, I asked this person where in my code I was providing a login + password? I don't see where I am doing that.
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  36. #36
    Superbly Moderated NeedSomeAnswers's Avatar
    Join Date
    Jun 2002
    Location
    Manchester uk
    Posts
    2,440

    Re: Make a webrequest in asana

    Your not providing a user name and password, you providing an Authorisation code, but in there documentation it suggest that you use the Auth Code to get a time limited token, then use the token to get data.

    You appear to be able to just use the Auth Code to get Data skipping the get token step, which seems a bit weird to me but if it works it works i guess.
    Please Mark your Thread "Resolved", if the query is solved & Rate those who have helped you



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width


×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.