Return List<myobject> using REST from SharePoint 2010

 

I’m having a good time playing with WCF tonight. This is a quick post on the setup for returning lists of objects defined in a WCF REST service from within SharePoint 2010 – a common scenario. For related information see the following posts

https://scottcurrier.wordpress.com/2010/07/28/simple-wcf-service-within-sp2010-note-to-self/

https://scottcurrier.wordpress.com/2011/06/26/simple-wcf-based-rest-service-for-sharepoint-2010-note-to-self/

Its actually very simple but please see my previous posts for more detail. Assuming you have a separate file for the interface you can return the sample List<Project> by defining a class that looks something like the following

[DataContract]
   public class Project {

       [DataMember]
       public string Name;

       [DataMember]
       public DateTime StartDate;

       [DataMember]
       public DateTime EndDate;
   }

Obviously, this is a simple demonstration – next I implement the actual method as follows

public List<Project> EnumProjects()
        {

            List<Project> projects = new List<Project>();

            // add a new project sample data
            projects.Add(
                new Project {
                    Name = "Project 2",
                    StartDate = DateTime.Parse("3/3/2012"),
                    EndDate = DateTime.Parse("12/15/2012")
                });

            return projects;
        }

The service itself looks as follows (in fact the WebGet attribute can be further simplified)

//http://dev/_layouts/MyServices/MyService.svc/EnumProjects
[WebGet(UriTemplate = "/EnumProjects", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml)]
[OperationContract]
List<Project> EnumProjects(string webUrl);

For XML the result looks as follows,

– <ArrayOfProject xmlns=”http://schemas.datacontract.org/2004/07/MyServices” xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
– <Project>
  <EndDate>2012-12-15T00:00:00</EndDate>
  <Name>Project 2</Name>
  <StartDate>2012-03-03T00:00:00</StartDate>
  </Project>
  </ArrayOfProject>

For Json the result looks as follows,

[{"EndDate":"\/Date(1355547600000-0500)\/","Name":"Project 2","StartDate":"\/Date(1330750800000-0500)\/"}]

 

Crazy Simple!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s