Example #1
0
 public static T Select <T>(this IConsumerRequest request, Func <NameValueCollection, T> selectFunc)
 {
     try
     {
         return(selectFunc(request.ToBodyParameters()));
     }
     catch (ArgumentNullException)
     {
         throw Error.FailedToParseResponse(request.ToString());
     }
 }
        public String AccessProtectedResource(HMEntities.UserProfiles.User currentUser, String parameters)
        {
            String       URL          = Chpp.ResourcesURL + "?" + parameters;
            OAuthSession oAuthSession = GetOAuthSession(Chpp.ConsumerKey, Chpp.ConsumerSecret);

            oAuthSession.AccessToken = new TokenBase()
            {
                ConsumerKey = Chpp.ConsumerKey, Token = currentUser.accessToken, TokenSecret = currentUser.accessTokenSecret
            };

            IConsumerRequest request = oAuthSession.Request().Get().ForUrl(URL);

            return(request.ToString());
        }
Example #3
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <param name="selectFunc"></param>
        /// <returns></returns>
        public static T Select <T>(this IConsumerRequest request, Func <NameValueCollection, T> selectFunc)
        {
            try
            {
                return(selectFunc(request.ToBodyParameters()));
            }
            catch (ArgumentNullException argumentException)
            {
                if (argumentException.Message.Contains("Value cannot be null.\r\nParameter name: str"))
                {
                    throw Error.ExperiencingIssueWithCreatingUriDueToMissingAppConfig(argumentException);
                }

                throw Error.FailedToParseResponse(request.ToString());
            }
        }
        public void MakeAuthenticatedCallForTokenRsaSha1WithPostAndHeaders()
        {
            IOAuthSession session = CreateConsumer(SignatureMethod.RsaSha1);

            session.AccessToken = new TokenBase {
                ConsumerKey = "key", Token = "accesskey", TokenSecret = "accesssecret"
            };
            session.ConsumerContext.UseHeaderForOAuthParameters = true;

            IConsumerRequest context = session.Request().Post().ForUrl("http://term.ie/oauth/example/echo_api.php")
                                       .WithFormParameters(new { success = "true" })
                                       .SignWithToken();

            string contents = context.ToString();

            Assert.Equal("success=true", contents);
        }
Example #5
0
        public void TestContactCanBePosted()
        {
            string contactName  = "Steve Jobs " + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss");
            string contactEmail = contactName.Replace(' ', '-');

            string postContactRequestBody = string.Format("<Contacts><Contact><Name>{0}</Name><EmailAddress>{1}@nowhere.com</EmailAddress></Contact></Contacts>", contactName, contactEmail);

            IConsumerRequest postContactRequest = ConsumerSessionFactory.CreatePrivateConsumerSession()
                                                  .Request()
                                                  .ForMethod("POST")
                                                  .ForUri(new Uri(apiEndpointUrl))
                                                  .WithFormParameters(new { xml = postContactRequestBody })
                                                  .SignWithToken(ConsumerSessionFactory.CreatePrivateAccessToken());

            string postContactResponse = postContactRequest.ToString();

            Assert.IsNotEmpty(postContactResponse);
        }
        public string GetResource(string parameters)
        {
            System.Console.Out.WriteLine("Requesting: {0}", parameters);

            string           url     = OAuthProtectedResourceUrl + "?" + parameters;
            IConsumerRequest request = _oAuthSession.Request().Get().ForUrl(url);

            string result = request.ToString();

            if (result.Contains(@"chpperror.xml")) // <FileName>chpperror.xml</FileName>
            {
                int    errorCode        = -1;
                string errorDescription = "unknown CHPP error";

                try
                {
                    XDocument doc    = XDocument.Load(new StringReader(result));
                    XElement  elRoot = doc.Root;

                    if (elRoot != null)
                    {
                        XElement elErrorCode = elRoot.Element("ErrorCode");
                        if (elErrorCode != null)
                        {
                            int.TryParse(elErrorCode.Value, out errorCode);
                        }

                        XElement elErrorDescription = elRoot.Element("Error");
                        if (elErrorDescription != null && !string.IsNullOrEmpty(elErrorDescription.Value))
                        {
                            errorDescription = elErrorDescription.Value;
                        }
                    }
                }
                finally
                {
                    throw new ChppException(errorCode, errorDescription);
                }
            }

            return(result);
        }
Example #7
0
        public void TestEmptyContactNameReturnsHttp400Error()
        {
            string contactName  = "Steve Jobs " + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss");
            string contactEmail = contactName.Replace(' ', '-');

            string postContactRequestBody  = string.Format("<Contacts><Contact><Name></Name><EmailAddress>{0}@nowhere.com</EmailAddress></Contact></Contacts>", contactEmail);
            string postContactResponseBody = string.Empty;

            IConsumerRequest postContactRequest = ConsumerSessionFactory.CreatePrivateConsumerSession()
                                                  .Request()
                                                  .ForMethod("POST")
                                                  .ForUri(new Uri(apiEndpointUrl))
                                                  .WithFormParameters(new { xml = postContactRequestBody })
                                                  .SignWithToken(ConsumerSessionFactory.CreatePrivateAccessToken());

            try
            {
                postContactResponseBody = postContactRequest.ToString();
            }
            catch (OAuthException ex)
            {
                Assert.Fail(string.Format("An OAuth Exception occurred: {0}", ex.Report));
            }
            catch (WebException ex)
            {
                postContactResponseBody = ex.Response.GetResponseStream().ReadToEnd();
            }

            // Even if an error occurs, the response body should have been captured
            Assert.IsNotEmpty(postContactResponseBody);

            Console.WriteLine("Error Number : " + postContactResponseBody.ReadSingleNode(@"/ApiException/ErrorNumber"));
            Console.WriteLine("Error Message : " + postContactResponseBody.ReadSingleNode(@"/ApiException/Message"));

            foreach (string validationError in postContactResponseBody.ReadNodes(@"/ApiException/Elements/DataContractBase/ValidationErrors/ValidationError"))
            {
                Console.WriteLine("Validation Error : " + validationError);
            }
        }
Example #8
0
        public static void Run()
        {
            // 0. Create the consumer session
            OAuthConsumerContext consumerContext = new OAuthConsumerContext
            {
                ConsumerKey                 = PartnerConsumerKey,
                ConsumerSecret              = PartnerConsumerSecret,
                SignatureMethod             = SignatureMethod.RsaSha1,
                UseHeaderForOAuthParameters = true,
                UserAgent = PartnerUserAgentString,
                Key       = OAuthSigningCertificate.PrivateKey
            };

            OAuthSession consumerSession = new OAuthSession(
                consumerContext,
                Settings.Default.PartnerRequestTokenURI,
                Settings.Default.AuthoriseURI,
                Settings.Default.PartnerAccessTokenURI);

            // Replace the default ConsumerRequest factory with one that can create ConsumerRequest classes which use a client SSL certificate
            consumerSession.ConsumerRequestFactory = new DefaultConsumerRequestFactory(ClientSslCertificateFactory);


            // 1. Get a request token
            IToken requestToken;

            try
            {
                requestToken = consumerSession.GetRequestToken();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return;
            }

            Console.WriteLine("Request Token Key: {0}", requestToken.Token);
            Console.WriteLine("Request Token Secret: {0}", requestToken.TokenSecret);


            // 2. Get the user to log into Xero using the request token in the querystring
            //string authorisationUrl = Settings.Default.AuthoriseURI.AbsoluteUri + "?oauth_token=" + HttpUtility.UrlEncode(requestTokenKey);
            string authorisationUrl = consumerSession.GetUserAuthorizationUrlForToken(requestToken);

            Process.Start(authorisationUrl);

            // 3. Get the use to enter the authorisation code from Xero (4-7 digit number)
            Console.WriteLine("Please input the code you were given in Xero:");
            var verificationCode = Console.ReadLine();

            if (string.IsNullOrEmpty(verificationCode))
            {
                Console.WriteLine("You didn't type a verification code!");
                return;
            }

            verificationCode = verificationCode.Trim();


            // 4. Use the request token and verification code to get an access token
            AccessToken accessToken;

            try
            {
                accessToken = consumerSession.ExchangeRequestTokenForAccessToken(requestToken, verificationCode);
            }
            catch (OAuthException ex)
            {
                Console.WriteLine("An OAuthException was caught:");
                Console.WriteLine(ex.Report);
                return;
            }

            Console.WriteLine("Access Token Key: {0}", accessToken.Token);
            Console.WriteLine("Access Token Secret: {0}", accessToken.TokenSecret);


            // 5. Make a call to api-partner.network.xero.com to check that we can use the access token.
            IConsumerRequest getOrganisationRequest = consumerSession
                                                      .Request()
                                                      .ForMethod("GET")
                                                      .ForUri(new Uri("https://api-partner.network.xero.com/api.xro/2.0/Organisation"))
                                                      .SignWithToken(accessToken);

            string getOrganisationResponse = getOrganisationRequest.ToString();

            if (getOrganisationResponse != string.Empty)
            {
                XElement organisationXml  = XElement.Parse(getOrganisationResponse);
                string   organisationName = organisationXml.XPathSelectElement("//Organisation/Name").Value;
                Console.WriteLine(string.Format("You have been authorised against organisation: {0}", organisationName));
            }


            // 5.1 Refresh the access token using the session handle
            try
            {
                accessToken = consumerSession.RenewAccessToken(accessToken, accessToken.SessionHandle);

                Console.WriteLine("The access token has been refreshed");
                Console.WriteLine("New Access Token: " + accessToken.Token);
                Console.WriteLine("New Access Secret: " + accessToken.TokenSecret);
            }
            catch (Exception ex)
            {
                Console.WriteLine("The access token could not be refreshed:\r\n" + ex);
                return;
            }


            // 6. Make a PUT call to the API - add a dummy contact
            Console.WriteLine("Please enter the name of a new contact to add to Xero");
            string contactName = Console.ReadLine();

            if (string.IsNullOrEmpty(contactName))
            {
                return;
            }

            string putContactRequestBody = string.Format("<Contacts><Contact><Name>{0}</Name></Contact></Contacts>", contactName);
            string putContactResponse;

            IConsumerRequest putContactRequest = consumerSession
                                                 .Request()
                                                 .ForMethod("PUT")
                                                 .ForUri(new Uri("https://api-partner.network.xero.com/api.xro/2.0/Contacts"))
                                                 .WithFormParameters(new { xml = putContactRequestBody })
                                                 .SignWithToken(accessToken);

            try
            {
                putContactResponse = putContactRequest.ToString();
            }
            catch (OAuthException ex)
            {
                Console.WriteLine("An OAuthException was caught:");
                Console.WriteLine(ex.Report);
                return;
            }
            catch (WebException ex)
            {
                putContactResponse = ex.Response.GetResponseStream().ReadToEnd();

                Console.WriteLine("A WebException was caught:");
                Console.WriteLine(putContactResponse);
                return;
            }

            if (putContactResponse != string.Empty)
            {
                var    responseElement = XElement.Parse(putContactResponse);
                string statusCode      = responseElement.XPathSelectElement("/Status").Value;

                if (statusCode == "OK")
                {
                    string contactId = responseElement.XPathSelectElement("/Contacts/Contact[1]/ContactID").Value;
                    Console.WriteLine(string.Format("The contact '{0}' was created with id: {1}", contactName, contactId));
                }
            }


            // 7. Try to update the contact that's just been created, but this time use a POST method
            string postContactRequestBody = string.Format("<Contacts><Contact><Name>{0}</Name><EmailAddress>{1}@nowhere.com</EmailAddress></Contact></Contacts>", contactName, contactName.ToLower().Replace(" ", "."));
            string postContactResponse;

            IConsumerRequest postContactRequest = consumerSession
                                                  .Request()
                                                  .ForMethod("POST")
                                                  .ForUri(new Uri("https://api-partner.network.xero.com/api.xro/2.0/Contacts"))
                                                  .WithFormParameters(new { xml = postContactRequestBody })
                                                  .SignWithToken(accessToken);

            try
            {
                postContactResponse = postContactRequest.ToString();
            }
            catch (OAuthException ex)
            {
                Console.WriteLine("An OAuthException was caught:");
                Console.WriteLine(ex.Report);
                return;
            }
            catch (WebException ex)
            {
                putContactResponse = ex.Response.GetResponseStream().ReadToEnd();

                Console.WriteLine("A WebException was caught:");
                Console.WriteLine(putContactResponse);
                return;
            }

            if (postContactResponse != string.Empty)
            {
                var    responseElement = XElement.Parse(postContactResponse);
                string statusCode      = responseElement.XPathSelectElement("/Status").Value;

                if (statusCode == "OK")
                {
                    string emailAddress = responseElement.XPathSelectElement("/Contacts/Contact[1]/EmailAddress").Value;
                    Console.WriteLine(string.Format("The contact '{0}' was updated with email address: {1}", contactName, emailAddress));
                }
            }
        }
Example #9
0
        public static void Run()
        {
            // Create the consumer session
            OAuthConsumerContext consumerContext = new OAuthConsumerContext
            {
                ConsumerKey                 = "ZGIXM2M1Y2RIZJGYNGY1Y2EWZGYZMW",
                ConsumerSecret              = "RZRCMBRPK57EAG6GRO4GPLYDH9REPX",
                SignatureMethod             = SignatureMethod.HmacSha1,
                UseHeaderForOAuthParameters = true,
                UserAgent = string.Format("Xero.API.ScreenCast v1.0 (Public App Testing)")
            };

            OAuthSession consumerSession = new OAuthSession(
                consumerContext,
                Settings.Default.RequestTokenURI,
                Settings.Default.AuthoriseURI,
                Settings.Default.AccessTokenURI);

            // 1. Get a request token
            IToken requestToken = consumerSession.GetRequestToken();

            Console.WriteLine("Request Token Key: {0}", requestToken.Token);
            Console.WriteLine("Request Token Secret: {0}", requestToken.TokenSecret);


            // 2. Get the user to log into Xero using the request token in the querystring
            //string authorisationUrl = Settings.Default.AuthoriseURI.AbsoluteUri + "?oauth_token=" + HttpUtility.UrlEncode(requestTokenKey);
            string authorisationUrl = consumerSession.GetUserAuthorizationUrlForToken(requestToken);

            Process.Start(authorisationUrl);

            // 3. Get the use to enter the authorisation code from Xero (4-7 digit number)
            Console.WriteLine("Please input the code you were given in Xero:");
            var verificationCode = Console.ReadLine();

            if (string.IsNullOrEmpty(verificationCode))
            {
                Console.WriteLine("You didn't type a verification code!");
                return;
            }

            verificationCode = verificationCode.Trim();


            // 4. Use the request token and verification code to get an access token
            IToken accessToken;

            try
            {
                accessToken = consumerSession.ExchangeRequestTokenForAccessToken(requestToken, verificationCode);
            }
            catch (OAuthException ex)
            {
                Console.WriteLine("An OAuthException was caught:");
                Console.WriteLine(ex.Report);
                return;
            }

            Console.WriteLine("Access Token Key: {0}", accessToken.Token);
            Console.WriteLine("Access Token Secret: {0}", accessToken.TokenSecret);


            // 5. Make a call to api.xero.com to check that we can use the access token.
            IConsumerRequest getOrganisationRequest = consumerSession
                                                      .Request()
                                                      .ForMethod("GET")
                                                      .ForUri(new Uri("https://api.xero.com/api.xro/2.0/Organisation"))
                                                      .SignWithToken(accessToken);

            string getOrganisationResponse = getOrganisationRequest.ToString();

            if (getOrganisationResponse != string.Empty)
            {
                var    organisationXml  = XElement.Parse(getOrganisationResponse);
                string organisationName = organisationXml.XPathSelectElement("//Organisation/Name").Value;
                Console.WriteLine(string.Format("You have been authorised against organisation: {0}", organisationName));
            }


            // 6. Make a PUT call to the API - add a dummy contact
            Console.WriteLine("Please enter the name of a new contact to add to Xero");
            string contactName = Console.ReadLine();

            if (string.IsNullOrEmpty(contactName))
            {
                return;
            }

            string putContactRequestBody = string.Format("<Contacts><Contact><Name>{0}</Name></Contact></Contacts>", contactName);
            string putContactResponse;

            IConsumerRequest putContactRequest = consumerSession
                                                 .Request()
                                                 .ForMethod("PUT")
                                                 .ForUri(new Uri("https://api.xero.com/api.xro/2.0/Contacts"))
                                                 .WithFormParameters(new { xml = putContactRequestBody })
                                                 .SignWithToken(accessToken);

            try
            {
                putContactResponse = putContactRequest.ToString();
            }
            catch (OAuthException ex)
            {
                Console.WriteLine("An OAuthException was caught:");
                Console.WriteLine(ex.Report);
                return;
            }
            catch (WebException ex)
            {
                putContactResponse = ex.Response.GetResponseStream().ReadToEnd();

                Console.WriteLine("A WebException was caught:");
                Console.WriteLine(putContactResponse);
                return;
            }

            if (putContactResponse != string.Empty)
            {
                var    responseElement = XElement.Parse(putContactResponse);
                string statusCode      = responseElement.XPathSelectElement("/Status").Value;

                if (statusCode == "OK")
                {
                    string contactId = responseElement.XPathSelectElement("/Contacts/Contact[1]/ContactID").Value;
                    Console.WriteLine(string.Format("The contact '{0}' was created with id: {1}", contactName, contactId));
                }
            }


            // 7. Try to update the contact that's just been created, but this time use a POST method
            string postContactRequestBody = string.Format("<Contacts><Contact><Name>{0}</Name><EmailAddress>{1}@nowhere.com</EmailAddress></Contact></Contacts>", contactName, contactName.ToLower().Replace(" ", "."));
            string postContactResponse;

            IConsumerRequest postContactRequest = consumerSession
                                                  .Request()
                                                  .ForMethod("POST")
                                                  .ForUri(new Uri("https://api.xero.com/api.xro/2.0/Contacts"))
                                                  .WithFormParameters(new { xml = postContactRequestBody })
                                                  .SignWithToken(accessToken);

            try
            {
                postContactResponse = postContactRequest.ToString();
            }
            catch (OAuthException ex)
            {
                Console.WriteLine("An OAuthException was caught:");
                Console.WriteLine(ex.Report);
                return;
            }
            catch (WebException ex)
            {
                putContactResponse = ex.Response.GetResponseStream().ReadToEnd();

                Console.WriteLine("A WebException was caught:");
                Console.WriteLine(putContactResponse);
                return;
            }

            if (postContactResponse != string.Empty)
            {
                var    responseElement = XElement.Parse(postContactResponse);
                string statusCode      = responseElement.XPathSelectElement("/Status").Value;

                if (statusCode == "OK")
                {
                    string emailAddress = responseElement.XPathSelectElement("/Contacts/Contact[1]/EmailAddress").Value;
                    Console.WriteLine(string.Format("The contact '{0}' was updated with email address: {1}", contactName, emailAddress));
                }
            }
        }
Example #10
0
        public static void Run()
        {
            IToken        accessToken     = ConsumerSessionFactory.CreatePrivateAccessToken();
            IOAuthSession consumerSession = ConsumerSessionFactory.CreatePrivateConsumerSession();


            // 5. Make a call to api.xero.com to check that we can use the access token.
            IConsumerRequest getOrganisationRequest = consumerSession
                                                      .Request()
                                                      .ForMethod("GET")
                                                      .ForUri(new Uri("https://api.xero.com/api.xro/2.0/Organisation"))
                                                      .SignWithToken(accessToken);

            string getOrganisationResponse = getOrganisationRequest.ToString();

            if (getOrganisationResponse != string.Empty)
            {
                var    organisationXml  = XElement.Parse(getOrganisationResponse);
                string organisationName = organisationXml.XPathSelectElement("//Organisation/Name").Value;
                Console.WriteLine(string.Format("You have been authorised against organisation: {0}", organisationName));
            }

            // 5.5 Call GET Invoices using a filter
            IConsumerRequest getInvoicesRequest = consumerSession
                                                  .Request()
                                                  .ForMethod("GET")
                                                  .ForUri(new Uri("https://api.xero.com/api.xro/2.0/Invoices"))
                                                  .WithHeaders(new Dictionary <string, string> {
                { "If-Modified-Since", new DateTime(2000, 3, 1).ToString("yyyy-MM-dd") }
            })
                                                  .SignWithToken(accessToken);

            string getInvoicesResponse = getInvoicesRequest.ToString();

            if (getInvoicesResponse != string.Empty)
            {
                var invoicesXml = XElement.Parse(getInvoicesResponse);

                foreach (var invoiceNode in invoicesXml.XPathSelectElements("//Invoice"))
                {
                    var invoiceNumberNode = invoiceNode.XPathSelectElement("InvoiceNumber");
                    var invoiceDateNode   = invoiceNode.XPathSelectElement("Date");

                    if (invoiceNumberNode != null && invoiceDateNode != null)
                    {
                        Console.WriteLine(string.Format("Invoice Number {0} was created on {1}", invoiceNumberNode.Value, invoiceDateNode.Value));
                    }
                }
            }


            // 6. Make a PUT call to the API - add a dummy contact
            Console.WriteLine("Please enter the name of a new contact to add to Xero");
            string contactName = Console.ReadLine();

            if (string.IsNullOrEmpty(contactName))
            {
                return;
            }

            string putContactRequestBody = string.Format("<Contacts><Contact><Name>{0}</Name></Contact></Contacts>", contactName);
            string putContactResponse;

            IConsumerRequest putContactRequest = consumerSession
                                                 .Request()
                                                 .ForMethod("PUT")
                                                 .ForUri(new Uri("https://api.xero.com/api.xro/2.0/Contacts"))
                                                 .WithFormParameters(new { xml = putContactRequestBody })
                                                 .SignWithToken(accessToken);

            try
            {
                putContactResponse = putContactRequest.ToString();
            }
            catch (OAuthException ex)
            {
                Console.WriteLine("An OAuthException was caught:");
                Console.WriteLine(ex.Report);
                return;
            }
            catch (WebException ex)
            {
                putContactResponse = ex.Response.GetResponseStream().ReadToEnd();

                Console.WriteLine("A WebException was caught:");
                Console.WriteLine(putContactResponse);
                return;
            }

            if (putContactResponse != string.Empty)
            {
                var    responseElement = XElement.Parse(putContactResponse);
                string statusCode      = responseElement.XPathSelectElement("/Status").Value;

                if (statusCode == "OK")
                {
                    string contactId = responseElement.XPathSelectElement("/Contacts/Contact[1]/ContactID").Value;
                    Console.WriteLine(string.Format("The contact '{0}' was created with id: {1}", contactName, contactId));
                }
            }


            // 7. Try to update the contact that's just been created, but this time use a POST method
            string postContactRequestBody = string.Format("<Contacts><Contact><Name>{0}</Name><EmailAddress>{1}@nowhere.com</EmailAddress></Contact></Contacts>", contactName, contactName.ToLower().Replace(" ", "."));
            string postContactResponse;

            IConsumerRequest postContactRequest = consumerSession
                                                  .Request()
                                                  .ForMethod("POST")
                                                  .ForUri(new Uri("https://api.xero.com/api.xro/2.0/Contacts"))
                                                  .WithFormParameters(new { xml = postContactRequestBody })
                                                  .SignWithToken(accessToken);

            try
            {
                postContactResponse = postContactRequest.ToString();
            }
            catch (OAuthException ex)
            {
                Console.WriteLine("An OAuthException was caught:");
                Console.WriteLine(ex.Report);
                return;
            }
            catch (WebException ex)
            {
                putContactResponse = ex.Response.GetResponseStream().ReadToEnd();

                Console.WriteLine("A WebException was caught:");
                Console.WriteLine(putContactResponse);
                return;
            }

            if (postContactResponse != string.Empty)
            {
                var    responseElement = XElement.Parse(postContactResponse);
                string statusCode      = responseElement.XPathSelectElement("/Status").Value;

                if (statusCode == "OK")
                {
                    string emailAddress = responseElement.XPathSelectElement("/Contacts/Contact[1]/EmailAddress").Value;
                    Console.WriteLine(string.Format("The contact '{0}' was updated with email address: {1}", contactName, emailAddress));
                }
            }
        }