Share via


Creating an Entity Using REST (C#)

[This document supports a preliminary release of a software product that may be changed substantially prior to final commercial release. This document is provided for informational purposes only.]

As described in Creating an Entity Using REST, the following C# sample creates a non-blob entity in the specified container. The application performs the following steps:

  • Create an XML payload describing the new entity.
  • Initialize a WebRequest instance with the container URI as the parameter. This is the container in which the new entity is created.
  • Set the Content-Type request header to application/x-ssds+xml indicating XML payload. For blob entities the Content-Type shouldl be set to the appropriate MIME type.
  • Send the request.
  • Process the response by printing the system assigned entity version returned in the ETag response header.

Note

Credentials are required to access the service. To make a working sample, update following code and provide your existing authority id, container id and a unique id for the new entity being created.

If you are using the Microsoft Visual Studio integrated development environment, create a console application, and then add the following code.

using System;
using System.Text;
using System.Net;
using System.IO;
using System.Xml.Linq;

namespace CreateEntityUsingREST
{
    class Program
    {
        private static string userName;
        private static string password;
        private const string authorityId = "<YourExistingAuthorityId>";
        private const string containerId = "<YourExistingContainerID>";
        private const string sampleEntityId = "<NewEntityId>";

        static void Main(string[] args)
        {
            Console.Write("Username: ");
            userName = Console.ReadLine();
            Console.Write("Password: ");
            password = ReadPassword();

            // Identify specific container resource (to add a new entity)
            string ContainerUri = String.Format("https://{0}.data.database.windows.net/v1/{1}", authorityId, containerId);

            // Data going over to the server
            string requestPayload = CreateBook(sampleEntityId, "My first used book using REST",
                                               "Some summary", "1-57880-057-9", 
                                               "Author A", "Publisher B");

            CreateEntity(ContainerUri, requestPayload);

        }

        public static string CreateBook(string id, string title, string summary,
                                        string isbn, string author, string publisher)
        {
            // Need to create request payload, as shown, describing the entity we want to create.
            const string EntityTemplate =
                @"<Book xmlns:s='https://schemas.microsoft.com/sitka/2008/03/'
                         xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
                         xmlns:x='http://www.w3.org/2001/XMLSchema' >
                     <s:Id>{0}</s:Id> 
                     <title xsi:type='x:string'>{1}</title>
                     <summary xsi:type='x:string'>{2}</summary> 
                     <isbn xsi:type='x:string'>{3}</isbn> 
                     <author xsi:type='x:string'>{4}</author> 
                     <publisher xsi:type='x:string'>{5}</publisher> 
                 </Book>";
            return String.Format(EntityTemplate, id, title, summary, isbn, author, publisher);
        }

        public static string CreateEntity(string containerUri, string requestPayload)
        {
            const string HttpPostMethod = "POST";
            const string ssdsContentType = "application/x-ssds+xml";
            string entityUri = null;

            if (String.IsNullOrEmpty(containerUri))
            {
                throw new ArgumentOutOfRangeException(containerUri);
            }

            if (String.IsNullOrEmpty(requestPayload))
            {
                throw new ArgumentOutOfRangeException(requestPayload);
            }

            try
            {
                // Create the request to send.
                WebRequest request = HttpWebRequest.Create(containerUri);
                request.Credentials = new NetworkCredential(userName, password);
                // POST=create; PUT=update; DELETE=delete; GET=retrieve
                request.Method = HttpPostMethod;
                UTF8Encoding encoding = new UTF8Encoding();
                request.ContentLength = encoding.GetByteCount(requestPayload);
                request.ContentType = ssdsContentType;

                // Write the request data over the wire.
                using (Stream reqStm = request.GetRequestStream())
                {
                    reqStm.Write(encoding.GetBytes(requestPayload), 0,
                                 encoding.GetByteCount(requestPayload));
                }

                // Get the response and read it in to a string.
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {

                    if (response.StatusCode == HttpStatusCode.Created)
                    {
                        Console.WriteLine("Entity created. System assigned version: {0}", response.Headers["ETag"]);
                        // Since current implementation returns response.Headers[HttpResponseHeader.Location]
                        // value null, construct entity URI
                        entityUri = string.Format(containerUri + "/" + sampleEntityId);
                    }
                    else
                    {
                        Console.WriteLine("Unexpected status code returned: {0}", response.StatusCode);
                    }
                }
            }
            catch (WebException ex)
            {
                using (HttpWebResponse response = ex.Response as HttpWebResponse)
                {
                    if (response != null)
                    {
                        string errorMsg = ReadResponse(response);
                        Console.WriteLine(string.Format("Error:{0}", errorMsg));
                        Console.WriteLine("Unexpected status code returned: {0} ", response.StatusCode);
                    }
                }
            }

            return entityUri;
        }

        public static string ReadResponse(HttpWebResponse response)
        {
            // Begin by validating our inbound parameters.
            //
            if (response == null)
            {
                throw new ArgumentNullException("response", "Value cannot be null");
            }

            // Then, open up a reader to the response and read the contents to a string
            // and return that to the caller.
            //
            string responseBody = "";
            using (Stream rspStm = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(rspStm))
                {
                    responseBody = reader.ReadToEnd();
                }
            }

            return responseBody;
        }

               private static string ReadPassword()
        {
            StringBuilder retval = new StringBuilder();
            ConsoleKeyInfo keyInfo;
            while ((keyInfo = Console.ReadKey(true)).Key != ConsoleKey.Enter)
            {
                Console.Write("*");
                retval.Append(keyInfo.KeyChar);
            }
            Console.WriteLine();

            return retval.ToString();
        }

    }
}

To verify the result, enter the entity URI in the browser to retrieve the specific entity:

https://<authority-id>.data.database.windows.net/v1/<container-id>/<entity-id>

Note

When querying for non-blob entities your browser need to be aware of the application/x-ssds+xml SDS content type. For Internet Explorer this can be done by adding a new key in the registry. For more information, see Guidelines and Limitations.

The result for the sample above might look like this:

<Book xmlns:s="https://schemas.microsoft.com/sitka/2008/03/"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xmlns:x="http://www.w3.org/2001/XMLSchema">
    <s:Id>SampleBookUsingREST</s:Id>
    <s:Version>version-number</s:Version>
    <title xsi:type="x:string">My first used book using REST</title>
    <summary xsi:type="x:string">Some summary</summary>
    <isbn xsi:type="x:string">1-57880-057-9</isbn>
    <author xsi:type="x:string">Author A</author>
    <publisher xsi:type="x:string">Publisher B</publisher>
</Book>

You can specify empty query with specific container in scope to find all the entities in that container:

https://<authority-id>.data.database.windows.net/v1/<container-id>?q='' 

For details about queries, see Querying SQL Data Services.

See Also

Concepts

Creating an Entity Using REST
Guidelines and Limitations