1. 程式人生 > >.NET Code Samples

.NET Code Samples

Code Sample: Create an Amazon DynamoDB Table Use PowerShell Cmdlets to create a DynamoDB Table.
# Uses the "dynamodb:CreateTable" IAM Policy.

# Create a Table with a Hash Key only
$tableName1 = 'MyTableWithHashKey'
$schema1 = New-DDBTableSchema
$schema1 | Add-DDBKeySchema -KeyName 'id' -KeyDataType 'S'
$schema1 | New-DDBTable -TableName $tableName1 -ReadCapacity 5 -WriteCapacity 5

# Create a Table with Hash and Range Keys
$tableName2 = 'MyTableWithRangeKey'
$schema2 = New-DDBTableSchema
$schema2 | Add-DDBKeySchema -KeyName 'id' -KeyDataType 'S' -KeyType 'HASH'
$schema2 | Add-DDBKeySchema -KeyName 'range' -KeyDataType 'S' -KeyType 'RANGE'
$schema2 | New-DDBTable -TableName $tableName2 -ReadCapacity 5 -WriteCapacity 5
Code Sample: Create a .NET Table object for interacting with an Amazon DynamoDB Table

To support the CRUD operations from PowerShell, we will use the AWS .NET SDK and the DynamoDB Document Model. In this section we will create the required clients for interacting with a DynamoDB Table

# Create an Amazon DynamoDB Document Model Table Object
# To create this client, we likely need an AWS Credential and AWS RegionEndpoint object

# You may be able to use default credentials, however in this exampe we will create a
# credential object to use.
$awsCredential = Get-AWSCredential -ProfileName profilename

# Create a RegionEndpoint object directly, or using an AWS Region name
$region = [Amazon.RegionEndpoint]::USWest2
$region = [Amazon.RegionEndpoint]::GetBySystemName('us-west-2')

# Create an AmazonDynamoDBClient. This is used for the underlying API calls
#   - Use default AWS credentials, or an AWS credential object
$client = New-Object -TypeName Amazon.DynamoDBv2.AmazonDynamoDBClient -ArgumentList $region
$client = New-Object -TypeName Amazon.DynamoDBv2.AmazonDynamoDBClient -ArgumentList $awsCredential, $region

# Create a Table object. This is used for calls using the DynamoDB Document Model
$table = [Amazon.DynamoDBv2.DocumentModel.Table]::LoadTable($client, $tableName)
Code Sample: Put an item in an Amazon DynamoDB Table This example demonstrates performing a PutItem request against a DynamoDB Table that only has a Hash Key.
# Uses the "dynamodb:PutItem" IAM Policy.

# Create a Document object from a json string.
$json = ConvertTo-Json -Compress -InputObject @{
    id       = 'MyHashKeyValue'
    property = 'My Value'
    type     = 'TestObject'
}
$document = [Amazon.DynamoDBv2.DocumentModel.Document]::FromJson($json)

# Perform the PutItem operation. Note the PowerShell Core request is asynchronous.
if ($PSEdition -eq 'Core')
{
    # PowerShell Core
    $table.PutItemAsync($document).Wait()
}
else
{
    # Windows PowerShell
    $table.PutItem($document)
}
This example demonstrates performing a PutItem request with a conditional statement against a DynamoDB Table that only has a Hash Key. For more information about formatting conditional statements, refer to the "Code Sample: Expression Statements" section below.
# Uses the "dynamodb:PutItem" IAM Policy.

# Create a Document object from a json string.
$key = 'id'
$value = 'MyHashKeyValue'
$json = ConvertTo-Json -Compress -InputObject @{
    $key     = $value
    property = 'My Value'
    type     = 'TestObject'
}
$document = [Amazon.DynamoDBv2.DocumentModel.Document]::FromJson($json)

# Create a DocumentModel Expression
$expression = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.Expression

# Example ExpressionStatement for attribute_not_exists
$expression.ExpressionStatement = "attribute_not_exists ($key)"

# Example ExpressionStatement for does not equal
$expression.ExpressionStatement = "$key <> :evaluation"
$expression.ExpressionAttributeValues[':evaluation'] = $value

$putItemConfiguration = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.PutItemOperationConfig
$putItemConfiguration.ConditionalExpression = $expression

# Perform the PutItem operation. Note the PowerShell Core request is asynchronous.
if ($PSEdition -eq 'Core')
{
    # PowerShell Core
    $table.PutItemAsync($document, $putItemConfiguration).Wait()
}
else
{
    # Windows PowerShell
    $table.PutItem($document, $putItemConfiguration)
}
This example demonstrates performing a PutItem request against a DynamoDB Table that has a Hash and Range Key.
# Uses the "dynamodb:PutItem" IAM Policy.

# Create a Document object from a json string.
# This example uses a Range key called "range", and sets it to a
# string value of the number of seconds since epoch.
$epoch = [DateTimeOffset]::Now.ToUnixTimeSeconds()
$json = ConvertTo-Json -Compress -InputObject @{
    id       = 'MyHashKeyValue'
    range    = $epoch.ToString()
    property = 'My Value'
    type     = 'TestObject'
}
$document = [Amazon.DynamoDBv2.DocumentModel.Document]::FromJson($json)

# Perform the PutItem operation. Note the PowerShell Core request is asynchronous.
if ($PSEdition -eq 'Core')
{
    # PowerShell Core
    $table.PutItemAsync($document).Wait()
}
else
{
    # Windows PowerShell
    $table.PutItem($document)
}
Code Sample: Update an item in an Amazon DynamoDB Table This example demonstrates performing an UpdateItem request against a DynamoDB Table that only has a Hash Key.
# Uses the "dynamodb:UpdateItem" IAM Policy.

# Create a Document object from a json string.
$json = ConvertTo-Json -Compress -InputObject @{
    id       = 'MyHashKeyValue'
    property = 'My New Value'
}
$document = [Amazon.DynamoDBv2.DocumentModel.Document]::FromJson($json)

# Perform the UpdateItem operation. Note the PowerShell Core request is asynchronous.
if ($PSEdition -eq 'Core')
{
    # PowerShell Core
    $table.UpdateItemAsync($document).Wait()
}
else
{
    # Windows PowerShell
    $table.UpdateItem($document)
}
This example demonstrates performing an UpdateItem request with a conditional statement against a DynamoDB Table that only has a Hash Key. For more informaiton about formatting conditional statements, refer to the "Code Sample: Expression Statements" section below.
# Uses the "dynamodb:UpdateItem" IAM Policy.

# Create a Document object from a json string.
$key = 'id'
$value = 'MyHashKeyValue'
$json = ConvertTo-Json -Compress -InputObject @{
    $key     = $value
    property = 'My New Value'
}
$document = [Amazon.DynamoDBv2.DocumentModel.Document]::FromJson($json)

# Create a DocumentModel Expression
$expression = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.Expression

# Example ExpressionStatement for attribute_not_exists
$expression.ExpressionStatement = "attribute_not_exists ($key)"

# Example ExpressionStatement for does not equal
$expression.ExpressionStatement = "$key <> :evaluation"
$expression.ExpressionAttributeValues[':evaluation'] = $value

$updateItemConfiguration = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.UpdateItemOperationConfig
$updateItemConfiguration.ConditionalExpression = $expression

# Perform the UpdateItem operation. Note the PowerShell Core request is asynchronous.
if ($PSEdition -eq 'Core')
{
    # PowerShell Core
    $table.UpdateItemAsync($document, $updateItemConfiguration).Wait()
}
else
{
    # Windows PowerShell
    $table.UpdateItem($document, $updateItemConfiguration)
}
This example demonstrates performing an UpdateItem request against a DynamoDB Table that has a Hash and Range Key.
# Uses the "dynamodb:UpdateItem" IAM Policy.

# Create a Document object from a json string.
$epoch = [DateTimeOffset]::Now.ToUnixTimeSeconds()
$json = ConvertTo-Json -Compress -InputObject @{
    id       = 'MyHashKeyValue'
    range    = $epoch.ToString()
    property = 'My New Value'
}
$document = [Amazon.DynamoDBv2.DocumentModel.Document]::FromJson($json)

# Perform the UpdateItem operation. Note the PowerShell Core request is asynchronous.
if ($PSEdition -eq 'Core')
{
    # PowerShell Core
    $table.UpdateItemAsync($document).Wait()
}
else
{
    # Windows PowerShell
    $table.UpdateItem($document)
}
Code Sample: Get an item from an Amazon DynamoDB Table This example demonstrates performing a GetItem request against a DynamoDB Table that only has a Hash Key.
# Uses the "dynamodb:GetItem" IAM Policy.

# Create the Hash Key Primitive
$hashKey = [Amazon.DynamoDBv2.DocumentModel.Primitive]::new('MyHashKeyValue')

# Returns a Amazon.DynamoDBv2.DocumentModel.Document object
if ($PSEdition -eq 'Core')
{
    # PowerShell Core
    $result = $table.GetItemAsync($hashKey).Result
}
else
{
    # Windows PowerShell
    $result = $table.GetItem($hashKey)
}

# Print the output as Json
$result.ToJson()
$result.ToJsonPretty()

# Access the DynamoDB properties like a hashtable
$result['property']
$result['property'].Value

# Get a PowerShell Object from the response object
$item = ConvertFrom-Json -InputObject $result.ToJson()
$item
This example demonstrates using a JSON object to perform a GetItem request against a DynamoDB Table that only has a Hash Key.
# Uses the "dynamodb:GetItem" IAM Policy.

# Create the Hash Key Primitive
$json = ConvertTo-Json -Compress -InputObject @{
    HashKey = 'HashKeyValue'
}
$document = [Amazon.DynamoDBv2.DocumentModel.Document]::FromJson($json)

# Returns a Amazon.DynamoDBv2.DocumentModel.Document object
if ($PSEdition -eq 'Core')
{
    # PowerShell Core
    $result = $table.GetItemAsync($document).Result
}
else
{
    # Windows PowerShell
    $result = $table.GetItem($document)
}

# Print the output as Json
$result.ToJson()
$result.ToJsonPretty()

# Access the DynamoDB properties like a hashtable
$result['property']
$result['property'].Value

# Get a PowerShell Object from the response object
$item = ConvertFrom-Json -InputObject $result.ToJson()
$item
This example demonstrates performing a GetItem request against a DynamoDB Table that has a Hash and Range Key.
# Uses the "dynamodb:GetItem" IAM Policy.

# Create the Hash and Range Key Primitives
$hashKey = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.Primitive -ArgumentList 'MyHashKeyValue'
$rangeKey = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.Primitive -ArgumentList $epoch.ToString()

# Returns a Amazon.DynamoDBv2.DocumentModel.Document object
if ($PSEdition -eq 'Core')
{
    # PowerShell Core
    $result = $table.GetItemAsync($hashKey,$rangeKey).Result
}
else
{
    # Windows PowerShell
    $result = $table.GetItem($hashKey, $rangeKey)
}

# Print the output as Json
$result.ToJson()
$result.ToJsonPretty()

# Access the DynamoDB properties like a hashtable
$result['property']
$result['property'].Value

# Get a PowerShell Object from the response object
$item = ConvertFrom-Json -InputObject $result.ToJson()
$item
Code Sample: Query an Amazon DynamoDB Table This example demonstrates performing a Query against a DynamoDB Table that only has a Hash Key.
# Uses the "dynamodb:Query" IAM Policy.

# Create the Query Operator and Query Filter objects.
$operator = [Amazon.DynamoDBv2.DocumentModel.QueryOperator]::Equal
$filter = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.QueryFilter -ArgumentList 'id', $operator, 'MyHashKeyValue'

# Create the Query object
$search = $table.Query($filter)

# Create the List for storing the retrieved Document objects
$documentList = New-Object -TypeName 'System.Collections.Generic.List[Amazon.DynamoDBv2.DocumentModel.Document]'

# To ensure errors are terminating and we don't get stuck in a loop, use ErrorActionPreference
$eap = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
try
{
    do {
        if ($PSEdition -eq 'Core')
        {
            # PowerShell Core
            $documentSet = $search.GetNextSetAsync().Result
        }
        else
        {
            # Windows PowerShell
            $documentSet = $search.GetNextSet()
        }

        # Process the Document objects retrieves in this API call
        foreach ($document in $documentSet)
        {
            # Perform work against each document here, or
            # save each document to an array for processing later
            $null = $documentList.Add($document)
        }
    }
    while (-not $search.IsDone)
}
catch
{
    # Take action on exception
}
finally
{
    $ErrorActionPreference = $eap
}
This example demonstrates performing a Query against a DynamoDB Table that using both a Hash and Range Key.
# Uses the "dynamodb:Query" IAM Policy.

# This example will query for a range key greater than the seconds since Epoch from 50 days ago
$hashKey = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.Primitive -ArgumentList 'MyHashKeyValue'

# Calculate the seconds since epoch value for our starting timestamp
$startTime = [datetime][DateTimeOffset]::Now.ToUnixTimeSeconds()
$twoWeeksAgo = [datetime]::UtcNow.AddDays(-50)
$twoWeeksAgoEpoch = (New-TimeSpan -Start $startTime -End $twoWeeksAgo).TotalSeconds.ToString()

# Create the Query Operator and Query Filter objects.
$operator = [Amazon.DynamoDBv2.DocumentModel.QueryOperator]::GreaterThan
$filter = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.QueryFilter -ArgumentList 'range', $operator, $twoWeeksAgoEpoch

# Create the Query object
$search = $table2.Query($hashKey, $filter)

# Create the List for storing the retrieved Document objects
$documentList = New-Object -TypeName 'System.Collections.Generic.List[Amazon.DynamoDBv2.DocumentModel.Document]'

# To ensure errors are terminating and we don't get stuck in a loop, use ErrorActionPreference
$eap = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
try
{
    do {
        if ($PSEdition -eq 'Core')
        {
            # PowerShell Core
            $documentSet = $search.GetNextSetAsync().Result
        }
        else
        {
            # Windows PowerShell
            $documentSet = $search.GetNextSet()
        }

        # Process the Document objects retrieves in this API call
        foreach ($document in $documentSet)
        {
            # Perform work against each document here, or
            # save each document to an array for processing later
            $null = $documentList.Add($document)
        }
    }
    while (-not $search.IsDone)
}
catch
{
    # Take action on exception
}
finally
{
    $ErrorActionPreference = $eap
}
Code Sample: Scan an Amazon DynamoDB Table
# Uses the "dynamodb:Scan" IAM Policy.

# Create the List for storing the retrieved Document objects
$documentList = New-Object -TypeName 'System.Collections.Generic.List[Amazon.DynamoDBv2.DocumentModel.Document]'

# To ensure errors are terminating and we don't get stuck in a loop, use ErrorActionPreference
$eap = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
try
{
    $search = $table.Scan($filter)
    do
    {
        if ($PSEdition -eq 'Core')
        {
            # PowerShell Core
            $documentSet = $search.GetNextSetAsync().Result
        }
        else
        {
            # Windows PowerShell
            $documentSet = $search.GetNextSet()
        }

        # Process the Document objects retrieves in this API call
        foreach ($document in $documentList)
        {
            # Do something with the document or print it for output stream
            ConvertFrom-Json -InputObject $document.ToJson()
        }
    }
    while ($search.IsDone -eq $false)
}
catch
{
    # Take action on exception
}
finally
{
    $ErrorActionPreference = $eap
}
Code Sample: Delete an item from an Amazon DynamoDB Table
# Uses the "dynamodb:DeleteItem" IAM Policy.

# Create a Document object from a json string.
$json = ConvertTo-Json -Compress -InputObject @{
    id = 'MyHashKeyValue'
}
$document = [Amazon.DynamoDBv2.DocumentModel.Document]::FromJson($json)

# Perform the PutItem operation. Note the PowerShell Core request is asynchronous.
if ($PSEdition -eq 'Core')
{
    # PowerShell Core
    $table.DeleteItemAsync($document)
}
else
{
    # Windows PowerShell
    $table.DeleteItem($document)
}
Code Sample: Delete an Amazon DynamoDB Table
# Uses the "dynamodb:DeleteTable" IAM Policy.

Remove-DDBTable -TableName $tableName -Force
Code Sample: Expression Statements When performing conditional actions, you need to specify an Expression Statement. Below are sample Expression Statements.
$key = 'HashKey'
$value = 'HashValue'
$expression = New-Object -TypeName Amazon.DynamoDBv2.DocumentModel.Expression

# Key Begins With
$expression.ExpressionStatement = "begins_with ($key, :evaluation)"
$expression.ExpressionAttributeValues[':evaluation'] = $value

# Key Contains
$expression.ExpressionStatement = "contains ($key, :evaluation)"
$expression.ExpressionAttributeValues[':evaluation'] = $value

# Key Is Not Equal
$expression.ExpressionStatement = "$key <> :evaluation"
$expression.ExpressionAttributeValues[':evaluation'] = $value

# Key Does Not Exist
$expression.ExpressionStatement = "attribute_not_exists ($key)"

# Key Exists
$expression.ExpressionStatement = "attribute_exists ($key)"

# Key Is Equal To
$expression.ExpressionStatement = "$key = :evaluation"
$expression.ExpressionAttributeValues[':evaluation'] = $value

# Key Is Greater Than
$expression.ExpressionStatement = "$key > :evaluation"
$expression.ExpressionAttributeValues[':evaluation'] = $value

# Key Is Greater Than or Equal To
$expression.ExpressionStatement = "$key >= :evaluation"
$expression.ExpressionAttributeValues[':evaluation'] = $value

# Key Is Less Than
$expression.ExpressionStatement = "$key < :evaluation"
$expression.ExpressionAttributeValues[':evaluation'] = $value

# Key Is Less Than or Equal To
$expression.ExpressionStatement = "$key <= :evaluation"
$expression.ExpressionAttributeValues[':evaluation'] = $value

# Key is between two values
$lowValue = 2
$highValue = 10

$expression.ExpressionStatement = "$key BETWEEN :lowvalue AND :highvalue"
$expression.ExpressionAttributeValues[':lowvalue'] = $lowValue
$expression.ExpressionAttributeValues[':highvalue'] = $highValue

相關推薦

.NET Code Samples

Code Sample: Create an Amazon DynamoDB Table Use Pow

.Net Code First

blog www. 上下 ini vid 引入 目前 配置連接 pro Code First 的方式有一個有點就是便於以後修改字段。 引入EntityFramework 打開NuGet包管理工具,搜索EntityFramework,安裝好。 創建數據模型 添加數據模型

.net code first 將數據表導入數據庫

程序包管理器 導入數據庫 database 項目 ons pda code 程序包 div 控制臺輸入命令: 切換到項目的project.json 文件所在文件 dotnet ef migrations add XXX dotnet ef database update

.NET Code WebApi CentOS部署

  準備 Visual Studio Code CentOS 7 FTP 建立webapi專案 >dotnet new webapi 專案簡單模擬通過POST呼叫介面,讀取配置檔案傳送訊息,返回傳送結果 建立這幾個檔案: ServerConfig.cs//用於讀

Why does a 'for' loop behave differently when migrating VB.NET code to C#?

Because the for in VB is a different semantic than the for in C# (or any other C-like language) In VB, the for statement is specifically incrementing a

Scary Code Samples?

I'm putting together a Halloween display of scary code sample (SQL injections come to mind). What would you add to the scary code display?

Blockchain Innovators: Leveraging Code Samples (3/6)

Loading… If you’re interested in the IBM Blockchain Platform, this is a great opportunity to learn how to use the it. We’ll walk you through how to build

Can I submit my own code samples?

We have some great code samples for you to use, but we know you'll have ideas for more samples and we want to hear them. Share your ideas

ASP.Net MVC連接MySQL和Code First的使用

config文件 onf tsql .com mysql字符串 spa set web 不同 首先要準備一下的工具作為環境 MySQL Community Server 5.7.x My Workbench 6.3 VS2017 新建一個項目,NetMySQLCodeF

visual studio code調試.net core 2.0程序

vs code 調試控制臺 debuger console datatable 最近在試.net 2.0 Preview時,在VS2017中相對麻煩,現說也怕把生產環境搞壞,於是就想在vs code下試試。首在安裝.net core 2.0的SDK和Runtime,這裏下載https://gi

VS Code開發調試.NET Core 2.0

lin res blog ram sco img vscode 不用 store VS Code開發調試.NET Core 2.0 使用VS Code 從零開始開發調試.NET Core 2.0。無需安裝VS 2017 15.3+即可開發調試.NET Core 2.0應用。

[.NET Core 32]升級vs code之後,vs code無法調試net core web項目

visual spa it is net sem not 安裝 during mach 錯誤提示&處理方法 參考鏈接:https://github.com/OmniSharp/omnisharp-vscode/issues/1742 錯誤:The .NET Core

.net core 2.0 Code First Fluent API配置

asp 完成 eating cte word his text -1 src A.net core 2.0新特性支持通過IEntityTypeConfiguration<>添加Code First配置到一個封裝類。 新建目標框架為.NET Core類庫 新建完

.NET CORE 框架ABP的代碼生成器(ABP Code Power Tools )使用說明文檔

rmq 重新 視頻教程 新版本 ring person 推出 進行 pla 前言 各位好,又是一個多月沒更新文章了。 原因嘛,大家都懂的,太忙了~ 臨近年末,公司的項目、年會的做技術支持,同事朋友聚餐也比較頻繁。 當然視頻教程也沒有繼續更新。我的鍋~ 但是這個月好歹抽空做了

使用VS Code開發asp.net core (上)

insider pub 方法 開發 ctr 自動安裝 查看 系統 地址 本文是基於Windows10的. 下載地址: https://code.visualstudio.com/ insider 版下載地址: https://code.visualstudio.com/in

輕松掌握VS Code開發.Net Core及創建Xunit單元測試

blog logs 寫文章 編譯 分享 單獨 etc 2.0 ren 前言 本篇文章主要還是介紹使用 VS Code 進行.Net Core開發和常用 CLI命令的使用,至於為啥要用VS Code ,因為它是真的是好看又好用 :) ,哈哈,主要還是為了跨平臺開發做準備。 開

【親測】Asp.net Mvc5 + EF6 code first 方式連接MySQL總結

save created eof 節點配置 posit 創建 img from 建立連接時 本文原文地址為:https://www.cnblogs.com/summit7ca/p/5423637.html 原文測試環境為windows 8.1+Vs2013+MySql5.7

Code:.NET快速開發平臺 NFine.Framework Web框架

邏輯 輕松開發 chart 3.2 Edito 郵件 技術 360瀏覽器 在線 ylbtech-Code:.NET快速開發平臺 NFine.Framework Web框架 1.NFine.Framework 詳細介紹返回頂部 1、 NFine

.net core code frist帶數據庫遷移

初始 連接字符串 .com 由於 soft mysql 項目 book 執行 1、新建.net core 工程。 2、添加類book。 public class Book { public int ID { get; set; }

使用Visual Studio Code開發.NET Core看這篇就夠了

原文: 使用Visual Studio Code開發.NET Core看這篇就夠了 作者:依樂祝 原文地址:https://www.cnblogs.com/yilezhu/p/9926078.html 在本文中,我將帶著大家一步一步的通過圖文的形式來演示如何在Visual Studio Code