locked
Consume REST services

    Question

  • Hello , 

    I am trying to feth some data from Twitter . 

    Usually I use Hammock but as it is not available for Windows 8 apps  (I am not able to install this package on my app)  

    This is how I usually use Hammock  to fetch Twitter Data  (In this example I post a status) :

    var credentials = new OAuthCredentials
                {
                    Type = OAuthType.ProtectedResource,
                    SignatureMethod = OAuthSignatureMethod.HmacSha1,
                    ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                    ConsumerKey = AppSettings.consumerKey,
                    ConsumerSecret = AppSettings.consumerKeySecret,
                    Token = this.accessToken,
                    TokenSecret = this.accessTokenSecret,
                    Version = "1.0"
                };
    
    
    
     var restClient = new RestClient
                    {
                        Authority = "https://api.twitter.com",
                        HasElevatedPermissions = true,
                        Credentials = credentials
    
                    };
    
    
                    var restRequest = new RestRequest
                    {
                        Credentials = credentials,
                        Path = "1.1/statuses/update_with_media.json",
                        Method = WebMethod.Post
    
    
                    };
    
    
    
                    restRequest.AddField("status", "Test");
    
    
    
    
    
    
    
    
    
    
    
                    restClient.BeginRequest(restRequest,RequestCallBack);
    
    
    
    
    
    
            private void AutreRequestCallBack(RestRequest request, RestResponse response, object obj)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    if (reponse.StatusCode == HttpStatusCode.OK)
                    {
    
    
                       MessaBox.Show("Success");
    
    
                    }
    
    
    
    
                    else
                    {
                        MessageBox.Show("Failure");
    
    
                    }
                }
                    );
    
    
    
            }
    
    
    
    
    
    
    
    

    How can I use a similar method to  get (or post)   Twitter Data in a Windows 8 Application ? 

    Please tell me if I can use Hammock but I was mislead

    Thank you !

    Wednesday, March 12, 2014 12:11 AM

All replies

  • Hi,

    Hammock cannot used in windows store app. You can download the json string from the Twitter server and then parse the json string. Please refer to the link below:

    http://www.codeproject.com/Articles/546430/Parse-JSON-to-Csharp-in-WinRT-Silverlight-WPF-Wind

    In the link, you can use the method below to load Twitter data:

    public static async Task<ObservableCollection<TwitterItem>> Load(string uri)
    {
        ObservableCollection<TwitterItem> result = new ObservableCollection<TwitterItem>();
        try
        {
            var client = WebRequest.CreateHttp(uri);
            var response = await client.GetResponseAsync();
    
            #region ** parse twitter data
            using (System.IO.Stream stream = response.GetResponseStream())
            {
                // parse Json data
                DataContractJsonSerializer rootSer = new DataContractJsonSerializer(typeof(RootObject));
    
                RootObject root = (RootObject)rootSer.ReadObject(stream);
                foreach (Result res in root.results)
                {
                    TwitterItem ti = new TwitterItem();
                    ti.Title = res.text;
                    DateTimeOffset dateOffset;
                    if (DateTimeOffset.TryParse(res.created_at, out dateOffset))
                    {
                        ti.PublishDate = dateOffset.UtcDateTime;
                    }
                    ti.Handle = res.from_user;
                    if (res.entities.urls != null && res.entities.urls.Count > 0)
                    {
                        ti.Link = res.entities.urls[0].url;
                    }
                    result.Insert(GetFirstIndexOfOlderTwitterItem(ti.PublishDate, result), ti);
                }
            }
            #endregion
        }
        catch
        {
        }
        return result;
    }
    Best Wishes!


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey. Thanks<br/> MSDN Community Support<br/> <br/> Please remember to &quot;Mark as Answer&quot; the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Wednesday, March 12, 2014 5:57 AM
  • I understood how to parse Json  but i did'n't really understand how to make a REST request . 

    How can I do it using your method with this Request :

    (Let's say for example that I have to add the paramter : "count"  = "5")

    https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline

    Wednesday, March 12, 2014 8:41 AM
  • A cleaner way to do this is to create the C# data contracts for the REST services. I'm not sure if these are documented or if you can find these already made. If not they are fairly easy to create. Take look at the Bing Maps REST service data contracts as an example: http://msdn.microsoft.com/en-us/library/jj870778.aspx

    Once you have data contracts you can then use the DataContractJsonSerializer. HEre is a method I use all the time for doing this:

    private async Task<T> GetResponse<T>(Uri uri)
    {
        System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
        var response = await client.GetAsync(uri);
    
        using (var stream = await response.Content.ReadAsStreamAsync())
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            return (T)ser.ReadObject(stream);
        }
    }

    Simply set T as the type you want to serialize to (i.e. the base Twitter feed class).

    Here is a twitter related example: http://stackoverflow.com/questions/9592623/c-sharp-serialize-json-from-twitter-without-data-member

    Alternatively take a look through CodePlex. There are a lot of different Twitter related code samples. Here is one that uses Linq to read the twitter data and works in Windows Store apps: https://linqtotwitter.codeplex.com/


    http://rbrundritt.wordpress.com

    Wednesday, March 12, 2014 3:12 PM
  • Thank you for your answer but as I said earlier my question is not about JSON  I know how to parse Json . 

    I don't understand how can I create the    "the c# data contracts for the REST Service"   can you provide me an example please ?

    Wednesday, March 12, 2014 5:14 PM
  • Be sure to look at the Web Auth Broker sample; you can use the Windows.Web.Http HttpClient OAUTH filter in your Http pipeline in order to make the oauth handling transparent to your business logic.

    http://code.msdn.microsoft.com/windowsapps/Web-Authentication-d0485122


    Network Developer Experience Team (Microsoft)

    Wednesday, March 12, 2014 5:18 PM
  •  private async Task<T> GetResponse<T>(Uri uri)
            {
                System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
                var response = await client.GetAsync("https://api.twitter.com/1.1/statuses/user_timeline.json");
    
                using (var stream = await response.Content.ReadAsStreamAsync())
                {
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
                    return (T)ser.ReadObject(stream);
                }
            }
        }

    Is this how I sould proceed ?

    I used the sample borcker and to Authentificate  but then I don't see how to roceed.  Can show me an example please?

    Wednesday, March 12, 2014 5:52 PM
  • Read through the sample! 

    1. Use Windows.Web.Http HttpClient, not the System.Net one (they are different, and the Oauth filter is designed for Windows.Web)

    2. When you make the HttpClient, you'll need to pass in a filter pipeline.  The simplest possible pipeline is just a single HttpBaseProtocolFilter().  But you want something else there, too: the actual OAuth filter.  You will first make your HttpBaseProtocolFilter.  Then make an OAuth filter.  When you make the OAuth filter, it needs -- tada!  -- a filter pipeline; you can just use the HttpBaseProtocolFilter that you just made.  Now you have a filter pipeline of length two.  Pass THAT into the HttpClient constructor.

    3. You also need to initialize the OAuth filter with basic information like the url of the token service, etc.

    Wednesday, April 23, 2014 1:28 AM