Share via


Deleting 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 Deleting an Entity Using REST, the following C# code deletes a specified entity from a container.

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 entity id you wish to delete.

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

using System;
using System.Text;
using System.Net;
using System.IO;

namespace DeleteEntityUsingREST
{
    class Program
    {
        // Provide your data here
        private static string userName;
        private static string password;
        private const string authorityId = "<YourExistingAuthorityId>";
        private const string containerId = "<YourExistingContainerId>";
        private const string entityId = "<YourExistingEntityIDToDelete>";


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

            const string HttpDeleteMethod = "DELETE";

            // URI of the entity (book entity in this example) to delete.
            string BookUri = string.Format("https://{0}.data.database.windows.net/v1/{1}/{2}", 
                                                       authorityId, containerId, entityId);
            try
            {
                // Create the request to send.
                WebRequest request = HttpWebRequest.Create(BookUri);
                request.Credentials = new NetworkCredential(userName, password);
                request.Method = HttpDeleteMethod;

                // Get the response and read it in to a string.
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        Console.WriteLine("Failed to delete the entity resource.");
                    }
                }
            }
            catch (WebException ex)
            {
                string errorMsg = ex.Message;
                Console.WriteLine("Deletion failed: {0}", errorMsg);

                if (ex.Response != null)
                {
                    using (HttpWebResponse response = ex.Response as HttpWebResponse)
                    {
                            Console.WriteLine("Unexpected status code returned: {0}", response.StatusCode);
                    }
                }
            }
        }

        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 that the entity was deleted, specify the entity URI in the Web browser and you should get an "entity not found" error.

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

You can specify an empty query with the specific container in the scope to retrieve all the entities in that container. For details about queries, see Querying SQL Data Services.

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

See Also

Concepts

Deleting an Entity Using REST
Examples of Using SOAP and REST Interfaces with the SQL Data Services