Share via


Deleting a Container 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 a Container Using REST, this following C# sample first sends a POST request to create a sample container and then sends a DELETE request to delete the sample container.

Note

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

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 DeleteContainerUsingREST
{
    class Program
    {
        // Provide your data here
        private static string userName;
        private static string password;
        private const string authorityId = "<YourExistingAuthorityId>"; 
        private const string sampleContainerId = "<IdForTheSampleContainer>";

        private const string HttpDeleteMethod = "DELETE";
        private const string HttpPostMethod = "POST";
        private const string ssdsContentType = "application/x-ssds+xml";

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

            string AuthorityUri = String.Format("https://{0}.data.database.windows.net/v1/",
                                                 authorityId);
            try
            {
                // Create a sample container that we will delete
                string newContainerUri = CreateContainer(AuthorityUri);
                if (newContainerUri == null)
                {
                    Console.WriteLine("Container URI is null... problem creating sample container");
                    return;
                }
                // Delete sample container created
                WebRequest request = HttpWebRequest.Create(newContainerUri);
                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("Container deletion failed");
                    }
                }
            }
            catch (WebException ex)
            {
                using (HttpWebResponse response = ex.Response as HttpWebResponse)
                {
                    Console.WriteLine("Unexpected status code returned: " + response.StatusCode);
                }
            }
        }

        private static string CreateContainer(string authorityUri)
        {
            if (String.IsNullOrEmpty(authorityUri))
            {
                throw new ArgumentOutOfRangeException("AuthorityUri");
            }

             string containerUri = null;
            try
            {
                // We need to create XML Payload as follows by creating a template for a 
                // new container request.
                const string ContainerTemplate = 
                    @"<s:Container xmlns:s='https://schemas.microsoft.com/sitka/2008/03/'>
                        <s:Id>{0}</s:Id>
                      </s:Container>";

                // Data going over to the server
                string requestPayload = string.Format(ContainerTemplate, sampleContainerId);

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(authorityUri);
                // Security requirement - need to pass userid, password
                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 (1st container).
                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("Container created. System assigned version: {0}", response.Headers["ETag"]);
                        // Container created successfully. Get the container URI.
                        // Since this implementation sets the response.Headers[HttpResponseHeader.Location] to 
                        // null, we construct the container uri.
                        containerUri = string.Format(authorityUri + sampleContainerId);
                    }
                    else
                    {
                        Console.WriteLine("Failed to create container");
                    }
                }
            }
            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 containerUri;
        }

        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 container was deleted, enter the container URI in the browser, and you will get appropriate "not found" error.

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

You may also specify an empty query with the authority in the scope. This query returns all the containers in the specified authority. For more information on queries, see Querying SQL Data Services.

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

See Also

Concepts

Deleting a Container Using REST