views:

280

answers:

1

I'm trying to consume twitter's REST api mentioned at this link using WCF REST starter kit mentioned at this link.

I'm using the same objects in DataContract as mentioned in the article - statusList and status.

[assembly: ContractNamespace("", ClrNamespace = "TwitterShell")]
[CollectionDataContract(Name = "statuses", ItemName = "status")]
public class statusList : List<status> { }
public class user
{
    public string id;
    public string name;
    public string screen_name;
}
public class status
{
    public string id;
    public string text;
    public user user;
}

I'm reading the XML contents using ReadAsDataContract() method.

HttpClient http = new HttpClient("http://twitter.com/statuses/");
http.TransportSettings.Credentials =
    new NetworkCredential("{username}", "{password}");
HttpResponseMessage resp = http.Get("friends_timeline.xml");
resp.EnsureStatusIsSuccessful();
statusList sList = resp.Content.ReadAsDataContract<statusList>();

And I get the following exception. I have not defined the following namespace at all.

Error in line 1 position 24. Expecting element 'statuses' from namespace 'http://schemas.datacontract.org/2004/07/sitename'.. Encountered 'Element' with name 'statuses', namespace ''.

Please help. Thanks.

+2  A: 

Just don't do it. You are in for a world of pain if you try using Datacontracts and operation contracts to access non-wcf services.

Ok, so I guess that was a bit unfair leaving you high and dry without an alternative, so try this:

var response = client.Get("http://twitter.com/statuses/friends_timeline.xml");

var statuses = response.Content.ReadAsXElement();

var statusQuery = from st in statuses.Elements("status")
                  select new status {
                                id = st.Element("id").Value,
                                text = st.Element("text").Value,
                                user = (from us in st.Elements("user")
                                        select new user {
                                             id = us.Element("id").Value,
                                             name = us.Element("name").Value,
                                             screen_name = us.Element("screen_name").Value
                                                         }).FirstOrDefault()
                                      };
var statuses = statusQuery.ToList();

Using Linq to XML to create objects from the XML document allows you to avoid the magic of serializers and completely control the names and datatypes of your client side objects. It would be really easy to wrap this as a new HttpContent extension method so that you could simply do:

var statuses = response.Content.ReadAsTwitterStatuses();
Darrel Miller
thanks Darrel, this works. :-)
hIpPy