Search code examples
c#restsharepointodatams-project-server-2013

How can I read plain text from MS Project Rest api using C#?


I want to query the number of projects in Project 2013 using the Rest API.

I am able to read the Atom XML files it sends back with the help of Atom10FeedFormatter class, but I do not know how to process the response if it is in plain text format.

This request:

http://{my_pwa_site}/_api/ProjectData/Projects/$count

Gives back the response "15" in html body, showing the number of projects I have in Project 2013.

Also, accessing this site requires network credentials. I usually do it using this code:

Atom10FeedFormatter formatter = new Atom10FeedFormatter();

        XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";

        XmlUrlResolver res = new XmlUrlResolver();
        res.Credentials = new NetworkCredential("myusername", "mypassword");

        XmlReaderSettings set = new XmlReaderSettings();
        set.XmlResolver = res;



        using (XmlReader reader = XmlReader.Create("http://{mypwasite}/_api/ProjectData/Projects", set))
        {
            formatter.ReadFrom(reader);
        }

But I can not use XML reader for that purpose.

What should I use to read this plain text content?


Solution

  • No special library needed and this is nothing to do with OData feeds. To process this kind of data, it is enough to use httpclient instead of xml reader like a regular rest api case. Here is an example of how to do so:

            var credentials = new NetworkCredential("myusername", "mypass");
            var handler = new HttpClientHandler { Credentials = credentials };
    
            string result="";
    
            string path = "http://{mypwasite}/_api/ProjectData/Projects";
    
    
            using (var _client = new HttpClient(handler))
            {
                HttpResponseMessage response = await _client.GetAsync(path);
    
                if (response.IsSuccessStatusCode)
                {
                    result = await response.Content.ReadAsStringAsync(); ;   
                }
            }