AWS SimpleDB开发笔记

6 篇文章 0 订阅
AWS SimpleDB is one of the could productions from Amazon AWS. It offers a very simple way of using database. Basically, SimpleDB is more likely a huge XML file that allows you add upto 10 billion nodes. Here I will introduce how to create a SimpleDB program with AWS .NET SDK.

After installing the SDK and create a project with template, you will get those head files:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Configuration;
using System.Text;
using System.IO;

// Amazon SimpleDB
using Amazon;
using Amazon.SimpleDB;
using Amazon.SimpleDB.Model;
using System.Collections.Specialized;

using System.Xml.Serialization;
using System.Web.Configuration;

when creating the project, VS will ask for the Access key and Secret key, you can get those in your account info page.

// announce AmazonSimpleDB
        protected AmazonSimpleDB sdb;
        
        /*
        * Setup AWS Access Key and AWS Secret Key
        */
        String AWSAccessKey = "";
        String AWSSecretKey = "";

        /*
         * =====================
         * initialize everything
         * =====================
         */

so you have to initialize your keys for the program at the very first.

            /* 
             * in this example, simpleDB will be tested only.               
             */

            // initialize the AWS Access Key and Secret Key.
            AWSAccessKey = WebConfigurationManager.AppSettings["AWSAccessKey"];
            AWSSecretKey = WebConfigurationManager.AppSettings["AWSSecretKey"];

            // Authentication
            sdb = AWSClientFactory.CreateAmazonSimpleDBClient(AWSAccessKey, AWSSecretKey);

The structure of SimpleDB is:

Domain - Item - Attribute

So the basic idea is to create domain first, then think about the item with attributes. Please notice that, items without attributes are not accepted by the SDK and AWS SimpleDB.

        /*
         * ================================
         * Create and List Existing Domains
         * ================================
         */
        protected void createDomainButton_Click(object sender, EventArgs e)
        {

            try
            {
                if (TextBox1.Text.Trim() != "")
                {
                    // get the value from foreground
                    String cDomainName = TextBox1.Text.Trim();

                    // setup Create Domain Request
                    CreateDomainRequest createRequest = new CreateDomainRequest();
                    createRequest.WithDomainName(cDomainName);
                    // send request to Amazon
                    sdb.CreateDomain(createRequest);

                    // setup List Domain Request and Response
                    StringBuilder output = new StringBuilder();
                    ListDomainsRequest listRequest = new ListDomainsRequest();
                    ListDomainsResponse listResponse = sdb.ListDomains(listRequest);

                    // initialize dropdownlist
                    DropDownList1.Items.Clear();

                    // read response from Amazon
                    foreach (string domainName in listResponse.ListDomainsResult.DomainName)
                    {
                        DropDownList1.Items.Add(domainName);
                        output.AppendFormat("-{0}<br/>", domainName);
                    }

                    Label1.Text = output.ToString();
                }

            }
            catch (Exception ex)
            {
                Label1.Text = "Something happens:<br/>" + ex.Message;
            }
 
        }

        /*
         * =====================
         * List Existing Domains
         * =====================
         */
        protected void listDomainButton_Click(object sender, EventArgs e)
        {
            try
            {
                // setup List Domain Request and Response
                StringBuilder output = new StringBuilder();
                ListDomainsRequest listRequest = new ListDomainsRequest();
                ListDomainsResponse listResponse = sdb.ListDomains(listRequest);

                // initialize dropdownlist
                DropDownList1.Items.Clear();

                // read response from Amazon
                foreach (string domainName in listResponse.ListDomainsResult.DomainName)
                {
                    DropDownList1.Items.Add(domainName);
                    output.AppendFormat("-{0}<br/>", domainName);
                }

                Label1.Text = output.ToString();

            }
            catch (Exception ex)
            {
                Label1.Text = "Something happens:<br/>" + ex.Message;
            }
        }

        /*
         * =======================
         * Delete Existing Domains
         * =======================
         */
        protected void deleteDomainButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (TextBox1.Text.Trim() != "")
                {
                    // get the value from foreground
                    String cDomainName = TextBox1.Text.Trim();

                    // setup Delete Domain Request
                    DeleteDomainRequest deleteRequest = new DeleteDomainRequest();
                    deleteRequest.WithDomainName(cDomainName);
                    // send request to Amazon
                    sdb.DeleteDomain(deleteRequest);

                    // setup List Domain Request and Response
                    StringBuilder output = new StringBuilder();
                    ListDomainsRequest listRequest = new ListDomainsRequest();
                    ListDomainsResponse listResponse = sdb.ListDomains(listRequest);

                    // initialize dropdownlist
                    DropDownList1.Items.Clear();

                    // read response from Amazon
                    foreach (string domainName in listResponse.ListDomainsResult.DomainName)
                    {
                        DropDownList1.Items.Add(domainName);
                        output.AppendFormat("-{0}<br/>", domainName);
                    }

                    Label1.Text = output.ToString();
                }

            }
            catch (Exception ex)
            {
                Label1.Text = "Something happens:<br/>" + ex.Message;
            }
        }

        protected void addAtrributeButon_Click(object sender, EventArgs e)
        {
            try
            {

                // get the value from foreground
                String cDomainName = "program";

                PutAttributesRequest request = new PutAttributesRequest();
                request.WithDomainName(cDomainName).WithItemName("MIE");
                List<ReplaceableAttribute> attribute = request.Attribute;
                attribute.Add(new ReplaceableAttribute().WithName("name").WithValue("MIE"));
                sdb.PutAttributes(request);
                request.WithDomainName(cDomainName).WithItemName("MF");
                attribute.Add(new ReplaceableAttribute().WithName("name").WithValue("MF"));
                sdb.PutAttributes(request);
                request.WithDomainName(cDomainName).WithItemName("MEP");
                attribute.Add(new ReplaceableAttribute().WithName("name").WithValue("MEP"));
                sdb.PutAttributes(request);

                String sqlExpr = "select * from program";

                SelectRequest selectRequest = new SelectRequest();
                selectRequest.WithSelectExpression(sqlExpr);
                SelectResponse selectResponse = sdb.Select(selectRequest);
                

                if(selectResponse.IsSetSelectResult())
                {
                    SelectResult result = selectResponse.SelectResult;

                    foreach (Item programItem in result.Item)
                    {
                        programList.Items.Add(programItem.Name);
                    }
                }



            }
            catch (Exception ex)
            {
                Label1.Text = "Something happens:<br/>" + ex.Message;
            }

       /*
        * =======================
        * Add Attributes to Student
        * =======================
        */
        protected void addAtrributeButon_Click(object sender, EventArgs e)
        {
            try
            {
                // setup the domain
                String cDomainName = "student";

                // get value from the foreground
                String name = sName.Text.Trim();
                String age = sAge.Text.Trim();
                String gender = genderList.SelectedItem.Text;
                String prog = programList.SelectedItem.Text;

                if (name != "")
                {
                    // announce Put Action
                    PutAttributesRequest request = new PutAttributesRequest();
                    // create a list of Replaceable Attribute
                    List<ReplaceableAttribute> attribute = request.Attribute;

                    // setup item with attributes
                    request.WithDomainName(cDomainName).WithItemName(name);
                    attribute.Add(new ReplaceableAttribute().WithName("age").WithValue(age));
                    attribute.Add(new ReplaceableAttribute().WithName("gender").WithValue(gender));
                    attribute.Add(new ReplaceableAttribute().WithName("program").WithValue(prog));

                    // submit
                    sdb.PutAttributes(request);

                    // refresh list
                    listAttributeButton_Click(sender, e);
                }
            }
            catch (Exception ex)
            {
                Label1.Text = "Something happens:<br/>" + ex.Message;
            }
        }

        /*
        * =======================
        * List Attributes in Student
        * =======================
        */
        protected void listAttributeButton_Click(object sender, EventArgs e)
        {
            try
            {
                // state a sql expression
                String sqlExpr = "select * from student";

                // announce the select request
                SelectRequest selectRequest = new SelectRequest();
                // setup the expression in request
                selectRequest.WithSelectExpression(sqlExpr);
                // setup response
                SelectResponse selectResponse = sdb.Select(selectRequest);

                StringBuilder output = new StringBuilder();

                // retrieve data: if result exists
                if (selectResponse.IsSetSelectResult())
                {
                    // announce the result
                    SelectResult result = selectResponse.SelectResult;

                    output.AppendFormat("<table border='1'><tr><th>Name</th><th>Program</th><th>Age</th><th>Gender</th></tr>");

                    // get items
                    foreach (Item sItem in result.Item)
                    {
                        output.AppendFormat("<tr><td>{0}</td>", sItem.Name);

                        // get attributes for each item
                        foreach (Amazon.SimpleDB.Model.Attribute sAttri in sItem.Attribute)
                        {
                            // get the value of the attribute
                            // if you want to get the name of attribute as well,
                            // use Attribute.IsSetName()
                            if (sAttri.IsSetValue())
                            {
                                output.AppendFormat("<td>{0}</td>", sAttri.Value);
                            }
                        }

                        output.AppendFormat("</tr>");
                    }

                    output.AppendFormat("</table>");

                    Label2.Text = output.ToString();
                }
            }
            catch (Exception ex)
            {
                Label1.Text = "Something happens:<br/>" + ex.Message;
            }


        }

Update:

       /*
        * =======================
        * Add Attributes to Student
        * =======================
        */
        protected void addAtrributeButon_Click(object sender, EventArgs e)
        {
            try
            {
                // setup the domain
                String cDomainName = "student";

                // get value from the foreground
                String name = sName.Text.Trim();
                String age = sAge.Text.Trim();
                String gender = genderList.SelectedItem.Text;
                String prog = programList.SelectedItem.Text;

                if (name != "")
                {
                    // announce Put Action
                    PutAttributesRequest request = new PutAttributesRequest();
                    
                    // create a list of Replaceable Attribute
                    List<ReplaceableAttribute> attribute = request.Attribute;

                    // setup item with attributes
                    request.WithDomainName(cDomainName).WithItemName(name);

                    // here we create a replaceable attribute with replace enabled.
                    attribute.Add(new ReplaceableAttribute().WithReplace(true).WithName("name").WithValue(name));
                    attribute.Add(new ReplaceableAttribute().WithReplace(true).WithName("age").WithValue(age));
                    attribute.Add(new ReplaceableAttribute().WithReplace(true).WithName("gender").WithValue(gender));
                    attribute.Add(new ReplaceableAttribute().WithReplace(true).WithName("program").WithValue(prog));

                    // submit
                    sdb.PutAttributes(request);

                    // refresh list
                    listAttributeButton_Click(sender, e);
                }
            }
            catch (Exception ex)
            {
                Label1.Text = "Something happens:<br/>" + ex.Message;
            }
        }

Remove

       /*
        * =======================
        * remove Attributes in Student
        * =======================
        */
        protected void removeAttributeButton_Click(object sender, EventArgs e)
        {
            try
            {
                String sname = studentNameList.SelectedItem.Value;

                if (sname != "")
                {
                    // state a sql expression
                    // first is to find the itemName of attributes.
                    //String sqlExpr = "select itemName() from student where name='"+sname+"'";

                     announce the select request
                    //SelectRequest selectRequest = new SelectRequest();
                     setup the expression in request
                    //selectRequest.WithSelectExpression(sqlExpr);
                     setup response
                    //SelectResponse selectResponse = sdb.Select(selectRequest);

                    //StringBuilder output = new StringBuilder();

                     retrieve data: if result exists
                    //if (selectResponse.IsSetSelectResult())
                    //{
                    //    // announce the result
                    //    SelectResult result = selectResponse.SelectResult;
                    //
                    // ... ...
                    //}
                    // since sname is the itemName, so we don't have to search for it.

                    // delete attributes
                    DeleteAttributesRequest request = new DeleteAttributesRequest();
                    // with domainname and itemname
                    request.WithDomainName("student").WithItemName(sname);
                    // send request
                    sdb.DeleteAttributes(request);

                    // refresh list
                    Label2.Text = listAttributeStudent();
                }
            }
            catch (Exception ex)
            {
                Label2.Text = "Something happens:<br/>" + ex.Message;
            }
        }

http://www.sdbexplorer.com/documentation/simpledb--how-to-run-select-query.html

NOTE: Covers all subsets of the full SQL language. Amazon SimpleDB does not support joins, aggregations, sub queries, custom syntax extensions to support multi-value in SELECT queries.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值