Amazon DynamoDB
Developer Guide (API Version 2012-08-10)
« PreviousNext »
View the PDF for this guide.Go to the AWS Discussion Forum for this product.Go to the Kindle Store to download this guide in Kindle format.Did this page help you?  Yes | No |  Tell us about it...

Example: Handling Binary Type Attributes Using the AWS SDK for .NET Low-Level API

The following C# code example illustrates the handling of binary type attributes. The example adds an item to the Reply table. The item includes a binary type attribute (ExtendedMessage) that stores compressed data. The example then retrieves the item and prints all the attribute values. For illustration, the example uses the GZipStream class to compress a sample stream and assigns it to the ExtendedMessage attribute, and decompresses it when printing the attribute value.

If you followed the Getting Started, you already have the Reply table created. You can also create these sample tables programmatically. For more information, see Creating Example Tables and Uploading Data Using the AWS SDK for .NET Low-Level API.

For step-by-step instructions to test the following sample, see Using the AWS SDK for .NET.

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Amazon.Runtime;

namespace Amazon.DynamoDBv2.Documentation
{
  class Program
  {
    private static string tableName = "Reply";
    private static AmazonDynamoDBClient client;

    static void Main(string[] args)
    {
      // Reply table primary key.
      string replyIdHashAttribute = "Amazon DynamoDB#DynamoDB Thread 1";
      string replyDateTimeRangeAttribute = Convert.ToString(DateTime.UtcNow);

      var config = new AmazonDynamoDBConfig();
      config.ServiceURL = System.Configuration.ConfigurationManager.AppSettings["ServiceURL"];
      client = new AmazonDynamoDBClient(config);

      try
      {
        CreateItem(replyIdHashAttribute, replyDateTimeRangeAttribute);
        RetrieveItem(replyIdHashAttribute, replyDateTimeRangeAttribute);
        // Delete item.
        DeleteItem(replyIdHashAttribute, replyDateTimeRangeAttribute);
        Console.WriteLine("To continue, press Enter");
        Console.ReadLine();
      }
      catch (AmazonDynamoDBException e) { Console.WriteLine(e.Message); }
      catch (AmazonServiceException e) { Console.WriteLine(e.Message); }
      catch (Exception e) { Console.WriteLine(e.Message); }
    }

    private static void CreateItem(string hashAttribute, string rangeAttribute)
    {
      MemoryStream compressedMessage = ToGzipMemoryStream("Some long extended message to compress.");
      var request = new PutItemRequest
      {
        TableName = tableName,
        Item = new Dictionary<string, AttributeValue>()
        {
          { "Id", new AttributeValue { S = hashAttribute }},
          { "ReplyDateTime", new AttributeValue { S = rangeAttribute }},
          { "Subject", new AttributeValue { S = "Binary type " }},
          { "Message", new AttributeValue { S = "Some message about the binary type" }},
          { "ExtendedMessage", new AttributeValue { B = compressedMessage }}
        }
      };
      client.PutItem(request);
    }

    private static void RetrieveItem(string hashAttribute, string rangeAttribute)
    {
      var request = new GetItemRequest
      {
        TableName = tableName,
        Key = new Dictionary<string, AttributeValue>()
        {
          { "Id", new AttributeValue { S = hashAttribute } },
          { "ReplyDateTime", new AttributeValue { S = rangeAttribute } }
        },
        ConsistentRead = true
      };
      var response = client.GetItem(request);

      // Check the response.
      var result = response.GetItemResult;
      var attributeList = result.Item; // attribute list in the response.
      Console.WriteLine("\nPrinting item after retrieving it ............");

      PrintItem(attributeList);
    }

    private static void DeleteItem(string hashAttribute, string rangeAttribute)
    {
      var request = new DeleteItemRequest
      {
        TableName = tableName,
        Key = new Dictionary<string, AttributeValue>()
        {
          { "Id", new AttributeValue { S = hashAttribute } },
          { "ReplyDateTime", new AttributeValue { S = rangeAttribute } }
        }
      };
      var response = client.DeleteItem(request);

      // Check the response.
      var result = response.DeleteItemResult;
    }

    private static void PrintItem(Dictionary<string, AttributeValue> attributeList)
    {
      foreach (KeyValuePair<string, AttributeValue> kvp in attributeList)
      {
        string attributeName = kvp.Key;
        AttributeValue value = kvp.Value;

        Console.WriteLine(
            attributeName + " " +
            (value.S == null ? "" : "S=[" + value.S + "]") +
            (value.N == null ? "" : "N=[" + value.N + "]") +
            (value.SS == null ? "" : "SS=[" + string.Join(",", value.SS.ToArray()) + "]") +
            (value.NS == null ? "" : "NS=[" + string.Join(",", value.NS.ToArray()) + "]") +
            (value.B == null ? "" : "B=[" + FromGzipMemoryStream(value.B) + "]")
        );
      }
      Console.WriteLine("************************************************");
    }

    private static MemoryStream ToGzipMemoryStream(string value)
    {
      MemoryStream output = new MemoryStream();
      using (GZipStream zipStream = new GZipStream(output, CompressionMode.Compress, true))
      using (StreamWriter writer = new StreamWriter(zipStream))
      {
        writer.Write(value);
      }
      return output;
    }

    private static string FromGzipMemoryStream(MemoryStream stream)
    {
      using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress))
      using (StreamReader reader = new StreamReader(zipStream))
      {
        return reader.ReadToEnd();
      }
    }

  }
}