repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using AWSSDKDocSamples.Util; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; using System.Collections.Specialized; using System.Configuration; using System.Threading.Tasks; using System.IO; namespace AWSSDKDocSamples.DynamoDBv2 { public class LowLevelSamples : ISample { public void DataPlaneSamples() { { #region CreateTable Sample // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Define table schema: // Table has a hash-key "Author" and a range-key "Title" List<KeySchemaElement> schema = new List<KeySchemaElement> { new KeySchemaElement { AttributeName = "Author", KeyType = "HASH" }, new KeySchemaElement { AttributeName = "Title", KeyType = "RANGE" } }; // Define key attributes: // The key attributes "Author" and "Title" are string types List<AttributeDefinition> definitions = new List<AttributeDefinition> { new AttributeDefinition { AttributeName = "Author", AttributeType = "S" }, new AttributeDefinition { AttributeName = "Title", AttributeType = "S" } }; // Define table throughput: // Table has capacity of 20 reads and 50 writes ProvisionedThroughput throughput = new ProvisionedThroughput { ReadCapacityUnits = 20, WriteCapacityUnits = 50 }; // Configure the CreateTable request CreateTableRequest request = new CreateTableRequest { TableName = "SampleTable", KeySchema = schema, ProvisionedThroughput = throughput, AttributeDefinitions = definitions }; // View new table properties TableDescription tableDescription = client.CreateTable(request).TableDescription; Console.WriteLine("Table name: {0}", tableDescription.TableName); Console.WriteLine("Creation time: {0}", tableDescription.CreationDateTime); Console.WriteLine("Item count: {0}", tableDescription.ItemCount); Console.WriteLine("Table size (bytes): {0}", tableDescription.TableSizeBytes); Console.WriteLine("Table status: {0}", tableDescription.TableStatus); // List table key schema List<KeySchemaElement> tableSchema = tableDescription.KeySchema; for (int i = 0; i < tableSchema.Count; i++) { KeySchemaElement element = tableSchema[i]; Console.WriteLine("Key: Name = {0}, KeyType = {1}", element.AttributeName, element.KeyType); } // List attribute definitions List<AttributeDefinition> attributeDefinitions = tableDescription.AttributeDefinitions; for (int i = 0; i < attributeDefinitions.Count; i++) { AttributeDefinition definition = attributeDefinitions[i]; Console.WriteLine("Attribute: Name = {0}, Type = {1}", definition.AttributeName, definition.AttributeType); } Console.WriteLine("Throughput: Reads = {0}, Writes = {1}", tableDescription.ProvisionedThroughput.ReadCapacityUnits, tableDescription.ProvisionedThroughput.WriteCapacityUnits); #endregion } { #region DescribeTable Sample // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Create DescribeTable request DescribeTableRequest request = new DescribeTableRequest { TableName = "SampleTable" }; // Issue DescribeTable request and retrieve the table description TableDescription tableDescription = client.DescribeTable(request).Table; // View new table properties Console.WriteLine("Table name: {0}", tableDescription.TableName); Console.WriteLine("Creation time: {0}", tableDescription.CreationDateTime); Console.WriteLine("Item count: {0}", tableDescription.ItemCount); Console.WriteLine("Table size (bytes): {0}", tableDescription.TableSizeBytes); Console.WriteLine("Table status: {0}", tableDescription.TableStatus); // List table key schema List<KeySchemaElement> tableSchema = tableDescription.KeySchema; for (int i = 0; i < tableSchema.Count; i++) { KeySchemaElement element = tableSchema[i]; Console.WriteLine("Key: Name = {0}, KeyType = {1}", element.AttributeName, element.KeyType); } // List attribute definitions List<AttributeDefinition> attributeDefinitions = tableDescription.AttributeDefinitions; for (int i = 0; i < attributeDefinitions.Count; i++) { AttributeDefinition definition = attributeDefinitions[i]; Console.WriteLine("Attribute: Name = {0}, Type = {1}", definition.AttributeName, definition.AttributeType); } Console.WriteLine("Throughput: Reads = {0}, Writes = {1}", tableDescription.ProvisionedThroughput.ReadCapacityUnits, tableDescription.ProvisionedThroughput.WriteCapacityUnits); #endregion } { #region ListTables Paging Sample // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string startTableName = null; do { // Configure ListTables request with the marker value ListTablesRequest request = new ListTablesRequest { ExclusiveStartTableName = startTableName, }; // Issue call ListTablesResult result = client.ListTables(request); // List retrieved tables List<string> tables = result.TableNames; Console.WriteLine("Retrieved tables: {0}", string.Join(", ", tables)); // Update marker value from the result startTableName = result.LastEvaluatedTableName; } while (!string.IsNullOrEmpty(startTableName)); // Test marker value #endregion } { #region ListTables NonPaging Sample // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Issue call ListTablesResult result = client.ListTables(); // List retrieved tables List<string> tables = result.TableNames; Console.WriteLine("Retrieved tables: {0}", string.Join(", ", tables)); #endregion } TableUtils.WaitUntilTableActive("SampleTable", TestClient); { #region UpdateTable Sample // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Define new table throughput: // Table will now have capacity of 40 reads and 50 writes ProvisionedThroughput throughput = new ProvisionedThroughput { ReadCapacityUnits = 40, WriteCapacityUnits = 50 }; // Compose the UpdateTable request UpdateTableRequest request = new UpdateTableRequest { TableName = "SampleTable", ProvisionedThroughput = throughput }; // View new table properties TableDescription tableDescription = client.UpdateTable(request).TableDescription; Console.WriteLine("Table name: {0}", tableDescription.TableName); Console.WriteLine("Throughput: Reads = {0}, Writes = {1}", tableDescription.ProvisionedThroughput.ReadCapacityUnits, tableDescription.ProvisionedThroughput.WriteCapacityUnits); #endregion } TableUtils.WaitUntilTableActive("SampleTable", TestClient); { #region DeleteTable Sample // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Configure the DeleteTable request DeleteTableRequest request = new DeleteTableRequest { TableName = "SampleTable" }; // Issue DeleteTable request and retrieve the table description TableDescription tableDescription = client.DeleteTable(request).TableDescription; Console.WriteLine("Table name: {0}", tableDescription.TableName); Console.WriteLine("Table status: {0}", tableDescription.TableStatus); #endregion } } private void CreateLSITable() { #region CreateTable LSI Sample // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Define table schema: // Table has a hash-key "Author" and a range-key "Title" List<KeySchemaElement> schema = new List<KeySchemaElement> { new KeySchemaElement { AttributeName = "Author", KeyType = "HASH" }, new KeySchemaElement { AttributeName = "Title", KeyType = "RANGE" } }; // Define local secondary indexes: // Table has two indexes, one on "Year" and the other on "Setting" List<LocalSecondaryIndex> indexes = new List<LocalSecondaryIndex> { new LocalSecondaryIndex { IndexName = "YearsIndex", KeySchema = new List<KeySchemaElement> { // Hash key must match table hash key new KeySchemaElement { AttributeName = "Author", KeyType = "HASH" }, // Secondary index on "Year" attribute new KeySchemaElement { AttributeName = "Year", KeyType = "RANGE" } }, // Projection type is set to ALL, all attributes returned for this index Projection = new Projection { ProjectionType = "ALL" } }, new LocalSecondaryIndex { IndexName = "SettingsIndex", KeySchema = new List<KeySchemaElement> { // Hash key must match table hash key new KeySchemaElement { AttributeName = "Author", KeyType = "HASH" }, // Secondary index on "Setting" attribute new KeySchemaElement { AttributeName = "Setting", KeyType = "RANGE" } }, // Projection type is set to INCLUDE, the specified attributes + keys are returned Projection = new Projection { ProjectionType = "INCLUDE", NonKeyAttributes = new List<string> { "Pages", "Genres" } } } }; // Define key attributes: // The key attributes "Author" and "Title" are string types. // The local secondary index attributes are "Year" (numerical) and "Setting" (string). List<AttributeDefinition> definitions = new List<AttributeDefinition> { new AttributeDefinition { AttributeName = "Author", AttributeType = "S" }, new AttributeDefinition { AttributeName = "Title", AttributeType = "S" }, new AttributeDefinition { AttributeName = "Year", AttributeType = "N" }, new AttributeDefinition { AttributeName = "Setting", AttributeType = "S" } }; // Define table throughput: // Table has capacity of 20 reads and 50 writes ProvisionedThroughput throughput = new ProvisionedThroughput { ReadCapacityUnits = 20, WriteCapacityUnits = 50 }; // Configure the CreateTable request CreateTableRequest request = new CreateTableRequest { TableName = "SampleTable", KeySchema = schema, ProvisionedThroughput = throughput, AttributeDefinitions = definitions, LocalSecondaryIndexes = indexes }; // View new table properties TableDescription tableDescription = client.CreateTable(request).TableDescription; Console.WriteLine("Table name: {0}", tableDescription.TableName); Console.WriteLine("Creation time: {0}", tableDescription.CreationDateTime); Console.WriteLine("Item count: {0}", tableDescription.ItemCount); Console.WriteLine("Table size (bytes): {0}", tableDescription.TableSizeBytes); Console.WriteLine("Table status: {0}", tableDescription.TableStatus); // List table key schema List<KeySchemaElement> tableSchema = tableDescription.KeySchema; for (int i = 0; i < tableSchema.Count; i++) { KeySchemaElement element = tableSchema[i]; Console.WriteLine("Key: Name = {0}, KeyType = {1}", element.AttributeName, element.KeyType); } // List attribute definitions List<AttributeDefinition> attributeDefinitions = tableDescription.AttributeDefinitions; for (int i = 0; i < attributeDefinitions.Count; i++) { AttributeDefinition definition = attributeDefinitions[i]; Console.WriteLine("Attribute: Name = {0}, Type = {1}", definition.AttributeName, definition.AttributeType); } Console.WriteLine("Throughput: Reads = {0}, Writes = {1}", tableDescription.ProvisionedThroughput.ReadCapacityUnits, tableDescription.ProvisionedThroughput.WriteCapacityUnits); #endregion } private void PutSample() { { #region PutItem Sample 1 // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Define item attributes Dictionary<string, AttributeValue> attributes = new Dictionary<string, AttributeValue>(); // Author is hash-key attributes["Author"] = new AttributeValue { S = "Mark Twain" }; // Title is range-key attributes["Title"] = new AttributeValue { S = "The Adventures of Tom Sawyer" }; // Other attributes attributes["Year"] = new AttributeValue { N = "1876" }; attributes["Setting"] = new AttributeValue { S = "Missouri" }; attributes["Pages"] = new AttributeValue { N = "275" }; attributes["Genres"] = new AttributeValue { SS = new List<string> { "Satire", "Folk", "Children's Novel" } }; // Create PutItem request PutItemRequest request = new PutItemRequest { TableName = "SampleTable", Item = attributes }; // Issue PutItem request client.PutItem(request); #endregion } } public void CRUDSamples() { EnsureTables(); PutSample(); { #region GetItem Sample // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Define item key // Hash-key of the target item is string value "Mark Twain" // Range-key of the target item is string value "The Adventures of Tom Sawyer" Dictionary<string, AttributeValue> key = new Dictionary<string, AttributeValue> { { "Author", new AttributeValue { S = "Mark Twain" } }, { "Title", new AttributeValue { S = "The Adventures of Tom Sawyer" } } }; // Create GetItem request GetItemRequest request = new GetItemRequest { TableName = "SampleTable", Key = key, }; // Issue request var result = client.GetItem(request); // View response Console.WriteLine("Item:"); Dictionary<string, AttributeValue> item = result.Item; foreach (var keyValuePair in item) { Console.WriteLine("{0} : S={1}, N={2}, SS=[{3}], NS=[{4}]", keyValuePair.Key, keyValuePair.Value.S, keyValuePair.Value.N, string.Join(", ", keyValuePair.Value.SS ?? new List<string>()), string.Join(", ", keyValuePair.Value.NS ?? new List<string>())); } #endregion } { #region UpdateItem Sample // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Define item key // Hash-key of the target item is string value "Mark Twain" // Range-key of the target item is string value "The Adventures of Tom Sawyer" Dictionary<string, AttributeValue> key = new Dictionary<string, AttributeValue> { { "Author", new AttributeValue { S = "Mark Twain" } }, { "Title", new AttributeValue { S = "The Adventures of Tom Sawyer" } } }; // Define attribute updates Dictionary<string, AttributeValueUpdate> updates = new Dictionary<string, AttributeValueUpdate>(); // Update item's Setting attribute updates["Setting"] = new AttributeValueUpdate() { Action = AttributeAction.PUT, Value = new AttributeValue { S = "St. Petersburg, Missouri" } }; // Remove item's Bibliography attribute updates["Bibliography"] = new AttributeValueUpdate() { Action = AttributeAction.DELETE }; // Add a new string to the item's Genres SS attribute updates["Genres"] = new AttributeValueUpdate() { Action = AttributeAction.ADD, Value = new AttributeValue { SS = new List<string> { "Bildungsroman" } } }; // Create UpdateItem request UpdateItemRequest request = new UpdateItemRequest { TableName = "SampleTable", Key = key, AttributeUpdates = updates }; // Issue request client.UpdateItem(request); #endregion } { #region DeleteItem Sample // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Define item key // Hash-key of the target item is string value "Mark Twain" // Range-key of the target item is string value "The Adventures of Tom Sawyer" Dictionary<string, AttributeValue> key = new Dictionary<string, AttributeValue> { { "Author", new AttributeValue { S = "Mark Twain" } }, { "Title", new AttributeValue { S = "The Adventures of Tom Sawyer" } } }; // Create DeleteItem request DeleteItemRequest request = new DeleteItemRequest { TableName = "SampleTable", Key = key }; // Issue request client.DeleteItem(request); #endregion } } public void SearchSamples() { RemoveTables(); CreateLSITable(); TableUtils.WaitUntilTableActive("SampleTable", TestClient); { // Create items to put into first table Dictionary<string, AttributeValue> item1 = new Dictionary<string, AttributeValue>(); item1["Author"] = new AttributeValue { S = "Mark Twain" }; item1["Title"] = new AttributeValue { S = "A Connecticut Yankee in King Arthur's Court" }; item1["Pages"] = new AttributeValue { N = "575" }; Dictionary<string, AttributeValue> item2 = new Dictionary<string, AttributeValue>(); item2["Author"] = new AttributeValue { S = "Booker Taliaferro Washington" }; item2["Title"] = new AttributeValue { S = "My Larger Education" }; item2["Pages"] = new AttributeValue { N = "313" }; item2["Year"] = new AttributeValue { N = "1911" }; // Construct write-request for first table List<WriteRequest> sampleTableItems = new List<WriteRequest>(); sampleTableItems.Add(new WriteRequest { PutRequest = new PutRequest { Item = item1 } }); sampleTableItems.Add(new WriteRequest { PutRequest = new PutRequest { Item = item2 } }); AmazonDynamoDBClient client = new AmazonDynamoDBClient(); client.BatchWriteItem(new BatchWriteItemRequest { RequestItems = new Dictionary<string, List<WriteRequest>> { { "SampleTable", sampleTableItems } } }); PutSample(); } { #region Query Sample // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Define item hash-key to be string value "Mark Twain" AttributeValue hashKey = new AttributeValue { S = "Mark Twain" }; // Define query condition to search for range-keys that begin with the string "The Adventures" Condition condition = new Condition { ComparisonOperator = "BEGINS_WITH", AttributeValueList = new List<AttributeValue> { new AttributeValue { S = "The Adventures" } } }; // Create the key conditions from hashKey and condition Dictionary<string, Condition> keyConditions = new Dictionary<string, Condition> { // Hash key condition. ComparisonOperator must be "EQ". { "Author", new Condition { ComparisonOperator = "EQ", AttributeValueList = new List<AttributeValue> { hashKey } } }, // Range key condition { "Title", condition } }; // Define marker variable Dictionary<string, AttributeValue> startKey = null; do { // Create Query request QueryRequest request = new QueryRequest { TableName = "SampleTable", ExclusiveStartKey = startKey, KeyConditions = keyConditions }; // Issue request var result = client.Query(request); // View all returned items List<Dictionary<string, AttributeValue>> items = result.Items; foreach (Dictionary<string, AttributeValue> item in items) { Console.WriteLine("Item:"); foreach (var keyValuePair in item) { Console.WriteLine("{0} : S={1}, N={2}, SS=[{3}], NS=[{4}]", keyValuePair.Key, keyValuePair.Value.S, keyValuePair.Value.N, string.Join(", ", keyValuePair.Value.SS ?? new List<string>()), string.Join(", ", keyValuePair.Value.NS ?? new List<string>())); } } // Set marker variable startKey = result.LastEvaluatedKey; } while (startKey != null && startKey.Count > 0); #endregion } { #region Query Local Secondary Index Sample // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Define item hash-key to be string value "Mark Twain" AttributeValue hashKey = new AttributeValue { S = "Mark Twain" }; // Define query condition to search for range-keys ("Year", in "YearsIndex") that are less than 1900 Condition condition = new Condition { ComparisonOperator = "LT", AttributeValueList = new List<AttributeValue> { new AttributeValue { N = "1900" } } }; // Create the key conditions from hashKey and condition Dictionary<string, Condition> keyConditions = new Dictionary<string, Condition> { // Hash key condition. ComparisonOperator must be "EQ". { "Author", new Condition { ComparisonOperator = "EQ", AttributeValueList = new List<AttributeValue> { hashKey } } }, // Range key condition { "Year", // Reference the correct range key when using indexes condition } }; // Define marker variable Dictionary<string, AttributeValue> startKey = null; do { // Create Query request QueryRequest request = new QueryRequest { TableName = "SampleTable", ExclusiveStartKey = startKey, KeyConditions = keyConditions, IndexName = "YearsIndex" // Specify the index to query against }; // Issue request var result = client.Query(request); // View all returned items List<Dictionary<string, AttributeValue>> items = result.Items; foreach (Dictionary<string, AttributeValue> item in items) { Console.WriteLine("Item:"); foreach (var keyValuePair in item) { Console.WriteLine("{0} : S={1}, N={2}, SS=[{3}], NS=[{4}]", keyValuePair.Key, keyValuePair.Value.S, keyValuePair.Value.N, string.Join(", ", keyValuePair.Value.SS ?? new List<string>()), string.Join(", ", keyValuePair.Value.NS ?? new List<string>())); } } // Set marker variable startKey = result.LastEvaluatedKey; } while (startKey != null && startKey.Count > 0); #endregion } { #region Scan Sample // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Define scan conditions Dictionary<string, Condition> conditions = new Dictionary<string, Condition>(); // Title attribute should contain the string "Adventures" Condition titleCondition = new Condition(); titleCondition.ComparisonOperator = ComparisonOperator.CONTAINS; titleCondition.AttributeValueList.Add(new AttributeValue { S = "Adventures" }); conditions["Title"] = titleCondition; // Pages attributes must be greater-than the numeric value "200" Condition pagesCondition = new Condition(); pagesCondition.ComparisonOperator = ComparisonOperator.GT; pagesCondition.AttributeValueList.Add(new AttributeValue { N = "200" }); conditions["Pages"] = pagesCondition; // Define marker variable Dictionary<string, AttributeValue> startKey = null; do { // Create Scan request ScanRequest request = new ScanRequest { TableName = "SampleTable", ExclusiveStartKey = startKey, ScanFilter = conditions }; // Issue request ScanResult result = client.Scan(request); // View all returned items List<Dictionary<string, AttributeValue>> items = result.Items; foreach (Dictionary<string, AttributeValue> item in items) { Console.WriteLine("Item:"); foreach (var keyValuePair in item) { Console.WriteLine("{0} : S={1}, N={2}, SS=[{3}], NS=[{4}]", keyValuePair.Key, keyValuePair.Value.S, keyValuePair.Value.N, string.Join(", ", keyValuePair.Value.SS ?? new List<string>()), string.Join(", ", keyValuePair.Value.NS ?? new List<string>())); } } // Set marker variable startKey = result.LastEvaluatedKey; } while (startKey != null && startKey.Count > 0); #endregion } { // Create lots of items to put into first table var table = Amazon.DynamoDBv2.DocumentModel.Table.LoadTable(TestClient, "SampleTable"); var batchWrite = table.CreateBatchWrite(); for (int i = 0; i < 100; i++) { var document = new Amazon.DynamoDBv2.DocumentModel.Document(); document["Author"] = "FakeAuthor" + i; document["Title"] = "Book" + i; document["Pages"] = (180 + i); document["Year"] = 1900 + i; batchWrite.AddDocumentToPut(document); } batchWrite.Execute(); } { #region Parallel Scan Sample // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Define scan conditions Dictionary<string, Condition> conditions = new Dictionary<string, Condition>(); // Pages attributes must be greater-than the numeric value "200" Condition pagesCondition = new Condition(); pagesCondition.ComparisonOperator = ComparisonOperator.GT; pagesCondition.AttributeValueList.Add(new AttributeValue { N = "200" }); conditions["Pages"] = pagesCondition; // Setup 10 simultaneous threads, each thread calling Scan operation // with its own segment value. int totalSegments = 10; Parallel.For(0, totalSegments, segment => { // Define marker variable Dictionary<string, AttributeValue> startKey = null; do { // Create Scan request ScanRequest request = new ScanRequest { TableName = "SampleTable", ExclusiveStartKey = startKey, ScanFilter = conditions, // Total segments to split the table into TotalSegments = totalSegments, // Current segment to scan Segment = segment }; // Issue request var result = client.Scan(request); // Write returned items to file string path = string.Format("ParallelScan-{0}-of-{1}.txt", totalSegments, segment); List<Dictionary<string, AttributeValue>> items = result.Items; using (Stream stream = File.OpenWrite(path)) using (StreamWriter writer = new StreamWriter(stream)) { foreach (Dictionary<string, AttributeValue> item in items) { writer.WriteLine("Item:"); foreach (var keyValuePair in item) { writer.WriteLine("{0} : S={1}, N={2}, SS=[{3}], NS=[{4}]", keyValuePair.Key, keyValuePair.Value.S, keyValuePair.Value.N, string.Join(", ", keyValuePair.Value.SS ?? new List<string>()), string.Join(", ", keyValuePair.Value.NS ?? new List<string>())); } } } // Set marker variable startKey = result.LastEvaluatedKey; } while (startKey != null && startKey.Count > 0); }); #endregion } } public void BatchSamples() { EnsureTables(); { #region BatchGet Sample 1 // Define attributes to get and keys to retrieve List<string> attributesToGet = new List<string> { "Author", "Title", "Year" }; List<Dictionary<string, AttributeValue>> sampleTableKeys = new List<Dictionary<string, AttributeValue>> { new Dictionary<string, AttributeValue> { { "Author", new AttributeValue { S = "Mark Twain" } }, { "Title", new AttributeValue { S = "The Adventures of Tom Sawyer" } } }, new Dictionary<string, AttributeValue> { { "Author", new AttributeValue { S = "Mark Twain" } }, { "Title", new AttributeValue { S = "Adventures of Huckleberry Finn" } } } }; // Construct get-request for first table KeysAndAttributes sampleTableItems = new KeysAndAttributes { AttributesToGet = attributesToGet, Keys = sampleTableKeys }; #endregion #region BatchGet Sample 2 // Define keys to retrieve List<Dictionary<string, AttributeValue>> authorsTableKeys = new List<Dictionary<string, AttributeValue>> { new Dictionary<string, AttributeValue> { { "Author", new AttributeValue { S = "Mark Twain" } }, }, new Dictionary<string, AttributeValue> { { "Author", new AttributeValue { S = "Booker Taliaferro Washington" } }, } }; // Construct get-request for second table // Skip setting AttributesToGet property to retrieve all attributes KeysAndAttributes authorsTableItems = new KeysAndAttributes { Keys = authorsTableKeys, }; #endregion #region BatchGet Sample 3 // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Construct table-keys mapping Dictionary<string, KeysAndAttributes> requestItems = new Dictionary<string, KeysAndAttributes>(); requestItems["SampleTable"] = sampleTableItems; requestItems["AuthorsTable"] = authorsTableItems; // Construct request BatchGetItemRequest request = new BatchGetItemRequest { RequestItems = requestItems }; BatchGetItemResult result; do { // Issue request and retrieve items result = client.BatchGetItem(request); // Iterate through responses Dictionary<string, List<Dictionary<string, AttributeValue>>> responses = result.Responses; foreach (string tableName in responses.Keys) { // Get items for each table List<Dictionary<string, AttributeValue>> tableItems = responses[tableName]; // View items foreach (Dictionary<string, AttributeValue> item in tableItems) { Console.WriteLine("Item:"); foreach (var keyValuePair in item) { Console.WriteLine("{0} : S={1}, N={2}, SS=[{3}], NS=[{4}]", keyValuePair.Key, keyValuePair.Value.S, keyValuePair.Value.N, string.Join(", ", keyValuePair.Value.SS ?? new List<string>()), string.Join(", ", keyValuePair.Value.NS ?? new List<string>())); } } } // Some items may not have been retrieved! // Set RequestItems to the result's UnprocessedKeys and reissue request request.RequestItems = result.UnprocessedKeys; } while (result.UnprocessedKeys.Count > 0); #endregion } { #region BatchWrite Sample 1 // Create items to put into first table Dictionary<string, AttributeValue> item1 = new Dictionary<string, AttributeValue>(); item1["Author"] = new AttributeValue { S = "Mark Twain" }; item1["Title"] = new AttributeValue { S = "A Connecticut Yankee in King Arthur's Court" }; item1["Pages"] = new AttributeValue { N = "575" }; Dictionary<string, AttributeValue> item2 = new Dictionary<string, AttributeValue>(); item2["Author"] = new AttributeValue { S = "Booker Taliaferro Washington" }; item2["Title"] = new AttributeValue { S = "My Larger Education" }; item2["Pages"] = new AttributeValue { N = "313" }; item2["Year"] = new AttributeValue { N = "1911" }; // Create key for item to delete from first table // Hash-key of the target item is string value "Mark Twain" // Range-key of the target item is string value "Tom Sawyer, Detective" Dictionary<string, AttributeValue> keyToDelete1 = new Dictionary<string, AttributeValue> { { "Author", new AttributeValue { S = "Mark Twain" } }, { "Title", new AttributeValue { S = "Tom Sawyer, Detective" } } }; // Construct write-request for first table List<WriteRequest> sampleTableItems = new List<WriteRequest>(); sampleTableItems.Add(new WriteRequest { PutRequest = new PutRequest { Item = item1 } }); sampleTableItems.Add(new WriteRequest { PutRequest = new PutRequest { Item = item2 } }); sampleTableItems.Add(new WriteRequest { DeleteRequest = new DeleteRequest { Key = keyToDelete1 } }); #endregion #region BatchWrite Sample 2 // Create key for item to delete from second table // Hash-key of the target item is string value "Francis Scott Key Fitzgerald" Dictionary<string, AttributeValue> keyToDelete2 = new Dictionary<string, AttributeValue> { { "Author", new AttributeValue { S = "Francis Scott Key Fitzgerald" } }, }; // Construct write-request for first table List<WriteRequest> authorsTableItems = new List<WriteRequest>(); authorsTableItems.Add(new WriteRequest { DeleteRequest = new DeleteRequest { Key = keyToDelete2 } }); #endregion #region BatchWrite Sample 3 // Create a client AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Construct table-keys mapping Dictionary<string, List<WriteRequest>> requestItems = new Dictionary<string, List<WriteRequest>>(); requestItems["SampleTable"] = sampleTableItems; requestItems["AuthorsTable"] = authorsTableItems; BatchWriteItemRequest request = new BatchWriteItemRequest { RequestItems = requestItems }; BatchWriteItemResult result; do { // Issue request and retrieve items result = client.BatchWriteItem(request); // Some items may not have been processed! // Set RequestItems to the result's UnprocessedItems and reissue request request.RequestItems = result.UnprocessedItems; } while (result.UnprocessedItems.Count > 0); #endregion } } private static void EnsureTables() { List<KeySchemaElement> schema = new List<KeySchemaElement> { new KeySchemaElement { AttributeName = "Author", KeyType = "HASH" }, new KeySchemaElement { AttributeName = "Title", KeyType = "RANGE" } }; List<AttributeDefinition> definitions = new List<AttributeDefinition> { new AttributeDefinition { AttributeName = "Author", AttributeType = "S" }, new AttributeDefinition { AttributeName = "Title", AttributeType = "S" } }; TableUtils.ConfirmTableExistence("SampleTable", TestClient, schema, definitions, 5, 5); schema.RemoveAt(1); definitions.RemoveAt(1); TableUtils.ConfirmTableExistence("AuthorsTable", TestClient, schema, definitions, 5, 5); } private static void RemoveTables() { TableUtils.DeleteTables(TestClient, "SampleTable", "AuthorsTable"); } private static IAmazonDynamoDB TestClient; #region ISample Members public void Run() { using (TestClient = new AmazonDynamoDBClient()) { RemoveTables(); DataPlaneSamples(); CRUDSamples(); SearchSamples(); BatchSamples(); RemoveTables(); } } #endregion } }
1,150
aws-sdk-net
aws
C#
using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; using AWSSDKDocSamples.Util; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AWSSDKDocSamples.DynamoDBv2 { public static class TableUtils { public static void ConfirmTableExistence(string tableName, IAmazonDynamoDB client, List<KeySchemaElement> tableSchema, List<AttributeDefinition> attributeDefinitions) { ConfirmTableExistence(tableName, client, tableSchema, attributeDefinitions, 10, 10); } public static void ConfirmTableExistence(string tableName, IAmazonDynamoDB client, List<KeySchemaElement> tableSchema, List<AttributeDefinition> attributeDefinitions, int reads, int writes) { Console.WriteLine("Confirming table " + tableName + " existence"); string tableStatus = null; tableStatus = WaitUntilTableStable(tableName, client, tableStatus); if (string.IsNullOrEmpty(tableStatus)) { Console.WriteLine("Creating table " + tableName); var tableDescription = client.CreateTable(new CreateTableRequest { TableName = tableName, ProvisionedThroughput = new ProvisionedThroughput { ReadCapacityUnits = reads, WriteCapacityUnits = writes }, KeySchema = tableSchema, AttributeDefinitions = attributeDefinitions }).TableDescription; WaitUntilTableCreated(tableName, client); } else { Console.WriteLine("Not creating table " + tableName + ", status is " + tableStatus); } } public static void WaitUntilTableCreated(string tableName, IAmazonDynamoDB client) { Common.WaitUntil(() => { string status = GetTableStatus(tableName, client); return !status.Equals("CREATING") && !status.Equals(string.Empty); }); } public static void WaitUntilTableDeleted(string tableName, IAmazonDynamoDB client) { Common.WaitUntil(() => GetTableStatus(tableName, client) == null); } public static void WaitUntilTableActive(string tableName, IAmazonDynamoDB client) { Common.WaitUntil(() => GetTableStatus(tableName, client) == TableStatus.ACTIVE); } private static string WaitUntilTableStable(string tableName, IAmazonDynamoDB client, string tableStatus) { Common.WaitUntil(() => { tableStatus = GetTableStatus(tableName, client); if (tableStatus == null) return true; return !tableStatus.Equals("DELETING", StringComparison.OrdinalIgnoreCase) && !tableStatus.Equals("CREATING", StringComparison.OrdinalIgnoreCase); }); return tableStatus; } public static void DeleteTables(IAmazonDynamoDB client, string partialName) { DeleteTables(client, tableName => tableName.IndexOf(partialName, StringComparison.OrdinalIgnoreCase) >= 0); } public static void DeleteTable(IAmazonDynamoDB client, string tableName) { DeleteTables(client, name => string.Equals(name, tableName, StringComparison.Ordinal)); } public static void DeleteTables(IAmazonDynamoDB client, Predicate<string> tableNameMatch) { try { var tableNames = client.ListTables().TableNames; foreach (var tableName in tableNames) { DescribeTableResponse descResponse = client.DescribeTable(new DescribeTableRequest { TableName = tableName }); if (descResponse.Table == null) continue; TableDescription table = descResponse.Table; if (table.TableStatus == TableStatus.ACTIVE && tableNameMatch(table.TableName)) { Console.WriteLine("Table: {0}, {1}, {2}, {3}", table.TableName, table.TableStatus, table.ProvisionedThroughput.ReadCapacityUnits, table.ProvisionedThroughput.WriteCapacityUnits); Console.WriteLine("Deleting table " + table.TableName + "..."); try { client.DeleteTable(new DeleteTableRequest { TableName = table.TableName }); WaitUntilTableDeleted(table.TableName, client); Console.WriteLine("Succeeded!"); } catch { Console.WriteLine("Failed!"); } } } Console.WriteLine(tableNames.Count); } catch (Exception e) { Console.WriteLine(e.ToString()); throw; } } public static void DeleteTables(IAmazonDynamoDB client, params string[] tableNames) { DeleteTables(client, tableName => tableNames.Contains(tableName, StringComparer.Ordinal)); } public static TableStatus GetTableStatus(string tableName, IAmazonDynamoDB client) { try { var table = client.DescribeTable(new DescribeTableRequest { TableName = tableName }).Table; return table.TableStatus; } catch (AmazonDynamoDBException db) { if (db.ErrorCode == "ResourceNotFoundException") return null; throw; } } } }
144
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.EC2; using Amazon.EC2.Model; namespace AWSSDKDocSamples.Amazon.EC2.Generated { class EC2Samples : ISample { public void EC2AllocateAddress() { #region ec2-allocate-address-1 var client = new AmazonEC2Client(); var response = client.AllocateAddress(new AllocateAddressRequest { }); string allocationId = response.AllocationId; string domain = response.Domain; string networkBorderGroup = response.NetworkBorderGroup; string publicIp = response.PublicIp; string publicIpv4Pool = response.PublicIpv4Pool; #endregion } public void EC2AssignPrivateIpAddresses() { #region ec2-assign-private-ip-addresses-1 var client = new AmazonEC2Client(); var response = client.AssignPrivateIpAddresses(new AssignPrivateIpAddressesRequest { NetworkInterfaceId = "eni-e5aa89a3", PrivateIpAddresses = new List<string> { "10.0.0.82" } }); #endregion } public void EC2AssignPrivateIpAddresses() { #region ec2-assign-private-ip-addresses-2 var client = new AmazonEC2Client(); var response = client.AssignPrivateIpAddresses(new AssignPrivateIpAddressesRequest { NetworkInterfaceId = "eni-e5aa89a3", SecondaryPrivateIpAddressCount = 2 }); #endregion } public void EC2AssociateAddress() { #region ec2-associate-address-1 var client = new AmazonEC2Client(); var response = client.AssociateAddress(new AssociateAddressRequest { AllocationId = "eipalloc-64d5890a", InstanceId = "i-0b263919b6498b123" }); string associationId = response.AssociationId; #endregion } public void EC2AssociateAddress() { #region ec2-associate-address-2 var client = new AmazonEC2Client(); var response = client.AssociateAddress(new AssociateAddressRequest { AllocationId = "eipalloc-64d5890a", NetworkInterfaceId = "eni-1a2b3c4d" }); string associationId = response.AssociationId; #endregion } public void EC2AssociateDhcpOptions() { #region ec2-associate-dhcp-options-1 var client = new AmazonEC2Client(); var response = client.AssociateDhcpOptions(new AssociateDhcpOptionsRequest { DhcpOptionsId = "dopt-d9070ebb", VpcId = "vpc-a01106c2" }); #endregion } public void EC2AssociateDhcpOptions() { #region ec2-associate-dhcp-options-2 var client = new AmazonEC2Client(); var response = client.AssociateDhcpOptions(new AssociateDhcpOptionsRequest { DhcpOptionsId = "default", VpcId = "vpc-a01106c2" }); #endregion } public void EC2AssociateIamInstanceProfile() { #region to-associate-an-iam-instance-profile-with-an-instance-1528928429850 var client = new AmazonEC2Client(); var response = client.AssociateIamInstanceProfile(new AssociateIamInstanceProfileRequest { IamInstanceProfile = new IamInstanceProfileSpecification { Name = "admin-role" }, InstanceId = "i-123456789abcde123" }); IamInstanceProfileAssociation iamInstanceProfileAssociation = response.IamInstanceProfileAssociation; #endregion } public void EC2AssociateRouteTable() { #region ec2-associate-route-table-1 var client = new AmazonEC2Client(); var response = client.AssociateRouteTable(new AssociateRouteTableRequest { RouteTableId = "rtb-22574640", SubnetId = "subnet-9d4a7b6" }); string associationId = response.AssociationId; #endregion } public void EC2AttachInternetGateway() { #region ec2-attach-internet-gateway-1 var client = new AmazonEC2Client(); var response = client.AttachInternetGateway(new AttachInternetGatewayRequest { InternetGatewayId = "igw-c0a643a9", VpcId = "vpc-a01106c2" }); #endregion } public void EC2AttachNetworkInterface() { #region ec2-attach-network-interface-1 var client = new AmazonEC2Client(); var response = client.AttachNetworkInterface(new AttachNetworkInterfaceRequest { DeviceIndex = 1, InstanceId = "i-1234567890abcdef0", NetworkInterfaceId = "eni-e5aa89a3" }); string attachmentId = response.AttachmentId; #endregion } public void EC2AttachVolume() { #region to-attach-a-volume-to-an-instance-1472499213109 var client = new AmazonEC2Client(); var response = client.AttachVolume(new AttachVolumeRequest { Device = "/dev/sdf", InstanceId = "i-01474ef662b89480", VolumeId = "vol-1234567890abcdef0" }); DateTime attachTime = response.AttachTime; string device = response.Device; string instanceId = response.InstanceId; string state = response.State; string volumeId = response.VolumeId; #endregion } public void EC2AuthorizeSecurityGroupEgress() { #region to-add-a-rule-that-allows-outbound-traffic-to-a-specific-address-range-1528929309636 var client = new AmazonEC2Client(); var response = client.AuthorizeSecurityGroupEgress(new AuthorizeSecurityGroupEgressRequest { GroupId = "sg-1a2b3c4d", IpPermissions = new List<IpPermission> { new IpPermission { FromPort = 80, IpProtocol = "tcp", ToPort = 80 } } }); #endregion } public void EC2AuthorizeSecurityGroupEgress() { #region to-add-a-rule-that-allows-outbound-traffic-to-a-specific-security-group-1528929760260 var client = new AmazonEC2Client(); var response = client.AuthorizeSecurityGroupEgress(new AuthorizeSecurityGroupEgressRequest { GroupId = "sg-1a2b3c4d", IpPermissions = new List<IpPermission> { new IpPermission { FromPort = 80, IpProtocol = "tcp", ToPort = 80, UserIdGroupPairs = new List<UserIdGroupPair> { new UserIdGroupPair { GroupId = "sg-4b51a32f" } } } } }); #endregion } public void EC2AuthorizeSecurityGroupIngress() { #region to-add-a-rule-that-allows-inbound-ssh-traffic-1529011610328 var client = new AmazonEC2Client(); var response = client.AuthorizeSecurityGroupIngress(new AuthorizeSecurityGroupIngressRequest { GroupId = "sg-903004f8", IpPermissions = new List<IpPermission> { new IpPermission { FromPort = 22, IpProtocol = "tcp", ToPort = 22 } } }); #endregion } public void EC2AuthorizeSecurityGroupIngress() { #region to-add-a-rule-that-allows-inbound-http-traffic-from-another-security-group-1529012163168 var client = new AmazonEC2Client(); var response = client.AuthorizeSecurityGroupIngress(new AuthorizeSecurityGroupIngressRequest { GroupId = "sg-111aaa22", IpPermissions = new List<IpPermission> { new IpPermission { FromPort = 80, IpProtocol = "tcp", ToPort = 80, UserIdGroupPairs = new List<UserIdGroupPair> { new UserIdGroupPair { Description = "HTTP access from other instances", GroupId = "sg-1a2b3c4d" } } } } }); #endregion } public void EC2AuthorizeSecurityGroupIngress() { #region to-add-a-rule-with-a-description-1529012418116 var client = new AmazonEC2Client(); var response = client.AuthorizeSecurityGroupIngress(new AuthorizeSecurityGroupIngressRequest { GroupId = "sg-123abc12 ", IpPermissions = new List<IpPermission> { new IpPermission { FromPort = 3389, IpProtocol = "tcp", Ipv6Ranges = new List<Ipv6Range> { new Ipv6Range { CidrIpv6 = "2001:db8:1234:1a00::/64", Description = "RDP access from the NY office" } }, ToPort = 3389 } } }); #endregion } public void EC2CancelSpotFleetRequests() { #region ec2-cancel-spot-fleet-requests-1 var client = new AmazonEC2Client(); var response = client.CancelSpotFleetRequests(new CancelSpotFleetRequestsRequest { SpotFleetRequestIds = new List<string> { "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE" }, TerminateInstances = true }); List<CancelSpotFleetRequestsSuccessItem> successfulFleetRequests = response.SuccessfulFleetRequests; #endregion } public void EC2CancelSpotFleetRequests() { #region ec2-cancel-spot-fleet-requests-2 var client = new AmazonEC2Client(); var response = client.CancelSpotFleetRequests(new CancelSpotFleetRequestsRequest { SpotFleetRequestIds = new List<string> { "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE" }, TerminateInstances = false }); List<CancelSpotFleetRequestsSuccessItem> successfulFleetRequests = response.SuccessfulFleetRequests; #endregion } public void EC2CancelSpotInstanceRequests() { #region ec2-cancel-spot-instance-requests-1 var client = new AmazonEC2Client(); var response = client.CancelSpotInstanceRequests(new CancelSpotInstanceRequestsRequest { SpotInstanceRequestIds = new List<string> { "sir-08b93456" } }); List<CancelledSpotInstanceRequest> cancelledSpotInstanceRequests = response.CancelledSpotInstanceRequests; #endregion } public void EC2ConfirmProductInstance() { #region to-confirm-the-product-instance-1472712108494 var client = new AmazonEC2Client(); var response = client.ConfirmProductInstance(new ConfirmProductInstanceRequest { InstanceId = "i-1234567890abcdef0", ProductCode = "774F4FF8" }); string ownerId = response.OwnerId; #endregion } public void EC2CopyImage() { #region to-copy-an-ami-to-another-region-1529022820832 var client = new AmazonEC2Client(); var response = client.CopyImage(new CopyImageRequest { Description = "", Name = "My server", SourceImageId = "ami-5731123e", SourceRegion = "us-east-1" }); string imageId = response.ImageId; #endregion } public void EC2CopySnapshot() { #region to-copy-a-snapshot-1472502259774 var client = new AmazonEC2Client(); var response = client.CopySnapshot(new CopySnapshotRequest { Description = "This is my copied snapshot.", DestinationRegion = "us-east-1", SourceRegion = "us-west-2", SourceSnapshotId = "snap-066877671789bd71b" }); string snapshotId = response.SnapshotId; #endregion } public void EC2CreateCustomerGateway() { #region ec2-create-customer-gateway-1 var client = new AmazonEC2Client(); var response = client.CreateCustomerGateway(new CreateCustomerGatewayRequest { BgpAsn = 65534, PublicIp = "12.1.2.3", Type = "ipsec.1" }); CustomerGateway customerGateway = response.CustomerGateway; #endregion } public void EC2CreateDhcpOptions() { #region ec2-create-dhcp-options-1 var client = new AmazonEC2Client(); var response = client.CreateDhcpOptions(new CreateDhcpOptionsRequest { DhcpConfigurations = new List<DhcpConfiguration> { new DhcpConfiguration { Key = "domain-name-servers", Values = new List<string> { "10.2.5.1", "10.2.5.2" } } } }); DhcpOptions dhcpOptions = response.DhcpOptions; #endregion } public void EC2CreateImage() { #region to-create-an-ami-from-an-amazon-ebs-backed-instance-1529023150636 var client = new AmazonEC2Client(); var response = client.CreateImage(new CreateImageRequest { BlockDeviceMappings = new List<BlockDeviceMapping> { new BlockDeviceMapping { DeviceName = "/dev/sdh", Ebs = new EbsBlockDevice { VolumeSize = 100 } }, new BlockDeviceMapping { DeviceName = "/dev/sdc", VirtualName = "ephemeral1" } }, Description = "An AMI for my server", InstanceId = "i-1234567890abcdef0", Name = "My server", NoReboot = true }); string imageId = response.ImageId; #endregion } public void EC2CreateInternetGateway() { #region ec2-create-internet-gateway-1 var client = new AmazonEC2Client(); var response = client.CreateInternetGateway(new CreateInternetGatewayRequest { }); InternetGateway internetGateway = response.InternetGateway; #endregion } public void EC2CreateKeyPair() { #region ec2-create-key-pair-1 var client = new AmazonEC2Client(); var response = client.CreateKeyPair(new CreateKeyPairRequest { KeyName = "my-key-pair" }); #endregion } public void EC2CreateLaunchTemplate() { #region to-create-a-launch-template-1529023655488 var client = new AmazonEC2Client(); var response = client.CreateLaunchTemplate(new CreateLaunchTemplateRequest { LaunchTemplateData = new RequestLaunchTemplateData { ImageId = "ami-8c1be5f6", InstanceType = "t2.small", NetworkInterfaces = new List<LaunchTemplateInstanceNetworkInterfaceSpecificationRequest> { new LaunchTemplateInstanceNetworkInterfaceSpecificationRequest { AssociatePublicIpAddress = true, DeviceIndex = 0, Ipv6AddressCount = 1, SubnetId = "subnet-7b16de0c" } }, TagSpecifications = new List<LaunchTemplateTagSpecificationRequest> { new LaunchTemplateTagSpecificationRequest { ResourceType = "instance", Tags = new List<Tag> { new Tag { Key = "Name", Value = "webserver" } } } } }, LaunchTemplateName = "my-template", VersionDescription = "WebVersion1" }); LaunchTemplate launchTemplate = response.LaunchTemplate; #endregion } public void EC2CreateLaunchTemplateVersion() { #region to-create-a-launch-template-version-1529024195702 var client = new AmazonEC2Client(); var response = client.CreateLaunchTemplateVersion(new CreateLaunchTemplateVersionRequest { LaunchTemplateData = new RequestLaunchTemplateData { ImageId = "ami-c998b6b2" }, LaunchTemplateId = "lt-0abcd290751193123", SourceVersion = "1", VersionDescription = "WebVersion2" }); LaunchTemplateVersion launchTemplateVersion = response.LaunchTemplateVersion; #endregion } public void EC2CreateNatGateway() { #region ec2-create-nat-gateway-1 var client = new AmazonEC2Client(); var response = client.CreateNatGateway(new CreateNatGatewayRequest { AllocationId = "eipalloc-37fc1a52", SubnetId = "subnet-1a2b3c4d" }); NatGateway natGateway = response.NatGateway; #endregion } public void EC2CreateNetworkAcl() { #region ec2-create-network-acl-1 var client = new AmazonEC2Client(); var response = client.CreateNetworkAcl(new CreateNetworkAclRequest { VpcId = "vpc-a01106c2" }); NetworkAcl networkAcl = response.NetworkAcl; #endregion } public void EC2CreateNetworkAclEntry() { #region ec2-create-network-acl-entry-1 var client = new AmazonEC2Client(); var response = client.CreateNetworkAclEntry(new CreateNetworkAclEntryRequest { CidrBlock = "0.0.0.0/0", Egress = false, NetworkAclId = "acl-5fb85d36", PortRange = new PortRange { From = 53, To = 53 }, Protocol = "17", RuleAction = "allow", RuleNumber = 100 }); #endregion } public void EC2CreateNetworkInterface() { #region ec2-create-network-interface-1 var client = new AmazonEC2Client(); var response = client.CreateNetworkInterface(new CreateNetworkInterfaceRequest { Description = "my network interface", Groups = new List<string> { "sg-903004f8" }, PrivateIpAddress = "10.0.2.17", SubnetId = "subnet-9d4a7b6c" }); NetworkInterface networkInterface = response.NetworkInterface; #endregion } public void EC2CreatePlacementGroup() { #region to-create-a-placement-group-1472712245768 var client = new AmazonEC2Client(); var response = client.CreatePlacementGroup(new CreatePlacementGroupRequest { GroupName = "my-cluster", Strategy = "cluster" }); #endregion } public void EC2CreateRoute() { #region ec2-create-route-1 var client = new AmazonEC2Client(); var response = client.CreateRoute(new CreateRouteRequest { DestinationCidrBlock = "0.0.0.0/0", GatewayId = "igw-c0a643a9", RouteTableId = "rtb-22574640" }); #endregion } public void EC2CreateRouteTable() { #region ec2-create-route-table-1 var client = new AmazonEC2Client(); var response = client.CreateRouteTable(new CreateRouteTableRequest { VpcId = "vpc-a01106c2" }); RouteTable routeTable = response.RouteTable; #endregion } public void EC2CreateSecurityGroup() { #region to-create-a-security-group-for-a-vpc-1529024532716 var client = new AmazonEC2Client(); var response = client.CreateSecurityGroup(new CreateSecurityGroupRequest { Description = "My security group", GroupName = "my-security-group", VpcId = "vpc-1a2b3c4d" }); string groupId = response.GroupId; #endregion } public void EC2CreateSnapshot() { #region to-create-a-snapshot-1472502529790 var client = new AmazonEC2Client(); var response = client.CreateSnapshot(new CreateSnapshotRequest { Description = "This is my root volume snapshot.", VolumeId = "vol-1234567890abcdef0" }); string description = response.Description; string ownerId = response.OwnerId; string snapshotId = response.SnapshotId; DateTime startTime = response.StartTime; string state = response.State; List<Tag> tags = response.Tags; string volumeId = response.VolumeId; int volumeSize = response.VolumeSize; #endregion } public void EC2CreateSpotDatafeedSubscription() { #region ec2-create-spot-datafeed-subscription-1 var client = new AmazonEC2Client(); var response = client.CreateSpotDatafeedSubscription(new CreateSpotDatafeedSubscriptionRequest { Bucket = "my-s3-bucket", Prefix = "spotdata" }); SpotDatafeedSubscription spotDatafeedSubscription = response.SpotDatafeedSubscription; #endregion } public void EC2CreateSubnet() { #region ec2-create-subnet-1 var client = new AmazonEC2Client(); var response = client.CreateSubnet(new CreateSubnetRequest { CidrBlock = "10.0.1.0/24", VpcId = "vpc-a01106c2" }); Subnet subnet = response.Subnet; #endregion } public void EC2CreateTags() { #region ec2-create-tags-1 var client = new AmazonEC2Client(); var response = client.CreateTags(new CreateTagsRequest { Resources = new List<string> { "ami-78a54011" }, Tags = new List<Tag> { new Tag { Key = "Stack", Value = "production" } } }); #endregion } public void EC2CreateVolume() { #region to-create-a-new-volume-1472496724296 var client = new AmazonEC2Client(); var response = client.CreateVolume(new CreateVolumeRequest { AvailabilityZone = "us-east-1a", Size = 80, VolumeType = "gp2" }); string availabilityZone = response.AvailabilityZone; DateTime createTime = response.CreateTime; bool encrypted = response.Encrypted; int iops = response.Iops; int size = response.Size; string snapshotId = response.SnapshotId; string state = response.State; string volumeId = response.VolumeId; string volumeType = response.VolumeType; #endregion } public void EC2CreateVolume() { #region to-create-a-new-provisioned-iops-ssd-volume-from-a-snapshot-1472498975176 var client = new AmazonEC2Client(); var response = client.CreateVolume(new CreateVolumeRequest { AvailabilityZone = "us-east-1a", Iops = 1000, SnapshotId = "snap-066877671789bd71b", VolumeType = "io1" }); List<VolumeAttachment> attachments = response.Attachments; string availabilityZone = response.AvailabilityZone; DateTime createTime = response.CreateTime; int iops = response.Iops; int size = response.Size; string snapshotId = response.SnapshotId; string state = response.State; List<Tag> tags = response.Tags; string volumeId = response.VolumeId; string volumeType = response.VolumeType; #endregion } public void EC2CreateVpc() { #region ec2-create-vpc-1 var client = new AmazonEC2Client(); var response = client.CreateVpc(new CreateVpcRequest { CidrBlock = "10.0.0.0/16" }); Vpc vpc = response.Vpc; #endregion } public void EC2DeleteCustomerGateway() { #region ec2-delete-customer-gateway-1 var client = new AmazonEC2Client(); var response = client.DeleteCustomerGateway(new DeleteCustomerGatewayRequest { CustomerGatewayId = "cgw-0e11f167" }); #endregion } public void EC2DeleteDhcpOptions() { #region ec2-delete-dhcp-options-1 var client = new AmazonEC2Client(); var response = client.DeleteDhcpOptions(new DeleteDhcpOptionsRequest { DhcpOptionsId = "dopt-d9070ebb" }); #endregion } public void EC2DeleteInternetGateway() { #region ec2-delete-internet-gateway-1 var client = new AmazonEC2Client(); var response = client.DeleteInternetGateway(new DeleteInternetGatewayRequest { InternetGatewayId = "igw-c0a643a9" }); #endregion } public void EC2DeleteKeyPair() { #region ec2-delete-key-pair-1 var client = new AmazonEC2Client(); var response = client.DeleteKeyPair(new DeleteKeyPairRequest { KeyName = "my-key-pair" }); #endregion } public void EC2DeleteLaunchTemplate() { #region to-delete-a-launch-template-1529024658216 var client = new AmazonEC2Client(); var response = client.DeleteLaunchTemplate(new DeleteLaunchTemplateRequest { LaunchTemplateId = "lt-0abcd290751193123" }); LaunchTemplate launchTemplate = response.LaunchTemplate; #endregion } public void EC2DeleteLaunchTemplateVersions() { #region to-delete-a-launch-template-version-1529024790864 var client = new AmazonEC2Client(); var response = client.DeleteLaunchTemplateVersions(new DeleteLaunchTemplateVersionsRequest { LaunchTemplateId = "lt-0abcd290751193123", Versions = new List<string> { "1" } }); List<DeleteLaunchTemplateVersionsResponseSuccessItem> successfullyDeletedLaunchTemplateVersions = response.SuccessfullyDeletedLaunchTemplateVersions; List<DeleteLaunchTemplateVersionsResponseErrorItem> unsuccessfullyDeletedLaunchTemplateVersions = response.UnsuccessfullyDeletedLaunchTemplateVersions; #endregion } public void EC2DeleteNatGateway() { #region ec2-delete-nat-gateway-1 var client = new AmazonEC2Client(); var response = client.DeleteNatGateway(new DeleteNatGatewayRequest { NatGatewayId = "nat-04ae55e711cec5680" }); string natGatewayId = response.NatGatewayId; #endregion } public void EC2DeleteNetworkAcl() { #region ec2-delete-network-acl-1 var client = new AmazonEC2Client(); var response = client.DeleteNetworkAcl(new DeleteNetworkAclRequest { NetworkAclId = "acl-5fb85d36" }); #endregion } public void EC2DeleteNetworkAclEntry() { #region ec2-delete-network-acl-entry-1 var client = new AmazonEC2Client(); var response = client.DeleteNetworkAclEntry(new DeleteNetworkAclEntryRequest { Egress = true, NetworkAclId = "acl-5fb85d36", RuleNumber = 100 }); #endregion } public void EC2DeleteNetworkInterface() { #region ec2-delete-network-interface-1 var client = new AmazonEC2Client(); var response = client.DeleteNetworkInterface(new DeleteNetworkInterfaceRequest { NetworkInterfaceId = "eni-e5aa89a3" }); #endregion } public void EC2DeletePlacementGroup() { #region to-delete-a-placement-group-1472712349959 var client = new AmazonEC2Client(); var response = client.DeletePlacementGroup(new DeletePlacementGroupRequest { GroupName = "my-cluster" }); #endregion } public void EC2DeleteRoute() { #region ec2-delete-route-1 var client = new AmazonEC2Client(); var response = client.DeleteRoute(new DeleteRouteRequest { DestinationCidrBlock = "0.0.0.0/0", RouteTableId = "rtb-22574640" }); #endregion } public void EC2DeleteRouteTable() { #region ec2-delete-route-table-1 var client = new AmazonEC2Client(); var response = client.DeleteRouteTable(new DeleteRouteTableRequest { RouteTableId = "rtb-22574640" }); #endregion } public void EC2DeleteSecurityGroup() { #region to-delete-a-security-group-1529024952972 var client = new AmazonEC2Client(); var response = client.DeleteSecurityGroup(new DeleteSecurityGroupRequest { GroupId = "sg-903004f8" }); #endregion } public void EC2DeleteSnapshot() { #region to-delete-a-snapshot-1472503042567 var client = new AmazonEC2Client(); var response = client.DeleteSnapshot(new DeleteSnapshotRequest { SnapshotId = "snap-1234567890abcdef0" }); #endregion } public void EC2DeleteSpotDatafeedSubscription() { #region ec2-delete-spot-datafeed-subscription-1 var client = new AmazonEC2Client(); var response = client.DeleteSpotDatafeedSubscription(new DeleteSpotDatafeedSubscriptionRequest { }); #endregion } public void EC2DeleteSubnet() { #region ec2-delete-subnet-1 var client = new AmazonEC2Client(); var response = client.DeleteSubnet(new DeleteSubnetRequest { SubnetId = "subnet-9d4a7b6c" }); #endregion } public void EC2DeleteTags() { #region ec2-delete-tags-1 var client = new AmazonEC2Client(); var response = client.DeleteTags(new DeleteTagsRequest { Resources = new List<string> { "ami-78a54011" }, Tags = new List<Tag> { new Tag { Key = "Stack", Value = "test" } } }); #endregion } public void EC2DeleteVolume() { #region to-delete-a-volume-1472503111160 var client = new AmazonEC2Client(); var response = client.DeleteVolume(new DeleteVolumeRequest { VolumeId = "vol-049df61146c4d7901" }); #endregion } public void EC2DeleteVpc() { #region ec2-delete-vpc-1 var client = new AmazonEC2Client(); var response = client.DeleteVpc(new DeleteVpcRequest { VpcId = "vpc-a01106c2" }); #endregion } public void EC2DescribeAccountAttributes() { #region ec2-describe-account-attributes-1 var client = new AmazonEC2Client(); var response = client.DescribeAccountAttributes(new DescribeAccountAttributesRequest { AttributeNames = new List<string> { "supported-platforms" } }); List<AccountAttribute> accountAttributes = response.AccountAttributes; #endregion } public void EC2DescribeAccountAttributes() { #region ec2-describe-account-attributes-2 var client = new AmazonEC2Client(); var response = client.DescribeAccountAttributes(new DescribeAccountAttributesRequest { }); List<AccountAttribute> accountAttributes = response.AccountAttributes; #endregion } public void EC2DescribeAddresses() { #region ec2-describe-addresses-1 var client = new AmazonEC2Client(); var response = client.DescribeAddresses(new DescribeAddressesRequest { }); List<Address> addresses = response.Addresses; #endregion } public void EC2DescribeAvailabilityZones() { #region ec2-describe-availability-zones-1 var client = new AmazonEC2Client(); var response = client.DescribeAvailabilityZones(new DescribeAvailabilityZonesRequest { }); List<AvailabilityZone> availabilityZones = response.AvailabilityZones; #endregion } public void EC2DescribeCustomerGateways() { #region ec2-describe-customer-gateways-1 var client = new AmazonEC2Client(); var response = client.DescribeCustomerGateways(new DescribeCustomerGatewaysRequest { CustomerGatewayIds = new List<string> { "cgw-0e11f167" } }); List<CustomerGateway> customerGateways = response.CustomerGateways; #endregion } public void EC2DescribeDhcpOptions() { #region ec2-describe-dhcp-options-1 var client = new AmazonEC2Client(); var response = client.DescribeDhcpOptions(new DescribeDhcpOptionsRequest { DhcpOptionsIds = new List<string> { "dopt-d9070ebb" } }); List<DhcpOptions> dhcpOptions = response.DhcpOptions; #endregion } public void EC2DescribeIamInstanceProfileAssociations() { #region to-describe-an-iam-instance-profile-association-1529025123918 var client = new AmazonEC2Client(); var response = client.DescribeIamInstanceProfileAssociations(new DescribeIamInstanceProfileAssociationsRequest { AssociationIds = new List<string> { "iip-assoc-0db249b1f25fa24b8" } }); List<IamInstanceProfileAssociation> iamInstanceProfileAssociations = response.IamInstanceProfileAssociations; #endregion } public void EC2DescribeImageAttribute() { #region to-describe-the-launch-permissions-for-an-ami-1529025296264 var client = new AmazonEC2Client(); var response = client.DescribeImageAttribute(new DescribeImageAttributeRequest { Attribute = "launchPermission", ImageId = "ami-5731123e" }); string imageId = response.ImageId; List<LaunchPermission> launchPermissions = response.LaunchPermissions; #endregion } public void EC2DescribeImages() { #region to-describe-an-ami-1529025482866 var client = new AmazonEC2Client(); var response = client.DescribeImages(new DescribeImagesRequest { ImageIds = new List<string> { "ami-5731123e" } }); List<Image> images = response.Images; #endregion } public void EC2DescribeInstanceAttribute() { #region to-describe-the-instance-type-1472712432132 var client = new AmazonEC2Client(); var response = client.DescribeInstanceAttribute(new DescribeInstanceAttributeRequest { Attribute = "instanceType", InstanceId = "i-1234567890abcdef0" }); string instanceId = response.InstanceId; string instanceType = response.InstanceType; #endregion } public void EC2DescribeInstanceAttribute() { #region to-describe-the-disableapitermination-attribute-1472712533466 var client = new AmazonEC2Client(); var response = client.DescribeInstanceAttribute(new DescribeInstanceAttributeRequest { Attribute = "disableApiTermination", InstanceId = "i-1234567890abcdef0" }); bool disableApiTermination = response.DisableApiTermination; string instanceId = response.InstanceId; #endregion } public void EC2DescribeInstanceAttribute() { #region to-describe-the-block-device-mapping-for-an-instance-1472712645423 var client = new AmazonEC2Client(); var response = client.DescribeInstanceAttribute(new DescribeInstanceAttributeRequest { Attribute = "blockDeviceMapping", InstanceId = "i-1234567890abcdef0" }); List<InstanceBlockDeviceMapping> blockDeviceMappings = response.BlockDeviceMappings; string instanceId = response.InstanceId; #endregion } public void EC2DescribeInstances() { #region to-describe-an-amazon-ec2-instance-1529025982172 var client = new AmazonEC2Client(); var response = client.DescribeInstances(new DescribeInstancesRequest { InstanceIds = new List<string> { "i-1234567890abcdef0" } }); #endregion } public void EC2DescribeInstances() { #region to-describe-the-instances-with-the-instance-type-t2micro-1529026147602 var client = new AmazonEC2Client(); var response = client.DescribeInstances(new DescribeInstancesRequest { Filters = new List<Filter> { new Filter { Name = "instance-type", Values = new List<string> { "t2.micro" } } } }); #endregion } public void EC2DescribeInstances() { #region to-describe-the-instances-with-a-specific-tag-1529026251928 var client = new AmazonEC2Client(); var response = client.DescribeInstances(new DescribeInstancesRequest { Filters = new List<Filter> { new Filter { Name = "tag:Purpose", Values = new List<string> { "test" } } } }); #endregion } public void EC2DescribeInstanceStatus() { #region to-describe-the-status-of-an-instance-1529025696830 var client = new AmazonEC2Client(); var response = client.DescribeInstanceStatus(new DescribeInstanceStatusRequest { InstanceIds = new List<string> { "i-1234567890abcdef0" } }); List<InstanceStatus> instanceStatuses = response.InstanceStatuses; #endregion } public void EC2DescribeInternetGateways() { #region ec2-describe-internet-gateways-1 var client = new AmazonEC2Client(); var response = client.DescribeInternetGateways(new DescribeInternetGatewaysRequest { Filters = new List<Filter> { new Filter { Name = "attachment.vpc-id", Values = new List<string> { "vpc-a01106c2" } } } }); List<InternetGateway> internetGateways = response.InternetGateways; #endregion } public void EC2DescribeKeyPairs() { #region ec2-describe-key-pairs-1 var client = new AmazonEC2Client(); var response = client.DescribeKeyPairs(new DescribeKeyPairsRequest { KeyNames = new List<string> { "my-key-pair" } }); List<KeyPairInfo> keyPairs = response.KeyPairs; #endregion } public void EC2DescribeLaunchTemplates() { #region to-describe-a-launch-template-1529344182862 var client = new AmazonEC2Client(); var response = client.DescribeLaunchTemplates(new DescribeLaunchTemplatesRequest { LaunchTemplateIds = new List<string> { "lt-01238c059e3466abc" } }); List<LaunchTemplate> launchTemplates = response.LaunchTemplates; #endregion } public void EC2DescribeLaunchTemplateVersions() { #region to-describe-the-versions-for-a-launch-template-1529344425048 var client = new AmazonEC2Client(); var response = client.DescribeLaunchTemplateVersions(new DescribeLaunchTemplateVersionsRequest { LaunchTemplateId = "068f72b72934aff71" }); List<LaunchTemplateVersion> launchTemplateVersions = response.LaunchTemplateVersions; #endregion } public void EC2DescribeMovingAddresses() { #region ec2-describe-moving-addresses-1 var client = new AmazonEC2Client(); var response = client.DescribeMovingAddresses(new DescribeMovingAddressesRequest { }); List<MovingAddressStatus> movingAddressStatuses = response.MovingAddressStatuses; #endregion } public void EC2DescribeNatGateways() { #region ec2-describe-nat-gateways-1 var client = new AmazonEC2Client(); var response = client.DescribeNatGateways(new DescribeNatGatewaysRequest { Filter = new List<Filter> { new Filter { Name = "vpc-id", Values = new List<string> { "vpc-1a2b3c4d" } } } }); List<NatGateway> natGateways = response.NatGateways; #endregion } public void EC2DescribeNetworkAcls() { #region ec2- var client = new AmazonEC2Client(); var response = client.DescribeNetworkAcls(new DescribeNetworkAclsRequest { NetworkAclIds = new List<string> { "acl-5fb85d36" } }); List<NetworkAcl> networkAcls = response.NetworkAcls; #endregion } public void EC2DescribeNetworkInterfaceAttribute() { #region ec2-describe-network-interface-attribute-1 var client = new AmazonEC2Client(); var response = client.DescribeNetworkInterfaceAttribute(new DescribeNetworkInterfaceAttributeRequest { Attribute = "attachment", NetworkInterfaceId = "eni-686ea200" }); NetworkInterfaceAttachment attachment = response.Attachment; string networkInterfaceId = response.NetworkInterfaceId; #endregion } public void EC2DescribeNetworkInterfaceAttribute() { #region ec2-describe-network-interface-attribute-2 var client = new AmazonEC2Client(); var response = client.DescribeNetworkInterfaceAttribute(new DescribeNetworkInterfaceAttributeRequest { Attribute = "description", NetworkInterfaceId = "eni-686ea200" }); string description = response.Description; string networkInterfaceId = response.NetworkInterfaceId; #endregion } public void EC2DescribeNetworkInterfaceAttribute() { #region ec2-describe-network-interface-attribute-3 var client = new AmazonEC2Client(); var response = client.DescribeNetworkInterfaceAttribute(new DescribeNetworkInterfaceAttributeRequest { Attribute = "groupSet", NetworkInterfaceId = "eni-686ea200" }); List<GroupIdentifier> groups = response.Groups; string networkInterfaceId = response.NetworkInterfaceId; #endregion } public void EC2DescribeNetworkInterfaceAttribute() { #region ec2-describe-network-interface-attribute-4 var client = new AmazonEC2Client(); var response = client.DescribeNetworkInterfaceAttribute(new DescribeNetworkInterfaceAttributeRequest { Attribute = "sourceDestCheck", NetworkInterfaceId = "eni-686ea200" }); string networkInterfaceId = response.NetworkInterfaceId; bool sourceDestCheck = response.SourceDestCheck; #endregion } public void EC2DescribeNetworkInterfaces() { #region ec2-describe-network-interfaces-1 var client = new AmazonEC2Client(); var response = client.DescribeNetworkInterfaces(new DescribeNetworkInterfacesRequest { NetworkInterfaceIds = new List<string> { "eni-e5aa89a3" } }); List<NetworkInterface> networkInterfaces = response.NetworkInterfaces; #endregion } public void EC2DescribeRegions() { #region ec2-describe-regions-1 var client = new AmazonEC2Client(); var response = client.DescribeRegions(new DescribeRegionsRequest { }); List<Region> regions = response.Regions; #endregion } public void EC2DescribeRouteTables() { #region ec2-describe-route-tables-1 var client = new AmazonEC2Client(); var response = client.DescribeRouteTables(new DescribeRouteTablesRequest { RouteTableIds = new List<string> { "rtb-1f382e7d" } }); List<RouteTable> routeTables = response.RouteTables; #endregion } public void EC2DescribeSecurityGroupReferences() { #region to-describe-security-group-references-1529354312088 var client = new AmazonEC2Client(); var response = client.DescribeSecurityGroupReferences(new DescribeSecurityGroupReferencesRequest { GroupId = new List<string> { "sg-903004f8" } }); List<SecurityGroupReference> securityGroupReferenceSet = response.SecurityGroupReferenceSet; #endregion } public void EC2DescribeSecurityGroups() { #region to-describe-a-security-group-1529354426314 var client = new AmazonEC2Client(); var response = client.DescribeSecurityGroups(new DescribeSecurityGroupsRequest { GroupIds = new List<string> { "sg-903004f8" } }); #endregion } public void EC2DescribeSecurityGroups() { #region to-describe-a-tagged-security-group-1529354553880 var client = new AmazonEC2Client(); var response = client.DescribeSecurityGroups(new DescribeSecurityGroupsRequest { Filters = new List<Filter> { new Filter { Name = "tag:Purpose", Values = new List<string> { "test" } } } }); #endregion } public void EC2DescribeSnapshotAttribute() { #region to-describe-snapshot-attributes-1472503199736 var client = new AmazonEC2Client(); var response = client.DescribeSnapshotAttribute(new DescribeSnapshotAttributeRequest { Attribute = "createVolumePermission", SnapshotId = "snap-066877671789bd71b" }); List<CreateVolumePermission> createVolumePermissions = response.CreateVolumePermissions; string snapshotId = response.SnapshotId; #endregion } public void EC2DescribeSnapshots() { #region to-describe-a-snapshot-1472503807850 var client = new AmazonEC2Client(); var response = client.DescribeSnapshots(new DescribeSnapshotsRequest { SnapshotIds = new List<string> { "snap-1234567890abcdef0" } }); string nextToken = response.NextToken; List<Snapshot> snapshots = response.Snapshots; #endregion } public void EC2DescribeSnapshots() { #region to-describe-snapshots-using-filters-1472503929793 var client = new AmazonEC2Client(); var response = client.DescribeSnapshots(new DescribeSnapshotsRequest { Filters = new List<Filter> { new Filter { Name = "status", Values = new List<string> { "pending" } } }, OwnerIds = new List<string> { "012345678910" } }); string nextToken = response.NextToken; List<Snapshot> snapshots = response.Snapshots; #endregion } public void EC2DescribeSpotDatafeedSubscription() { #region ec2-describe-spot-datafeed-subscription-1 var client = new AmazonEC2Client(); var response = client.DescribeSpotDatafeedSubscription(new DescribeSpotDatafeedSubscriptionRequest { }); SpotDatafeedSubscription spotDatafeedSubscription = response.SpotDatafeedSubscription; #endregion } public void EC2DescribeSpotFleetInstances() { #region ec2-describe-spot-fleet-instances-1 var client = new AmazonEC2Client(); var response = client.DescribeSpotFleetInstances(new DescribeSpotFleetInstancesRequest { SpotFleetRequestId = "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE" }); List<ActiveInstance> activeInstances = response.ActiveInstances; string spotFleetRequestId = response.SpotFleetRequestId; #endregion } public void EC2DescribeSpotFleetRequestHistory() { #region ec2-describe-spot-fleet-request-history-1 var client = new AmazonEC2Client(); var response = client.DescribeSpotFleetRequestHistory(new DescribeSpotFleetRequestHistoryRequest { SpotFleetRequestId = "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE", StartTimeUtc = new DateTime(2015, 5, 25, 5, 0, 0, DateTimeKind.Utc) }); List<HistoryRecord> historyRecords = response.HistoryRecords; string nextToken = response.NextToken; string spotFleetRequestId = response.SpotFleetRequestId; DateTime startTime = response.StartTime; #endregion } public void EC2DescribeSpotFleetRequests() { #region ec2-describe-spot-fleet-requests-1 var client = new AmazonEC2Client(); var response = client.DescribeSpotFleetRequests(new DescribeSpotFleetRequestsRequest { SpotFleetRequestIds = new List<string> { "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE" } }); List<SpotFleetRequestConfig> spotFleetRequestConfigs = response.SpotFleetRequestConfigs; #endregion } public void EC2DescribeSpotInstanceRequests() { #region ec2-describe-spot-instance-requests-1 var client = new AmazonEC2Client(); var response = client.DescribeSpotInstanceRequests(new DescribeSpotInstanceRequestsRequest { SpotInstanceRequestIds = new List<string> { "sir-08b93456" } }); List<SpotInstanceRequest> spotInstanceRequests = response.SpotInstanceRequests; #endregion } public void EC2DescribeSpotPriceHistory() { #region ec2-describe-spot-price-history-1 var client = new AmazonEC2Client(); var response = client.DescribeSpotPriceHistory(new DescribeSpotPriceHistoryRequest { EndTimeUtc = new DateTime(2014, 1, 6, 12, 9, 10, DateTimeKind.Utc), InstanceTypes = new List<string> { "m1.xlarge" }, ProductDescriptions = new List<string> { "Linux/UNIX (Amazon VPC)" }, StartTimeUtc = new DateTime(2014, 1, 5, 11, 8, 9, DateTimeKind.Utc) }); List<SpotPrice> spotPriceHistory = response.SpotPriceHistory; #endregion } public void EC2DescribeSubnets() { #region ec2-describe-subnets-1 var client = new AmazonEC2Client(); var response = client.DescribeSubnets(new DescribeSubnetsRequest { Filters = new List<Filter> { new Filter { Name = "vpc-id", Values = new List<string> { "vpc-a01106c2" } } } }); List<Subnet> subnets = response.Subnets; #endregion } public void EC2DescribeTags() { #region ec2-describe-tags-1 var client = new AmazonEC2Client(); var response = client.DescribeTags(new DescribeTagsRequest { Filters = new List<Filter> { new Filter { Name = "resource-id", Values = new List<string> { "i-1234567890abcdef8" } } } }); List<TagDescription> tags = response.Tags; #endregion } public void EC2DescribeVolumeAttribute() { #region to-describe-a-volume-attribute-1472505773492 var client = new AmazonEC2Client(); var response = client.DescribeVolumeAttribute(new DescribeVolumeAttributeRequest { Attribute = "autoEnableIO", VolumeId = "vol-049df61146c4d7901" }); bool autoEnableIO = response.AutoEnableIO; string volumeId = response.VolumeId; #endregion } public void EC2DescribeVolumes() { #region to-describe-all-volumes-1472506358883 var client = new AmazonEC2Client(); var response = client.DescribeVolumes(new DescribeVolumesRequest { }); string nextToken = response.NextToken; List<Volume> volumes = response.Volumes; #endregion } public void EC2DescribeVolumes() { #region to-describe-volumes-that-are-attached-to-a-specific-instance-1472506613578 var client = new AmazonEC2Client(); var response = client.DescribeVolumes(new DescribeVolumesRequest { Filters = new List<Filter> { new Filter { Name = "attachment.instance-id", Values = new List<string> { "i-1234567890abcdef0" } }, new Filter { Name = "attachment.delete-on-termination", Values = new List<string> { "true" } } } }); List<Volume> volumes = response.Volumes; #endregion } public void EC2DescribeVolumeStatus() { #region to-describe-the-status-of-a-single-volume-1472507016193 var client = new AmazonEC2Client(); var response = client.DescribeVolumeStatus(new DescribeVolumeStatusRequest { VolumeIds = new List<string> { "vol-1234567890abcdef0" } }); List<VolumeStatusItem> volumeStatuses = response.VolumeStatuses; #endregion } public void EC2DescribeVolumeStatus() { #region to-describe-the-status-of-impaired-volumes-1472507239821 var client = new AmazonEC2Client(); var response = client.DescribeVolumeStatus(new DescribeVolumeStatusRequest { Filters = new List<Filter> { new Filter { Name = "volume-status.status", Values = new List<string> { "impaired" } } } }); List<VolumeStatusItem> volumeStatuses = response.VolumeStatuses; #endregion } public void EC2DescribeVpcAttribute() { #region ec2-describe-vpc-attribute-1 var client = new AmazonEC2Client(); var response = client.DescribeVpcAttribute(new DescribeVpcAttributeRequest { Attribute = "enableDnsSupport", VpcId = "vpc-a01106c2" }); bool enableDnsSupport = response.EnableDnsSupport; string vpcId = response.VpcId; #endregion } public void EC2DescribeVpcAttribute() { #region ec2-describe-vpc-attribute-2 var client = new AmazonEC2Client(); var response = client.DescribeVpcAttribute(new DescribeVpcAttributeRequest { Attribute = "enableDnsHostnames", VpcId = "vpc-a01106c2" }); bool enableDnsHostnames = response.EnableDnsHostnames; string vpcId = response.VpcId; #endregion } public void EC2DescribeVpcs() { #region ec2-describe-vpcs-1 var client = new AmazonEC2Client(); var response = client.DescribeVpcs(new DescribeVpcsRequest { VpcIds = new List<string> { "vpc-a01106c2" } }); List<Vpc> vpcs = response.Vpcs; #endregion } public void EC2DetachInternetGateway() { #region ec2-detach-internet-gateway-1 var client = new AmazonEC2Client(); var response = client.DetachInternetGateway(new DetachInternetGatewayRequest { InternetGatewayId = "igw-c0a643a9", VpcId = "vpc-a01106c2" }); #endregion } public void EC2DetachNetworkInterface() { #region ec2-detach-network-interface-1 var client = new AmazonEC2Client(); var response = client.DetachNetworkInterface(new DetachNetworkInterfaceRequest { AttachmentId = "eni-attach-66c4350a" }); #endregion } public void EC2DetachVolume() { #region to-detach-a-volume-from-an-instance-1472507977694 var client = new AmazonEC2Client(); var response = client.DetachVolume(new DetachVolumeRequest { VolumeId = "vol-1234567890abcdef0" }); DateTime attachTime = response.AttachTime; string device = response.Device; string instanceId = response.InstanceId; string state = response.State; string volumeId = response.VolumeId; #endregion } public void EC2DisableVgwRoutePropagation() { #region ec2-disable-vgw-route-propagation-1 var client = new AmazonEC2Client(); var response = client.DisableVgwRoutePropagation(new DisableVgwRoutePropagationRequest { GatewayId = "vgw-9a4cacf3", RouteTableId = "rtb-22574640" }); #endregion } public void EC2DisassociateAddress() { #region ec2-disassociate-address-1 var client = new AmazonEC2Client(); var response = client.DisassociateAddress(new DisassociateAddressRequest { AssociationId = "eipassoc-2bebb745" }); #endregion } public void EC2DisassociateIamInstanceProfile() { #region to-disassociate-an-iam-instance-profile-1529355364478 var client = new AmazonEC2Client(); var response = client.DisassociateIamInstanceProfile(new DisassociateIamInstanceProfileRequest { AssociationId = "iip-assoc-05020b59952902f5f" }); IamInstanceProfileAssociation iamInstanceProfileAssociation = response.IamInstanceProfileAssociation; #endregion } public void EC2DisassociateRouteTable() { #region ec2-disassociate-route-table-1 var client = new AmazonEC2Client(); var response = client.DisassociateRouteTable(new DisassociateRouteTableRequest { AssociationId = "rtbassoc-781d0d1a" }); #endregion } public void EC2EnableVgwRoutePropagation() { #region ec2-enable-vgw-route-propagation-1 var client = new AmazonEC2Client(); var response = client.EnableVgwRoutePropagation(new EnableVgwRoutePropagationRequest { GatewayId = "vgw-9a4cacf3", RouteTableId = "rtb-22574640" }); #endregion } public void EC2EnableVolumeIO() { #region to-enable-io-for-a-volume-1472508114867 var client = new AmazonEC2Client(); var response = client.EnableVolumeIO(new EnableVolumeIORequest { VolumeId = "vol-1234567890abcdef0" }); #endregion } public void EC2GetConsoleOutput() { #region to-get-the-console-output-1529355683194 var client = new AmazonEC2Client(); var response = client.GetConsoleOutput(new GetConsoleOutputRequest { InstanceId = "i-1234567890abcdef0" }); string instanceId = response.InstanceId; string output = response.Output; DateTime timestamp = response.Timestamp; #endregion } public void EC2GetLaunchTemplateData() { #region to-get-the-launch-template-data-for-an-instance--1529356515702 var client = new AmazonEC2Client(); var response = client.GetLaunchTemplateData(new GetLaunchTemplateDataRequest { InstanceId = "0123d646e8048babc" }); ResponseLaunchTemplateData launchTemplateData = response.LaunchTemplateData; #endregion } public void EC2ModifyImageAttribute() { #region to-make-an-ami-public-1529357395278 var client = new AmazonEC2Client(); var response = client.ModifyImageAttribute(new ModifyImageAttributeRequest { ImageId = "ami-5731123e", LaunchPermission = new LaunchPermissionModifications { Add = new List<LaunchPermission> { new LaunchPermission { Group = "all" } } } }); #endregion } public void EC2ModifyImageAttribute() { #region to-grant-launch-permissions-1529357727906 var client = new AmazonEC2Client(); var response = client.ModifyImageAttribute(new ModifyImageAttributeRequest { ImageId = "ami-5731123e", LaunchPermission = new LaunchPermissionModifications { Add = new List<LaunchPermission> { new LaunchPermission { UserId = "123456789012" } } } }); #endregion } public void EC2ModifyInstanceAttribute() { #region to-modify-the-instance-type-1529357844378 var client = new AmazonEC2Client(); var response = client.ModifyInstanceAttribute(new ModifyInstanceAttributeRequest { InstanceId = "i-1234567890abcdef0", InstanceType = <data> }); #endregion } public void EC2ModifyInstanceAttribute() { #region to-enable-enhanced-networking-1529358279870 var client = new AmazonEC2Client(); var response = client.ModifyInstanceAttribute(new ModifyInstanceAttributeRequest { EnaSupport = jsondata object, InstanceId = "i-1234567890abcdef0" }); #endregion } public void EC2ModifyLaunchTemplate() { #region to-change-the-default-version-of-a-launch-template-1529358440364 var client = new AmazonEC2Client(); var response = client.ModifyLaunchTemplate(new ModifyLaunchTemplateRequest { DefaultVersion = "2", LaunchTemplateId = "lt-0abcd290751193123" }); LaunchTemplate launchTemplate = response.LaunchTemplate; #endregion } public void EC2ModifyNetworkInterfaceAttribute() { #region ec2-modify-network-interface-attribute-1 var client = new AmazonEC2Client(); var response = client.ModifyNetworkInterfaceAttribute(new ModifyNetworkInterfaceAttributeRequest { Attachment = new NetworkInterfaceAttachmentChanges { AttachmentId = "eni-attach-43348162", DeleteOnTermination = false }, NetworkInterfaceId = "eni-686ea200" }); #endregion } public void EC2ModifyNetworkInterfaceAttribute() { #region ec2-modify-network-interface-attribute-2 var client = new AmazonEC2Client(); var response = client.ModifyNetworkInterfaceAttribute(new ModifyNetworkInterfaceAttributeRequest { Description = <data>, NetworkInterfaceId = "eni-686ea200" }); #endregion } public void EC2ModifyNetworkInterfaceAttribute() { #region ec2-modify-network-interface-attribute-3 var client = new AmazonEC2Client(); var response = client.ModifyNetworkInterfaceAttribute(new ModifyNetworkInterfaceAttributeRequest { Groups = new List<string> { "sg-903004f8", "sg-1a2b3c4d" }, NetworkInterfaceId = "eni-686ea200" }); #endregion } public void EC2ModifyNetworkInterfaceAttribute() { #region ec2-modify-network-interface-attribute-4 var client = new AmazonEC2Client(); var response = client.ModifyNetworkInterfaceAttribute(new ModifyNetworkInterfaceAttributeRequest { NetworkInterfaceId = "eni-686ea200", SourceDestCheck = jsondata object }); #endregion } public void EC2ModifySnapshotAttribute() { #region to-modify-a-snapshot-attribute-1472508385907 var client = new AmazonEC2Client(); var response = client.ModifySnapshotAttribute(new ModifySnapshotAttributeRequest { Attribute = "createVolumePermission", OperationType = "remove", SnapshotId = "snap-1234567890abcdef0", UserIds = new List<string> { "123456789012" } }); #endregion } public void EC2ModifySnapshotAttribute() { #region to-make-a-snapshot-public-1472508470529 var client = new AmazonEC2Client(); var response = client.ModifySnapshotAttribute(new ModifySnapshotAttributeRequest { Attribute = "createVolumePermission", GroupNames = new List<string> { "all" }, OperationType = "add", SnapshotId = "snap-1234567890abcdef0" }); #endregion } public void EC2ModifySpotFleetRequest() { #region ec2-modify-spot-fleet-request-1 var client = new AmazonEC2Client(); var response = client.ModifySpotFleetRequest(new ModifySpotFleetRequestRequest { SpotFleetRequestId = "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE", TargetCapacity = 20 }); bool return = response.Return; #endregion } public void EC2ModifySpotFleetRequest() { #region ec2-modify-spot-fleet-request-2 var client = new AmazonEC2Client(); var response = client.ModifySpotFleetRequest(new ModifySpotFleetRequestRequest { ExcessCapacityTerminationPolicy = "NoTermination ", SpotFleetRequestId = "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE", TargetCapacity = 10 }); bool return = response.Return; #endregion } public void EC2ModifySubnetAttribute() { #region ec2-modify-subnet-attribute-1 var client = new AmazonEC2Client(); var response = client.ModifySubnetAttribute(new ModifySubnetAttributeRequest { MapPublicIpOnLaunch = jsondata object, SubnetId = "subnet-1a2b3c4d" }); #endregion } public void EC2ModifyVolumeAttribute() { #region to-modify-a-volume-attribute-1472508596749 var client = new AmazonEC2Client(); var response = client.ModifyVolumeAttribute(new ModifyVolumeAttributeRequest { AutoEnableIO = jsondata object, VolumeId = "vol-1234567890abcdef0" }); #endregion } public void EC2ModifyVpcAttribute() { #region ec2-modify-vpc-attribute-1 var client = new AmazonEC2Client(); var response = client.ModifyVpcAttribute(new ModifyVpcAttributeRequest { EnableDnsSupport = jsondata object, VpcId = "vpc-a01106c2" }); #endregion } public void EC2ModifyVpcAttribute() { #region ec2-modify-vpc-attribute-2 var client = new AmazonEC2Client(); var response = client.ModifyVpcAttribute(new ModifyVpcAttributeRequest { EnableDnsHostnames = jsondata object, VpcId = "vpc-a01106c2" }); #endregion } public void EC2MoveAddressToVpc() { #region ec2-move-address-to-vpc-1 var client = new AmazonEC2Client(); var response = client.MoveAddressToVpc(new MoveAddressToVpcRequest { PublicIp = "54.123.4.56" }); string status = response.Status; #endregion } public void EC2RebootInstances() { #region to-reboot-an-ec2-instance-1529358566382 var client = new AmazonEC2Client(); var response = client.RebootInstances(new RebootInstancesRequest { InstanceIds = new List<string> { "i-1234567890abcdef5" } }); #endregion } public void EC2ReleaseAddress() { #region ec2-release-address-1 var client = new AmazonEC2Client(); var response = client.ReleaseAddress(new ReleaseAddressRequest { AllocationId = "eipalloc-64d5890a" }); #endregion } public void EC2ReplaceNetworkAclAssociation() { #region ec2-replace-network-acl-association-1 var client = new AmazonEC2Client(); var response = client.ReplaceNetworkAclAssociation(new ReplaceNetworkAclAssociationRequest { AssociationId = "aclassoc-e5b95c8c", NetworkAclId = "acl-5fb85d36" }); string newAssociationId = response.NewAssociationId; #endregion } public void EC2ReplaceNetworkAclEntry() { #region ec2-replace-network-acl-entry-1 var client = new AmazonEC2Client(); var response = client.ReplaceNetworkAclEntry(new ReplaceNetworkAclEntryRequest { CidrBlock = "203.0.113.12/24", Egress = false, NetworkAclId = "acl-5fb85d36", PortRange = new PortRange { From = 53, To = 53 }, Protocol = "17", RuleAction = "allow", RuleNumber = 100 }); #endregion } public void EC2ReplaceRoute() { #region ec2-replace-route-1 var client = new AmazonEC2Client(); var response = client.ReplaceRoute(new ReplaceRouteRequest { DestinationCidrBlock = "10.0.0.0/16", GatewayId = "vgw-9a4cacf3", RouteTableId = "rtb-22574640" }); #endregion } public void EC2ReplaceRouteTableAssociation() { #region ec2-replace-route-table-association-1 var client = new AmazonEC2Client(); var response = client.ReplaceRouteTableAssociation(new ReplaceRouteTableAssociationRequest { AssociationId = "rtbassoc-781d0d1a", RouteTableId = "rtb-22574640" }); string newAssociationId = response.NewAssociationId; #endregion } public void EC2RequestSpotFleet() { #region ec2-request-spot-fleet-1 var client = new AmazonEC2Client(); var response = client.RequestSpotFleet(new RequestSpotFleetRequest { SpotFleetRequestConfig = new SpotFleetRequestConfigData { IamFleetRole = "arn:aws:iam::123456789012:role/my-spot-fleet-role", LaunchSpecifications = new List<SpotFleetLaunchSpecification> { new SpotFleetLaunchSpecification { IamInstanceProfile = new IamInstanceProfileSpecification { Arn = "arn:aws:iam::123456789012:instance-profile/my-iam-role" }, ImageId = "ami-1a2b3c4d", InstanceType = "m3.medium", KeyName = "my-key-pair", SecurityGroups = new List<GroupIdentifier> { new GroupIdentifier { GroupId = "sg-1a2b3c4d" } }, SubnetId = "subnet-1a2b3c4d, subnet-3c4d5e6f" } }, SpotPrice = "0.04", TargetCapacity = 2 } }); string spotFleetRequestId = response.SpotFleetRequestId; #endregion } public void EC2RequestSpotFleet() { #region ec2-request-spot-fleet-2 var client = new AmazonEC2Client(); var response = client.RequestSpotFleet(new RequestSpotFleetRequest { SpotFleetRequestConfig = new SpotFleetRequestConfigData { IamFleetRole = "arn:aws:iam::123456789012:role/my-spot-fleet-role", LaunchSpecifications = new List<SpotFleetLaunchSpecification> { new SpotFleetLaunchSpecification { IamInstanceProfile = new IamInstanceProfileSpecification { Arn = "arn:aws:iam::123456789012:instance-profile/my-iam-role" }, ImageId = "ami-1a2b3c4d", InstanceType = "m3.medium", KeyName = "my-key-pair", Placement = new SpotPlacement { AvailabilityZone = "us-west-2a, us-west-2b" }, SecurityGroups = new List<GroupIdentifier> { new GroupIdentifier { GroupId = "sg-1a2b3c4d" } } } }, SpotPrice = "0.04", TargetCapacity = 2 } }); string spotFleetRequestId = response.SpotFleetRequestId; #endregion } public void EC2RequestSpotFleet() { #region ec2-request-spot-fleet-3 var client = new AmazonEC2Client(); var response = client.RequestSpotFleet(new RequestSpotFleetRequest { SpotFleetRequestConfig = new SpotFleetRequestConfigData { IamFleetRole = "arn:aws:iam::123456789012:role/my-spot-fleet-role", LaunchSpecifications = new List<SpotFleetLaunchSpecification> { new SpotFleetLaunchSpecification { IamInstanceProfile = new IamInstanceProfileSpecification { Arn = "arn:aws:iam::880185128111:instance-profile/my-iam-role" }, ImageId = "ami-1a2b3c4d", InstanceType = "m3.medium", KeyName = "my-key-pair", NetworkInterfaces = new List<InstanceNetworkInterfaceSpecification> { new InstanceNetworkInterfaceSpecification { AssociatePublicIpAddress = true, DeviceIndex = 0, Groups = new List<string> { "sg-1a2b3c4d" }, SubnetId = "subnet-1a2b3c4d" } } } }, SpotPrice = "0.04", TargetCapacity = 2 } }); string spotFleetRequestId = response.SpotFleetRequestId; #endregion } public void EC2RequestSpotFleet() { #region ec2-request-spot-fleet-4 var client = new AmazonEC2Client(); var response = client.RequestSpotFleet(new RequestSpotFleetRequest { SpotFleetRequestConfig = new SpotFleetRequestConfigData { AllocationStrategy = "diversified", IamFleetRole = "arn:aws:iam::123456789012:role/my-spot-fleet-role", LaunchSpecifications = new List<SpotFleetLaunchSpecification> { new SpotFleetLaunchSpecification { ImageId = "ami-1a2b3c4d", InstanceType = "c4.2xlarge", SubnetId = "subnet-1a2b3c4d" }, new SpotFleetLaunchSpecification { ImageId = "ami-1a2b3c4d", InstanceType = "m3.2xlarge", SubnetId = "subnet-1a2b3c4d" }, new SpotFleetLaunchSpecification { ImageId = "ami-1a2b3c4d", InstanceType = "r3.2xlarge", SubnetId = "subnet-1a2b3c4d" } }, SpotPrice = "0.70", TargetCapacity = 30 } }); string spotFleetRequestId = response.SpotFleetRequestId; #endregion } public void EC2RequestSpotInstances() { #region ec2-request-spot-instances-1 var client = new AmazonEC2Client(); var response = client.RequestSpotInstances(new RequestSpotInstancesRequest { InstanceCount = 5, LaunchSpecification = new RequestSpotLaunchSpecification { IamInstanceProfile = new IamInstanceProfileSpecification { Arn = "arn:aws:iam::123456789012:instance-profile/my-iam-role" }, ImageId = "ami-1a2b3c4d", InstanceType = "m3.medium", KeyName = "my-key-pair", Placement = new SpotPlacement { AvailabilityZone = "us-west-2a" }, }, SpotPrice = "0.03", Type = "one-time" }); #endregion } public void EC2RequestSpotInstances() { #region ec2-request-spot-instances-2 var client = new AmazonEC2Client(); var response = client.RequestSpotInstances(new RequestSpotInstancesRequest { InstanceCount = 5, LaunchSpecification = new RequestSpotLaunchSpecification { IamInstanceProfile = new IamInstanceProfileSpecification { Arn = "arn:aws:iam::123456789012:instance-profile/my-iam-role" }, ImageId = "ami-1a2b3c4d", InstanceType = "m3.medium", SubnetId = "subnet-1a2b3c4d" }, SpotPrice = "0.050", Type = "one-time" }); #endregion } public void EC2ResetImageAttribute() { #region to-reset-the-launchpermission-attribute-1529359519534 var client = new AmazonEC2Client(); var response = client.ResetImageAttribute(new ResetImageAttributeRequest { Attribute = "launchPermission", ImageId = "ami-5731123e" }); #endregion } public void EC2ResetInstanceAttribute() { #region to-reset-the-sourcedestcheck-attribute-1529359630708 var client = new AmazonEC2Client(); var response = client.ResetInstanceAttribute(new ResetInstanceAttributeRequest { Attribute = "sourceDestCheck", InstanceId = "i-1234567890abcdef0" }); #endregion } public void EC2ResetSnapshotAttribute() { #region to-reset-a-snapshot-attribute-1472508825735 var client = new AmazonEC2Client(); var response = client.ResetSnapshotAttribute(new ResetSnapshotAttributeRequest { Attribute = "createVolumePermission", SnapshotId = "snap-1234567890abcdef0" }); #endregion } public void EC2RunInstances() { #region to-launch-an-instance-1529360150806 var client = new AmazonEC2Client(); var response = client.RunInstances(new RunInstancesRequest { BlockDeviceMappings = new List<BlockDeviceMapping> { new BlockDeviceMapping { DeviceName = "/dev/sdh", Ebs = new EbsBlockDevice { VolumeSize = 100 } } }, ImageId = "ami-abc12345", InstanceType = "t2.micro", KeyName = "my-key-pair", MaxCount = 1, MinCount = 1, SecurityGroupIds = new List<string> { "sg-1a2b3c4d" }, SubnetId = "subnet-6e7f829e", TagSpecifications = new List<TagSpecification> { new TagSpecification { ResourceType = "instance", Tags = new List<Tag> { new Tag { Key = "Purpose", Value = "test" } } } } }); #endregion } public void EC2StartInstances() { #region to-start-a-stopped-ec2-instance-1529358792730 var client = new AmazonEC2Client(); var response = client.StartInstances(new StartInstancesRequest { InstanceIds = new List<string> { "i-1234567890abcdef0" } }); List<InstanceStateChange> startingInstances = response.StartingInstances; #endregion } public void EC2StopInstances() { #region to-stop-a-running-ec2-instance-1529358905540 var client = new AmazonEC2Client(); var response = client.StopInstances(new StopInstancesRequest { InstanceIds = new List<string> { "i-1234567890abcdef0" } }); List<InstanceStateChange> stoppingInstances = response.StoppingInstances; #endregion } public void EC2TerminateInstances() { #region to-terminate-an-ec2-instance-1529359350660 var client = new AmazonEC2Client(); var response = client.TerminateInstances(new TerminateInstancesRequest { InstanceIds = new List<string> { "i-1234567890abcdef0" } }); List<InstanceStateChange> terminatingInstances = response.TerminatingInstances; #endregion } public void EC2UnassignPrivateIpAddresses() { #region ec2-unassign-private-ip-addresses-1 var client = new AmazonEC2Client(); var response = client.UnassignPrivateIpAddresses(new UnassignPrivateIpAddressesRequest { NetworkInterfaceId = "eni-e5aa89a3", PrivateIpAddresses = new List<string> { "10.0.0.82" } }); #endregion } public void EC2UpdateSecurityGroupRuleDescriptionsEgress() { #region to-update-an-outbound-security-group-rule-description-1529360481544 var client = new AmazonEC2Client(); var response = client.UpdateSecurityGroupRuleDescriptionsEgress(new UpdateSecurityGroupRuleDescriptionsEgressRequest { GroupId = "sg-123abc12", IpPermissions = new List<IpPermission> { new IpPermission { FromPort = 80, IpProtocol = "tcp", ToPort = 80 } } }); #endregion } public void EC2UpdateSecurityGroupRuleDescriptionsIngress() { #region to-update-an-inbound-security-group-rule-description-1529360820372 var client = new AmazonEC2Client(); var response = client.UpdateSecurityGroupRuleDescriptionsIngress(new UpdateSecurityGroupRuleDescriptionsIngressRequest { GroupId = "sg-123abc12", IpPermissions = new List<IpPermission> { new IpPermission { FromPort = 22, IpProtocol = "tcp", ToPort = 22 } } }); #endregion } # region ISample Members public virtual void Run() { } # endregion } }
3,036
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.EC2InstanceConnect; using Amazon.EC2InstanceConnect.Model; namespace AWSSDKDocSamples.Amazon.EC2InstanceConnect.Generated { class EC2InstanceConnectSamples : ISample { public void EC2InstanceConnectSendSSHPublicKey() { #region send-ssh-key-to-an-ec2-instance-1518124883100 var client = new AmazonEC2InstanceConnectClient(); var response = client.SendSSHPublicKey(new SendSSHPublicKeyRequest { AvailabilityZone = "us-west-2a", // The zone where the instance was launched InstanceId = "i-abcd1234", // The instance ID to publish the key to. InstanceOSUser = "ec2-user", // This should be the user you wish to be when ssh-ing to the instance (eg, ec2-user@[instance IP]) SSHPublicKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC3FlHqj2eqCdrGHuA6dRjfZXQ4HX5lXEIRHaNbxEwE5Te7xNF7StwhrDtiV7IdT5fDqbRyGw/szPj3xGkNTVoElCZ2dDFb2qYZ1WLIpZwj/UhO9l2mgfjR56UojjQut5Jvn2KZ1OcyrNO0J83kCaJCV7JoVbXY79FBMUccYNY45zmv9+1FMCfY6i2jdIhwR6+yLk8oubL8lIPyq7X+6b9S0yKCkB7Peml1DvghlybpAIUrC9vofHt6XP4V1i0bImw1IlljQS+DUmULRFSccATDscCX9ajnj7Crhm0HAZC0tBPXpFdHkPwL3yzYo546SCS9LKEwz62ymxxbL9k7h09t" // This should be in standard OpenSSH format (ssh-rsa [key body]) }); string requestId = response.RequestId; // This request ID should be provided when contacting AWS Support. bool success = response.Success; // Should be true if the service does not return an error response. #endregion } # region ISample Members public virtual void Run() { } # endregion } }
42
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.ECR; using Amazon.ECR.Model; namespace AWSSDKDocSamples.Amazon.ECR.Generated { class ECRSamples : ISample { public void ECRBatchDeleteImage() { #region batchdeleteimages-example-1470860541707 var client = new AmazonECRClient(); var response = client.BatchDeleteImage(new BatchDeleteImageRequest { ImageIds = new List<ImageIdentifier> { new ImageIdentifier { ImageTag = "precise" } }, RepositoryName = "ubuntu" }); List<ImageFailure> failures = response.Failures; List<ImageIdentifier> imageIds = response.ImageIds; #endregion } public void ECRBatchGetImage() { #region batchgetimage-example-1470862771437 var client = new AmazonECRClient(); var response = client.BatchGetImage(new BatchGetImageRequest { ImageIds = new List<ImageIdentifier> { new ImageIdentifier { ImageTag = "precise" } }, RepositoryName = "ubuntu" }); List<ImageFailure> failures = response.Failures; List<Image> images = response.Images; #endregion } public void ECRCreateRepository() { #region createrepository-example-1470863688724 var client = new AmazonECRClient(); var response = client.CreateRepository(new CreateRepositoryRequest { RepositoryName = "project-a/nginx-web-app" }); Repository repository = response.Repository; #endregion } public void ECRDeleteRepository() { #region deleterepository-example-1470863805703 var client = new AmazonECRClient(); var response = client.DeleteRepository(new DeleteRepositoryRequest { Force = true, RepositoryName = "ubuntu" }); Repository repository = response.Repository; #endregion } public void ECRDeleteRepositoryPolicy() { #region deleterepositorypolicy-example-1470866943748 var client = new AmazonECRClient(); var response = client.DeleteRepositoryPolicy(new DeleteRepositoryPolicyRequest { RepositoryName = "ubuntu" }); string policyText = response.PolicyText; string registryId = response.RegistryId; string repositoryName = response.RepositoryName; #endregion } public void ECRDescribeRepositories() { #region describe-repositories-1470856017467 var client = new AmazonECRClient(); var response = client.DescribeRepositories(new DescribeRepositoriesRequest { }); List<Repository> repositories = response.Repositories; #endregion } public void ECRGetAuthorizationToken() { #region getauthorizationtoken-example-1470867047084 var client = new AmazonECRClient(); var response = client.GetAuthorizationToken(new GetAuthorizationTokenRequest { }); List<AuthorizationData> authorizationData = response.AuthorizationData; #endregion } public void ECRGetRepositoryPolicy() { #region getrepositorypolicy-example-1470867669211 var client = new AmazonECRClient(); var response = client.GetRepositoryPolicy(new GetRepositoryPolicyRequest { RepositoryName = "ubuntu" }); string policyText = response.PolicyText; string registryId = response.RegistryId; string repositoryName = response.RepositoryName; #endregion } public void ECRListImages() { #region listimages-example-1470868161594 var client = new AmazonECRClient(); var response = client.ListImages(new ListImagesRequest { RepositoryName = "ubuntu" }); List<ImageIdentifier> imageIds = response.ImageIds; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
169
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.ECS; using Amazon.ECS.Model; namespace AWSSDKDocSamples.Amazon.ECS.Generated { class ECSSamples : ISample { public void ECSCreateCluster() { #region to-create-a-new-cluster-1472514079365 var client = new AmazonECSClient(); var response = client.CreateCluster(new CreateClusterRequest { ClusterName = "my_cluster" }); Cluster cluster = response.Cluster; #endregion } public void ECSCreateService() { #region to-create-a-new-service-1472512584282 var client = new AmazonECSClient(); var response = client.CreateService(new CreateServiceRequest { DesiredCount = 10, ServiceName = "ecs-simple-service", TaskDefinition = "hello_world" }); Service service = response.Service; #endregion } public void ECSCreateService() { #region to-create-a-new-service-behind-a-load-balancer-1472512484823 var client = new AmazonECSClient(); var response = client.CreateService(new CreateServiceRequest { DesiredCount = 10, LoadBalancers = new List<LoadBalancer> { new LoadBalancer { ContainerName = "simple-app", ContainerPort = 80, LoadBalancerName = "EC2Contai-EcsElast-15DCDAURT3ZO2" } }, Role = "ecsServiceRole", ServiceName = "ecs-simple-service-elb", TaskDefinition = "console-sample-app-static" }); Service service = response.Service; #endregion } public void ECSDeleteAccountSetting() { #region to-delete-the-account-setting-for-your-user-account-1549524548115 var client = new AmazonECSClient(); var response = client.DeleteAccountSetting(new DeleteAccountSettingRequest { Name = "serviceLongArnFormat" }); Setting setting = response.Setting; #endregion } public void ECSDeleteAccountSetting() { #region to-delete-the-account-setting-for-a-specific-iam-user-or-iam-role-1549524612917 var client = new AmazonECSClient(); var response = client.DeleteAccountSetting(new DeleteAccountSettingRequest { Name = "containerInstanceLongArnFormat", PrincipalArn = "arn:aws:iam::<aws_account_id>:user/principalName" }); Setting setting = response.Setting; #endregion } public void ECSDeleteCluster() { #region to-delete-an-empty-cluster-1472512705352 var client = new AmazonECSClient(); var response = client.DeleteCluster(new DeleteClusterRequest { Cluster = "my_cluster" }); Cluster cluster = response.Cluster; #endregion } public void ECSDeleteService() { #region e8183e38-f86e-4390-b811-f74f30a6007d var client = new AmazonECSClient(); var response = client.DeleteService(new DeleteServiceRequest { Service = "my-http-service" }); #endregion } public void ECSDeregisterContainerInstance() { #region bf624927-cf64-4f4b-8b7e-c024a4e682f6 var client = new AmazonECSClient(); var response = client.DeregisterContainerInstance(new DeregisterContainerInstanceRequest { Cluster = "default", ContainerInstance = "container_instance_UUID", Force = true }); #endregion } public void ECSDescribeClusters() { #region ba88d100-9672-4231-80da-a4bd210bf728 var client = new AmazonECSClient(); var response = client.DescribeClusters(new DescribeClustersRequest { Clusters = new List<string> { "default" } }); List<Cluster> clusters = response.Clusters; List<Failure> failures = response.Failures; #endregion } public void ECSDescribeContainerInstances() { #region c8f439de-eb27-4269-8ca7-2c0a7ba75ab0 var client = new AmazonECSClient(); var response = client.DescribeContainerInstances(new DescribeContainerInstancesRequest { Cluster = "default", ContainerInstances = new List<string> { "f2756532-8f13-4d53-87c9-aed50dc94cd7" } }); List<ContainerInstance> containerInstances = response.ContainerInstances; List<Failure> failures = response.Failures; #endregion } public void ECSDescribeServices() { #region to-describe-a-service-1472513256350 var client = new AmazonECSClient(); var response = client.DescribeServices(new DescribeServicesRequest { Services = new List<string> { "ecs-simple-service" } }); List<Failure> failures = response.Failures; List<Service> services = response.Services; #endregion } public void ECSDescribeTaskDefinition() { #region 4c21eeb1-f1da-4a08-8c44-297fc8d0ea88 var client = new AmazonECSClient(); var response = client.DescribeTaskDefinition(new DescribeTaskDefinitionRequest { TaskDefinition = "hello_world:8" }); TaskDefinition taskDefinition = response.TaskDefinition; #endregion } public void ECSDescribeTasks() { #region a90b0cde-f965-4946-b55e-cfd8cc54e827 var client = new AmazonECSClient(); var response = client.DescribeTasks(new DescribeTasksRequest { Tasks = new List<string> { "c5cba4eb-5dad-405e-96db-71ef8eefe6a8" } }); List<Failure> failures = response.Failures; List<Task> tasks = response.Tasks; #endregion } public void ECSGetTaskProtection() { #region get-the-protection-status-for-a-single-task-2022-11-02T06:56:32.553Z var client = new AmazonECSClient(); var response = client.GetTaskProtection(new GetTaskProtectionRequest { Cluster = "test-task-protection", Tasks = new List<string> { "b8b1cf532d0e46ba8d44a40d1de16772" } }); List<Failure> failures = response.Failures; List<ProtectedTask> protectedTasks = response.ProtectedTasks; #endregion } public void ECSListAccountSettings() { #region to-view-your-account-settings-1549524118170 var client = new AmazonECSClient(); var response = client.ListAccountSettings(new ListAccountSettingsRequest { EffectiveSettings = true }); List<Setting> settings = response.Settings; #endregion } public void ECSListAccountSettings() { #region to-view-the-account-settings-for-a-specific-iam-user-or-iam-role-1549524237932 var client = new AmazonECSClient(); var response = client.ListAccountSettings(new ListAccountSettingsRequest { EffectiveSettings = true, PrincipalArn = "arn:aws:iam::<aws_account_id>:user/principalName" }); List<Setting> settings = response.Settings; #endregion } public void ECSListClusters() { #region e337d059-134f-4125-ba8e-4f499139facf var client = new AmazonECSClient(); var response = client.ListClusters(new ListClustersRequest { }); List<string> clusterArns = response.ClusterArns; #endregion } public void ECSListContainerInstances() { #region 62a82a94-713c-4e18-8420-1d2b2ba9d484 var client = new AmazonECSClient(); var response = client.ListContainerInstances(new ListContainerInstancesRequest { Cluster = "default" }); List<string> containerInstanceArns = response.ContainerInstanceArns; #endregion } public void ECSListServices() { #region 1d9a8037-4e0e-4234-a528-609656809a3a var client = new AmazonECSClient(); var response = client.ListServices(new ListServicesRequest { }); List<string> serviceArns = response.ServiceArns; #endregion } public void ECSListTagsForResource() { #region to-list-the-tags-for-a-cluster-1540582700259 var client = new AmazonECSClient(); var response = client.ListTagsForResource(new ListTagsForResourceRequest { ResourceArn = "arn:aws:ecs:region:aws_account_id:cluster/dev" }); List<Tag> tags = response.Tags; #endregion } public void ECSListTaskDefinitionFamilies() { #region b5c89769-1d94-4ca2-a79e-8069103c7f75 var client = new AmazonECSClient(); var response = client.ListTaskDefinitionFamilies(new ListTaskDefinitionFamiliesRequest { }); List<string> families = response.Families; #endregion } public void ECSListTaskDefinitionFamilies() { #region 8a4cf9a6-42c1-4fe3-852d-99ac8968e11b var client = new AmazonECSClient(); var response = client.ListTaskDefinitionFamilies(new ListTaskDefinitionFamiliesRequest { FamilyPrefix = "hpcc" }); List<string> families = response.Families; #endregion } public void ECSListTaskDefinitions() { #region b381ebaf-7eba-4d60-b99b-7f6ae49d3d60 var client = new AmazonECSClient(); var response = client.ListTaskDefinitions(new ListTaskDefinitionsRequest { }); List<string> taskDefinitionArns = response.TaskDefinitionArns; #endregion } public void ECSListTaskDefinitions() { #region 734e7afd-753a-4bc2-85d0-badddce10910 var client = new AmazonECSClient(); var response = client.ListTaskDefinitions(new ListTaskDefinitionsRequest { FamilyPrefix = "wordpress" }); List<string> taskDefinitionArns = response.TaskDefinitionArns; #endregion } public void ECSListTasks() { #region 9a6ec707-1a77-45d0-b2eb-516b5dd9e924 var client = new AmazonECSClient(); var response = client.ListTasks(new ListTasksRequest { Cluster = "default" }); List<string> taskArns = response.TaskArns; #endregion } public void ECSListTasks() { #region 024bf3b7-9cbb-44e3-848f-9d074e1fecce var client = new AmazonECSClient(); var response = client.ListTasks(new ListTasksRequest { Cluster = "default", ContainerInstance = "f6bbb147-5370-4ace-8c73-c7181ded911f" }); List<string> taskArns = response.TaskArns; #endregion } public void ECSPutAccountSetting() { #region to-modify-the-account-settings-for-your-iam-user-account-1549523130939 var client = new AmazonECSClient(); var response = client.PutAccountSetting(new PutAccountSettingRequest { Name = "serviceLongArnFormat", Value = "enabled" }); Setting setting = response.Setting; #endregion } public void ECSPutAccountSetting() { #region to-modify-the-account-settings-for-a-specific-iam-user-or-iam-role-1549523518390 var client = new AmazonECSClient(); var response = client.PutAccountSetting(new PutAccountSettingRequest { Name = "containerInstanceLongArnFormat", Value = "enabled", PrincipalArn = "arn:aws:iam::<aws_account_id>:user/principalName" }); Setting setting = response.Setting; #endregion } public void ECSPutAccountSettingDefault() { #region to-modify-the-default-account-settings-for-all-iam-users-or-roles-on-your-account-1549523794603 var client = new AmazonECSClient(); var response = client.PutAccountSettingDefault(new PutAccountSettingDefaultRequest { Name = "serviceLongArnFormat", Value = "enabled" }); Setting setting = response.Setting; #endregion } public void ECSRegisterTaskDefinition() { #region to-register-a-task-definition-1470764550877 var client = new AmazonECSClient(); var response = client.RegisterTaskDefinition(new RegisterTaskDefinitionRequest { ContainerDefinitions = new List<ContainerDefinition> { new ContainerDefinition { Name = "sleep", Command = new List<string> { "sleep", "360" }, Cpu = 10, Essential = true, Image = "busybox", Memory = 10 } }, Family = "sleep360", TaskRoleArn = "", Volumes = new List<Volume> { } }); TaskDefinition taskDefinition = response.TaskDefinition; #endregion } public void ECSRunTask() { #region 6f238c83-a133-42cd-ab3d-abeca0560445 var client = new AmazonECSClient(); var response = client.RunTask(new RunTaskRequest { Cluster = "default", TaskDefinition = "sleep360:1" }); List<Task> tasks = response.Tasks; #endregion } public void ECSTagResource() { #region to-tag-a-cluster-1540581863751 var client = new AmazonECSClient(); var response = client.TagResource(new TagResourceRequest { ResourceArn = "arn:aws:ecs:region:aws_account_id:cluster/dev", Tags = new List<Tag> { new Tag { Key = "team", Value = "dev" } } }); #endregion } public void ECSUntagResource() { #region to-untag-a-cluster-1540582546056 var client = new AmazonECSClient(); var response = client.UntagResource(new UntagResourceRequest { ResourceArn = "arn:aws:ecs:region:aws_account_id:cluster/dev", TagKeys = new List<string> { "team" } }); #endregion } public void ECSUpdateService() { #region cc9e8900-0cc2-44d2-8491-64d1d3d37887 var client = new AmazonECSClient(); var response = client.UpdateService(new UpdateServiceRequest { Service = "my-http-service", TaskDefinition = "amazon-ecs-sample" }); #endregion } public void ECSUpdateService() { #region 9581d6c5-02e3-4140-8cc1-5a4301586633 var client = new AmazonECSClient(); var response = client.UpdateService(new UpdateServiceRequest { DesiredCount = 10, Service = "my-http-service" }); #endregion } public void ECSUpdateTaskProtection() { #region enable-the-protection-status-for-a-single-task-for-60-minutes-2022-11-02T06:56:32.553Z var client = new AmazonECSClient(); var response = client.UpdateTaskProtection(new UpdateTaskProtectionRequest { Cluster = "test-task-protection", ExpiresInMinutes = 60, ProtectionEnabled = true, Tasks = new List<string> { "b8b1cf532d0e46ba8d44a40d1de16772" } }); List<Failure> failures = response.Failures; List<ProtectedTask> protectedTasks = response.ProtectedTasks; #endregion } public void ECSUpdateTaskProtection() { #region enable-the-protection-status-for-a-single-task-with-default-expiresinminutes-2022-11-02T06:56:32.553Z var client = new AmazonECSClient(); var response = client.UpdateTaskProtection(new UpdateTaskProtectionRequest { Cluster = "test-task-protection", ProtectionEnabled = true, Tasks = new List<string> { "b8b1cf532d0e46ba8d44a40d1de16772" } }); List<Failure> failures = response.Failures; List<ProtectedTask> protectedTasks = response.ProtectedTasks; #endregion } public void ECSUpdateTaskProtection() { #region disable-scale-in-protection-on-a-single-task var client = new AmazonECSClient(); var response = client.UpdateTaskProtection(new UpdateTaskProtectionRequest { Cluster = "test-task-protection", ProtectionEnabled = false, Tasks = new List<string> { "b8b1cf532d0e46ba8d44a40d1de16772" } }); List<Failure> failures = response.Failures; List<ProtectedTask> protectedTasks = response.ProtectedTasks; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
666
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.EKS; using Amazon.EKS.Model; namespace AWSSDKDocSamples.Amazon.EKS.Generated { class EKSSamples : ISample { public void EKSCreateCluster() { #region to-create-a-new-cluster-1527868185648 var client = new AmazonEKSClient(); var response = client.CreateCluster(new CreateClusterRequest { Version = "1.10", Name = "prod", ClientRequestToken = "1d2129a1-3d38-460a-9756-e5b91fddb951", ResourcesVpcConfig = new VpcConfigRequest { SecurityGroupIds = new List<string> { "sg-6979fe18" }, SubnetIds = new List<string> { "subnet-6782e71e", "subnet-e7e761ac" } }, RoleArn = "arn:aws:iam::012345678910:role/eks-service-role-AWSServiceRoleForAmazonEKS-J7ONKE3BQ4PI" }); #endregion } public void EKSDeleteCluster() { #region to-delete-a-cluster-1527868641252 var client = new AmazonEKSClient(); var response = client.DeleteCluster(new DeleteClusterRequest { Name = "devel" }); #endregion } public void EKSDescribeCluster() { #region to-describe-a-cluster-1527868708512 var client = new AmazonEKSClient(); var response = client.DescribeCluster(new DescribeClusterRequest { Name = "devel" }); Cluster cluster = response.Cluster; #endregion } public void EKSListClusters() { #region to-list-your-available-clusters-1527868801040 var client = new AmazonEKSClient(); var response = client.ListClusters(new ListClustersRequest { }); List<string> clusters = response.Clusters; #endregion } public void EKSListTagsForResource() { #region to-list-tags-for-a-cluster-1568666903378 var client = new AmazonEKSClient(); var response = client.ListTagsForResource(new ListTagsForResourceRequest { ResourceArn = "arn:aws:eks:us-west-2:012345678910:cluster/beta" }); Dictionary<string, string> tags = response.Tags; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
107
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.ElastiCache; using Amazon.ElastiCache.Model; namespace AWSSDKDocSamples.Amazon.ElastiCache.Generated { class ElastiCacheSamples : ISample { public void ElastiCacheAddTagsToResource() { #region addtagstoresource-1482430264385 var client = new AmazonElastiCacheClient(); var response = client.AddTagsToResource(new AddTagsToResourceRequest { ResourceName = "arn:aws:elasticache:us-east-1:1234567890:cluster:my-mem-cluster", Tags = new List<Tag> { new Tag { Key = "APIVersion", Value = "20150202" }, new Tag { Key = "Service", Value = "ElastiCache" } } }); List<Tag> tagList = response.TagList; #endregion } public void ElastiCacheAuthorizeCacheSecurityGroupIngress() { #region authorizecachecachesecuritygroupingress-1483046446206 var client = new AmazonElastiCacheClient(); var response = client.AuthorizeCacheSecurityGroupIngress(new AuthorizeCacheSecurityGroupIngressRequest { CacheSecurityGroupName = "my-sec-grp", EC2SecurityGroupName = "my-ec2-sec-grp", EC2SecurityGroupOwnerId = "1234567890" }); #endregion } public void ElastiCacheCopySnapshot() { #region copysnapshot-1482961393820 var client = new AmazonElastiCacheClient(); var response = client.CopySnapshot(new CopySnapshotRequest { SourceSnapshotName = "my-snapshot", TargetBucket = "", TargetSnapshotName = "my-snapshot-copy" }); Snapshot snapshot = response.Snapshot; #endregion } public void ElastiCacheCreateCacheCluster() { #region createcachecluster-1474994727381 var client = new AmazonElastiCacheClient(); var response = client.CreateCacheCluster(new CreateCacheClusterRequest { AZMode = "cross-az", CacheClusterId = "my-memcached-cluster", CacheNodeType = "cache.r3.large", CacheSubnetGroupName = "default", Engine = "memcached", EngineVersion = "1.4.24", NumCacheNodes = 2, Port = 11211 }); CacheCluster cacheCluster = response.CacheCluster; #endregion } public void ElastiCacheCreateCacheCluster() { #region createcachecluster-1474994727381 var client = new AmazonElastiCacheClient(); var response = client.CreateCacheCluster(new CreateCacheClusterRequest { AutoMinorVersionUpgrade = true, CacheClusterId = "my-redis", CacheNodeType = "cache.r3.larage", CacheSubnetGroupName = "default", Engine = "redis", EngineVersion = "3.2.4", NumCacheNodes = 1, Port = 6379, PreferredAvailabilityZone = "us-east-1c", SnapshotRetentionLimit = 7 }); CacheCluster cacheCluster = response.CacheCluster; #endregion } public void ElastiCacheCreateCacheParameterGroup() { #region createcacheparametergroup-1474997699362 var client = new AmazonElastiCacheClient(); var response = client.CreateCacheParameterGroup(new CreateCacheParameterGroupRequest { CacheParameterGroupFamily = "redis2.8", CacheParameterGroupName = "custom-redis2-8", Description = "Custom Redis 2.8 parameter group." }); CacheParameterGroup cacheParameterGroup = response.CacheParameterGroup; #endregion } public void ElastiCacheCreateCacheSecurityGroup() { #region createcachesecuritygroup-1483041506604 var client = new AmazonElastiCacheClient(); var response = client.CreateCacheSecurityGroup(new CreateCacheSecurityGroupRequest { CacheSecurityGroupName = "my-cache-sec-grp", Description = "Example ElastiCache security group." }); #endregion } public void ElastiCacheCreateCacheSubnetGroup() { #region createcachesubnet-1483042274558 var client = new AmazonElastiCacheClient(); var response = client.CreateCacheSubnetGroup(new CreateCacheSubnetGroupRequest { CacheSubnetGroupDescription = "Sample subnet group", CacheSubnetGroupName = "my-sn-grp2", SubnetIds = new List<string> { "subnet-6f28c982", "subnet-bcd382f3", "subnet-845b3e7c0" } }); CacheSubnetGroup cacheSubnetGroup = response.CacheSubnetGroup; #endregion } public void ElastiCacheCreateReplicationGroup() { #region createcachereplicationgroup-1474998730655 var client = new AmazonElastiCacheClient(); var response = client.CreateReplicationGroup(new CreateReplicationGroupRequest { AutomaticFailoverEnabled = true, CacheNodeType = "cache.m3.medium", Engine = "redis", EngineVersion = "2.8.24", NumCacheClusters = 3, ReplicationGroupDescription = "A Redis replication group.", ReplicationGroupId = "my-redis-rg", SnapshotRetentionLimit = 30 }); ReplicationGroup replicationGroup = response.ReplicationGroup; #endregion } public void ElastiCacheCreateReplicationGroup() { #region createreplicationgroup-1483657035585 var client = new AmazonElastiCacheClient(); var response = client.CreateReplicationGroup(new CreateReplicationGroupRequest { AutoMinorVersionUpgrade = true, CacheNodeType = "cache.m3.medium", CacheParameterGroupName = "default.redis3.2.cluster.on", Engine = "redis", EngineVersion = "3.2.4", NodeGroupConfiguration = new List<NodeGroupConfiguration> { new NodeGroupConfiguration { PrimaryAvailabilityZone = "us-east-1c", ReplicaAvailabilityZones = new List<string> { "us-east-1b" }, ReplicaCount = 1, Slots = "0-8999" }, new NodeGroupConfiguration { PrimaryAvailabilityZone = "us-east-1a", ReplicaAvailabilityZones = new List<string> { "us-east-1a", "us-east-1c" }, ReplicaCount = 2, Slots = "9000-16383" } }, NumNodeGroups = 2, ReplicationGroupDescription = "A multi-sharded replication group", ReplicationGroupId = "clustered-redis-rg", SnapshotRetentionLimit = 8 }); ReplicationGroup replicationGroup = response.ReplicationGroup; #endregion } public void ElastiCacheCreateSnapshot() { #region createsnapshot-1474999681024 var client = new AmazonElastiCacheClient(); var response = client.CreateSnapshot(new CreateSnapshotRequest { CacheClusterId = "onenoderedis", SnapshotName = "snapshot-1" }); Snapshot snapshot = response.Snapshot; #endregion } public void ElastiCacheCreateSnapshot() { #region createsnapshot-1474999681024 var client = new AmazonElastiCacheClient(); var response = client.CreateSnapshot(new CreateSnapshotRequest { CacheClusterId = "threenoderedis-001", SnapshotName = "snapshot-2" }); Snapshot snapshot = response.Snapshot; #endregion } public void ElastiCacheCreateSnapshot() { #region createsnapshot-clustered-redis-1486144841758 var client = new AmazonElastiCacheClient(); var response = client.CreateSnapshot(new CreateSnapshotRequest { ReplicationGroupId = "clusteredredis", SnapshotName = "snapshot-2x5" }); Snapshot snapshot = response.Snapshot; #endregion } public void ElastiCacheDeleteCacheCluster() { #region deletecachecluster-1475010605291 var client = new AmazonElastiCacheClient(); var response = client.DeleteCacheCluster(new DeleteCacheClusterRequest { CacheClusterId = "my-memcached" }); CacheCluster cacheCluster = response.CacheCluster; #endregion } public void ElastiCacheDeleteCacheParameterGroup() { #region deletecacheparametergroup-1475010933957 var client = new AmazonElastiCacheClient(); var response = client.DeleteCacheParameterGroup(new DeleteCacheParameterGroupRequest { CacheParameterGroupName = "custom-mem1-4" }); #endregion } public void ElastiCacheDeleteCacheSecurityGroup() { #region deletecachesecuritygroup-1483046967507 var client = new AmazonElastiCacheClient(); var response = client.DeleteCacheSecurityGroup(new DeleteCacheSecurityGroupRequest { CacheSecurityGroupName = "my-sec-group" }); #endregion } public void ElastiCacheDeleteCacheSubnetGroup() { #region deletecachesubnetgroup-1475011431325 var client = new AmazonElastiCacheClient(); var response = client.DeleteCacheSubnetGroup(new DeleteCacheSubnetGroupRequest { CacheSubnetGroupName = "my-subnet-group" }); #endregion } public void ElastiCacheDeleteReplicationGroup() { #region deletereplicationgroup-1475011641804 var client = new AmazonElastiCacheClient(); var response = client.DeleteReplicationGroup(new DeleteReplicationGroupRequest { ReplicationGroupId = "my-redis-rg", RetainPrimaryCluster = false }); ReplicationGroup replicationGroup = response.ReplicationGroup; #endregion } public void ElastiCacheDeleteSnapshot() { #region deletesnapshot-1475011945779 var client = new AmazonElastiCacheClient(); var response = client.DeleteSnapshot(new DeleteSnapshotRequest { SnapshotName = "snapshot-20161212" }); Snapshot snapshot = response.Snapshot; #endregion } public void ElastiCacheDescribeCacheClusters() { #region describecacheclusters-1475012269754 var client = new AmazonElastiCacheClient(); var response = client.DescribeCacheClusters(new DescribeCacheClustersRequest { CacheClusterId = "my-mem-cluster" }); List<CacheCluster> cacheClusters = response.CacheClusters; #endregion } public void ElastiCacheDescribeCacheClusters() { #region describecacheclusters-1475012269754 var client = new AmazonElastiCacheClient(); var response = client.DescribeCacheClusters(new DescribeCacheClustersRequest { CacheClusterId = "my-mem-cluster", ShowCacheNodeInfo = true }); List<CacheCluster> cacheClusters = response.CacheClusters; #endregion } public void ElastiCacheDescribeCacheEngineVersions() { #region describecacheengineversions-1475012638790 var client = new AmazonElastiCacheClient(); var response = client.DescribeCacheEngineVersions(new DescribeCacheEngineVersionsRequest { }); List<CacheEngineVersion> cacheEngineVersions = response.CacheEngineVersions; #endregion } public void ElastiCacheDescribeCacheEngineVersions() { #region describecacheengineversions-1475012638790 var client = new AmazonElastiCacheClient(); var response = client.DescribeCacheEngineVersions(new DescribeCacheEngineVersionsRequest { DefaultOnly = false, Engine = "redis", MaxRecords = 50 }); List<CacheEngineVersion> cacheEngineVersions = response.CacheEngineVersions; string marker = response.Marker; #endregion } public void ElastiCacheDescribeCacheParameterGroups() { #region describecacheparametergroups-1483045457557 var client = new AmazonElastiCacheClient(); var response = client.DescribeCacheParameterGroups(new DescribeCacheParameterGroupsRequest { CacheParameterGroupName = "custom-mem1-4" }); List<CacheParameterGroup> cacheParameterGroups = response.CacheParameterGroups; #endregion } public void ElastiCacheDescribeCacheParameters() { #region describecacheparameters-1475013576900 var client = new AmazonElastiCacheClient(); var response = client.DescribeCacheParameters(new DescribeCacheParametersRequest { CacheParameterGroupName = "custom-redis2-8", MaxRecords = 100, Source = "user" }); string marker = response.Marker; List<Parameter> parameters = response.Parameters; #endregion } public void ElastiCacheDescribeCacheSecurityGroups() { #region describecachesecuritygroups-1483047200801 var client = new AmazonElastiCacheClient(); var response = client.DescribeCacheSecurityGroups(new DescribeCacheSecurityGroupsRequest { CacheSecurityGroupName = "my-sec-group" }); #endregion } public void ElastiCacheDescribeCacheSubnetGroups() { #region describecachesubnetgroups-1482439214064 var client = new AmazonElastiCacheClient(); var response = client.DescribeCacheSubnetGroups(new DescribeCacheSubnetGroupsRequest { MaxRecords = 25 }); List<CacheSubnetGroup> cacheSubnetGroups = response.CacheSubnetGroups; string marker = response.Marker; #endregion } public void ElastiCacheDescribeEngineDefaultParameters() { #region describeenginedefaultparameters-1481738057686 var client = new AmazonElastiCacheClient(); var response = client.DescribeEngineDefaultParameters(new DescribeEngineDefaultParametersRequest { CacheParameterGroupFamily = "redis2.8", MaxRecords = 25 }); EngineDefaults engineDefaults = response.EngineDefaults; #endregion } public void ElastiCacheDescribeEvents() { #region describeevents-1481843894757 var client = new AmazonElastiCacheClient(); var response = client.DescribeEvents(new DescribeEventsRequest { Duration = 360, SourceType = "cache-cluster" }); List<Event> events = response.Events; string marker = response.Marker; #endregion } public void ElastiCacheDescribeEvents() { #region describeevents-1481843894757 var client = new AmazonElastiCacheClient(); var response = client.DescribeEvents(new DescribeEventsRequest { StartTimeUtc = new DateTime(2016, 12, 22, 7, 0, 0, DateTimeKind.Utc) }); List<Event> events = response.Events; string marker = response.Marker; #endregion } public void ElastiCacheDescribeReplicationGroups() { #region describereplicationgroups-1481742639427 var client = new AmazonElastiCacheClient(); var response = client.DescribeReplicationGroups(new DescribeReplicationGroupsRequest { }); string marker = response.Marker; List<ReplicationGroup> replicationGroups = response.ReplicationGroups; #endregion } public void ElastiCacheDescribeReservedCacheNodes() { #region describereservedcachenodes-1481742348045 var client = new AmazonElastiCacheClient(); var response = client.DescribeReservedCacheNodes(new DescribeReservedCacheNodesRequest { MaxRecords = 25 }); #endregion } public void ElastiCacheDescribeReservedCacheNodesOfferings() { #region describereseredcachenodeofferings-1481742869998 var client = new AmazonElastiCacheClient(); var response = client.DescribeReservedCacheNodesOfferings(new DescribeReservedCacheNodesOfferingsRequest { MaxRecords = 20 }); string marker = response.Marker; List<ReservedCacheNodesOffering> reservedCacheNodesOfferings = response.ReservedCacheNodesOfferings; #endregion } public void ElastiCacheDescribeReservedCacheNodesOfferings() { #region describereseredcachenodeofferings-1481742869998 var client = new AmazonElastiCacheClient(); var response = client.DescribeReservedCacheNodesOfferings(new DescribeReservedCacheNodesOfferingsRequest { CacheNodeType = "cache.r3.large", Duration = "3", MaxRecords = 25, OfferingType = "Light Utilization", ReservedCacheNodesOfferingId = "" }); string marker = response.Marker; List<ReservedCacheNodesOffering> reservedCacheNodesOfferings = response.ReservedCacheNodesOfferings; #endregion } public void ElastiCacheDescribeReservedCacheNodesOfferings() { #region describereseredcachenodeofferings-1481742869998 var client = new AmazonElastiCacheClient(); var response = client.DescribeReservedCacheNodesOfferings(new DescribeReservedCacheNodesOfferingsRequest { CacheNodeType = "", Duration = "", Marker = "", MaxRecords = 25, OfferingType = "", ProductDescription = "", ReservedCacheNodesOfferingId = "438012d3-4052-4cc7-b2e3-8d3372e0e706" }); string marker = response.Marker; List<ReservedCacheNodesOffering> reservedCacheNodesOfferings = response.ReservedCacheNodesOfferings; #endregion } public void ElastiCacheDescribeSnapshots() { #region describesnapshots-1481743399584 var client = new AmazonElastiCacheClient(); var response = client.DescribeSnapshots(new DescribeSnapshotsRequest { SnapshotName = "snapshot-20161212" }); string marker = response.Marker; List<Snapshot> snapshots = response.Snapshots; #endregion } public void ElastiCacheListAllowedNodeTypeModifications() { #region listallowednodetypemodifications-1481748494872 var client = new AmazonElastiCacheClient(); var response = client.ListAllowedNodeTypeModifications(new ListAllowedNodeTypeModificationsRequest { ReplicationGroupId = "myreplgroup" }); List<string> scaleUpModifications = response.ScaleUpModifications; #endregion } public void ElastiCacheListAllowedNodeTypeModifications() { #region listallowednodetypemodifications-1481748494872 var client = new AmazonElastiCacheClient(); var response = client.ListAllowedNodeTypeModifications(new ListAllowedNodeTypeModificationsRequest { CacheClusterId = "mycluster" }); List<string> scaleUpModifications = response.ScaleUpModifications; #endregion } public void ElastiCacheListTagsForResource() { #region listtagsforresource-1481748784584 var client = new AmazonElastiCacheClient(); var response = client.ListTagsForResource(new ListTagsForResourceRequest { ResourceName = "arn:aws:elasticache:us-west-2:<my-account-id>:cluster:mycluster" }); List<Tag> tagList = response.TagList; #endregion } public void ElastiCacheModifyCacheCluster() { #region modifycachecluster-1482962725919 var client = new AmazonElastiCacheClient(); var response = client.ModifyCacheCluster(new ModifyCacheClusterRequest { ApplyImmediately = true, CacheClusterId = "redis-cluster", SnapshotRetentionLimit = 14 }); CacheCluster cacheCluster = response.CacheCluster; #endregion } public void ElastiCacheModifyCacheParameterGroup() { #region modifycacheparametergroup-1482966746787 var client = new AmazonElastiCacheClient(); var response = client.ModifyCacheParameterGroup(new ModifyCacheParameterGroupRequest { CacheParameterGroupName = "custom-mem1-4", ParameterNameValues = new List<ParameterNameValue> { new ParameterNameValue { ParameterName = "binding_protocol", ParameterValue = "ascii" }, new ParameterNameValue { ParameterName = "chunk_size", ParameterValue = "96" } } }); string cacheParameterGroupName = response.CacheParameterGroupName; #endregion } public void ElastiCacheModifyCacheSubnetGroup() { #region modifycachesubnetgroup-1483043446226 var client = new AmazonElastiCacheClient(); var response = client.ModifyCacheSubnetGroup(new ModifyCacheSubnetGroupRequest { CacheSubnetGroupName = "my-sn-grp", SubnetIds = new List<string> { "subnet-bcde2345" } }); CacheSubnetGroup cacheSubnetGroup = response.CacheSubnetGroup; #endregion } public void ElastiCacheModifyReplicationGroup() { #region modifyreplicationgroup-1483039689581 var client = new AmazonElastiCacheClient(); var response = client.ModifyReplicationGroup(new ModifyReplicationGroupRequest { ApplyImmediately = true, ReplicationGroupDescription = "Modified replication group", ReplicationGroupId = "my-redis-rg", SnapshotRetentionLimit = 30, SnapshottingClusterId = "my-redis-rg-001" }); ReplicationGroup replicationGroup = response.ReplicationGroup; #endregion } public void ElastiCachePurchaseReservedCacheNodesOffering() { #region purchasereservedcachenodesofferings-1483040798484 var client = new AmazonElastiCacheClient(); var response = client.PurchaseReservedCacheNodesOffering(new PurchaseReservedCacheNodesOfferingRequest { ReservedCacheNodesOfferingId = "1ef01f5b-94ff-433f-a530-61a56bfc8e7a" }); #endregion } public void ElastiCacheRebootCacheCluster() { #region rebootcachecluster-1482969019505 var client = new AmazonElastiCacheClient(); var response = client.RebootCacheCluster(new RebootCacheClusterRequest { CacheClusterId = "custom-mem1-4 ", CacheNodeIdsToReboot = new List<string> { "0001", "0002" } }); CacheCluster cacheCluster = response.CacheCluster; #endregion } public void ElastiCacheRemoveTagsFromResource() { #region removetagsfromresource-1483037920947 var client = new AmazonElastiCacheClient(); var response = client.RemoveTagsFromResource(new RemoveTagsFromResourceRequest { ResourceName = "arn:aws:elasticache:us-east-1:1234567890:cluster:my-mem-cluster", TagKeys = new List<string> { "A", "C", "E" } }); List<Tag> tagList = response.TagList; #endregion } public void ElastiCacheResetCacheParameterGroup() { #region resetcacheparametergroup-1483038334014 var client = new AmazonElastiCacheClient(); var response = client.ResetCacheParameterGroup(new ResetCacheParameterGroupRequest { CacheParameterGroupName = "custom-mem1-4", ResetAllParameters = true }); string cacheParameterGroupName = response.CacheParameterGroupName; #endregion } public void ElastiCacheRevokeCacheSecurityGroupIngress() { #region describecachesecuritygroups-1483047200801 var client = new AmazonElastiCacheClient(); var response = client.RevokeCacheSecurityGroupIngress(new RevokeCacheSecurityGroupIngressRequest { CacheSecurityGroupName = "my-sec-grp", EC2SecurityGroupName = "my-ec2-sec-grp", EC2SecurityGroupOwnerId = "1234567890" }); #endregion } # region ISample Members public virtual void Run() { } # endregion } }
867
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.ElasticBeanstalk; using Amazon.ElasticBeanstalk.Model; namespace AWSSDKDocSamples.Amazon.ElasticBeanstalk.Generated { class ElasticBeanstalkSamples : ISample { public void ElasticBeanstalkAbortEnvironmentUpdate() { #region to-abort-a-deployment-1456267848227 var client = new AmazonElasticBeanstalkClient(); var response = client.AbortEnvironmentUpdate(new AbortEnvironmentUpdateRequest { EnvironmentName = "my-env" }); #endregion } public void ElasticBeanstalkCheckDNSAvailability() { #region to-check-the-availability-of-a-cname-1456268589537 var client = new AmazonElasticBeanstalkClient(); var response = client.CheckDNSAvailability(new CheckDNSAvailabilityRequest { CNAMEPrefix = "my-cname" }); bool available = response.Available; string fullyQualifiedCNAME = response.FullyQualifiedCNAME; #endregion } public void ElasticBeanstalkCreateApplication() { #region to-create-a-new-application-1456268895683 var client = new AmazonElasticBeanstalkClient(); var response = client.CreateApplication(new CreateApplicationRequest { ApplicationName = "my-app", Description = "my application" }); ApplicationDescription application = response.Application; #endregion } public void ElasticBeanstalkCreateApplicationVersion() { #region to-create-a-new-application-1456268895683 var client = new AmazonElasticBeanstalkClient(); var response = client.CreateApplicationVersion(new CreateApplicationVersionRequest { ApplicationName = "my-app", AutoCreateApplication = true, Description = "my-app-v1", Process = true, SourceBundle = new S3Location { S3Bucket = "my-bucket", S3Key = "sample.war" }, VersionLabel = "v1" }); ApplicationVersionDescription applicationVersion = response.ApplicationVersion; #endregion } public void ElasticBeanstalkCreateConfigurationTemplate() { #region to-create-a-configuration-template-1456269283586 var client = new AmazonElasticBeanstalkClient(); var response = client.CreateConfigurationTemplate(new CreateConfigurationTemplateRequest { ApplicationName = "my-app", EnvironmentId = "e-rpqsewtp2j", TemplateName = "my-app-v1" }); string applicationName = response.ApplicationName; DateTime dateCreated = response.DateCreated; DateTime dateUpdated = response.DateUpdated; string solutionStackName = response.SolutionStackName; string templateName = response.TemplateName; #endregion } public void ElasticBeanstalkCreateEnvironment() { #region to-create-a-new-environment-for-an-application-1456269380396 var client = new AmazonElasticBeanstalkClient(); var response = client.CreateEnvironment(new CreateEnvironmentRequest { ApplicationName = "my-app", CNAMEPrefix = "my-app", EnvironmentName = "my-env", SolutionStackName = "64bit Amazon Linux 2015.03 v2.0.0 running Tomcat 8 Java 8", VersionLabel = "v1" }); string applicationName = response.ApplicationName; string cname = response.CNAME; DateTime dateCreated = response.DateCreated; DateTime dateUpdated = response.DateUpdated; string environmentId = response.EnvironmentId; string environmentName = response.EnvironmentName; string health = response.Health; string solutionStackName = response.SolutionStackName; string status = response.Status; EnvironmentTier tier = response.Tier; string versionLabel = response.VersionLabel; #endregion } public void ElasticBeanstalkCreateStorageLocation() { #region to-create-a-new-environment-for-an-application-1456269380396 var client = new AmazonElasticBeanstalkClient(); var response = client.CreateStorageLocation(new CreateStorageLocationRequest { }); string s3Bucket = response.S3Bucket; #endregion } public void ElasticBeanstalkDeleteApplication() { #region to-delete-an-application-1456269699366 var client = new AmazonElasticBeanstalkClient(); var response = client.DeleteApplication(new DeleteApplicationRequest { ApplicationName = "my-app" }); #endregion } public void ElasticBeanstalkDeleteApplicationVersion() { #region to-delete-an-application-version-1456269792956 var client = new AmazonElasticBeanstalkClient(); var response = client.DeleteApplicationVersion(new DeleteApplicationVersionRequest { ApplicationName = "my-app", DeleteSourceBundle = true, VersionLabel = "22a0-stage-150819_182129" }); #endregion } public void ElasticBeanstalkDeleteConfigurationTemplate() { #region to-delete-a-configuration-template-1456269836701 var client = new AmazonElasticBeanstalkClient(); var response = client.DeleteConfigurationTemplate(new DeleteConfigurationTemplateRequest { ApplicationName = "my-app", TemplateName = "my-template" }); #endregion } public void ElasticBeanstalkDeleteEnvironmentConfiguration() { #region to-delete-a-draft-configuration-1456269886654 var client = new AmazonElasticBeanstalkClient(); var response = client.DeleteEnvironmentConfiguration(new DeleteEnvironmentConfigurationRequest { ApplicationName = "my-app", EnvironmentName = "my-env" }); #endregion } public void ElasticBeanstalkDescribeApplications() { #region to-view-a-list-of-applications-1456270027373 var client = new AmazonElasticBeanstalkClient(); var response = client.DescribeApplications(new DescribeApplicationsRequest { }); List<ApplicationDescription> applications = response.Applications; #endregion } public void ElasticBeanstalkDescribeApplicationVersions() { #region to-view-information-about-an-application-version-1456269947428 var client = new AmazonElasticBeanstalkClient(); var response = client.DescribeApplicationVersions(new DescribeApplicationVersionsRequest { ApplicationName = "my-app", VersionLabels = new List<string> { "v2" } }); List<ApplicationVersionDescription> applicationVersions = response.ApplicationVersions; #endregion } public void ElasticBeanstalkDescribeConfigurationOptions() { #region to-view-configuration-options-for-an-environment-1456276763917 var client = new AmazonElasticBeanstalkClient(); var response = client.DescribeConfigurationOptions(new DescribeConfigurationOptionsRequest { ApplicationName = "my-app", EnvironmentName = "my-env" }); List<ConfigurationOptionDescription> options = response.Options; #endregion } public void ElasticBeanstalkDescribeConfigurationSettings() { #region to-view-configurations-settings-for-an-environment-1456276924537 var client = new AmazonElasticBeanstalkClient(); var response = client.DescribeConfigurationSettings(new DescribeConfigurationSettingsRequest { ApplicationName = "my-app", EnvironmentName = "my-env" }); List<ConfigurationSettingsDescription> configurationSettings = response.ConfigurationSettings; #endregion } public void ElasticBeanstalkDescribeEnvironmentHealth() { #region to-view-environment-health-1456277109510 var client = new AmazonElasticBeanstalkClient(); var response = client.DescribeEnvironmentHealth(new DescribeEnvironmentHealthRequest { AttributeNames = new List<string> { "All" }, EnvironmentName = "my-env" }); ApplicationMetrics applicationMetrics = response.ApplicationMetrics; List<string> causes = response.Causes; string color = response.Color; string environmentName = response.EnvironmentName; string healthStatus = response.HealthStatus; InstanceHealthSummary instancesHealth = response.InstancesHealth; DateTime refreshedAt = response.RefreshedAt; #endregion } public void ElasticBeanstalkDescribeEnvironmentResources() { #region to-view-information-about-the-aws-resources-in-your-environment-1456277206232 var client = new AmazonElasticBeanstalkClient(); var response = client.DescribeEnvironmentResources(new DescribeEnvironmentResourcesRequest { EnvironmentName = "my-env" }); EnvironmentResourceDescription environmentResources = response.EnvironmentResources; #endregion } public void ElasticBeanstalkDescribeEnvironments() { #region to-view-information-about-an-environment-1456277288662 var client = new AmazonElasticBeanstalkClient(); var response = client.DescribeEnvironments(new DescribeEnvironmentsRequest { EnvironmentNames = new List<string> { "my-env" } }); List<EnvironmentDescription> environments = response.Environments; #endregion } public void ElasticBeanstalkDescribeEvents() { #region to-view-events-for-an-environment-1456277367589 var client = new AmazonElasticBeanstalkClient(); var response = client.DescribeEvents(new DescribeEventsRequest { EnvironmentName = "my-env" }); List<EventDescription> events = response.Events; #endregion } public void ElasticBeanstalkDescribeInstancesHealth() { #region to-view-environment-health-1456277424757 var client = new AmazonElasticBeanstalkClient(); var response = client.DescribeInstancesHealth(new DescribeInstancesHealthRequest { AttributeNames = new List<string> { "All" }, EnvironmentName = "my-env" }); List<SingleInstanceHealth> instanceHealthList = response.InstanceHealthList; DateTime refreshedAt = response.RefreshedAt; #endregion } public void ElasticBeanstalkListAvailableSolutionStacks() { #region to-view-solution-stacks-1456277504811 var client = new AmazonElasticBeanstalkClient(); var response = client.ListAvailableSolutionStacks(new ListAvailableSolutionStacksRequest { }); List<SolutionStackDescription> solutionStackDetails = response.SolutionStackDetails; List<string> solutionStacks = response.SolutionStacks; #endregion } public void ElasticBeanstalkRebuildEnvironment() { #region to-rebuild-an-environment-1456277600918 var client = new AmazonElasticBeanstalkClient(); var response = client.RebuildEnvironment(new RebuildEnvironmentRequest { EnvironmentName = "my-env" }); #endregion } public void ElasticBeanstalkRequestEnvironmentInfo() { #region to-request-tailed-logs-1456277657045 var client = new AmazonElasticBeanstalkClient(); var response = client.RequestEnvironmentInfo(new RequestEnvironmentInfoRequest { EnvironmentName = "my-env", InfoType = "tail" }); #endregion } public void ElasticBeanstalkRestartAppServer() { #region to-restart-application-servers-1456277739302 var client = new AmazonElasticBeanstalkClient(); var response = client.RestartAppServer(new RestartAppServerRequest { EnvironmentName = "my-env" }); #endregion } public void ElasticBeanstalkRetrieveEnvironmentInfo() { #region to-retrieve-tailed-logs-1456277792734 var client = new AmazonElasticBeanstalkClient(); var response = client.RetrieveEnvironmentInfo(new RetrieveEnvironmentInfoRequest { EnvironmentName = "my-env", InfoType = "tail" }); List<EnvironmentInfoDescription> environmentInfo = response.EnvironmentInfo; #endregion } public void ElasticBeanstalkSwapEnvironmentCNAMEs() { #region to-swap-environment-cnames-1456277839438 var client = new AmazonElasticBeanstalkClient(); var response = client.SwapEnvironmentCNAMEs(new SwapEnvironmentCNAMEsRequest { DestinationEnvironmentName = "my-env-green", SourceEnvironmentName = "my-env-blue" }); #endregion } public void ElasticBeanstalkTerminateEnvironment() { #region to-terminate-an-environment-1456277888556 var client = new AmazonElasticBeanstalkClient(); var response = client.TerminateEnvironment(new TerminateEnvironmentRequest { EnvironmentName = "my-env" }); bool abortableOperationInProgress = response.AbortableOperationInProgress; string applicationName = response.ApplicationName; string cname = response.CNAME; DateTime dateCreated = response.DateCreated; DateTime dateUpdated = response.DateUpdated; string endpointURL = response.EndpointURL; string environmentId = response.EnvironmentId; string environmentName = response.EnvironmentName; string health = response.Health; string solutionStackName = response.SolutionStackName; string status = response.Status; EnvironmentTier tier = response.Tier; #endregion } public void ElasticBeanstalkUpdateApplication() { #region to-change-an-applications-description-1456277957075 var client = new AmazonElasticBeanstalkClient(); var response = client.UpdateApplication(new UpdateApplicationRequest { ApplicationName = "my-app", Description = "my Elastic Beanstalk application" }); ApplicationDescription application = response.Application; #endregion } public void ElasticBeanstalkUpdateApplicationVersion() { #region to-change-an-application-versions-description-1456278019237 var client = new AmazonElasticBeanstalkClient(); var response = client.UpdateApplicationVersion(new UpdateApplicationVersionRequest { ApplicationName = "my-app", Description = "new description", VersionLabel = "22a0-stage-150819_185942" }); ApplicationVersionDescription applicationVersion = response.ApplicationVersion; #endregion } public void ElasticBeanstalkUpdateConfigurationTemplate() { #region to-update-a-configuration-template-1456278075300 var client = new AmazonElasticBeanstalkClient(); var response = client.UpdateConfigurationTemplate(new UpdateConfigurationTemplateRequest { ApplicationName = "my-app", OptionsToRemove = new List<OptionSpecification> { new OptionSpecification { Namespace = "aws:elasticbeanstalk:healthreporting:system", OptionName = "ConfigDocument" } }, TemplateName = "my-template" }); string applicationName = response.ApplicationName; DateTime dateCreated = response.DateCreated; DateTime dateUpdated = response.DateUpdated; string solutionStackName = response.SolutionStackName; string templateName = response.TemplateName; #endregion } public void ElasticBeanstalkUpdateEnvironment() { #region to-update-an-environment-to-a-new-version-1456278210718 var client = new AmazonElasticBeanstalkClient(); var response = client.UpdateEnvironment(new UpdateEnvironmentRequest { EnvironmentName = "my-env", VersionLabel = "v2" }); string applicationName = response.ApplicationName; string cname = response.CNAME; DateTime dateCreated = response.DateCreated; DateTime dateUpdated = response.DateUpdated; string endpointURL = response.EndpointURL; string environmentId = response.EnvironmentId; string environmentName = response.EnvironmentName; string health = response.Health; string solutionStackName = response.SolutionStackName; string status = response.Status; EnvironmentTier tier = response.Tier; string versionLabel = response.VersionLabel; #endregion } public void ElasticBeanstalkUpdateEnvironment() { #region to-configure-option-settings-1456278286349 var client = new AmazonElasticBeanstalkClient(); var response = client.UpdateEnvironment(new UpdateEnvironmentRequest { EnvironmentName = "my-env", OptionSettings = new List<ConfigurationOptionSetting> { new ConfigurationOptionSetting { Namespace = "aws:elb:healthcheck", OptionName = "Interval", Value = "15" }, new ConfigurationOptionSetting { Namespace = "aws:elb:healthcheck", OptionName = "Timeout", Value = "8" }, new ConfigurationOptionSetting { Namespace = "aws:elb:healthcheck", OptionName = "HealthyThreshold", Value = "2" }, new ConfigurationOptionSetting { Namespace = "aws:elb:healthcheck", OptionName = "UnhealthyThreshold", Value = "3" } } }); bool abortableOperationInProgress = response.AbortableOperationInProgress; string applicationName = response.ApplicationName; string cname = response.CNAME; DateTime dateCreated = response.DateCreated; DateTime dateUpdated = response.DateUpdated; string endpointURL = response.EndpointURL; string environmentId = response.EnvironmentId; string environmentName = response.EnvironmentName; string health = response.Health; string solutionStackName = response.SolutionStackName; string status = response.Status; EnvironmentTier tier = response.Tier; string versionLabel = response.VersionLabel; #endregion } public void ElasticBeanstalkValidateConfigurationSettings() { #region to-validate-configuration-settings-1456278393654 var client = new AmazonElasticBeanstalkClient(); var response = client.ValidateConfigurationSettings(new ValidateConfigurationSettingsRequest { ApplicationName = "my-app", EnvironmentName = "my-env", OptionSettings = new List<ConfigurationOptionSetting> { new ConfigurationOptionSetting { Namespace = "aws:elasticbeanstalk:healthreporting:system", OptionName = "ConfigDocument", Value = "{\"CloudWatchMetrics\": {\"Environment\": {\"ApplicationLatencyP99.9\": null,\"InstancesSevere\": 60,\"ApplicationLatencyP90\": 60,\"ApplicationLatencyP99\": null,\"ApplicationLatencyP95\": 60,\"InstancesUnknown\": 60,\"ApplicationLatencyP85\": 60,\"InstancesInfo\": null,\"ApplicationRequests2xx\": null,\"InstancesDegraded\": null,\"InstancesWarning\": 60,\"ApplicationLatencyP50\": 60,\"ApplicationRequestsTotal\": null,\"InstancesNoData\": null,\"InstancesPending\": 60,\"ApplicationLatencyP10\": null,\"ApplicationRequests5xx\": null,\"ApplicationLatencyP75\": null,\"InstancesOk\": 60,\"ApplicationRequests3xx\": null,\"ApplicationRequests4xx\": null},\"Instance\": {\"ApplicationLatencyP99.9\": null,\"ApplicationLatencyP90\": 60,\"ApplicationLatencyP99\": null,\"ApplicationLatencyP95\": null,\"ApplicationLatencyP85\": null,\"CPUUser\": 60,\"ApplicationRequests2xx\": null,\"CPUIdle\": null,\"ApplicationLatencyP50\": null,\"ApplicationRequestsTotal\": 60,\"RootFilesystemUtil\": null,\"LoadAverage1min\": null,\"CPUIrq\": null,\"CPUNice\": 60,\"CPUIowait\": 60,\"ApplicationLatencyP10\": null,\"LoadAverage5min\": null,\"ApplicationRequests5xx\": null,\"ApplicationLatencyP75\": 60,\"CPUSystem\": 60,\"ApplicationRequests3xx\": 60,\"ApplicationRequests4xx\": null,\"InstanceHealth\": null,\"CPUSoftirq\": 60}},\"Version\": 1}" } } }); List<ValidationMessage> messages = response.Messages; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
643
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.ElasticFileSystem; using Amazon.ElasticFileSystem.Model; namespace AWSSDKDocSamples.Amazon.ElasticFileSystem.Generated { class ElasticFileSystemSamples : ISample { public void ElasticFileSystemCreateFileSystem() { #region to-create-a-new-file-system-1481840798547 var client = new AmazonElasticFileSystemClient(); var response = client.CreateFileSystem(new CreateFileSystemRequest { Backup = true, CreationToken = "tokenstring", Encrypted = true, PerformanceMode = "generalPurpose", Tags = new List<Tag> { new Tag { Key = "Name", Value = "MyFileSystem" } } }); DateTime creationTime = response.CreationTime; string creationToken = response.CreationToken; bool encrypted = response.Encrypted; string fileSystemId = response.FileSystemId; string lifeCycleState = response.LifeCycleState; int numberOfMountTargets = response.NumberOfMountTargets; string ownerId = response.OwnerId; string performanceMode = response.PerformanceMode; FileSystemSize sizeInBytes = response.SizeInBytes; List<Tag> tags = response.Tags; #endregion } public void ElasticFileSystemCreateMountTarget() { #region to-create-a-new-mount-target-1481842289329 var client = new AmazonElasticFileSystemClient(); var response = client.CreateMountTarget(new CreateMountTargetRequest { FileSystemId = "fs-01234567", SubnetId = "subnet-1234abcd" }); string fileSystemId = response.FileSystemId; string ipAddress = response.IpAddress; string lifeCycleState = response.LifeCycleState; string mountTargetId = response.MountTargetId; string networkInterfaceId = response.NetworkInterfaceId; string ownerId = response.OwnerId; string subnetId = response.SubnetId; #endregion } public void ElasticFileSystemCreateTags() { #region to-create-a-new-tag-1481843409357 var client = new AmazonElasticFileSystemClient(); var response = client.CreateTags(new CreateTagsRequest { FileSystemId = "fs-01234567", Tags = new List<Tag> { new Tag { Key = "Name", Value = "MyFileSystem" } } }); #endregion } public void ElasticFileSystemDeleteFileSystem() { #region to-delete-a-file-system-1481847318348 var client = new AmazonElasticFileSystemClient(); var response = client.DeleteFileSystem(new DeleteFileSystemRequest { FileSystemId = "fs-01234567" }); #endregion } public void ElasticFileSystemDeleteMountTarget() { #region to-delete-a-mount-target-1481847635607 var client = new AmazonElasticFileSystemClient(); var response = client.DeleteMountTarget(new DeleteMountTargetRequest { MountTargetId = "fsmt-12340abc" }); #endregion } public void ElasticFileSystemDeleteTags() { #region to-delete-tags-for-an-efs-file-system-1481848189061 var client = new AmazonElasticFileSystemClient(); var response = client.DeleteTags(new DeleteTagsRequest { FileSystemId = "fs-01234567", TagKeys = new List<string> { "Name" } }); #endregion } public void ElasticFileSystemDescribeFileSystems() { #region to-describe-an-efs-file-system-1481848448460 var client = new AmazonElasticFileSystemClient(); var response = client.DescribeFileSystems(new DescribeFileSystemsRequest { }); List<FileSystemDescription> fileSystems = response.FileSystems; #endregion } public void ElasticFileSystemDescribeLifecycleConfiguration() { #region to-describe-the-lifecycle-configuration-for-a-file-system-1551200664502 var client = new AmazonElasticFileSystemClient(); var response = client.DescribeLifecycleConfiguration(new DescribeLifecycleConfigurationRequest { FileSystemId = "fs-01234567" }); List<LifecyclePolicy> lifecyclePolicies = response.LifecyclePolicies; #endregion } public void ElasticFileSystemDescribeMountTargets() { #region to-describe-the-mount-targets-for-a-file-system-1481849958584 var client = new AmazonElasticFileSystemClient(); var response = client.DescribeMountTargets(new DescribeMountTargetsRequest { FileSystemId = "fs-01234567" }); List<MountTargetDescription> mountTargets = response.MountTargets; #endregion } public void ElasticFileSystemDescribeMountTargetSecurityGroups() { #region to-describe-the-security-groups-for-a-mount-target-1481849317823 var client = new AmazonElasticFileSystemClient(); var response = client.DescribeMountTargetSecurityGroups(new DescribeMountTargetSecurityGroupsRequest { MountTargetId = "fsmt-12340abc" }); List<string> securityGroups = response.SecurityGroups; #endregion } public void ElasticFileSystemDescribeTags() { #region to-describe-the-tags-for-a-file-system-1481850497090 var client = new AmazonElasticFileSystemClient(); var response = client.DescribeTags(new DescribeTagsRequest { FileSystemId = "fs-01234567" }); List<Tag> tags = response.Tags; #endregion } public void ElasticFileSystemModifyMountTargetSecurityGroups() { #region to-modify-the-security-groups-associated-with-a-mount-target-for-a-file-system-1481850772562 var client = new AmazonElasticFileSystemClient(); var response = client.ModifyMountTargetSecurityGroups(new ModifyMountTargetSecurityGroupsRequest { MountTargetId = "fsmt-12340abc", SecurityGroups = new List<string> { "sg-abcd1234" } }); #endregion } public void ElasticFileSystemPutLifecycleConfiguration() { #region creates-a-new-lifecycleconfiguration-object-for-a-file-system-1551201594692 var client = new AmazonElasticFileSystemClient(); var response = client.PutLifecycleConfiguration(new PutLifecycleConfigurationRequest { FileSystemId = "fs-01234567", LifecyclePolicies = new List<LifecyclePolicy> { new LifecyclePolicy { TransitionToIA = "AFTER_30_DAYS" } } }); List<LifecyclePolicy> lifecyclePolicies = response.LifecyclePolicies; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
252
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.ElasticLoadBalancing; using Amazon.ElasticLoadBalancing.Model; namespace AWSSDKDocSamples.Amazon.ElasticLoadBalancing.Generated { class ElasticLoadBalancingSamples : ISample { public void ElasticLoadBalancingAddTags() { #region elb-add-tags-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.AddTags(new AddTagsRequest { LoadBalancerNames = new List<string> { "my-load-balancer" }, Tags = new List<Tag> { new Tag { Key = "project", Value = "lima" }, new Tag { Key = "department", Value = "digital-media" } } }); #endregion } public void ElasticLoadBalancingApplySecurityGroupsToLoadBalancer() { #region elb-apply-security-groups-to-load-balancer-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.ApplySecurityGroupsToLoadBalancer(new ApplySecurityGroupsToLoadBalancerRequest { LoadBalancerName = "my-load-balancer", SecurityGroups = new List<string> { "sg-fc448899" } }); List<string> securityGroups = response.SecurityGroups; #endregion } public void ElasticLoadBalancingAttachLoadBalancerToSubnets() { #region elb-attach-load-balancer-to-subnets-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.AttachLoadBalancerToSubnets(new AttachLoadBalancerToSubnetsRequest { LoadBalancerName = "my-load-balancer", Subnets = new List<string> { "subnet-0ecac448" } }); List<string> subnets = response.Subnets; #endregion } public void ElasticLoadBalancingConfigureHealthCheck() { #region elb-configure-health-check-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.ConfigureHealthCheck(new ConfigureHealthCheckRequest { HealthCheck = new HealthCheck { HealthyThreshold = 2, Interval = 30, Target = "HTTP:80/png", Timeout = 3, UnhealthyThreshold = 2 }, LoadBalancerName = "my-load-balancer" }); HealthCheck healthCheck = response.HealthCheck; #endregion } public void ElasticLoadBalancingCreateAppCookieStickinessPolicy() { #region elb-create-app-cookie-stickiness-policy-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.CreateAppCookieStickinessPolicy(new CreateAppCookieStickinessPolicyRequest { CookieName = "my-app-cookie", LoadBalancerName = "my-load-balancer", PolicyName = "my-app-cookie-policy" }); #endregion } public void ElasticLoadBalancingCreateLBCookieStickinessPolicy() { #region elb-create-lb-cookie-stickiness-policy-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.CreateLBCookieStickinessPolicy(new CreateLBCookieStickinessPolicyRequest { CookieExpirationPeriod = 60, LoadBalancerName = "my-load-balancer", PolicyName = "my-duration-cookie-policy" }); #endregion } public void ElasticLoadBalancingCreateLoadBalancer() { #region elb-create-load-balancer-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.CreateLoadBalancer(new CreateLoadBalancerRequest { Listeners = new List<Listener> { new Listener { InstancePort = 80, InstanceProtocol = "HTTP", LoadBalancerPort = 80, Protocol = "HTTP" } }, LoadBalancerName = "my-load-balancer", SecurityGroups = new List<string> { "sg-a61988c3" }, Subnets = new List<string> { "subnet-15aaab61" } }); string dnsName = response.DNSName; #endregion } public void ElasticLoadBalancingCreateLoadBalancer() { #region elb-create-load-balancer-2 var client = new AmazonElasticLoadBalancingClient(); var response = client.CreateLoadBalancer(new CreateLoadBalancerRequest { AvailabilityZones = new List<string> { "us-west-2a" }, Listeners = new List<Listener> { new Listener { InstancePort = 80, InstanceProtocol = "HTTP", LoadBalancerPort = 80, Protocol = "HTTP" } }, LoadBalancerName = "my-load-balancer" }); string dnsName = response.DNSName; #endregion } public void ElasticLoadBalancingCreateLoadBalancer() { #region elb-create-load-balancer-3 var client = new AmazonElasticLoadBalancingClient(); var response = client.CreateLoadBalancer(new CreateLoadBalancerRequest { Listeners = new List<Listener> { new Listener { InstancePort = 80, InstanceProtocol = "HTTP", LoadBalancerPort = 80, Protocol = "HTTP" }, new Listener { InstancePort = 80, InstanceProtocol = "HTTP", LoadBalancerPort = 443, Protocol = "HTTPS", SSLCertificateId = "arn:aws:iam::123456789012:server-certificate/my-server-cert" } }, LoadBalancerName = "my-load-balancer", SecurityGroups = new List<string> { "sg-a61988c3" }, Subnets = new List<string> { "subnet-15aaab61" } }); string dnsName = response.DNSName; #endregion } public void ElasticLoadBalancingCreateLoadBalancer() { #region elb-create-load-balancer-4 var client = new AmazonElasticLoadBalancingClient(); var response = client.CreateLoadBalancer(new CreateLoadBalancerRequest { AvailabilityZones = new List<string> { "us-west-2a" }, Listeners = new List<Listener> { new Listener { InstancePort = 80, InstanceProtocol = "HTTP", LoadBalancerPort = 80, Protocol = "HTTP" }, new Listener { InstancePort = 80, InstanceProtocol = "HTTP", LoadBalancerPort = 443, Protocol = "HTTPS", SSLCertificateId = "arn:aws:iam::123456789012:server-certificate/my-server-cert" } }, LoadBalancerName = "my-load-balancer" }); string dnsName = response.DNSName; #endregion } public void ElasticLoadBalancingCreateLoadBalancer() { #region elb-create-load-balancer-5 var client = new AmazonElasticLoadBalancingClient(); var response = client.CreateLoadBalancer(new CreateLoadBalancerRequest { Listeners = new List<Listener> { new Listener { InstancePort = 80, InstanceProtocol = "HTTP", LoadBalancerPort = 80, Protocol = "HTTP" } }, LoadBalancerName = "my-load-balancer", Scheme = "internal", SecurityGroups = new List<string> { "sg-a61988c3" }, Subnets = new List<string> { "subnet-15aaab61" } }); string dnsName = response.DNSName; #endregion } public void ElasticLoadBalancingCreateLoadBalancerListeners() { #region elb-create-load-balancer-listeners-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.CreateLoadBalancerListeners(new CreateLoadBalancerListenersRequest { Listeners = new List<Listener> { new Listener { InstancePort = 80, InstanceProtocol = "HTTP", LoadBalancerPort = 80, Protocol = "HTTP" } }, LoadBalancerName = "my-load-balancer" }); #endregion } public void ElasticLoadBalancingCreateLoadBalancerListeners() { #region elb-create-load-balancer-listeners-2 var client = new AmazonElasticLoadBalancingClient(); var response = client.CreateLoadBalancerListeners(new CreateLoadBalancerListenersRequest { Listeners = new List<Listener> { new Listener { InstancePort = 80, InstanceProtocol = "HTTP", LoadBalancerPort = 443, Protocol = "HTTPS", SSLCertificateId = "arn:aws:iam::123456789012:server-certificate/my-server-cert" } }, LoadBalancerName = "my-load-balancer" }); #endregion } public void ElasticLoadBalancingCreateLoadBalancerPolicy() { #region elb-create-load-balancer-policy-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.CreateLoadBalancerPolicy(new CreateLoadBalancerPolicyRequest { LoadBalancerName = "my-load-balancer", PolicyAttributes = new List<PolicyAttribute> { new PolicyAttribute { AttributeName = "ProxyProtocol", AttributeValue = "true" } }, PolicyName = "my-ProxyProtocol-policy", PolicyTypeName = "ProxyProtocolPolicyType" }); #endregion } public void ElasticLoadBalancingCreateLoadBalancerPolicy() { #region elb-create-load-balancer-policy-2 var client = new AmazonElasticLoadBalancingClient(); var response = client.CreateLoadBalancerPolicy(new CreateLoadBalancerPolicyRequest { LoadBalancerName = "my-load-balancer", PolicyAttributes = new List<PolicyAttribute> { new PolicyAttribute { AttributeName = "PublicKey", AttributeValue = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwAYUjnfyEyXr1pxjhFWBpMlggUcqoi3kl+dS74kj//c6x7ROtusUaeQCTgIUkayttRDWchuqo1pHC1u+n5xxXnBBe2ejbb2WRsKIQ5rXEeixsjFpFsojpSQKkzhVGI6mJVZBJDVKSHmswnwLBdofLhzvllpovBPTHe+o4haAWvDBALJU0pkSI1FecPHcs2hwxf14zHoXy1e2k36A64nXW43wtfx5qcVSIxtCEOjnYRg7RPvybaGfQ+v6Iaxb/+7J5kEvZhTFQId+bSiJImF1FSUT1W1xwzBZPUbcUkkXDj45vC2s3Z8E+Lk7a3uZhvsQHLZnrfuWjBWGWvZ/MhZYgEXAMPLE" } }, PolicyName = "my-PublicKey-policy", PolicyTypeName = "PublicKeyPolicyType" }); #endregion } public void ElasticLoadBalancingCreateLoadBalancerPolicy() { #region elb-create-load-balancer-policy-3 var client = new AmazonElasticLoadBalancingClient(); var response = client.CreateLoadBalancerPolicy(new CreateLoadBalancerPolicyRequest { LoadBalancerName = "my-load-balancer", PolicyAttributes = new List<PolicyAttribute> { new PolicyAttribute { AttributeName = "PublicKeyPolicyName", AttributeValue = "my-PublicKey-policy" } }, PolicyName = "my-authentication-policy", PolicyTypeName = "BackendServerAuthenticationPolicyType" }); #endregion } public void ElasticLoadBalancingDeleteLoadBalancer() { #region elb-delete-load-balancer-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.DeleteLoadBalancer(new DeleteLoadBalancerRequest { LoadBalancerName = "my-load-balancer" }); #endregion } public void ElasticLoadBalancingDeleteLoadBalancerListeners() { #region elb-delete-load-balancer-listeners-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.DeleteLoadBalancerListeners(new DeleteLoadBalancerListenersRequest { LoadBalancerName = "my-load-balancer", LoadBalancerPorts = new List<int> { 80 } }); #endregion } public void ElasticLoadBalancingDeleteLoadBalancerPolicy() { #region elb-delete-load-balancer-policy-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.DeleteLoadBalancerPolicy(new DeleteLoadBalancerPolicyRequest { LoadBalancerName = "my-load-balancer", PolicyName = "my-duration-cookie-policy" }); #endregion } public void ElasticLoadBalancingDeregisterInstancesFromLoadBalancer() { #region elb-deregister-instances-from-load-balancer-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.DeregisterInstancesFromLoadBalancer(new DeregisterInstancesFromLoadBalancerRequest { Instances = new List<Instance> { new Instance { InstanceId = "i-d6f6fae3" } }, LoadBalancerName = "my-load-balancer" }); List<Instance> instances = response.Instances; #endregion } public void ElasticLoadBalancingDescribeInstanceHealth() { #region elb-describe-instance-health-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.DescribeInstanceHealth(new DescribeInstanceHealthRequest { LoadBalancerName = "my-load-balancer" }); List<InstanceState> instanceStates = response.InstanceStates; #endregion } public void ElasticLoadBalancingDescribeLoadBalancerAttributes() { #region elb-describe-load-balancer-attributes-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.DescribeLoadBalancerAttributes(new DescribeLoadBalancerAttributesRequest { LoadBalancerName = "my-load-balancer" }); LoadBalancerAttributes loadBalancerAttributes = response.LoadBalancerAttributes; #endregion } public void ElasticLoadBalancingDescribeLoadBalancerPolicies() { #region elb-describe-load-balancer-policies-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.DescribeLoadBalancerPolicies(new DescribeLoadBalancerPoliciesRequest { LoadBalancerName = "my-load-balancer", PolicyNames = new List<string> { "my-authentication-policy" } }); List<PolicyDescription> policyDescriptions = response.PolicyDescriptions; #endregion } public void ElasticLoadBalancingDescribeLoadBalancerPolicyTypes() { #region elb-describe-load-balancer-policy-types-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.DescribeLoadBalancerPolicyTypes(new DescribeLoadBalancerPolicyTypesRequest { PolicyTypeNames = new List<string> { "ProxyProtocolPolicyType" } }); List<PolicyTypeDescription> policyTypeDescriptions = response.PolicyTypeDescriptions; #endregion } public void ElasticLoadBalancingDescribeLoadBalancers() { #region elb-describe-load-balancers-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.DescribeLoadBalancers(new DescribeLoadBalancersRequest { LoadBalancerNames = new List<string> { "my-load-balancer" } }); List<LoadBalancerDescription> loadBalancerDescriptions = response.LoadBalancerDescriptions; #endregion } public void ElasticLoadBalancingDescribeTags() { #region elb-describe-tags-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.DescribeTags(new DescribeTagsRequest { LoadBalancerNames = new List<string> { "my-load-balancer" } }); List<TagDescription> tagDescriptions = response.TagDescriptions; #endregion } public void ElasticLoadBalancingDetachLoadBalancerFromSubnets() { #region elb-detach-load-balancer-from-subnets-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.DetachLoadBalancerFromSubnets(new DetachLoadBalancerFromSubnetsRequest { LoadBalancerName = "my-load-balancer", Subnets = new List<string> { "subnet-0ecac448" } }); List<string> subnets = response.Subnets; #endregion } public void ElasticLoadBalancingDisableAvailabilityZonesForLoadBalancer() { #region elb-disable-availability-zones-for-load-balancer-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.DisableAvailabilityZonesForLoadBalancer(new DisableAvailabilityZonesForLoadBalancerRequest { AvailabilityZones = new List<string> { "us-west-2a" }, LoadBalancerName = "my-load-balancer" }); List<string> availabilityZones = response.AvailabilityZones; #endregion } public void ElasticLoadBalancingEnableAvailabilityZonesForLoadBalancer() { #region elb-enable-availability-zones-for-load-balancer-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.EnableAvailabilityZonesForLoadBalancer(new EnableAvailabilityZonesForLoadBalancerRequest { AvailabilityZones = new List<string> { "us-west-2b" }, LoadBalancerName = "my-load-balancer" }); List<string> availabilityZones = response.AvailabilityZones; #endregion } public void ElasticLoadBalancingModifyLoadBalancerAttributes() { #region elb-modify-load-balancer-attributes-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.ModifyLoadBalancerAttributes(new ModifyLoadBalancerAttributesRequest { LoadBalancerAttributes = new LoadBalancerAttributes { CrossZoneLoadBalancing = new CrossZoneLoadBalancing { Enabled = true } }, LoadBalancerName = "my-load-balancer" }); LoadBalancerAttributes loadBalancerAttributes = response.LoadBalancerAttributes; string loadBalancerName = response.LoadBalancerName; #endregion } public void ElasticLoadBalancingModifyLoadBalancerAttributes() { #region elb-modify-load-balancer-attributes-2 var client = new AmazonElasticLoadBalancingClient(); var response = client.ModifyLoadBalancerAttributes(new ModifyLoadBalancerAttributesRequest { LoadBalancerAttributes = new LoadBalancerAttributes { ConnectionDraining = new ConnectionDraining { Enabled = true, Timeout = 300 } }, LoadBalancerName = "my-load-balancer" }); LoadBalancerAttributes loadBalancerAttributes = response.LoadBalancerAttributes; string loadBalancerName = response.LoadBalancerName; #endregion } public void ElasticLoadBalancingRegisterInstancesWithLoadBalancer() { #region elb-register-instances-with-load-balancer-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.RegisterInstancesWithLoadBalancer(new RegisterInstancesWithLoadBalancerRequest { Instances = new List<Instance> { new Instance { InstanceId = "i-d6f6fae3" } }, LoadBalancerName = "my-load-balancer" }); List<Instance> instances = response.Instances; #endregion } public void ElasticLoadBalancingRemoveTags() { #region elb-remove-tags-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.RemoveTags(new RemoveTagsRequest { LoadBalancerNames = new List<string> { "my-load-balancer" }, Tags = new List<TagKeyOnly> { new TagKeyOnly { Key = "project" } } }); #endregion } public void ElasticLoadBalancingSetLoadBalancerListenerSSLCertificate() { #region elb-set-load-balancer-listener-ssl-certificate-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.SetLoadBalancerListenerSSLCertificate(new SetLoadBalancerListenerSSLCertificateRequest { LoadBalancerName = "my-load-balancer", LoadBalancerPort = 443, SSLCertificateId = "arn:aws:iam::123456789012:server-certificate/new-server-cert" }); #endregion } public void ElasticLoadBalancingSetLoadBalancerPoliciesForBackendServer() { #region elb-set-load-balancer-policies-for-backend-server-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.SetLoadBalancerPoliciesForBackendServer(new SetLoadBalancerPoliciesForBackendServerRequest { InstancePort = 80, LoadBalancerName = "my-load-balancer", PolicyNames = new List<string> { "my-ProxyProtocol-policy" } }); #endregion } public void ElasticLoadBalancingSetLoadBalancerPoliciesOfListener() { #region elb-set-load-balancer-policies-of-listener-1 var client = new AmazonElasticLoadBalancingClient(); var response = client.SetLoadBalancerPoliciesOfListener(new SetLoadBalancerPoliciesOfListenerRequest { LoadBalancerName = "my-load-balancer", LoadBalancerPort = 80, PolicyNames = new List<string> { "my-SSLNegotiation-policy" } }); #endregion } # region ISample Members public virtual void Run() { } # endregion } }
747
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.ElasticLoadBalancingV2; using Amazon.ElasticLoadBalancingV2.Model; namespace AWSSDKDocSamples.Amazon.ElasticLoadBalancingV2.Generated { class ElasticLoadBalancingV2Samples : ISample { public void ElasticLoadBalancingV2AddTags() { #region elbv2-add-tags-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.AddTags(new AddTagsRequest { ResourceArns = new List<string> { "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188" }, Tags = new List<Tag> { new Tag { Key = "project", Value = "lima" }, new Tag { Key = "department", Value = "digital-media" } } }); #endregion } public void ElasticLoadBalancingV2CreateListener() { #region elbv2-create-listener-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.CreateListener(new CreateListenerRequest { DefaultActions = new List<Action> { new Action { TargetGroupArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067", Type = "forward" } }, LoadBalancerArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188", Port = 80, Protocol = "HTTP" }); List<Listener> listeners = response.Listeners; #endregion } public void ElasticLoadBalancingV2CreateListener() { #region elbv2-create-listener-2 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.CreateListener(new CreateListenerRequest { Certificates = new List<Certificate> { new Certificate { CertificateArn = "arn:aws:iam::123456789012:server-certificate/my-server-cert" } }, DefaultActions = new List<Action> { new Action { TargetGroupArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067", Type = "forward" } }, LoadBalancerArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188", Port = 443, Protocol = "HTTPS", SslPolicy = "ELBSecurityPolicy-2015-05" }); List<Listener> listeners = response.Listeners; #endregion } public void ElasticLoadBalancingV2CreateLoadBalancer() { #region elbv2-create-load-balancer-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.CreateLoadBalancer(new CreateLoadBalancerRequest { Name = "my-load-balancer", Subnets = new List<string> { "subnet-b7d581c0", "subnet-8360a9e7" } }); List<LoadBalancer> loadBalancers = response.LoadBalancers; #endregion } public void ElasticLoadBalancingV2CreateLoadBalancer() { #region elbv2-create-load-balancer-2 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.CreateLoadBalancer(new CreateLoadBalancerRequest { Name = "my-internal-load-balancer", Scheme = "internal", SecurityGroups = new List<string> { }, Subnets = new List<string> { "subnet-b7d581c0", "subnet-8360a9e7" } }); List<LoadBalancer> loadBalancers = response.LoadBalancers; #endregion } public void ElasticLoadBalancingV2CreateRule() { #region elbv2-create-rule-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.CreateRule(new CreateRuleRequest { Actions = new List<Action> { new Action { TargetGroupArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067", Type = "forward" } }, Conditions = new List<RuleCondition> { new RuleCondition { Field = "path-pattern", Values = new List<string> { "/img/*" } } }, ListenerArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2", Priority = 10 }); List<Rule> rules = response.Rules; #endregion } public void ElasticLoadBalancingV2CreateTargetGroup() { #region elbv2-create-target-group-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.CreateTargetGroup(new CreateTargetGroupRequest { Name = "my-targets", Port = 80, Protocol = "HTTP", VpcId = "vpc-3ac0fb5f" }); List<TargetGroup> targetGroups = response.TargetGroups; #endregion } public void ElasticLoadBalancingV2DeleteListener() { #region elbv2-delete-listener-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.DeleteListener(new DeleteListenerRequest { ListenerArn = "arn:aws:elasticloadbalancing:ua-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2" }); #endregion } public void ElasticLoadBalancingV2DeleteLoadBalancer() { #region elbv2-delete-load-balancer-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.DeleteLoadBalancer(new DeleteLoadBalancerRequest { LoadBalancerArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188" }); #endregion } public void ElasticLoadBalancingV2DeleteRule() { #region elbv2-delete-rule-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.DeleteRule(new DeleteRuleRequest { RuleArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:listener-rule/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2/1291d13826f405c3" }); #endregion } public void ElasticLoadBalancingV2DeleteTargetGroup() { #region elbv2-delete-target-group-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.DeleteTargetGroup(new DeleteTargetGroupRequest { TargetGroupArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067" }); #endregion } public void ElasticLoadBalancingV2DeregisterTargets() { #region elbv2-deregister-targets-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.DeregisterTargets(new DeregisterTargetsRequest { TargetGroupArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067", Targets = new List<TargetDescription> { new TargetDescription { Id = "i-0f76fade" } } }); #endregion } public void ElasticLoadBalancingV2DescribeListeners() { #region elbv2-describe-listeners-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.DescribeListeners(new DescribeListenersRequest { ListenerArns = new List<string> { "arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2" } }); List<Listener> listeners = response.Listeners; #endregion } public void ElasticLoadBalancingV2DescribeLoadBalancerAttributes() { #region elbv2-describe-load-balancer-attributes-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.DescribeLoadBalancerAttributes(new DescribeLoadBalancerAttributesRequest { LoadBalancerArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188" }); List<LoadBalancerAttribute> attributes = response.Attributes; #endregion } public void ElasticLoadBalancingV2DescribeLoadBalancers() { #region elbv2-describe-load-balancers-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.DescribeLoadBalancers(new DescribeLoadBalancersRequest { LoadBalancerArns = new List<string> { "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188" } }); List<LoadBalancer> loadBalancers = response.LoadBalancers; #endregion } public void ElasticLoadBalancingV2DescribeRules() { #region elbv2-describe-rules-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.DescribeRules(new DescribeRulesRequest { RuleArns = new List<string> { "arn:aws:elasticloadbalancing:us-west-2:123456789012:listener-rule/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2/9683b2d02a6cabee" } }); List<Rule> rules = response.Rules; #endregion } public void ElasticLoadBalancingV2DescribeSSLPolicies() { #region elbv2-describe-ssl-policies-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.DescribeSSLPolicies(new DescribeSSLPoliciesRequest { Names = new List<string> { "ELBSecurityPolicy-2015-05" } }); List<SslPolicy> sslPolicies = response.SslPolicies; #endregion } public void ElasticLoadBalancingV2DescribeTags() { #region elbv2-describe-tags-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.DescribeTags(new DescribeTagsRequest { ResourceArns = new List<string> { "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188" } }); List<TagDescription> tagDescriptions = response.TagDescriptions; #endregion } public void ElasticLoadBalancingV2DescribeTargetGroupAttributes() { #region elbv2-describe-target-group-attributes-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.DescribeTargetGroupAttributes(new DescribeTargetGroupAttributesRequest { TargetGroupArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067" }); List<TargetGroupAttribute> attributes = response.Attributes; #endregion } public void ElasticLoadBalancingV2DescribeTargetGroups() { #region elbv2-describe-target-groups-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.DescribeTargetGroups(new DescribeTargetGroupsRequest { TargetGroupArns = new List<string> { "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067" } }); List<TargetGroup> targetGroups = response.TargetGroups; #endregion } public void ElasticLoadBalancingV2DescribeTargetHealth() { #region elbv2-describe-target-health-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.DescribeTargetHealth(new DescribeTargetHealthRequest { TargetGroupArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067" }); List<TargetHealthDescription> targetHealthDescriptions = response.TargetHealthDescriptions; #endregion } public void ElasticLoadBalancingV2DescribeTargetHealth() { #region elbv2-describe-target-health-2 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.DescribeTargetHealth(new DescribeTargetHealthRequest { TargetGroupArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067", Targets = new List<TargetDescription> { new TargetDescription { Id = "i-0f76fade", Port = 80 } } }); List<TargetHealthDescription> targetHealthDescriptions = response.TargetHealthDescriptions; #endregion } public void ElasticLoadBalancingV2ModifyListener() { #region elbv2-modify-listener-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.ModifyListener(new ModifyListenerRequest { DefaultActions = new List<Action> { new Action { TargetGroupArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-new-targets/2453ed029918f21f", Type = "forward" } }, ListenerArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2" }); List<Listener> listeners = response.Listeners; #endregion } public void ElasticLoadBalancingV2ModifyListener() { #region elbv2-modify-listener-2 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.ModifyListener(new ModifyListenerRequest { Certificates = new List<Certificate> { new Certificate { CertificateArn = "arn:aws:iam::123456789012:server-certificate/my-new-server-cert" } }, ListenerArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/0467ef3c8400ae65" }); List<Listener> listeners = response.Listeners; #endregion } public void ElasticLoadBalancingV2ModifyLoadBalancerAttributes() { #region elbv2-modify-load-balancer-attributes-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.ModifyLoadBalancerAttributes(new ModifyLoadBalancerAttributesRequest { Attributes = new List<LoadBalancerAttribute> { new LoadBalancerAttribute { Key = "deletion_protection.enabled", Value = "true" } }, LoadBalancerArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188" }); List<LoadBalancerAttribute> attributes = response.Attributes; #endregion } public void ElasticLoadBalancingV2ModifyLoadBalancerAttributes() { #region elbv2-modify-load-balancer-attributes-2 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.ModifyLoadBalancerAttributes(new ModifyLoadBalancerAttributesRequest { Attributes = new List<LoadBalancerAttribute> { new LoadBalancerAttribute { Key = "idle_timeout.timeout_seconds", Value = "30" } }, LoadBalancerArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188" }); List<LoadBalancerAttribute> attributes = response.Attributes; #endregion } public void ElasticLoadBalancingV2ModifyLoadBalancerAttributes() { #region elbv2-modify-load-balancer-attributes-3 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.ModifyLoadBalancerAttributes(new ModifyLoadBalancerAttributesRequest { Attributes = new List<LoadBalancerAttribute> { new LoadBalancerAttribute { Key = "access_logs.s3.enabled", Value = "true" }, new LoadBalancerAttribute { Key = "access_logs.s3.bucket", Value = "my-loadbalancer-logs" }, new LoadBalancerAttribute { Key = "access_logs.s3.prefix", Value = "myapp" } }, LoadBalancerArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188" }); List<LoadBalancerAttribute> attributes = response.Attributes; #endregion } public void ElasticLoadBalancingV2ModifyRule() { #region elbv2-modify-rule-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.ModifyRule(new ModifyRuleRequest { Conditions = new List<RuleCondition> { new RuleCondition { Field = "path-pattern", Values = new List<string> { "/images/*" } } }, RuleArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:listener-rule/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2/9683b2d02a6cabee" }); List<Rule> rules = response.Rules; #endregion } public void ElasticLoadBalancingV2ModifyTargetGroup() { #region elbv2-modify-target-group-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.ModifyTargetGroup(new ModifyTargetGroupRequest { HealthCheckPort = "443", HealthCheckProtocol = "HTTPS", TargetGroupArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-https-targets/2453ed029918f21f" }); List<TargetGroup> targetGroups = response.TargetGroups; #endregion } public void ElasticLoadBalancingV2ModifyTargetGroupAttributes() { #region elbv2-modify-target-group-attributes-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.ModifyTargetGroupAttributes(new ModifyTargetGroupAttributesRequest { Attributes = new List<TargetGroupAttribute> { new TargetGroupAttribute { Key = "deregistration_delay.timeout_seconds", Value = "600" } }, TargetGroupArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067" }); List<TargetGroupAttribute> attributes = response.Attributes; #endregion } public void ElasticLoadBalancingV2RegisterTargets() { #region elbv2-register-targets-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.RegisterTargets(new RegisterTargetsRequest { TargetGroupArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067", Targets = new List<TargetDescription> { new TargetDescription { Id = "i-80c8dd94" }, new TargetDescription { Id = "i-ceddcd4d" } } }); #endregion } public void ElasticLoadBalancingV2RegisterTargets() { #region elbv2-register-targets-2 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.RegisterTargets(new RegisterTargetsRequest { TargetGroupArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-new-targets/3bb63f11dfb0faf9", Targets = new List<TargetDescription> { new TargetDescription { Id = "i-80c8dd94", Port = 80 }, new TargetDescription { Id = "i-80c8dd94", Port = 766 } } }); #endregion } public void ElasticLoadBalancingV2RemoveTags() { #region elbv2-remove-tags-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.RemoveTags(new RemoveTagsRequest { ResourceArns = new List<string> { "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188" }, TagKeys = new List<string> { "project", "department" } }); #endregion } public void ElasticLoadBalancingV2SetRulePriorities() { #region elbv2-set-rule-priorities-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.SetRulePriorities(new SetRulePrioritiesRequest { RulePriorities = new List<RulePriorityPair> { new RulePriorityPair { Priority = 5, RuleArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:listener-rule/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2/1291d13826f405c3" } } }); List<Rule> rules = response.Rules; #endregion } public void ElasticLoadBalancingV2SetSecurityGroups() { #region elbv2-set-security-groups-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.SetSecurityGroups(new SetSecurityGroupsRequest { LoadBalancerArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188", SecurityGroups = new List<string> { "sg-5943793c" } }); List<string> securityGroupIds = response.SecurityGroupIds; #endregion } public void ElasticLoadBalancingV2SetSubnets() { #region elbv2-set-subnets-1 var client = new AmazonElasticLoadBalancingV2Client(); var response = client.SetSubnets(new SetSubnetsRequest { LoadBalancerArn = "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188", Subnets = new List<string> { "subnet-8360a9e7", "subnet-b7d581c0" } }); List<AvailabilityZone> availabilityZones = response.AvailabilityZones; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
720
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.FSx; using Amazon.FSx.Model; namespace AWSSDKDocSamples.Amazon.FSx.Generated { class FSxSamples : ISample { public void FSxCopyBackup() { #region to-copy-a-backup-1481847318640 var client = new AmazonFSxClient(); var response = client.CopyBackup(new CopyBackupRequest { SourceBackupId = "backup-03e3c82e0183b7b6b", SourceRegion = "us-east-2" }); Backup backup = response.Backup; #endregion } public void FSxCreateBackup() { #region to-create-a-new-backup-1481840798597 var client = new AmazonFSxClient(); var response = client.CreateBackup(new CreateBackupRequest { FileSystemId = "fs-0498eed5fe91001ec", Tags = new List<Tag> { new Tag { Key = "Name", Value = "MyBackup" } } }); Backup backup = response.Backup; #endregion } public void FSxCreateFileSystem() { #region to-create-a-new-file-system-1481840798547 var client = new AmazonFSxClient(); var response = client.CreateFileSystem(new CreateFileSystemRequest { ClientRequestToken = "a8ca07e4-61ec-4399-99f4-19853801bcd5", FileSystemType = "WINDOWS", KmsKeyId = "arn:aws:kms:us-east-1:012345678912:key/1111abcd-2222-3333-4444-55556666eeff", SecurityGroupIds = new List<string> { "sg-edcd9784" }, StorageCapacity = 3200, StorageType = "HDD", SubnetIds = new List<string> { "subnet-1234abcd" }, Tags = new List<Tag> { new Tag { Key = "Name", Value = "MyFileSystem" } }, WindowsConfiguration = new CreateFileSystemWindowsConfiguration { ActiveDirectoryId = "d-1234abcd12", Aliases = new List<string> { "accounting.corp.example.com" }, AutomaticBackupRetentionDays = 30, DailyAutomaticBackupStartTime = "05:00", ThroughputCapacity = 32, WeeklyMaintenanceStartTime = "1:05:00" } }); FileSystem fileSystem = response.FileSystem; #endregion } public void FSxCreateFileSystemFromBackup() { #region to-create-a-new-file-system-from-backup-1481840798598 var client = new AmazonFSxClient(); var response = client.CreateFileSystemFromBackup(new CreateFileSystemFromBackupRequest { BackupId = "backup-03e3c82e0183b7b6b", ClientRequestToken = "f4c94ed7-238d-4c46-93db-48cd62ec33b7", SecurityGroupIds = new List<string> { "sg-edcd9784" }, SubnetIds = new List<string> { "subnet-1234abcd" }, Tags = new List<Tag> { new Tag { Key = "Name", Value = "MyFileSystem" } }, WindowsConfiguration = new CreateFileSystemWindowsConfiguration { ThroughputCapacity = 8 } }); FileSystem fileSystem = response.FileSystem; #endregion } public void FSxDeleteBackup() { #region to-delete-a-file-system-1481847318399 var client = new AmazonFSxClient(); var response = client.DeleteBackup(new DeleteBackupRequest { BackupId = "backup-03e3c82e0183b7b6b" }); string backupId = response.BackupId; string lifecycle = response.Lifecycle; #endregion } public void FSxDeleteFileSystem() { #region to-delete-a-file-system-1481847318348 var client = new AmazonFSxClient(); var response = client.DeleteFileSystem(new DeleteFileSystemRequest { FileSystemId = "fs-0498eed5fe91001ec" }); string fileSystemId = response.FileSystemId; string lifecycle = response.Lifecycle; #endregion } public void FSxDescribeBackups() { #region to-describe-backups-1481848448499 var client = new AmazonFSxClient(); var response = client.DescribeBackups(new DescribeBackupsRequest { }); List<Backup> backups = response.Backups; #endregion } public void FSxDescribeFileSystems() { #region to-describe-a-file-systems-1481848448460 var client = new AmazonFSxClient(); var response = client.DescribeFileSystems(new DescribeFileSystemsRequest { }); List<FileSystem> fileSystems = response.FileSystems; #endregion } public void FSxListTagsForResource() { #region to-list-tags-for-a-fsx-resource-1481847318372 var client = new AmazonFSxClient(); var response = client.ListTagsForResource(new ListTagsForResourceRequest { ResourceARN = "arn:aws:fsx:us-east-1:012345678912:file-system/fs-0498eed5fe91001ec" }); List<Tag> tags = response.Tags; #endregion } public void FSxTagResource() { #region to-tag-a-fsx-resource-1481847318371 var client = new AmazonFSxClient(); var response = client.TagResource(new TagResourceRequest { ResourceARN = "arn:aws:fsx:us-east-1:012345678912:file-system/fs-0498eed5fe91001ec", Tags = new List<Tag> { new Tag { Key = "Name", Value = "MyFileSystem" } } }); #endregion } public void FSxUntagResource() { #region to-untag-a-fsx-resource-1481847318373 var client = new AmazonFSxClient(); var response = client.UntagResource(new UntagResourceRequest { ResourceARN = "arn:aws:fsx:us-east-1:012345678912:file-system/fs-0498eed5fe91001ec", TagKeys = new List<string> { "Name" } }); #endregion } public void FSxUpdateFileSystem() { #region to-update-a-file-system-1481840798595 var client = new AmazonFSxClient(); var response = client.UpdateFileSystem(new UpdateFileSystemRequest { FileSystemId = "fs-0498eed5fe91001ec", WindowsConfiguration = new UpdateFileSystemWindowsConfiguration { AutomaticBackupRetentionDays = 10, DailyAutomaticBackupStartTime = "06:00", WeeklyMaintenanceStartTime = "3:06:00" } }); FileSystem fileSystem = response.FileSystem; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
262
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.Glacier; using Amazon.Glacier.Model; namespace AWSSDKDocSamples.Amazon.Glacier.Generated { class GlacierSamples : ISample { public void GlacierAbortMultipartUpload() { #region f3d907f6-e71c-420c-8f71-502346a2c48a var client = new AmazonGlacierClient(); var response = client.AbortMultipartUpload(new AbortMultipartUploadRequest { AccountId = "-", UploadId = "19gaRezEXAMPLES6Ry5YYdqthHOC_kGRCT03L9yetr220UmPtBYKk-OssZtLqyFu7sY1_lR7vgFuJV6NtcV5zpsJ", VaultName = "my-vault" }); #endregion } public void GlacierAbortVaultLock() { #region to-abort-a-vault-lock-1481839357947 var client = new AmazonGlacierClient(); var response = client.AbortVaultLock(new AbortVaultLockRequest { AccountId = "-", VaultName = "examplevault" }); #endregion } public void GlacierAddTagsToVault() { #region add-tags-to-vault-post-tags-add-1481663457694 var client = new AmazonGlacierClient(); var response = client.AddTagsToVault(new AddTagsToVaultRequest { Tags = new Dictionary<string, string> { { "examplekey1", "examplevalue1" }, { "examplekey2", "examplevalue2" } }, AccountId = "-", VaultName = "my-vault" }); #endregion } public void GlacierCompleteMultipartUpload() { #region 272aa0b8-e44c-4a64-add2-ad905a37984d var client = new AmazonGlacierClient(); var response = client.CompleteMultipartUpload(new CompleteMultipartUploadRequest { AccountId = "-", ArchiveSize = "3145728", Checksum = "9628195fcdbcbbe76cdde456d4646fa7de5f219fb39823836d81f0cc0e18aa67", UploadId = "19gaRezEXAMPLES6Ry5YYdqthHOC_kGRCT03L9yetr220UmPtBYKk-OssZtLqyFu7sY1_lR7vgFuJV6NtcV5zpsJ", VaultName = "my-vault" }); string archiveId = response.ArchiveId; string checksum = response.Checksum; string location = response.Location; #endregion } public void GlacierCompleteVaultLock() { #region to-complete-a-vault-lock-1481839721312 var client = new AmazonGlacierClient(); var response = client.CompleteVaultLock(new CompleteVaultLockRequest { AccountId = "-", LockId = "AE863rKkWZU53SLW5be4DUcW", VaultName = "example-vault" }); #endregion } public void GlacierCreateVault() { #region 1dc0313d-ace1-4e6c-9d13-1ec7813b14b7 var client = new AmazonGlacierClient(); var response = client.CreateVault(new CreateVaultRequest { AccountId = "-", VaultName = "my-vault" }); string location = response.Location; #endregion } public void GlacierDeleteArchive() { #region delete-archive-1481667809463 var client = new AmazonGlacierClient(); var response = client.DeleteArchive(new DeleteArchiveRequest { AccountId = "-", ArchiveId = "NkbByEejwEggmBz2fTHgJrg0XBoDfjP4q6iu87-TjhqG6eGoOY9Z8i1_AUyUsuhPAdTqLHy8pTl5nfCFJmDl2yEZONi5L26Omw12vcs01MNGntHEQL8MBfGlqrEXAMPLEArchiveId", VaultName = "examplevault" }); #endregion } public void GlacierDeleteVault() { #region 7f7f000b-4bdb-40d2-91e6-7c902f60f60f var client = new AmazonGlacierClient(); var response = client.DeleteVault(new DeleteVaultRequest { AccountId = "-", VaultName = "my-vault" }); #endregion } public void GlacierDeleteVaultAccessPolicy() { #region to-delete-the-vault-access-policy-1481840424677 var client = new AmazonGlacierClient(); var response = client.DeleteVaultAccessPolicy(new DeleteVaultAccessPolicyRequest { AccountId = "-", VaultName = "examplevault" }); #endregion } public void GlacierDeleteVaultNotifications() { #region to-delete-the-notification-configuration-set-for-a-vault-1481840646090 var client = new AmazonGlacierClient(); var response = client.DeleteVaultNotifications(new DeleteVaultNotificationsRequest { AccountId = "-", VaultName = "examplevault" }); #endregion } public void GlacierDescribeJob() { #region to-get-information-about-a-job-you-previously-initiated-1481840928592 var client = new AmazonGlacierClient(); var response = client.DescribeJob(new DescribeJobRequest { AccountId = "-", JobId = "zbxcm3Z_3z5UkoroF7SuZKrxgGoDc3RloGduS7Eg-RO47Yc6FxsdGBgf_Q2DK5Ejh18CnTS5XW4_XqlNHS61dsO4Cn", VaultName = "my-vault" }); string action = response.Action; bool completed = response.Completed; string creationDate = response.CreationDate; InventoryRetrievalJobDescription inventoryRetrievalParameters = response.InventoryRetrievalParameters; string jobId = response.JobId; string statusCode = response.StatusCode; string vaultARN = response.VaultARN; #endregion } public void GlacierDescribeVault() { #region 3c1c6e9d-f5a2-427a-aa6a-f439eacfc05f var client = new AmazonGlacierClient(); var response = client.DescribeVault(new DescribeVaultRequest { AccountId = "-", VaultName = "my-vault" }); string creationDate = response.CreationDate; long numberOfArchives = response.NumberOfArchives; long sizeInBytes = response.SizeInBytes; string vaultARN = response.VaultARN; string vaultName = response.VaultName; #endregion } public void GlacierGetDataRetrievalPolicy() { #region to-get-the-current-data-retrieval-policy-for-the-account-1481851580439 var client = new AmazonGlacierClient(); var response = client.GetDataRetrievalPolicy(new GetDataRetrievalPolicyRequest { AccountId = "-" }); DataRetrievalPolicy policy = response.Policy; #endregion } public void GlacierGetJobOutput() { #region to-get-the-output-of-a-previously-initiated-job-1481848550859 var client = new AmazonGlacierClient(); var response = client.GetJobOutput(new GetJobOutputRequest { AccountId = "-", JobId = "zbxcm3Z_3z5UkoroF7SuZKrxgGoDc3RloGduS7Eg-RO47Yc6FxsdGBgf_Q2DK5Ejh18CnTS5XW4_XqlNHS61dsO4CnMW", Range = "", VaultName = "my-vaul" }); string acceptRanges = response.AcceptRanges; MemoryStream body = response.Body; string contentType = response.ContentType; int status = response.Status; #endregion } public void GlacierGetVaultAccessPolicy() { #region to--get-the-access-policy-set-on-the-vault-1481936004590 var client = new AmazonGlacierClient(); var response = client.GetVaultAccessPolicy(new GetVaultAccessPolicyRequest { AccountId = "-", VaultName = "example-vault" }); VaultAccessPolicy policy = response.Policy; #endregion } public void GlacierGetVaultLock() { #region to-retrieve-vault-lock-policy-related-attributes-that-are-set-on-a-vault-1481851363097 var client = new AmazonGlacierClient(); var response = client.GetVaultLock(new GetVaultLockRequest { AccountId = "-", VaultName = "examplevault" }); string creationDate = response.CreationDate; string expirationDate = response.ExpirationDate; string policy = response.Policy; string state = response.State; #endregion } public void GlacierGetVaultNotifications() { #region to-get-the-notification-configuration-for-the-specified-vault-1481918746677 var client = new AmazonGlacierClient(); var response = client.GetVaultNotifications(new GetVaultNotificationsRequest { AccountId = "-", VaultName = "my-vault" }); VaultNotificationConfig vaultNotificationConfig = response.VaultNotificationConfig; #endregion } public void GlacierInitiateJob() { #region to-initiate-an-inventory-retrieval-job-1482186883826 var client = new AmazonGlacierClient(); var response = client.InitiateJob(new InitiateJobRequest { AccountId = "-", JobParameters = new JobParameters { Description = "My inventory job", Format = "CSV", SNSTopic = "arn:aws:sns:us-west-2:111111111111:Glacier-InventoryRetrieval-topic-Example", Type = "inventory-retrieval" }, VaultName = "examplevault" }); string jobId = response.JobId; string location = response.Location; #endregion } public void GlacierInitiateMultipartUpload() { #region 72f2db19-3d93-4c74-b2ed-38703baacf49 var client = new AmazonGlacierClient(); var response = client.InitiateMultipartUpload(new InitiateMultipartUploadRequest { AccountId = "-", PartSize = "1048576", VaultName = "my-vault" }); string location = response.Location; string uploadId = response.UploadId; #endregion } public void GlacierInitiateVaultLock() { #region to-initiate-the-vault-locking-process-1481919693394 var client = new AmazonGlacierClient(); var response = client.InitiateVaultLock(new InitiateVaultLockRequest { AccountId = "-", Policy = new VaultLockPolicy { Policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Define-vault-lock\",\"Effect\":\"Deny\",\"Principal\":{\"AWS\":\"arn:aws:iam::999999999999:root\"},\"Action\":\"glacier:DeleteArchive\",\"Resource\":\"arn:aws:glacier:us-west-2:999999999999:vaults/examplevault\",\"Condition\":{\"NumericLessThanEquals\":{\"glacier:ArchiveAgeinDays\":\"365\"}}}]}" }, VaultName = "my-vault" }); string lockId = response.LockId; #endregion } public void GlacierListJobs() { #region to-list-jobs-for-a-vault-1481920530537 var client = new AmazonGlacierClient(); var response = client.ListJobs(new ListJobsRequest { AccountId = "-", VaultName = "my-vault" }); List<GlacierJobDescription> jobList = response.JobList; #endregion } public void GlacierListMultipartUploads() { #region to-list-all-the-in-progress-multipart-uploads-for-a-vault-1481935250590 var client = new AmazonGlacierClient(); var response = client.ListMultipartUploads(new ListMultipartUploadsRequest { AccountId = "-", VaultName = "examplevault" }); string marker = response.Marker; List<UploadListElement> uploadsList = response.UploadsList; #endregion } public void GlacierListParts() { #region to-list-the-parts-of-an-archive-that-have-been-uploaded-in-a-multipart-upload-1481921767590 var client = new AmazonGlacierClient(); var response = client.ListParts(new ListPartsRequest { AccountId = "-", UploadId = "OW2fM5iVylEpFEMM9_HpKowRapC3vn5sSL39_396UW9zLFUWVrnRHaPjUJddQ5OxSHVXjYtrN47NBZ-khxOjyEXAMPLE", VaultName = "examplevault" }); string archiveDescription = response.ArchiveDescription; string creationDate = response.CreationDate; string marker = response.Marker; string multipartUploadId = response.MultipartUploadId; long partSizeInBytes = response.PartSizeInBytes; List<PartListElement> parts = response.Parts; string vaultARN = response.VaultARN; #endregion } public void GlacierListProvisionedCapacity() { #region to-list-the-provisioned-capacity-units-for-an-account-1481923656130 var client = new AmazonGlacierClient(); var response = client.ListProvisionedCapacity(new ListProvisionedCapacityRequest { AccountId = "-" }); List<ProvisionedCapacityDescription> provisionedCapacityList = response.ProvisionedCapacityList; #endregion } public void GlacierListTagsForVault() { #region list-tags-for-vault-1481755839720 var client = new AmazonGlacierClient(); var response = client.ListTagsForVault(new ListTagsForVaultRequest { AccountId = "-", VaultName = "examplevault" }); Dictionary<string, string> tags = response.Tags; #endregion } public void GlacierListVaults() { #region list-vaults-1481753006990 var client = new AmazonGlacierClient(); var response = client.ListVaults(new ListVaultsRequest { AccountId = "-", Limit = "", Marker = "" }); List<DescribeVaultOutput> vaultList = response.VaultList; #endregion } public void GlacierPurchaseProvisionedCapacity() { #region to-purchases-a-provisioned-capacity-unit-for-an-aws-account-1481927446662 var client = new AmazonGlacierClient(); var response = client.PurchaseProvisionedCapacity(new PurchaseProvisionedCapacityRequest { AccountId = "-" }); string capacityId = response.CapacityId; #endregion } public void GlacierRemoveTagsFromVault() { #region remove-tags-from-vault-1481754998801 var client = new AmazonGlacierClient(); var response = client.RemoveTagsFromVault(new RemoveTagsFromVaultRequest { TagKeys = new List<string> { "examplekey1", "examplekey2" }, AccountId = "-", VaultName = "examplevault" }); #endregion } public void GlacierSetDataRetrievalPolicy() { #region to-set-and-then-enact-a-data-retrieval-policy--1481928352408 var client = new AmazonGlacierClient(); var response = client.SetDataRetrievalPolicy(new SetDataRetrievalPolicyRequest { Policy = new DataRetrievalPolicy { Rules = new List<DataRetrievalRule> { new DataRetrievalRule { BytesPerHour = 10737418240, Strategy = "BytesPerHour" } } }, AccountId = "-" }); #endregion } public void GlacierSetVaultAccessPolicy() { #region to--set-the-access-policy-on-a-vault-1482185872517 var client = new AmazonGlacierClient(); var response = client.SetVaultAccessPolicy(new SetVaultAccessPolicyRequest { AccountId = "-", Policy = new VaultAccessPolicy { Policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Define-owner-access-rights\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::999999999999:root\"},\"Action\":\"glacier:DeleteArchive\",\"Resource\":\"arn:aws:glacier:us-west-2:999999999999:vaults/examplevault\"}]}" }, VaultName = "examplevault" }); #endregion } public void GlacierSetVaultNotifications() { #region to-configure-a-vault-to-post-a-message-to-an-amazon-simple-notification-service-amazon-sns-topic-when-jobs-complete-1482186397475 var client = new AmazonGlacierClient(); var response = client.SetVaultNotifications(new SetVaultNotificationsRequest { AccountId = "-", VaultName = "examplevault", VaultNotificationConfig = new VaultNotificationConfig { Events = new List<string> { "ArchiveRetrievalCompleted", "InventoryRetrievalCompleted" }, SNSTopic = "arn:aws:sns:us-west-2:012345678901:mytopic" } }); #endregion } public void GlacierUploadArchive() { #region upload-archive-1481668510494 var client = new AmazonGlacierClient(); var response = client.UploadArchive(new UploadArchiveRequest { AccountId = "-", ArchiveDescription = "", Body = new MemoryStream(example-data-to-upload), Checksum = "", VaultName = "my-vault" }); string archiveId = response.ArchiveId; string checksum = response.Checksum; string location = response.Location; #endregion } public void GlacierUploadMultipartPart() { #region to-upload-the-first-part-of-an-archive-1481835899519 var client = new AmazonGlacierClient(); var response = client.UploadMultipartPart(new UploadMultipartPartRequest { AccountId = "-", Body = new MemoryStream(part1), Checksum = "c06f7cd4baacb087002a99a5f48bf953", Range = "bytes 0-1048575/*", UploadId = "19gaRezEXAMPLES6Ry5YYdqthHOC_kGRCT03L9yetr220UmPtBYKk-OssZtLqyFu7sY1_lR7vgFuJV6NtcV5zpsJ", VaultName = "examplevault" }); string checksum = response.Checksum; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
612
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; namespace AWSSDKDocSamples.Amazon.IdentityManagement.Generated { class IdentityManagementServiceSamples : ISample { public void IdentityManagementServiceAddClientIDToOpenIDConnectProvider() { #region 028e91f4-e2a6-4d59-9e3b-4965a3fb19be var client = new AmazonIdentityManagementServiceClient(); var response = client.AddClientIDToOpenIDConnectProvider(new AddClientIDToOpenIDConnectProviderRequest { ClientID = "my-application-ID", OpenIDConnectProviderArn = "arn:aws:iam::123456789012:oidc-provider/server.example.com" }); #endregion } public void IdentityManagementServiceAddRoleToInstanceProfile() { #region c107fac3-edb6-4827-8a71-8863ec91c81f var client = new AmazonIdentityManagementServiceClient(); var response = client.AddRoleToInstanceProfile(new AddRoleToInstanceProfileRequest { InstanceProfileName = "Webserver", RoleName = "S3Access" }); #endregion } public void IdentityManagementServiceAddUserToGroup() { #region 619c7e6b-09f8-4036-857b-51a6ea5027ca var client = new AmazonIdentityManagementServiceClient(); var response = client.AddUserToGroup(new AddUserToGroupRequest { GroupName = "Admins", UserName = "Bob" }); #endregion } public void IdentityManagementServiceAttachGroupPolicy() { #region 87551489-86f0-45db-9889-759936778f2b var client = new AmazonIdentityManagementServiceClient(); var response = client.AttachGroupPolicy(new AttachGroupPolicyRequest { GroupName = "Finance", PolicyArn = "arn:aws:iam::aws:policy/ReadOnlyAccess" }); #endregion } public void IdentityManagementServiceAttachRolePolicy() { #region 3e1b8c7c-99c8-4fc4-a20c-131fe3f22c7e var client = new AmazonIdentityManagementServiceClient(); var response = client.AttachRolePolicy(new AttachRolePolicyRequest { PolicyArn = "arn:aws:iam::aws:policy/ReadOnlyAccess", RoleName = "ReadOnlyRole" }); #endregion } public void IdentityManagementServiceAttachUserPolicy() { #region 1372ebd8-9475-4b1a-a479-23b6fd4b8b3e var client = new AmazonIdentityManagementServiceClient(); var response = client.AttachUserPolicy(new AttachUserPolicyRequest { PolicyArn = "arn:aws:iam::aws:policy/AdministratorAccess", UserName = "Alice" }); #endregion } public void IdentityManagementServiceChangePassword() { #region 3a80c66f-bffb-46df-947c-1e8fa583b470 var client = new AmazonIdentityManagementServiceClient(); var response = client.ChangePassword(new ChangePasswordRequest { NewPassword = "]35d/{pB9Fo9wJ", OldPassword = "3s0K_;xh4~8XXI" }); #endregion } public void IdentityManagementServiceCreateAccessKey() { #region 1fbb3211-4cf2-41db-8c20-ba58d9f5802d var client = new AmazonIdentityManagementServiceClient(); var response = client.CreateAccessKey(new CreateAccessKeyRequest { UserName = "Bob" }); AccessKey accessKey = response.AccessKey; #endregion } public void IdentityManagementServiceCreateAccountAlias() { #region 5adaf6fb-94fc-4ca2-b825-2fbc2062add1 var client = new AmazonIdentityManagementServiceClient(); var response = client.CreateAccountAlias(new CreateAccountAliasRequest { AccountAlias = "examplecorp" }); #endregion } public void IdentityManagementServiceCreateGroup() { #region d5da2a90-5e69-4ef7-8ae8-4c33dc21fd21 var client = new AmazonIdentityManagementServiceClient(); var response = client.CreateGroup(new CreateGroupRequest { GroupName = "Admins" }); Group group = response.Group; #endregion } public void IdentityManagementServiceCreateInstanceProfile() { #region 5d84e6ae-5921-4e39-8454-10232cd9ff9a var client = new AmazonIdentityManagementServiceClient(); var response = client.CreateInstanceProfile(new CreateInstanceProfileRequest { InstanceProfileName = "Webserver" }); InstanceProfile instanceProfile = response.InstanceProfile; #endregion } public void IdentityManagementServiceCreateLoginProfile() { #region c63795bc-3444-40b3-89df-83c474ef88be var client = new AmazonIdentityManagementServiceClient(); var response = client.CreateLoginProfile(new CreateLoginProfileRequest { Password = "h]6EszR}vJ*m", PasswordResetRequired = true, UserName = "Bob" }); LoginProfile loginProfile = response.LoginProfile; #endregion } public void IdentityManagementServiceCreateOpenIDConnectProvider() { #region 4e4a6bff-cc97-4406-922e-0ab4a82cdb63 var client = new AmazonIdentityManagementServiceClient(); var response = client.CreateOpenIDConnectProvider(new CreateOpenIDConnectProviderRequest { ClientIDList = new List<string> { "my-application-id" }, ThumbprintList = new List<string> { "3768084dfb3d2b68b7897bf5f565da8efEXAMPLE" }, Url = "https://server.example.com" }); string openIDConnectProviderArn = response.OpenIDConnectProviderArn; #endregion } public void IdentityManagementServiceCreateRole() { #region eaaa4b5f-51f1-4f73-b0d3-30127040eff8 var client = new AmazonIdentityManagementServiceClient(); var response = client.CreateRole(new CreateRoleRequest { AssumeRolePolicyDocument = "<Stringified-JSON>", Path = "/", RoleName = "Test-Role" }); Role role = response.Role; #endregion } public void IdentityManagementServiceCreateUser() { #region eb15f90b-e5f5-4af8-a594-e4e82b181a62 var client = new AmazonIdentityManagementServiceClient(); var response = client.CreateUser(new CreateUserRequest { UserName = "Bob" }); User user = response.User; #endregion } public void IdentityManagementServiceDeleteAccessKey() { #region 61a785a7-d30a-415a-ae18-ab9236e56871 var client = new AmazonIdentityManagementServiceClient(); var response = client.DeleteAccessKey(new DeleteAccessKeyRequest { AccessKeyId = "AKIDPMS9RO4H3FEXAMPLE", UserName = "Bob" }); #endregion } public void IdentityManagementServiceDeleteAccountAlias() { #region 7abeca65-04a8-4500-a890-47f1092bf766 var client = new AmazonIdentityManagementServiceClient(); var response = client.DeleteAccountAlias(new DeleteAccountAliasRequest { AccountAlias = "mycompany" }); #endregion } public void IdentityManagementServiceDeleteAccountPasswordPolicy() { #region 9ddf755e-495c-49bc-ae3b-ea6cc9b8ebcf var client = new AmazonIdentityManagementServiceClient(); var response = client.DeleteAccountPasswordPolicy(new DeleteAccountPasswordPolicyRequest { }); #endregion } public void IdentityManagementServiceDeleteGroupPolicy() { #region e683f2bd-98a4-4fe0-bb66-33169c692d4a var client = new AmazonIdentityManagementServiceClient(); var response = client.DeleteGroupPolicy(new DeleteGroupPolicyRequest { GroupName = "Admins", PolicyName = "ExamplePolicy" }); #endregion } public void IdentityManagementServiceDeleteInstanceProfile() { #region 12d74fb8-3433-49db-8171-a1fc764e354d var client = new AmazonIdentityManagementServiceClient(); var response = client.DeleteInstanceProfile(new DeleteInstanceProfileRequest { InstanceProfileName = "ExampleInstanceProfile" }); #endregion } public void IdentityManagementServiceDeleteLoginProfile() { #region 1fe57059-fc73-42e2-b992-517b7d573b5c var client = new AmazonIdentityManagementServiceClient(); var response = client.DeleteLoginProfile(new DeleteLoginProfileRequest { UserName = "Bob" }); #endregion } public void IdentityManagementServiceDeleteRole() { #region 053cdf74-9bda-44b8-bdbb-140fd5a32603 var client = new AmazonIdentityManagementServiceClient(); var response = client.DeleteRole(new DeleteRoleRequest { RoleName = "Test-Role" }); #endregion } public void IdentityManagementServiceDeleteRolePolicy() { #region 9c667336-fde3-462c-b8f3-950800821e27 var client = new AmazonIdentityManagementServiceClient(); var response = client.DeleteRolePolicy(new DeleteRolePolicyRequest { PolicyName = "ExamplePolicy", RoleName = "Test-Role" }); #endregion } public void IdentityManagementServiceDeleteSigningCertificate() { #region e3357586-ba9c-4070-b35b-d1a899b71987 var client = new AmazonIdentityManagementServiceClient(); var response = client.DeleteSigningCertificate(new DeleteSigningCertificateRequest { CertificateId = "TA7SMP42TDN5Z26OBPJE7EXAMPLE", UserName = "Anika" }); #endregion } public void IdentityManagementServiceDeleteUser() { #region a13dc3f9-59fe-42d9-abbb-fb98b204fdf0 var client = new AmazonIdentityManagementServiceClient(); var response = client.DeleteUser(new DeleteUserRequest { UserName = "Bob" }); #endregion } public void IdentityManagementServiceDeleteUserPolicy() { #region 34f07ddc-9bc1-4f52-bc59-cd0a3ccd06c8 var client = new AmazonIdentityManagementServiceClient(); var response = client.DeleteUserPolicy(new DeleteUserPolicyRequest { PolicyName = "ExamplePolicy", UserName = "Juan" }); #endregion } public void IdentityManagementServiceDeleteVirtualMFADevice() { #region 2933b08b-dbe7-4b89-b8c1-fdf75feea1ee var client = new AmazonIdentityManagementServiceClient(); var response = client.DeleteVirtualMFADevice(new DeleteVirtualMFADeviceRequest { SerialNumber = "arn:aws:iam::123456789012:mfa/ExampleName" }); #endregion } public void IdentityManagementServiceGenerateOrganizationsAccessReport() { #region generateorganizationsaccessreport-ou var client = new AmazonIdentityManagementServiceClient(); var response = client.GenerateOrganizationsAccessReport(new GenerateOrganizationsAccessReportRequest { EntityPath = "o-a1b2c3d4e5/r-f6g7h8i9j0example/ou-1a2b3c-k9l8m7n6o5example" }); string jobId = response.JobId; #endregion } public void IdentityManagementServiceGenerateServiceLastAccessedDetails() { #region generateaccessdata-policy-1541695178514 var client = new AmazonIdentityManagementServiceClient(); var response = client.GenerateServiceLastAccessedDetails(new GenerateServiceLastAccessedDetailsRequest { Arn = "arn:aws:iam::123456789012:policy/ExamplePolicy1" }); string jobId = response.JobId; #endregion } public void IdentityManagementServiceGetAccountPasswordPolicy() { #region 5e4598c7-c425-431f-8af1-19073b3c4a5f var client = new AmazonIdentityManagementServiceClient(); var response = client.GetAccountPasswordPolicy(new GetAccountPasswordPolicyRequest { }); PasswordPolicy passwordPolicy = response.PasswordPolicy; #endregion } public void IdentityManagementServiceGetAccountSummary() { #region 9d8447af-f344-45de-8219-2cebc3cce7f2 var client = new AmazonIdentityManagementServiceClient(); var response = client.GetAccountSummary(new GetAccountSummaryRequest { }); Dictionary<string, int> summaryMap = response.SummaryMap; #endregion } public void IdentityManagementServiceGetInstanceProfile() { #region 463b9ba5-18cc-4608-9ccb-5a7c6b6e5fe7 var client = new AmazonIdentityManagementServiceClient(); var response = client.GetInstanceProfile(new GetInstanceProfileRequest { InstanceProfileName = "ExampleInstanceProfile" }); InstanceProfile instanceProfile = response.InstanceProfile; #endregion } public void IdentityManagementServiceGetLoginProfile() { #region d6b580cc-909f-4925-9caa-d425cbc1ad47 var client = new AmazonIdentityManagementServiceClient(); var response = client.GetLoginProfile(new GetLoginProfileRequest { UserName = "Anika" }); LoginProfile loginProfile = response.LoginProfile; #endregion } public void IdentityManagementServiceGetOrganizationsAccessReport() { #region getorganizationsaccessreport-ou var client = new AmazonIdentityManagementServiceClient(); var response = client.GetOrganizationsAccessReport(new GetOrganizationsAccessReportRequest { JobId = "examplea-1234-b567-cde8-90fg123abcd4" }); List<AccessDetail> accessDetails = response.AccessDetails; bool isTruncated = response.IsTruncated; DateTime jobCompletionDate = response.JobCompletionDate; DateTime jobCreationDate = response.JobCreationDate; string jobStatus = response.JobStatus; int numberOfServicesAccessible = response.NumberOfServicesAccessible; int numberOfServicesNotAccessed = response.NumberOfServicesNotAccessed; #endregion } public void IdentityManagementServiceGetRole() { #region 5b7d03a6-340c-472d-aa77-56425950d8b0 var client = new AmazonIdentityManagementServiceClient(); var response = client.GetRole(new GetRoleRequest { RoleName = "Test-Role" }); Role role = response.Role; #endregion } public void IdentityManagementServiceGetServiceLastAccessedDetails() { #region getserviceaccessdetails-policy-1541696298085 var client = new AmazonIdentityManagementServiceClient(); var response = client.GetServiceLastAccessedDetails(new GetServiceLastAccessedDetailsRequest { JobId = "examplef-1305-c245-eba4-71fe298bcda7" }); bool isTruncated = response.IsTruncated; DateTime jobCompletionDate = response.JobCompletionDate; DateTime jobCreationDate = response.JobCreationDate; string jobStatus = response.JobStatus; List<ServiceLastAccessed> servicesLastAccessed = response.ServicesLastAccessed; #endregion } public void IdentityManagementServiceGetServiceLastAccessedDetailsWithEntities() { #region getserviceaccessdetailsentity-policy-1541697621384 var client = new AmazonIdentityManagementServiceClient(); var response = client.GetServiceLastAccessedDetailsWithEntities(new GetServiceLastAccessedDetailsWithEntitiesRequest { JobId = "examplef-1305-c245-eba4-71fe298bcda7", ServiceNamespace = "iam" }); List<EntityDetails> entityDetailsList = response.EntityDetailsList; bool isTruncated = response.IsTruncated; DateTime jobCompletionDate = response.JobCompletionDate; DateTime jobCreationDate = response.JobCreationDate; string jobStatus = response.JobStatus; #endregion } public void IdentityManagementServiceGetUser() { #region ede000a1-9e4c-40db-bd0a-d4f95e41a6ab var client = new AmazonIdentityManagementServiceClient(); var response = client.GetUser(new GetUserRequest { UserName = "Bob" }); User user = response.User; #endregion } public void IdentityManagementServiceListAccessKeys() { #region 15571463-ebea-411a-a021-1c76bd2a3625 var client = new AmazonIdentityManagementServiceClient(); var response = client.ListAccessKeys(new ListAccessKeysRequest { UserName = "Alice" }); List<AccessKeyMetadata> accessKeyMetadata = response.AccessKeyMetadata; #endregion } public void IdentityManagementServiceListAccountAliases() { #region e27b457a-16f9-4e05-a006-3df7b3472741 var client = new AmazonIdentityManagementServiceClient(); var response = client.ListAccountAliases(new ListAccountAliasesRequest { }); List<string> accountAliases = response.AccountAliases; #endregion } public void IdentityManagementServiceListGroupPolicies() { #region 02de5095-2410-4d3a-ac1b-cc40234af68f var client = new AmazonIdentityManagementServiceClient(); var response = client.ListGroupPolicies(new ListGroupPoliciesRequest { GroupName = "Admins" }); List<string> policyNames = response.PolicyNames; #endregion } public void IdentityManagementServiceListGroups() { #region b3ab1380-2a21-42fb-8e85-503f65512c66 var client = new AmazonIdentityManagementServiceClient(); var response = client.ListGroups(new ListGroupsRequest { }); List<Group> groups = response.Groups; #endregion } public void IdentityManagementServiceListGroupsForUser() { #region 278ec2ee-fc28-4136-83fb-433af0ae46a2 var client = new AmazonIdentityManagementServiceClient(); var response = client.ListGroupsForUser(new ListGroupsForUserRequest { UserName = "Bob" }); List<Group> groups = response.Groups; #endregion } public void IdentityManagementServiceListPoliciesGrantingServiceAccess() { #region listpoliciesaccess-user-1541698749508 var client = new AmazonIdentityManagementServiceClient(); var response = client.ListPoliciesGrantingServiceAccess(new ListPoliciesGrantingServiceAccessRequest { Arn = "arn:aws:iam::123456789012:user/ExampleUser01", ServiceNamespaces = new List<string> { "iam", "ec2" } }); bool isTruncated = response.IsTruncated; List<ListPoliciesGrantingServiceAccessEntry> policiesGrantingServiceAccess = response.PoliciesGrantingServiceAccess; #endregion } public void IdentityManagementServiceListRoleTags() { #region to-list-the-tags-attached-to-an-iam-role-1506719238376 var client = new AmazonIdentityManagementServiceClient(); var response = client.ListRoleTags(new ListRoleTagsRequest { RoleName = "taggedrole1" }); bool isTruncated = response.IsTruncated; List<Tag> tags = response.Tags; #endregion } public void IdentityManagementServiceListSigningCertificates() { #region b4c10256-4fc9-457e-b3fd-4a110d4d73dc var client = new AmazonIdentityManagementServiceClient(); var response = client.ListSigningCertificates(new ListSigningCertificatesRequest { UserName = "Bob" }); List<SigningCertificate> certificates = response.Certificates; #endregion } public void IdentityManagementServiceListUsers() { #region 9edfbd73-03d8-4d8a-9a79-76c85e8c8298 var client = new AmazonIdentityManagementServiceClient(); var response = client.ListUsers(new ListUsersRequest { }); List<User> users = response.Users; #endregion } public void IdentityManagementServiceListUserTags() { #region to-list-the-tags-attached-to-an-iam-user-1506719473186 var client = new AmazonIdentityManagementServiceClient(); var response = client.ListUserTags(new ListUserTagsRequest { UserName = "anika" }); bool isTruncated = response.IsTruncated; List<Tag> tags = response.Tags; #endregion } public void IdentityManagementServiceListVirtualMFADevices() { #region 54f9ac18-5100-4070-bec4-fe5f612710d5 var client = new AmazonIdentityManagementServiceClient(); var response = client.ListVirtualMFADevices(new ListVirtualMFADevicesRequest { }); List<VirtualMFADevice> virtualMFADevices = response.VirtualMFADevices; #endregion } public void IdentityManagementServicePutGroupPolicy() { #region 4bc17418-758f-4d0f-ab0c-4d00265fec2e var client = new AmazonIdentityManagementServiceClient(); var response = client.PutGroupPolicy(new PutGroupPolicyRequest { GroupName = "Admins", PolicyDocument = "{\"Version\":\"2012-10-17\",\"Statement\":{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}}", PolicyName = "AllPerms" }); #endregion } public void IdentityManagementServicePutRolePolicy() { #region de62fd00-46c7-4601-9e0d-71d5fbb11ecb var client = new AmazonIdentityManagementServiceClient(); var response = client.PutRolePolicy(new PutRolePolicyRequest { PolicyDocument = "{\"Version\":\"2012-10-17\",\"Statement\":{\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"}}", PolicyName = "S3AccessPolicy", RoleName = "S3Access" }); #endregion } public void IdentityManagementServicePutUserPolicy() { #region 2551ffc6-3576-4d39-823f-30b60bffc2c7 var client = new AmazonIdentityManagementServiceClient(); var response = client.PutUserPolicy(new PutUserPolicyRequest { PolicyDocument = "{\"Version\":\"2012-10-17\",\"Statement\":{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}}", PolicyName = "AllAccessPolicy", UserName = "Bob" }); #endregion } public void IdentityManagementServiceRemoveRoleFromInstanceProfile() { #region 6d9f46f1-9f4a-4873-b403-51a85c5c627c var client = new AmazonIdentityManagementServiceClient(); var response = client.RemoveRoleFromInstanceProfile(new RemoveRoleFromInstanceProfileRequest { InstanceProfileName = "ExampleInstanceProfile", RoleName = "Test-Role" }); #endregion } public void IdentityManagementServiceRemoveUserFromGroup() { #region fb54d5b4-0caf-41d8-af0e-10a84413f174 var client = new AmazonIdentityManagementServiceClient(); var response = client.RemoveUserFromGroup(new RemoveUserFromGroupRequest { GroupName = "Admins", UserName = "Bob" }); #endregion } public void IdentityManagementServiceSetSecurityTokenServicePreferences() { #region 61a785a7-d30a-415a-ae18-ab9236e56871 var client = new AmazonIdentityManagementServiceClient(); var response = client.SetSecurityTokenServicePreferences(new SetSecurityTokenServicePreferencesRequest { GlobalEndpointTokenVersion = "v2Token" }); #endregion } public void IdentityManagementServiceTagRole() { #region to-add-a-tag-key-and-value-to-an-iam-role-1506718791513 var client = new AmazonIdentityManagementServiceClient(); var response = client.TagRole(new TagRoleRequest { RoleName = "taggedrole", Tags = new List<Tag> { new Tag { Key = "Dept", Value = "Accounting" }, new Tag { Key = "CostCenter", Value = "12345" } } }); #endregion } public void IdentityManagementServiceTagUser() { #region to-add-a-tag-key-and-value-to-an-iam-user-1506719044227 var client = new AmazonIdentityManagementServiceClient(); var response = client.TagUser(new TagUserRequest { Tags = new List<Tag> { new Tag { Key = "Dept", Value = "Accounting" }, new Tag { Key = "CostCenter", Value = "12345" } }, UserName = "anika" }); #endregion } public void IdentityManagementServiceUntagRole() { #region to-remove-a-tag-from-an-iam-role-1506719589943 var client = new AmazonIdentityManagementServiceClient(); var response = client.UntagRole(new UntagRoleRequest { RoleName = "taggedrole", TagKeys = new List<string> { "Dept" } }); #endregion } public void IdentityManagementServiceUntagUser() { #region to-remove-a-tag-from-an-iam-user-1506719725554 var client = new AmazonIdentityManagementServiceClient(); var response = client.UntagUser(new UntagUserRequest { TagKeys = new List<string> { "Dept" }, UserName = "anika" }); #endregion } public void IdentityManagementServiceUpdateAccessKey() { #region 02b556fd-e673-49b7-ab6b-f2f9035967d0 var client = new AmazonIdentityManagementServiceClient(); var response = client.UpdateAccessKey(new UpdateAccessKeyRequest { AccessKeyId = "AKIAIOSFODNN7EXAMPLE", Status = "Inactive", UserName = "Bob" }); #endregion } public void IdentityManagementServiceUpdateAccountPasswordPolicy() { #region c263a1af-37dc-4423-8dba-9790284ef5e0 var client = new AmazonIdentityManagementServiceClient(); var response = client.UpdateAccountPasswordPolicy(new UpdateAccountPasswordPolicyRequest { MinimumPasswordLength = 8, RequireNumbers = true }); #endregion } public void IdentityManagementServiceUpdateAssumeRolePolicy() { #region c9150063-d953-4e99-9576-9685872006c6 var client = new AmazonIdentityManagementServiceClient(); var response = client.UpdateAssumeRolePolicy(new UpdateAssumeRolePolicyRequest { PolicyDocument = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":[\"ec2.amazonaws.com\"]},\"Action\":[\"sts:AssumeRole\"]}]}", RoleName = "S3AccessForEC2Instances" }); #endregion } public void IdentityManagementServiceUpdateGroup() { #region f0cf1662-91ae-4278-a80e-7db54256ccba var client = new AmazonIdentityManagementServiceClient(); var response = client.UpdateGroup(new UpdateGroupRequest { GroupName = "Test", NewGroupName = "Test-1" }); #endregion } public void IdentityManagementServiceUpdateLoginProfile() { #region 036d9498-ecdb-4ed6-a8d8-366c383d1487 var client = new AmazonIdentityManagementServiceClient(); var response = client.UpdateLoginProfile(new UpdateLoginProfileRequest { Password = "SomeKindOfPassword123!@#", UserName = "Bob" }); #endregion } public void IdentityManagementServiceUpdateSigningCertificate() { #region 829aee7b-efc5-4b3b-84a5-7f899b38018d var client = new AmazonIdentityManagementServiceClient(); var response = client.UpdateSigningCertificate(new UpdateSigningCertificateRequest { CertificateId = "TA7SMP42TDN5Z26OBPJE7EXAMPLE", Status = "Inactive", UserName = "Bob" }); #endregion } public void IdentityManagementServiceUpdateUser() { #region 275d53ed-347a-44e6-b7d0-a96276154352 var client = new AmazonIdentityManagementServiceClient(); var response = client.UpdateUser(new UpdateUserRequest { NewUserName = "Robert", UserName = "Bob" }); #endregion } public void IdentityManagementServiceUploadServerCertificate() { #region 06eab6d1-ebf2-4bd9-839d-f7508b9a38b6 var client = new AmazonIdentityManagementServiceClient(); var response = client.UploadServerCertificate(new UploadServerCertificateRequest { CertificateBody = "-----BEGIN CERTIFICATE-----<a very long certificate text string>-----END CERTIFICATE-----", Path = "/company/servercerts/", PrivateKey = "-----BEGIN DSA PRIVATE KEY-----<a very long private key string>-----END DSA PRIVATE KEY-----", ServerCertificateName = "ProdServerCert" }); ServerCertificateMetadata serverCertificateMetadata = response.ServerCertificateMetadata; #endregion } public void IdentityManagementServiceUploadSigningCertificate() { #region e67489b6-7b73-4e30-9ed3-9a9e0231e458 var client = new AmazonIdentityManagementServiceClient(); var response = client.UploadSigningCertificate(new UploadSigningCertificateRequest { CertificateBody = "-----BEGIN CERTIFICATE-----<certificate-body>-----END CERTIFICATE-----", UserName = "Bob" }); SigningCertificate certificate = response.Certificate; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
1,090
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.Inspector; using Amazon.Inspector.Model; namespace AWSSDKDocSamples.Amazon.Inspector.Generated { class InspectorSamples : ISample { public void InspectorAddAttributesToFindings() { #region add-attributes-to-findings-1481063856401 var client = new AmazonInspectorClient(); var response = client.AddAttributesToFindings(new AddAttributesToFindingsRequest { Attributes = new List<Attribute> { new Attribute { Key = "Example", Value = "example" } }, FindingArns = new List<string> { "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-8l1VIE0D/run/0-Z02cjjug/finding/0-T8yM9mEU" } }); Dictionary<string, FailedItemDetails> failedItems = response.FailedItems; #endregion } public void InspectorCreateAssessmentTarget() { #region create-assessment-target-1481063953657 var client = new AmazonInspectorClient(); var response = client.CreateAssessmentTarget(new CreateAssessmentTargetRequest { AssessmentTargetName = "ExampleAssessmentTarget", ResourceGroupArn = "arn:aws:inspector:us-west-2:123456789012:resourcegroup/0-AB6DMKnv" }); string assessmentTargetArn = response.AssessmentTargetArn; #endregion } public void InspectorCreateAssessmentTemplate() { #region create-assessment-template-1481064046719 var client = new AmazonInspectorClient(); var response = client.CreateAssessmentTemplate(new CreateAssessmentTemplateRequest { AssessmentTargetArn = "arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX", AssessmentTemplateName = "ExampleAssessmentTemplate", DurationInSeconds = 180, RulesPackageArns = new List<string> { "arn:aws:inspector:us-west-2:758058086616:rulespackage/0-11B9DBXp" }, UserAttributesForFindings = new List<Attribute> { new Attribute { Key = "Example", Value = "example" } } }); string assessmentTemplateArn = response.AssessmentTemplateArn; #endregion } public void InspectorCreateResourceGroup() { #region create-resource-group-1481064169037 var client = new AmazonInspectorClient(); var response = client.CreateResourceGroup(new CreateResourceGroupRequest { ResourceGroupTags = new List<ResourceGroupTag> { new ResourceGroupTag { Key = "Name", Value = "example" } } }); string resourceGroupArn = response.ResourceGroupArn; #endregion } public void InspectorDeleteAssessmentRun() { #region delete-assessment-run-1481064251629 var client = new AmazonInspectorClient(); var response = client.DeleteAssessmentRun(new DeleteAssessmentRunRequest { AssessmentRunArn = "arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-it5r2S4T/run/0-11LMTAVe" }); #endregion } public void InspectorDeleteAssessmentTarget() { #region delete-assessment-target-1481064309029 var client = new AmazonInspectorClient(); var response = client.DeleteAssessmentTarget(new DeleteAssessmentTargetRequest { AssessmentTargetArn = "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq" }); #endregion } public void InspectorDeleteAssessmentTemplate() { #region delete-assessment-template-1481064364074 var client = new AmazonInspectorClient(); var response = client.DeleteAssessmentTemplate(new DeleteAssessmentTemplateRequest { AssessmentTemplateArn = "arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-it5r2S4T" }); #endregion } public void InspectorDescribeAssessmentRuns() { #region describte-assessment-runs-1481064424352 var client = new AmazonInspectorClient(); var response = client.DescribeAssessmentRuns(new DescribeAssessmentRunsRequest { AssessmentRunArns = new List<string> { "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-MKkpXXPE" } }); List<AssessmentRun> assessmentRuns = response.AssessmentRuns; Dictionary<string, FailedItemDetails> failedItems = response.FailedItems; #endregion } public void InspectorDescribeAssessmentTargets() { #region describte-assessment-targets-1481064527735 var client = new AmazonInspectorClient(); var response = client.DescribeAssessmentTargets(new DescribeAssessmentTargetsRequest { AssessmentTargetArns = new List<string> { "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq" } }); List<AssessmentTarget> assessmentTargets = response.AssessmentTargets; Dictionary<string, FailedItemDetails> failedItems = response.FailedItems; #endregion } public void InspectorDescribeAssessmentTemplates() { #region describte-assessment-templates-1481064606829 var client = new AmazonInspectorClient(); var response = client.DescribeAssessmentTemplates(new DescribeAssessmentTemplatesRequest { AssessmentTemplateArns = new List<string> { "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw" } }); List<AssessmentTemplate> assessmentTemplates = response.AssessmentTemplates; Dictionary<string, FailedItemDetails> failedItems = response.FailedItems; #endregion } public void InspectorDescribeCrossAccountAccessRole() { #region describte-cross-account-access-role-1481064682267 var client = new AmazonInspectorClient(); var response = client.DescribeCrossAccountAccessRole(new DescribeCrossAccountAccessRoleRequest { }); DateTime registeredAt = response.RegisteredAt; string roleArn = response.RoleArn; bool valid = response.Valid; #endregion } public void InspectorDescribeFindings() { #region describte-findings-1481064771803 var client = new AmazonInspectorClient(); var response = client.DescribeFindings(new DescribeFindingsRequest { FindingArns = new List<string> { "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-MKkpXXPE/finding/0-HwPnsDm4" } }); Dictionary<string, FailedItemDetails> failedItems = response.FailedItems; List<Finding> findings = response.Findings; #endregion } public void InspectorDescribeResourceGroups() { #region describe-resource-groups-1481065787743 var client = new AmazonInspectorClient(); var response = client.DescribeResourceGroups(new DescribeResourceGroupsRequest { ResourceGroupArns = new List<string> { "arn:aws:inspector:us-west-2:123456789012:resourcegroup/0-PyGXopAI" } }); Dictionary<string, FailedItemDetails> failedItems = response.FailedItems; List<ResourceGroup> resourceGroups = response.ResourceGroups; #endregion } public void InspectorDescribeRulesPackages() { #region describe-rules-packages-1481069641979 var client = new AmazonInspectorClient(); var response = client.DescribeRulesPackages(new DescribeRulesPackagesRequest { RulesPackageArns = new List<string> { "arn:aws:inspector:us-west-2:758058086616:rulespackage/0-JJOtZiqQ" } }); Dictionary<string, FailedItemDetails> failedItems = response.FailedItems; List<RulesPackage> rulesPackages = response.RulesPackages; #endregion } public void InspectorGetTelemetryMetadata() { #region get-telemetry-metadata-1481066021297 var client = new AmazonInspectorClient(); var response = client.GetTelemetryMetadata(new GetTelemetryMetadataRequest { AssessmentRunArn = "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-MKkpXXPE" }); List<TelemetryMetadata> telemetryMetadata = response.TelemetryMetadata; #endregion } public void InspectorListAssessmentRunAgents() { #region list-assessment-run-agents-1481918140642 var client = new AmazonInspectorClient(); var response = client.ListAssessmentRunAgents(new ListAssessmentRunAgentsRequest { AssessmentRunArn = "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-MKkpXXPE", MaxResults = 123 }); List<AssessmentRunAgent> assessmentRunAgents = response.AssessmentRunAgents; string nextToken = response.NextToken; #endregion } public void InspectorListAssessmentRuns() { #region list-assessment-runs-1481066340844 var client = new AmazonInspectorClient(); var response = client.ListAssessmentRuns(new ListAssessmentRunsRequest { AssessmentTemplateArns = new List<string> { "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw" }, MaxResults = 123 }); List<string> assessmentRunArns = response.AssessmentRunArns; string nextToken = response.NextToken; #endregion } public void InspectorListAssessmentTargets() { #region list-assessment-targets-1481066540849 var client = new AmazonInspectorClient(); var response = client.ListAssessmentTargets(new ListAssessmentTargetsRequest { MaxResults = 123 }); List<string> assessmentTargetArns = response.AssessmentTargetArns; string nextToken = response.NextToken; #endregion } public void InspectorListAssessmentTemplates() { #region list-assessment-templates-1481066623520 var client = new AmazonInspectorClient(); var response = client.ListAssessmentTemplates(new ListAssessmentTemplatesRequest { AssessmentTargetArns = new List<string> { "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq" }, MaxResults = 123 }); List<string> assessmentTemplateArns = response.AssessmentTemplateArns; string nextToken = response.NextToken; #endregion } public void InspectorListEventSubscriptions() { #region list-event-subscriptions-1481068376945 var client = new AmazonInspectorClient(); var response = client.ListEventSubscriptions(new ListEventSubscriptionsRequest { MaxResults = 123, ResourceArn = "arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-7sbz2Kz0" }); string nextToken = response.NextToken; List<Subscription> subscriptions = response.Subscriptions; #endregion } public void InspectorListFindings() { #region list-findings-1481066840611 var client = new AmazonInspectorClient(); var response = client.ListFindings(new ListFindingsRequest { AssessmentRunArns = new List<string> { "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-MKkpXXPE" }, MaxResults = 123 }); List<string> findingArns = response.FindingArns; string nextToken = response.NextToken; #endregion } public void InspectorListRulesPackages() { #region list-rules-packages-1481066954883 var client = new AmazonInspectorClient(); var response = client.ListRulesPackages(new ListRulesPackagesRequest { MaxResults = 123 }); string nextToken = response.NextToken; List<string> rulesPackageArns = response.RulesPackageArns; #endregion } public void InspectorListTagsForResource() { #region list-tags-for-resource-1481067025240 var client = new AmazonInspectorClient(); var response = client.ListTagsForResource(new ListTagsForResourceRequest { ResourceArn = "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-gcwFliYu" }); List<Tag> tags = response.Tags; #endregion } public void InspectorPreviewAgents() { #region preview-agents-1481067101888 var client = new AmazonInspectorClient(); var response = client.PreviewAgents(new PreviewAgentsRequest { MaxResults = 123, PreviewAgentsArn = "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq" }); List<AgentPreview> agentPreviews = response.AgentPreviews; string nextToken = response.NextToken; #endregion } public void InspectorRegisterCrossAccountAccessRole() { #region register-cross-account-access-role-1481067178301 var client = new AmazonInspectorClient(); var response = client.RegisterCrossAccountAccessRole(new RegisterCrossAccountAccessRoleRequest { RoleArn = "arn:aws:iam::123456789012:role/inspector" }); #endregion } public void InspectorRemoveAttributesFromFindings() { #region remove-attributes-from-findings-1481067246548 var client = new AmazonInspectorClient(); var response = client.RemoveAttributesFromFindings(new RemoveAttributesFromFindingsRequest { AttributeKeys = new List<string> { "key=Example,value=example" }, FindingArns = new List<string> { "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-8l1VIE0D/run/0-Z02cjjug/finding/0-T8yM9mEU" } }); Dictionary<string, FailedItemDetails> failedItems = response.FailedItems; #endregion } public void InspectorSetTagsForResource() { #region set-tags-for-resource-1481067329646 var client = new AmazonInspectorClient(); var response = client.SetTagsForResource(new SetTagsForResourceRequest { ResourceArn = "arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-7sbz2Kz0", Tags = new List<Tag> { new Tag { Key = "Example", Value = "example" } } }); #endregion } public void InspectorStartAssessmentRun() { #region start-assessment-run-1481067407484 var client = new AmazonInspectorClient(); var response = client.StartAssessmentRun(new StartAssessmentRunRequest { AssessmentRunName = "examplerun", AssessmentTemplateArn = "arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-it5r2S4T" }); string assessmentRunArn = response.AssessmentRunArn; #endregion } public void InspectorStopAssessmentRun() { #region stop-assessment-run-1481067502857 var client = new AmazonInspectorClient(); var response = client.StopAssessmentRun(new StopAssessmentRunRequest { AssessmentRunArn = "arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-it5r2S4T/run/0-11LMTAVe" }); #endregion } public void InspectorSubscribeToEvent() { #region subscribe-to-event-1481067686031 var client = new AmazonInspectorClient(); var response = client.SubscribeToEvent(new SubscribeToEventRequest { Event = "ASSESSMENT_RUN_COMPLETED", ResourceArn = "arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-7sbz2Kz0", TopicArn = "arn:aws:sns:us-west-2:123456789012:exampletopic" }); #endregion } public void InspectorUnsubscribeFromEvent() { #region unsubscribe-from-event-1481067781705 var client = new AmazonInspectorClient(); var response = client.UnsubscribeFromEvent(new UnsubscribeFromEventRequest { Event = "ASSESSMENT_RUN_COMPLETED", ResourceArn = "arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-7sbz2Kz0", TopicArn = "arn:aws:sns:us-west-2:123456789012:exampletopic" }); #endregion } public void InspectorUpdateAssessmentTarget() { #region update-assessment-target-1481067866692 var client = new AmazonInspectorClient(); var response = client.UpdateAssessmentTarget(new UpdateAssessmentTargetRequest { AssessmentTargetArn = "arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX", AssessmentTargetName = "Example", ResourceGroupArn = "arn:aws:inspector:us-west-2:123456789012:resourcegroup/0-yNbgL5Pt" }); #endregion } # region ISample Members public virtual void Run() { } # endregion } }
576
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.KeyManagementService; using Amazon.KeyManagementService.Model; namespace AWSSDKDocSamples.Amazon.KeyManagementService.Generated { class KeyManagementServiceSamples : ISample { public void KeyManagementServiceCancelKeyDeletion() { #region to-cancel-deletion-of-a-cmk-1477428535102 var client = new AmazonKeyManagementServiceClient(); var response = client.CancelKeyDeletion(new CancelKeyDeletionRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab" // The identifier of the KMS key whose deletion you are canceling. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. }); string keyId = response.KeyId; // The ARN of the KMS key whose deletion you canceled. #endregion } public void KeyManagementServiceConnectCustomKeyStore() { #region to-connect-a-custom-key-store-1628626947750 var client = new AmazonKeyManagementServiceClient(); var response = client.ConnectCustomKeyStore(new ConnectCustomKeyStoreRequest { CustomKeyStoreId = "cks-1234567890abcdef0" // The ID of the AWS KMS custom key store. }); #endregion } public void KeyManagementServiceCreateAlias() { #region to-create-an-alias-1477505685119 var client = new AmazonKeyManagementServiceClient(); var response = client.CreateAlias(new CreateAliasRequest { AliasName = "alias/ExampleAlias", // The alias to create. Aliases must begin with 'alias/'. Do not use aliases that begin with 'alias/aws' because they are reserved for use by AWS. TargetKeyId = "1234abcd-12ab-34cd-56ef-1234567890ab" // The identifier of the KMS key whose alias you are creating. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. }); #endregion } public void KeyManagementServiceCreateCustomKeyStore() { #region to-create-an-aws-cloudhsm-custom-key-store-1 var client = new AmazonKeyManagementServiceClient(); var response = client.CreateCustomKeyStore(new CreateCustomKeyStoreRequest { CloudHsmClusterId = "cluster-234abcdefABC", // The ID of the CloudHSM cluster. CustomKeyStoreName = "ExampleKeyStore", // A friendly name for the custom key store. KeyStorePassword = "kmsPswd", // The password for the kmsuser CU account in the specified cluster. TrustAnchorCertificate = "<certificate-goes-here>" // The content of the customerCA.crt file that you created when you initialized the cluster. }); string customKeyStoreId = response.CustomKeyStoreId; // The ID of the new custom key store. #endregion } public void KeyManagementServiceCreateCustomKeyStore() { #region to-create-an-external-custom-key-store-with-vpc-connectivity-2 var client = new AmazonKeyManagementServiceClient(); var response = client.CreateCustomKeyStore(new CreateCustomKeyStoreRequest { CustomKeyStoreName = "ExampleVPCEndpointKeyStore", // A friendly name for the custom key store CustomKeyStoreType = "EXTERNAL_KEY_STORE", // For external key stores, the value must be EXTERNAL_KEY_STORE XksProxyAuthenticationCredential = new XksProxyAuthenticationCredentialType { AccessKeyId = "ABCDE12345670EXAMPLE", RawSecretAccessKey = "DXjSUawnel2fr6SKC7G25CNxTyWKE5PF9XX6H/u9pSo=" }, // The access key ID and secret access key that KMS uses to authenticate to your external key store proxy XksProxyConnectivity = "VPC_ENDPOINT_SERVICE", // Indicates how AWS KMS communicates with the external key store proxy XksProxyUriEndpoint = "https://myproxy-private.xks.example.com", // The URI that AWS KMS uses to connect to the external key store proxy XksProxyUriPath = "/example-prefix/kms/xks/v1", // The URI path to the external key store proxy APIs XksProxyVpcEndpointServiceName = "com.amazonaws.vpce.us-east-1.vpce-svc-example1" // The VPC endpoint service that KMS uses to communicate with the external key store proxy }); string customKeyStoreId = response.CustomKeyStoreId; // The ID of the new custom key store. #endregion } public void KeyManagementServiceCreateCustomKeyStore() { #region to-create-an-external-custom-key-store-with-a-public-endpoint-3 var client = new AmazonKeyManagementServiceClient(); var response = client.CreateCustomKeyStore(new CreateCustomKeyStoreRequest { CustomKeyStoreName = "ExamplePublicEndpointKeyStore", // A friendly name for the custom key store CustomKeyStoreType = "EXTERNAL_KEY_STORE", // For external key stores, the value must be EXTERNAL_KEY_STORE XksProxyAuthenticationCredential = new XksProxyAuthenticationCredentialType { AccessKeyId = "ABCDE12345670EXAMPLE", RawSecretAccessKey = "DXjSUawnel2fr6SKC7G25CNxTyWKE5PF9XX6H/u9pSo=" }, // The access key ID and secret access key that KMS uses to authenticate to your external key store proxy XksProxyConnectivity = "PUBLIC_ENDPOINT", // Indicates how AWS KMS communicates with the external key store proxy XksProxyUriEndpoint = "https://myproxy.xks.example.com", // The URI that AWS KMS uses to connect to the external key store proxy XksProxyUriPath = "/kms/xks/v1" // The URI path to your external key store proxy API }); string customKeyStoreId = response.CustomKeyStoreId; // The ID of the new custom key store. #endregion } public void KeyManagementServiceCreateGrant() { #region to-create-a-grant-1477972226782 var client = new AmazonKeyManagementServiceClient(); var response = client.CreateGrant(new CreateGrantRequest { GranteePrincipal = "arn:aws:iam::111122223333:role/ExampleRole", // The identity that is given permission to perform the operations specified in the grant. KeyId = "arn:aws:kms:us-east-2:444455556666:key/1234abcd-12ab-34cd-56ef-1234567890ab", // The identifier of the KMS key to which the grant applies. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. Operations = new List<string> { "Encrypt", "Decrypt" } // A list of operations that the grant allows. }); string grantId = response.GrantId; // The unique identifier of the grant. string grantToken = response.GrantToken; // The grant token. #endregion } public void KeyManagementServiceCreateKey() { #region to-create-a-cmk-1 var client = new AmazonKeyManagementServiceClient(); var response = client.CreateKey(new CreateKeyRequest { }); KeyMetadata keyMetadata = response.KeyMetadata; // Detailed information about the KMS key that this operation creates. #endregion } public void KeyManagementServiceCreateKey() { #region to-create-an-asymmetric-rsa-kms-key-for-encryption-and-decryption-2 var client = new AmazonKeyManagementServiceClient(); var response = client.CreateKey(new CreateKeyRequest { KeySpec = "RSA_4096", // Describes the type of key material in the KMS key. KeyUsage = "ENCRYPT_DECRYPT" // The cryptographic operations for which you can use the KMS key. }); KeyMetadata keyMetadata = response.KeyMetadata; // Detailed information about the KMS key that this operation creates. #endregion } public void KeyManagementServiceCreateKey() { #region to-create-an-asymmetric-elliptic-curve-kms-key-for-signing-and-verification-3 var client = new AmazonKeyManagementServiceClient(); var response = client.CreateKey(new CreateKeyRequest { KeySpec = "ECC_NIST_P521", // Describes the type of key material in the KMS key. KeyUsage = "SIGN_VERIFY" // The cryptographic operations for which you can use the KMS key. }); KeyMetadata keyMetadata = response.KeyMetadata; // Detailed information about the KMS key that this operation creates. #endregion } public void KeyManagementServiceCreateKey() { #region to-create-an-hmac-kms-key-1630628752841 var client = new AmazonKeyManagementServiceClient(); var response = client.CreateKey(new CreateKeyRequest { KeySpec = "HMAC_384", // Describes the type of key material in the KMS key. KeyUsage = "GENERATE_VERIFY_MAC" // The cryptographic operations for which you can use the KMS key. }); KeyMetadata keyMetadata = response.KeyMetadata; // Detailed information about the KMS key that this operation creates. #endregion } public void KeyManagementServiceCreateKey() { #region to-create-a-multi-region-primary-kms-key-4 var client = new AmazonKeyManagementServiceClient(); var response = client.CreateKey(new CreateKeyRequest { MultiRegion = true // Indicates whether the KMS key is a multi-Region (True) or regional (False) key. }); KeyMetadata keyMetadata = response.KeyMetadata; // Detailed information about the KMS key that this operation creates. #endregion } public void KeyManagementServiceCreateKey() { #region to-create-a-kms-key-for-imported-key-material-5 var client = new AmazonKeyManagementServiceClient(); var response = client.CreateKey(new CreateKeyRequest { Origin = "EXTERNAL" // The source of the key material for the KMS key. }); KeyMetadata keyMetadata = response.KeyMetadata; // Detailed information about the KMS key that this operation creates. #endregion } public void KeyManagementServiceCreateKey() { #region to-create-a-kms-key-in-an-aws-cloudhsm-custom-key-store-6 var client = new AmazonKeyManagementServiceClient(); var response = client.CreateKey(new CreateKeyRequest { CustomKeyStoreId = "cks-1234567890abcdef0", // Identifies the custom key store that hosts the KMS key. Origin = "AWS_CLOUDHSM" // Indicates the source of the key material for the KMS key. }); KeyMetadata keyMetadata = response.KeyMetadata; // Detailed information about the KMS key that this operation creates. #endregion } public void KeyManagementServiceCreateKey() { #region to-create-a-kms-key-in-an-external-custom-key-store-7 var client = new AmazonKeyManagementServiceClient(); var response = client.CreateKey(new CreateKeyRequest { CustomKeyStoreId = "cks-9876543210fedcba9", // Identifies the custom key store that hosts the KMS key. Origin = "EXTERNAL_KEY_STORE", // Indicates the source of the key material for the KMS key. XksKeyId = "bb8562717f809024" // Identifies the encryption key in your external key manager that is associated with the KMS key }); KeyMetadata keyMetadata = response.KeyMetadata; // Detailed information about the KMS key that this operation creates. #endregion } public void KeyManagementServiceDecrypt() { #region to-decrypt-data-1 var client = new AmazonKeyManagementServiceClient(); var response = client.Decrypt(new DecryptRequest { CiphertextBlob = new MemoryStream(<binary data>), // The encrypted data (ciphertext). KeyId = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab" // A key identifier for the KMS key to use to decrypt the data. }); string encryptionAlgorithm = response.EncryptionAlgorithm; // The encryption algorithm that was used to decrypt the ciphertext. SYMMETRIC_DEFAULT is the only valid value for symmetric encryption in AWS KMS. string keyId = response.KeyId; // The Amazon Resource Name (ARN) of the KMS key that was used to decrypt the data. MemoryStream plaintext = response.Plaintext; // The decrypted (plaintext) data. #endregion } public void KeyManagementServiceDecrypt() { #region to-decrypt-data-2 var client = new AmazonKeyManagementServiceClient(); var response = client.Decrypt(new DecryptRequest { CiphertextBlob = new MemoryStream(<binary data>), // The encrypted data (ciphertext). EncryptionAlgorithm = "RSAES_OAEP_SHA_256", // The encryption algorithm that was used to encrypt the data. This parameter is required to decrypt with an asymmetric KMS key. KeyId = "0987dcba-09fe-87dc-65ba-ab0987654321" // A key identifier for the KMS key to use to decrypt the data. This parameter is required to decrypt with an asymmetric KMS key. }); string encryptionAlgorithm = response.EncryptionAlgorithm; // The encryption algorithm that was used to decrypt the ciphertext. string keyId = response.KeyId; // The Amazon Resource Name (ARN) of the KMS key that was used to decrypt the data. MemoryStream plaintext = response.Plaintext; // The decrypted (plaintext) data. #endregion } public void KeyManagementServiceDecrypt() { #region to-decrypt-data-for-a-nitro-enclave-2 var client = new AmazonKeyManagementServiceClient(); var response = client.Decrypt(new DecryptRequest { CiphertextBlob = new MemoryStream(<binary data>), // The encrypted data. This ciphertext was encrypted with the KMS key KeyId = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", // The KMS key to use to decrypt the ciphertext Recipient = new RecipientInfo { AttestationDocument = new MemoryStream(<attestation document>), KeyEncryptionAlgorithm = "RSAES_OAEP_SHA_256" } // Specifies the attestation document from the Nitro enclave and the encryption algorithm to use with the public key from the attestation document }); MemoryStream ciphertextForRecipient = response.CiphertextForRecipient; // The decrypted CiphertextBlob encrypted with the public key from the attestation document string keyId = response.KeyId; // The KMS key that was used to decrypt the encrypted data (CiphertextBlob) MemoryStream plaintext = response.Plaintext; // This field is null or empty #endregion } public void KeyManagementServiceDeleteAlias() { #region to-delete-an-alias-1478285209338 var client = new AmazonKeyManagementServiceClient(); var response = client.DeleteAlias(new DeleteAliasRequest { AliasName = "alias/ExampleAlias" // The alias to delete. }); #endregion } public void KeyManagementServiceDeleteCustomKeyStore() { #region to-delete-a-custom-key-store-from-aws-kms-1628630837145 var client = new AmazonKeyManagementServiceClient(); var response = client.DeleteCustomKeyStore(new DeleteCustomKeyStoreRequest { CustomKeyStoreId = "cks-1234567890abcdef0" // The ID of the custom key store to be deleted. }); #endregion } public void KeyManagementServiceDeleteImportedKeyMaterial() { #region to-delete-imported-key-material-1478561674507 var client = new AmazonKeyManagementServiceClient(); var response = client.DeleteImportedKeyMaterial(new DeleteImportedKeyMaterialRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab" // The identifier of the KMS key whose imported key material you are deleting. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. }); #endregion } public void KeyManagementServiceDescribeCustomKeyStores() { #region to-get-detailed-information-about-custom-key-stores-in-the-account-and-region-1 var client = new AmazonKeyManagementServiceClient(); var response = client.DescribeCustomKeyStores(new DescribeCustomKeyStoresRequest { }); List<CustomKeyStoresListEntry> customKeyStores = response.CustomKeyStores; // Details about each custom key store in the account and Region. #endregion } public void KeyManagementServiceDescribeCustomKeyStores() { #region to-get-detailed-information-about-a-cloudhsm-custom-key-store-by-name-2 var client = new AmazonKeyManagementServiceClient(); var response = client.DescribeCustomKeyStores(new DescribeCustomKeyStoresRequest { CustomKeyStoreName = "ExampleKeyStore" // The friendly name of the custom key store. }); List<CustomKeyStoresListEntry> customKeyStores = response.CustomKeyStores; // Detailed information about the specified custom key store. #endregion } public void KeyManagementServiceDescribeCustomKeyStores() { #region to-get-detailed-information-about-an-external-key-store--3 var client = new AmazonKeyManagementServiceClient(); var response = client.DescribeCustomKeyStores(new DescribeCustomKeyStoresRequest { CustomKeyStoreId = "cks-9876543210fedcba9" // The ID of the custom key store. }); List<CustomKeyStoresListEntry> customKeyStores = response.CustomKeyStores; // Detailed information about the specified custom key store. #endregion } public void KeyManagementServiceDescribeCustomKeyStores() { #region to-get-detailed-information-about-an-external-custom-key-store-by-name-4 var client = new AmazonKeyManagementServiceClient(); var response = client.DescribeCustomKeyStores(new DescribeCustomKeyStoresRequest { CustomKeyStoreName = "VPCExternalKeystore" }); List<CustomKeyStoresListEntry> customKeyStores = response.CustomKeyStores; // Detailed information about the specified custom key store. #endregion } public void KeyManagementServiceDescribeKey() { #region get-key-details-1 var client = new AmazonKeyManagementServiceClient(); var response = client.DescribeKey(new DescribeKeyRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab" // An identifier for the KMS key. You can use the key ID, key ARN, alias name, alias ARN of the KMS key. }); KeyMetadata keyMetadata = response.KeyMetadata; // An object that contains information about the specified KMS key. #endregion } public void KeyManagementServiceDescribeKey() { #region to-get-details-about-an-rsa-asymmetric-kms-key-2 var client = new AmazonKeyManagementServiceClient(); var response = client.DescribeKey(new DescribeKeyRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab" // An identifier for the KMS key. You can use the key ID, key ARN, alias name, alias ARN of the KMS key. }); KeyMetadata keyMetadata = response.KeyMetadata; // An object that contains information about the specified KMS key. #endregion } public void KeyManagementServiceDescribeKey() { #region to-get-details-about-a-multi-region-key-3 var client = new AmazonKeyManagementServiceClient(); var response = client.DescribeKey(new DescribeKeyRequest { KeyId = "arn:aws:kms:ap-northeast-1:111122223333:key/mrk-1234abcd12ab34cd56ef1234567890ab" // An identifier for the KMS key. You can use the key ID, key ARN, alias name, alias ARN of the KMS key. }); KeyMetadata keyMetadata = response.KeyMetadata; // An object that contains information about the specified KMS key. #endregion } public void KeyManagementServiceDescribeKey() { #region to-get-details-about-an-hmac-kms-key-4 var client = new AmazonKeyManagementServiceClient(); var response = client.DescribeKey(new DescribeKeyRequest { KeyId = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab" // An identifier for the KMS key. You can use the key ID, key ARN, alias name, alias ARN of the KMS key. }); KeyMetadata keyMetadata = response.KeyMetadata; // An object that contains information about the specified KMS key. #endregion } public void KeyManagementServiceDescribeKey() { #region to-get-details-about-a-kms-key-in-an-AWS-CloudHSM-key-store-5 var client = new AmazonKeyManagementServiceClient(); var response = client.DescribeKey(new DescribeKeyRequest { KeyId = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab" // An identifier for the KMS key. You can use the key ID, key ARN, alias name, alias ARN of the KMS key. }); KeyMetadata keyMetadata = response.KeyMetadata; // An object that contains information about the specified KMS key. #endregion } public void KeyManagementServiceDescribeKey() { #region to-get-details-about-a-kms-key-in-an-external-key-store-6 var client = new AmazonKeyManagementServiceClient(); var response = client.DescribeKey(new DescribeKeyRequest { KeyId = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab" // An identifier for the KMS key. You can use the key ID, key ARN, alias name, alias ARN of the KMS key. }); KeyMetadata keyMetadata = response.KeyMetadata; // An object that contains information about the specified KMS key. #endregion } public void KeyManagementServiceDisableKey() { #region to-disable-a-cmk-1478566583659 var client = new AmazonKeyManagementServiceClient(); var response = client.DisableKey(new DisableKeyRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab" // The identifier of the KMS key to disable. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. }); #endregion } public void KeyManagementServiceDisableKeyRotation() { #region to-disable-automatic-rotation-of-key-material-1478624396092 var client = new AmazonKeyManagementServiceClient(); var response = client.DisableKeyRotation(new DisableKeyRotationRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab" // The identifier of the KMS key whose key material will no longer be rotated. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. }); #endregion } public void KeyManagementServiceDisconnectCustomKeyStore() { #region to-disconnect-a-custom-key-store-from-its-cloudhsm-cluster-234abcdefABC var client = new AmazonKeyManagementServiceClient(); var response = client.DisconnectCustomKeyStore(new DisconnectCustomKeyStoreRequest { CustomKeyStoreId = "cks-1234567890abcdef0" // The ID of the custom key store. }); #endregion } public void KeyManagementServiceEnableKey() { #region to-enable-a-cmk-1478627501129 var client = new AmazonKeyManagementServiceClient(); var response = client.EnableKey(new EnableKeyRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab" // The identifier of the KMS key to enable. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. }); #endregion } public void KeyManagementServiceEnableKeyRotation() { #region to-enable-automatic-rotation-of-key-material-1478629109677 var client = new AmazonKeyManagementServiceClient(); var response = client.EnableKeyRotation(new EnableKeyRotationRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab" // The identifier of the KMS key whose key material will be rotated annually. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. }); #endregion } public void KeyManagementServiceEncrypt() { #region to-encrypt-data-1 var client = new AmazonKeyManagementServiceClient(); var response = client.Encrypt(new EncryptRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab", // The identifier of the KMS key to use for encryption. You can use the key ID or Amazon Resource Name (ARN) of the KMS key, or the name or ARN of an alias that refers to the KMS key. Plaintext = new MemoryStream(<binary data>) // The data to encrypt. }); MemoryStream ciphertextBlob = response.CiphertextBlob; // The encrypted data (ciphertext). string encryptionAlgorithm = response.EncryptionAlgorithm; // The encryption algorithm that was used in the operation. For symmetric encryption keys, the encryption algorithm is always SYMMETRIC_DEFAULT. string keyId = response.KeyId; // The ARN of the KMS key that was used to encrypt the data. #endregion } public void KeyManagementServiceEncrypt() { #region to-encrypt-data-2 var client = new AmazonKeyManagementServiceClient(); var response = client.Encrypt(new EncryptRequest { EncryptionAlgorithm = "RSAES_OAEP_SHA_256", // The encryption algorithm to use in the operation. KeyId = "0987dcba-09fe-87dc-65ba-ab0987654321", // The identifier of the KMS key to use for encryption. You can use the key ID or Amazon Resource Name (ARN) of the KMS key, or the name or ARN of an alias that refers to the KMS key. Plaintext = new MemoryStream(<binary data>) // The data to encrypt. }); MemoryStream ciphertextBlob = response.CiphertextBlob; // The encrypted data (ciphertext). string encryptionAlgorithm = response.EncryptionAlgorithm; // The encryption algorithm that was used in the operation. string keyId = response.KeyId; // The ARN of the KMS key that was used to encrypt the data. #endregion } public void KeyManagementServiceGenerateDataKey() { #region to-generate-a-data-key-1 var client = new AmazonKeyManagementServiceClient(); var response = client.GenerateDataKey(new GenerateDataKeyRequest { KeyId = "alias/ExampleAlias", // The identifier of the KMS key to use to encrypt the data key. You can use the key ID or Amazon Resource Name (ARN) of the KMS key, or the name or ARN of an alias that refers to the KMS key. KeySpec = "AES_256" // Specifies the type of data key to return. }); MemoryStream ciphertextBlob = response.CiphertextBlob; // The encrypted data key. string keyId = response.KeyId; // The ARN of the KMS key that was used to encrypt the data key. MemoryStream plaintext = response.Plaintext; // The unencrypted (plaintext) data key. #endregion } public void KeyManagementServiceGenerateDataKey() { #region to-generate-a-data-key-for-a-nitro-enclave-2 var client = new AmazonKeyManagementServiceClient(); var response = client.GenerateDataKey(new GenerateDataKeyRequest { KeyId = "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", // Identifies the KMS key used to encrypt the encrypted data key (CiphertextBlob) KeySpec = "AES_256", // Specifies the type of data key to return Recipient = new RecipientInfo { AttestationDocument = new MemoryStream(<attestation document>), KeyEncryptionAlgorithm = "RSAES_OAEP_SHA_256" } // Specifies the attestation document from the Nitro enclave and the encryption algorithm to use with the public key from the attestation document }); MemoryStream ciphertextBlob = response.CiphertextBlob; // The data key encrypted by the specified KMS key MemoryStream ciphertextForRecipient = response.CiphertextForRecipient; // The plaintext data key encrypted by the public key from the attestation document string keyId = response.KeyId; // The KMS key used to encrypt the CiphertextBlob (encrypted data key) MemoryStream plaintext = response.Plaintext; // This field is null or empty #endregion } public void KeyManagementServiceGenerateDataKeyPair() { #region to-generate-an-rsa-key-pair-for-encryption-and-decryption-1 var client = new AmazonKeyManagementServiceClient(); var response = client.GenerateDataKeyPair(new GenerateDataKeyPairRequest { KeyId = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", // The key ID of the symmetric encryption KMS key that encrypts the private RSA key in the data key pair. KeyPairSpec = "RSA_3072" // The requested key spec of the RSA data key pair. }); string keyId = response.KeyId; // The key ARN of the symmetric encryption KMS key that was used to encrypt the private key. string keyPairSpec = response.KeyPairSpec; // The actual key spec of the RSA data key pair. MemoryStream privateKeyCiphertextBlob = response.PrivateKeyCiphertextBlob; // The encrypted private key of the RSA data key pair. MemoryStream privateKeyPlaintext = response.PrivateKeyPlaintext; // The plaintext private key of the RSA data key pair. MemoryStream publicKey = response.PublicKey; // The public key (plaintext) of the RSA data key pair. #endregion } public void KeyManagementServiceGenerateDataKeyPair() { #region to-generate-a-data-key-pair-for-a-nitro-enclave-2 var client = new AmazonKeyManagementServiceClient(); var response = client.GenerateDataKeyPair(new GenerateDataKeyPairRequest { KeyId = "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", // The key ID of the symmetric encryption KMS key that encrypts the private RSA key in the data key pair. KeyPairSpec = "RSA_3072", // The requested key spec of the RSA data key pair. Recipient = new RecipientInfo { AttestationDocument = new MemoryStream(<attestation document>), KeyEncryptionAlgorithm = "RSAES_OAEP_SHA_256" } // Specifies the attestation document from the Nitro enclave and the encryption algorithm to use with the public key from the attestation document. }); MemoryStream ciphertextForRecipient = response.CiphertextForRecipient; // The private key of the RSA data key pair encrypted by the public key from the attestation document string keyId = response.KeyId; // The key ARN of the symmetric encryption KMS key that was used to encrypt the PrivateKeyCiphertextBlob. string keyPairSpec = response.KeyPairSpec; // The actual key spec of the RSA data key pair. MemoryStream privateKeyCiphertextBlob = response.PrivateKeyCiphertextBlob; // The private key of the RSA data key pair encrypted by the KMS key. MemoryStream privateKeyPlaintext = response.PrivateKeyPlaintext; // This field is null or empty MemoryStream publicKey = response.PublicKey; // The public key (plaintext) of the RSA data key pair. #endregion } public void KeyManagementServiceGenerateDataKeyPairWithoutPlaintext() { #region to-generate-an-asymmetric-data-key-pair-without-a-plaintext-key-1628620971564 var client = new AmazonKeyManagementServiceClient(); var response = client.GenerateDataKeyPairWithoutPlaintext(new GenerateDataKeyPairWithoutPlaintextRequest { KeyId = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", // The symmetric encryption KMS key that encrypts the private key of the ECC data key pair. KeyPairSpec = "ECC_NIST_P521" // The requested key spec of the ECC asymmetric data key pair. }); string keyId = response.KeyId; // The key ARN of the symmetric encryption KMS key that encrypted the private key in the ECC asymmetric data key pair. string keyPairSpec = response.KeyPairSpec; // The actual key spec of the ECC asymmetric data key pair. MemoryStream privateKeyCiphertextBlob = response.PrivateKeyCiphertextBlob; // The encrypted private key of the asymmetric ECC data key pair. MemoryStream publicKey = response.PublicKey; // The public key (plaintext). #endregion } public void KeyManagementServiceGenerateDataKeyWithoutPlaintext() { #region to-generate-an-encrypted-data-key-1478914121134 var client = new AmazonKeyManagementServiceClient(); var response = client.GenerateDataKeyWithoutPlaintext(new GenerateDataKeyWithoutPlaintextRequest { KeyId = "alias/ExampleAlias", // The identifier of the KMS key to use to encrypt the data key. You can use the key ID or Amazon Resource Name (ARN) of the KMS key, or the name or ARN of an alias that refers to the KMS key. KeySpec = "AES_256" // Specifies the type of data key to return. }); MemoryStream ciphertextBlob = response.CiphertextBlob; // The encrypted data key. string keyId = response.KeyId; // The ARN of the KMS key that was used to encrypt the data key. #endregion } public void KeyManagementServiceGenerateMac() { #region to-generate-an-hmac-for-a-message-1631570135665 var client = new AmazonKeyManagementServiceClient(); var response = client.GenerateMac(new GenerateMacRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab", // The HMAC KMS key input to the HMAC algorithm. MacAlgorithm = "HMAC_SHA_384", // The HMAC algorithm requested for the operation. Message = new MemoryStream(Hello World) // The message input to the HMAC algorithm. }); string keyId = response.KeyId; // The key ARN of the HMAC KMS key used in the operation. MemoryStream mac = response.Mac; // The HMAC tag that results from this operation. string macAlgorithm = response.MacAlgorithm; // The HMAC algorithm used in the operation. #endregion } public void KeyManagementServiceGenerateRandom() { #region to-generate-random-data-1 var client = new AmazonKeyManagementServiceClient(); var response = client.GenerateRandom(new GenerateRandomRequest { NumberOfBytes = 32 // The length of the random data, specified in number of bytes. }); MemoryStream plaintext = response.Plaintext; // The random data. #endregion } public void KeyManagementServiceGenerateRandom() { #region to-generate-random-data-2 var client = new AmazonKeyManagementServiceClient(); var response = client.GenerateRandom(new GenerateRandomRequest { NumberOfBytes = 1024, // The length of the random byte string Recipient = new RecipientInfo { AttestationDocument = new MemoryStream(<attestation document>), KeyEncryptionAlgorithm = "RSAES_OAEP_SHA_256" } // Specifies the attestation document from the Nitro enclave and the encryption algorithm to use with the public key from the attestation document }); MemoryStream ciphertextForRecipient = response.CiphertextForRecipient; // The random data encrypted under the public key from the attestation document MemoryStream plaintext = response.Plaintext; // This field is null or empty #endregion } public void KeyManagementServiceGetKeyPolicy() { #region to-retrieve-a-key-policy-1479170128325 var client = new AmazonKeyManagementServiceClient(); var response = client.GetKeyPolicy(new GetKeyPolicyRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab", // The identifier of the KMS key whose key policy you want to retrieve. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. PolicyName = "default" // The name of the key policy to retrieve. }); string policy = response.Policy; // The key policy document. #endregion } public void KeyManagementServiceGetKeyRotationStatus() { #region to-retrieve-the-rotation-status-for-a-cmk-1479172287408 var client = new AmazonKeyManagementServiceClient(); var response = client.GetKeyRotationStatus(new GetKeyRotationStatusRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab" // The identifier of the KMS key whose key material rotation status you want to retrieve. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. }); bool keyRotationEnabled = response.KeyRotationEnabled; // A boolean that indicates the key material rotation status. Returns true when automatic annual rotation of the key material is enabled, or false when it is not. #endregion } public void KeyManagementServiceGetParametersForImport() { #region to-download-the-public-key-and-import-token-1 var client = new AmazonKeyManagementServiceClient(); var response = client.GetParametersForImport(new GetParametersForImportRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab", // The identifier of the KMS key that will be associated with the imported key material. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. WrappingAlgorithm = "RSAES_OAEP_SHA_1", // The algorithm that you will use to encrypt the key material before importing it. WrappingKeySpec = "RSA_2048" // The type of wrapping key (public key) to return in the response. }); MemoryStream importToken = response.ImportToken; // The import token to send with a subsequent ImportKeyMaterial request. string keyId = response.KeyId; // The ARN of the KMS key that will be associated with the imported key material. DateTime parametersValidTo = response.ParametersValidTo; // The date and time when the import token and public key expire. After this time, call GetParametersForImport again. MemoryStream publicKey = response.PublicKey; // The public key to use to encrypt the key material before importing it. #endregion } public void KeyManagementServiceGetParametersForImport() { #region to-download-the-public-key-and-import-token-2 var client = new AmazonKeyManagementServiceClient(); var response = client.GetParametersForImport(new GetParametersForImportRequest { KeyId = "arn:aws:kms:us-east-2:111122223333:key/8888abcd-12ab-34cd-56ef-1234567890ab", // The identifier of the KMS key that will be associated with the imported key material. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. WrappingAlgorithm = "RSA_AES_KEY_WRAP_SHA_256", // The algorithm that you will use to encrypt the key material before importing it. WrappingKeySpec = "RSA_4096" // The type of wrapping key (public key) to return in the response. }); MemoryStream importToken = response.ImportToken; // The import token to send with a subsequent ImportKeyMaterial request. string keyId = response.KeyId; // The ARN of the KMS key that will be associated with the imported key material. DateTime parametersValidTo = response.ParametersValidTo; // The date and time when the import token and public key expire. After this time, call GetParametersForImport again. MemoryStream publicKey = response.PublicKey; // The public key to use to encrypt the key material before importing it. #endregion } public void KeyManagementServiceGetParametersForImport() { #region to-download-the-public-key-and-import-token-3 var client = new AmazonKeyManagementServiceClient(); var response = client.GetParametersForImport(new GetParametersForImportRequest { KeyId = "arn:aws:kms:us-east-2:111122223333:key/9876abcd-12ab-34cd-56ef-1234567890ab", // The identifier of the KMS key that will be associated with the imported key material. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. WrappingAlgorithm = "RSAES_OAEP_SHA_256", // The algorithm that you will use to encrypt the key material before importing it. WrappingKeySpec = "RSA_3072" // The type of wrapping key (public key) to return in the response. }); MemoryStream importToken = response.ImportToken; // The import token to send with a subsequent ImportKeyMaterial request. string keyId = response.KeyId; // The ARN of the KMS key that will be associated with the imported key material. DateTime parametersValidTo = response.ParametersValidTo; // The date and time when the import token and public key expire. After this time, call GetParametersForImport again. MemoryStream publicKey = response.PublicKey; // The public key to use to encrypt the key material before importing it. #endregion } public void KeyManagementServiceGetParametersForImport() { #region to-download-the-public-key-and-import-token-4 var client = new AmazonKeyManagementServiceClient(); var response = client.GetParametersForImport(new GetParametersForImportRequest { KeyId = "2468abcd-12ab-34cd-56ef-1234567890ab", // The identifier of the KMS key that will be associated with the imported key material. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. WrappingAlgorithm = "RSAES_OAEP_SHA_256", // The algorithm that you will use to encrypt the key material before importing it. WrappingKeySpec = "RSA_4096" // The type of wrapping key (public key) to return in the response. }); MemoryStream importToken = response.ImportToken; // The import token to send with a subsequent ImportKeyMaterial request. string keyId = response.KeyId; // The ARN of the KMS key that will be associated with the imported key material. DateTime parametersValidTo = response.ParametersValidTo; // The date and time when the import token and public key expire. After this time, call GetParametersForImport again. MemoryStream publicKey = response.PublicKey; // The public key to use to encrypt the key material before importing it. #endregion } public void KeyManagementServiceGetPublicKey() { #region to-download-the-public-key-of-an-asymmetric-kms-key-1628621691873 var client = new AmazonKeyManagementServiceClient(); var response = client.GetPublicKey(new GetPublicKeyRequest { KeyId = "arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321" // The key ARN of the asymmetric KMS key. }); string customerMasterKeySpec = response.CustomerMasterKeySpec; // The key spec of the asymmetric KMS key from which the public key was downloaded. List<string> encryptionAlgorithms = response.EncryptionAlgorithms; // The encryption algorithms supported by the asymmetric KMS key that was downloaded. string keyId = response.KeyId; // The key ARN of the asymmetric KMS key from which the public key was downloaded. string keyUsage = response.KeyUsage; // The key usage of the asymmetric KMS key from which the public key was downloaded. MemoryStream publicKey = response.PublicKey; // The public key (plaintext) of the asymmetric KMS key. #endregion } public void KeyManagementServiceImportKeyMaterial() { #region to-import-key-material-into-a-kms-key-1 var client = new AmazonKeyManagementServiceClient(); var response = client.ImportKeyMaterial(new ImportKeyMaterialRequest { EncryptedKeyMaterial = new MemoryStream(<binary data>), // The encrypted key material to import. ExpirationModel = "KEY_MATERIAL_DOES_NOT_EXPIRE", // A value that specifies whether the key material expires. ImportToken = new MemoryStream(<binary data>), // The import token that you received in the response to a previous GetParametersForImport request. KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab" // The identifier of the KMS key to import the key material into. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. }); #endregion } public void KeyManagementServiceImportKeyMaterial() { #region to-import-key-material-into-a-kms-key-2 var client = new AmazonKeyManagementServiceClient(); var response = client.ImportKeyMaterial(new ImportKeyMaterialRequest { EncryptedKeyMaterial = new MemoryStream(<binary data>), // The encrypted key material to import. ExpirationModel = "KEY_MATERIAL_EXPIRES", // A value that specifies whether the key material expires. ImportToken = new MemoryStream(<binary data>), // The import token that you received in the response to a previous GetParametersForImport request. KeyId = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", // The identifier of the KMS key to import the key material into. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. ValidTo = new DateTime(2023, 9, 29, 5, 0, 0, DateTimeKind.Utc) // Specifies the date and time when the imported key material expires. }); #endregion } public void KeyManagementServiceListAliases() { #region to-list-aliases-1480729693349 var client = new AmazonKeyManagementServiceClient(); var response = client.ListAliases(new ListAliasesRequest { }); List<AliasListEntry> aliases = response.Aliases; // A list of aliases, including the key ID of the KMS key that each alias refers to. bool truncated = response.Truncated; // A boolean that indicates whether there are more items in the list. Returns true when there are more items, or false when there are not. #endregion } public void KeyManagementServiceListGrants() { #region to-list-grants-for-a-cmk-1481067365389 var client = new AmazonKeyManagementServiceClient(); var response = client.ListGrants(new ListGrantsRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab" // The identifier of the KMS key whose grants you want to list. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. }); List<GrantListEntry> grants = response.Grants; // A list of grants. bool truncated = response.Truncated; // A boolean that indicates whether there are more items in the list. Returns true when there are more items, or false when there are not. #endregion } public void KeyManagementServiceListKeyPolicies() { #region to-list-key-policies-for-a-cmk-1481069780998 var client = new AmazonKeyManagementServiceClient(); var response = client.ListKeyPolicies(new ListKeyPoliciesRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab" // The identifier of the KMS key whose key policies you want to list. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. }); List<string> policyNames = response.PolicyNames; // A list of key policy names. bool truncated = response.Truncated; // A boolean that indicates whether there are more items in the list. Returns true when there are more items, or false when there are not. #endregion } public void KeyManagementServiceListKeys() { #region to-list-cmks-1481071643069 var client = new AmazonKeyManagementServiceClient(); var response = client.ListKeys(new ListKeysRequest { }); List<KeyListEntry> keys = response.Keys; // A list of KMS keys, including the key ID and Amazon Resource Name (ARN) of each one. bool truncated = response.Truncated; // A boolean that indicates whether there are more items in the list. Returns true when there are more items, or false when there are not. #endregion } public void KeyManagementServiceListResourceTags() { #region to-list-tags-for-a-cmk-1483996855796 var client = new AmazonKeyManagementServiceClient(); var response = client.ListResourceTags(new ListResourceTagsRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab" // The identifier of the KMS key whose tags you are listing. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. }); List<Tag> tags = response.Tags; // A list of tags. bool truncated = response.Truncated; // A boolean that indicates whether there are more items in the list. Returns true when there are more items, or false when there are not. #endregion } public void KeyManagementServiceListRetirableGrants() { #region to-list-grants-that-the-specified-principal-can-retire-1481140499620 var client = new AmazonKeyManagementServiceClient(); var response = client.ListRetirableGrants(new ListRetirableGrantsRequest { RetiringPrincipal = "arn:aws:iam::111122223333:role/ExampleRole" // The retiring principal whose grants you want to list. Use the Amazon Resource Name (ARN) of a principal such as an AWS account (root), IAM user, federated user, or assumed role user. }); List<GrantListEntry> grants = response.Grants; // A list of grants that the specified principal can retire. bool truncated = response.Truncated; // A boolean that indicates whether there are more items in the list. Returns true when there are more items, or false when there are not. #endregion } public void KeyManagementServicePutKeyPolicy() { #region to-attach-a-key-policy-to-a-cmk-1481147345018 var client = new AmazonKeyManagementServiceClient(); var response = client.PutKeyPolicy(new PutKeyPolicyRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab", // The identifier of the KMS key to attach the key policy to. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. Policy = "{ \"Version\": \"2012-10-17\", \"Id\": \"custom-policy-2016-12-07\", \"Statement\": [ { \"Sid\": \"Enable IAM User Permissions\", \"Effect\": \"Allow\", \"Principal\": { \"AWS\": \"arn:aws:iam::111122223333:root\" }, \"Action\": \"kms:*\", \"Resource\": \"*\" }, { \"Sid\": \"Allow access for Key Administrators\", \"Effect\": \"Allow\", \"Principal\": { \"AWS\": [ \"arn:aws:iam::111122223333:user/ExampleAdminUser\", \"arn:aws:iam::111122223333:role/ExampleAdminRole\" ] }, \"Action\": [ \"kms:Create*\", \"kms:Describe*\", \"kms:Enable*\", \"kms:List*\", \"kms:Put*\", \"kms:Update*\", \"kms:Revoke*\", \"kms:Disable*\", \"kms:Get*\", \"kms:Delete*\", \"kms:ScheduleKeyDeletion\", \"kms:CancelKeyDeletion\" ], \"Resource\": \"*\" }, { \"Sid\": \"Allow use of the key\", \"Effect\": \"Allow\", \"Principal\": { \"AWS\": \"arn:aws:iam::111122223333:role/ExamplePowerUserRole\" }, \"Action\": [ \"kms:Encrypt\", \"kms:Decrypt\", \"kms:ReEncrypt*\", \"kms:GenerateDataKey*\", \"kms:DescribeKey\" ], \"Resource\": \"*\" }, { \"Sid\": \"Allow attachment of persistent resources\", \"Effect\": \"Allow\", \"Principal\": { \"AWS\": \"arn:aws:iam::111122223333:role/ExamplePowerUserRole\" }, \"Action\": [ \"kms:CreateGrant\", \"kms:ListGrants\", \"kms:RevokeGrant\" ], \"Resource\": \"*\", \"Condition\": { \"Bool\": { \"kms:GrantIsForAWSResource\": \"true\" } } } ] } ", // The key policy document. PolicyName = "default" // The name of the key policy. }); #endregion } public void KeyManagementServiceReEncrypt() { #region to-reencrypt-data-1481230358001 var client = new AmazonKeyManagementServiceClient(); var response = client.ReEncrypt(new ReEncryptRequest { CiphertextBlob = new MemoryStream(<binary data>), // The data to reencrypt. DestinationKeyId = "0987dcba-09fe-87dc-65ba-ab0987654321" // The identifier of the KMS key to use to reencrypt the data. You can use any valid key identifier. }); MemoryStream ciphertextBlob = response.CiphertextBlob; // The reencrypted data. string keyId = response.KeyId; // The ARN of the KMS key that was used to reencrypt the data. string sourceKeyId = response.SourceKeyId; // The ARN of the KMS key that was originally used to encrypt the data. #endregion } public void KeyManagementServiceReplicateKey() { #region to-replicate-a-multi-region-key-in-a-different-aws-region-1628622402887 var client = new AmazonKeyManagementServiceClient(); var response = client.ReplicateKey(new ReplicateKeyRequest { KeyId = "arn:aws:kms:us-east-1:111122223333:key/mrk-1234abcd12ab34cd56ef1234567890ab", // The key ID or key ARN of the multi-Region primary key ReplicaRegion = "us-west-2" // The Region of the new replica. }); KeyMetadata replicaKeyMetadata = response.ReplicaKeyMetadata; // An object that displays detailed information about the replica key. string replicaPolicy = response.ReplicaPolicy; // The key policy of the replica key. If you don't specify a key policy, the replica key gets the default key policy for a KMS key. List<Tag> replicaTags = response.ReplicaTags; // The tags on the replica key, if any. #endregion } public void KeyManagementServiceRetireGrant() { #region to-retire-a-grant-1481327028297 var client = new AmazonKeyManagementServiceClient(); var response = client.RetireGrant(new RetireGrantRequest { GrantId = "0c237476b39f8bc44e45212e08498fbe3151305030726c0590dd8d3e9f3d6a60", // The identifier of the grant to retire. KeyId = "arn:aws:kms:us-east-2:444455556666:key/1234abcd-12ab-34cd-56ef-1234567890ab" // The Amazon Resource Name (ARN) of the KMS key associated with the grant. }); #endregion } public void KeyManagementServiceRevokeGrant() { #region to-revoke-a-grant-1481329549302 var client = new AmazonKeyManagementServiceClient(); var response = client.RevokeGrant(new RevokeGrantRequest { GrantId = "0c237476b39f8bc44e45212e08498fbe3151305030726c0590dd8d3e9f3d6a60", // The identifier of the grant to revoke. KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab" // The identifier of the KMS key associated with the grant. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. }); #endregion } public void KeyManagementServiceScheduleKeyDeletion() { #region to-schedule-a-cmk-for-deletion-1481331111094 var client = new AmazonKeyManagementServiceClient(); var response = client.ScheduleKeyDeletion(new ScheduleKeyDeletionRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab", // The identifier of the KMS key to schedule for deletion. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. PendingWindowInDays = 7 // The waiting period, specified in number of days. After the waiting period ends, KMS deletes the KMS key. }); DateTime deletionDate = response.DeletionDate; // The date and time after which KMS deletes the KMS key. string keyId = response.KeyId; // The ARN of the KMS key that is scheduled for deletion. #endregion } public void KeyManagementServiceSign() { #region to-digitally-sign-a-message-with-an-asymmetric-kms-key-1 var client = new AmazonKeyManagementServiceClient(); var response = client.Sign(new SignRequest { KeyId = "alias/ECC_signing_key", // The asymmetric KMS key to be used to generate the digital signature. This example uses an alias of the KMS key. Message = new MemoryStream(<message to be signed>), // Message to be signed. Use Base-64 for the CLI. MessageType = "RAW", // Indicates whether the message is RAW or a DIGEST. SigningAlgorithm = "ECDSA_SHA_384" // The requested signing algorithm. This must be an algorithm that the KMS key supports. }); string keyId = response.KeyId; // The key ARN of the asymmetric KMS key that was used to sign the message. MemoryStream signature = response.Signature; // The digital signature of the message. string signingAlgorithm = response.SigningAlgorithm; // The actual signing algorithm that was used to generate the signature. #endregion } public void KeyManagementServiceSign() { #region to-digitally-sign-a-message-digest-with-an-asymmetric-kms-key-2 var client = new AmazonKeyManagementServiceClient(); var response = client.Sign(new SignRequest { KeyId = "alias/RSA_signing_key", // The asymmetric KMS key to be used to generate the digital signature. This example uses an alias of the KMS key. Message = new MemoryStream(<message digest to be signed>), // Message to be signed. Use Base-64 for the CLI. MessageType = "DIGEST", // Indicates whether the message is RAW or a DIGEST. When it is RAW, KMS hashes the message before signing. When it is DIGEST, KMS skips the hashing step and signs the Message value. SigningAlgorithm = "RSASSA_PKCS1_V1_5_SHA_256" // The requested signing algorithm. This must be an algorithm that the KMS key supports. }); string keyId = response.KeyId; // The key ARN of the asymmetric KMS key that was used to sign the message. MemoryStream signature = response.Signature; // The digital signature of the message. string signingAlgorithm = response.SigningAlgorithm; // The actual signing algorithm that was used to generate the signature. #endregion } public void KeyManagementServiceTagResource() { #region to-tag-a-cmk-1483997246518 var client = new AmazonKeyManagementServiceClient(); var response = client.TagResource(new TagResourceRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab", // The identifier of the KMS key you are tagging. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. Tags = new List<Tag> { new Tag { TagKey = "Purpose", TagValue = "Test" } } // A list of tags. }); #endregion } public void KeyManagementServiceUntagResource() { #region to-remove-tags-from-a-cmk-1483997590962 var client = new AmazonKeyManagementServiceClient(); var response = client.UntagResource(new UntagResourceRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab", // The identifier of the KMS key whose tags you are removing. TagKeys = new List<string> { "Purpose", "CostCenter" } // A list of tag keys. Provide only the tag keys, not the tag values. }); #endregion } public void KeyManagementServiceUpdateAlias() { #region to-update-an-alias-1481572726920 var client = new AmazonKeyManagementServiceClient(); var response = client.UpdateAlias(new UpdateAliasRequest { AliasName = "alias/ExampleAlias", // The alias to update. TargetKeyId = "1234abcd-12ab-34cd-56ef-1234567890ab" // The identifier of the KMS key that the alias will refer to after this operation succeeds. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. }); #endregion } public void KeyManagementServiceUpdateCustomKeyStore() { #region to-edit-the-friendly-name-of-a-custom-key-store-1 var client = new AmazonKeyManagementServiceClient(); var response = client.UpdateCustomKeyStore(new UpdateCustomKeyStoreRequest { CustomKeyStoreId = "cks-1234567890abcdef0", // The ID of the custom key store that you are updating. NewCustomKeyStoreName = "DevelopmentKeys" // A new friendly name for the custom key store. }); #endregion } public void KeyManagementServiceUpdateCustomKeyStore() { #region to-edit-the-properties-of-an-aws-cloudhsm-key-store-2 var client = new AmazonKeyManagementServiceClient(); var response = client.UpdateCustomKeyStore(new UpdateCustomKeyStoreRequest { CustomKeyStoreId = "cks-1234567890abcdef0", // The ID of the custom key store that you are updating. KeyStorePassword = "ExamplePassword" // The password for the kmsuser crypto user in the CloudHSM cluster. }); #endregion } public void KeyManagementServiceUpdateCustomKeyStore() { #region to-associate-the-custom-key-store-with-a-different-but-related-aws-cloudhsm-cluster-3 var client = new AmazonKeyManagementServiceClient(); var response = client.UpdateCustomKeyStore(new UpdateCustomKeyStoreRequest { CloudHsmClusterId = "cluster-234abcdefABC", // The ID of the AWS CloudHSM cluster that you want to associate with the custom key store. This cluster must be related to the original CloudHSM cluster for this key store. CustomKeyStoreId = "cks-1234567890abcdef0" // The ID of the custom key store that you are updating. }); #endregion } public void KeyManagementServiceUpdateCustomKeyStore() { #region to-update-the-proxy-authentication-credential-of-an-external-key-store-4 var client = new AmazonKeyManagementServiceClient(); var response = client.UpdateCustomKeyStore(new UpdateCustomKeyStoreRequest { CustomKeyStoreId = "cks-1234567890abcdef0", // Identifies the custom key store XksProxyAuthenticationCredential = new XksProxyAuthenticationCredentialType { AccessKeyId = "ABCDE12345670EXAMPLE", RawSecretAccessKey = "DXjSUawnel2fr6SKC7G25CNxTyWKE5PF9XX6H/u9pSo=" } // Specifies the values in the proxy authentication credential }); #endregion } public void KeyManagementServiceUpdateCustomKeyStore() { #region to-update-the-xks-proxy-api-path-of-an-external-key-store-5 var client = new AmazonKeyManagementServiceClient(); var response = client.UpdateCustomKeyStore(new UpdateCustomKeyStoreRequest { CustomKeyStoreId = "cks-1234567890abcdef0", // The ID of the custom key store that you are updating XksProxyUriPath = "/new-path/kms/xks/v1" // The URI path to the external key store proxy APIs }); #endregion } public void KeyManagementServiceUpdateCustomKeyStore() { #region to-update-the-proxy-connectivity-of-an-external-key-store-to-vpc_endpoint_service-6 var client = new AmazonKeyManagementServiceClient(); var response = client.UpdateCustomKeyStore(new UpdateCustomKeyStoreRequest { CustomKeyStoreId = "cks-1234567890abcdef0", // Identifies the custom key store XksProxyConnectivity = "VPC_ENDPOINT_SERVICE", // Specifies the connectivity option XksProxyUriEndpoint = "https://myproxy-private.xks.example.com", // Specifies the URI endpoint that AWS KMS uses when communicating with the external key store proxy XksProxyVpcEndpointServiceName = "com.amazonaws.vpce.us-east-1.vpce-svc-example" // Specifies the name of the VPC endpoint service that the proxy uses for communication }); #endregion } public void KeyManagementServiceUpdateKeyDescription() { #region to-update-the-description-of-a-cmk-1481574808619 var client = new AmazonKeyManagementServiceClient(); var response = client.UpdateKeyDescription(new UpdateKeyDescriptionRequest { Description = "Example description that indicates the intended use of this KMS key.", // The updated description. KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab" // The identifier of the KMS key whose description you are updating. You can use the key ID or the Amazon Resource Name (ARN) of the KMS key. }); #endregion } public void KeyManagementServiceUpdatePrimaryRegion() { #region to-update-the-primary-region-of-a-multi-region-kms-key-1660249555577 var client = new AmazonKeyManagementServiceClient(); var response = client.UpdatePrimaryRegion(new UpdatePrimaryRegionRequest { KeyId = "arn:aws:kms:us-west-1:111122223333:key/mrk-1234abcd12ab34cd56ef1234567890ab", // The current primary key. PrimaryRegion = "eu-central-1" // The Region of the replica key that will become the primary key. }); #endregion } public void KeyManagementServiceVerify() { #region to-use-an-asymmetric-kms-key-to-verify-a-digital-signature-1 var client = new AmazonKeyManagementServiceClient(); var response = client.Verify(new VerifyRequest { KeyId = "alias/ECC_signing_key", // The asymmetric KMS key to be used to verify the digital signature. This example uses an alias to identify the KMS key. Message = new MemoryStream(<message to be verified>), // The message that was signed. MessageType = "RAW", // Indicates whether the message is RAW or a DIGEST. Signature = new MemoryStream(<binary data>), // The signature to be verified. SigningAlgorithm = "ECDSA_SHA_384" // The signing algorithm to be used to verify the signature. }); string keyId = response.KeyId; // The key ARN of the asymmetric KMS key that was used to verify the digital signature. bool signatureValid = response.SignatureValid; // A value of 'true' Indicates that the signature was verified. If verification fails, the call to Verify fails. string signingAlgorithm = response.SigningAlgorithm; // The signing algorithm that was used to verify the signature. #endregion } public void KeyManagementServiceVerify() { #region to-use-an-asymmetric-kms-key-to-verify-a-digital-signature-on-a-message-digest-2 var client = new AmazonKeyManagementServiceClient(); var response = client.Verify(new VerifyRequest { KeyId = "arn:aws:kms:us-east-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321", // The asymmetric KMS key to be used to verify the digital signature. This example uses an alias to identify the KMS key. Message = new MemoryStream(<message digest to be verified>), // The message that was signed. MessageType = "DIGEST", // Indicates whether the message is RAW or a DIGEST. When it is RAW, KMS hashes the message before signing. When it is DIGEST, KMS skips the hashing step and signs the Message value. Signature = new MemoryStream(<binary data>), // The signature to be verified. SigningAlgorithm = "RSASSA_PSS_SHA_512" // The signing algorithm to be used to verify the signature. }); string keyId = response.KeyId; // The key ARN of the asymmetric KMS key that was used to verify the digital signature. bool signatureValid = response.SignatureValid; // A value of 'true' Indicates that the signature was verified. If verification fails, the call to Verify fails. string signingAlgorithm = response.SigningAlgorithm; // The signing algorithm that was used to verify the signature. #endregion } public void KeyManagementServiceVerifyMac() { #region to-verify-an-hmac-1631570863401 var client = new AmazonKeyManagementServiceClient(); var response = client.VerifyMac(new VerifyMacRequest { KeyId = "1234abcd-12ab-34cd-56ef-1234567890ab", // The HMAC KMS key input to the HMAC algorithm. Mac = new MemoryStream(<HMAC_TAG>), // The HMAC to be verified. MacAlgorithm = "HMAC_SHA_384", // The HMAC algorithm requested for the operation. Message = new MemoryStream(Hello World) // The message input to the HMAC algorithm. }); string keyId = response.KeyId; // The key ARN of the HMAC key used in the operation. string macAlgorithm = response.MacAlgorithm; // The HMAC algorithm used in the operation. bool macValid = response.MacValid; // A value of 'true' indicates that verification succeeded. If verification fails, the call to VerifyMac fails. #endregion } # region ISample Members public virtual void Run() { } # endregion } }
1,522
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.Lambda; using Amazon.Lambda.Model; namespace AWSSDKDocSamples.Amazon.Lambda.Generated { class LambdaSamples : ISample { static IAmazonLambda client = new AmazonLambdaClient(); public void LambdaAddLayerVersionPermission() { #region to-add-permissions-to-a-layer-version-1586479797163 var response = client.AddLayerVersionPermission(new AddLayerVersionPermissionRequest { Action = "lambda:GetLayerVersion", LayerName = "my-layer", Principal = "223456789012", StatementId = "xaccount", VersionNumber = 1 }); string revisionId = response.RevisionId; string statement = response.Statement; #endregion } public void LambdaAddPermission() { #region add-permission-1474651469455 var response = client.AddPermission(new AddPermissionRequest { Action = "lambda:InvokeFunction", FunctionName = "my-function", Principal = "s3.amazonaws.com", SourceAccount = "123456789012", SourceArn = "arn:aws:s3:::my-bucket-1xpuxmplzrlbh/*", StatementId = "s3" }); string statement = response.Statement; #endregion } public void LambdaAddPermission() { #region add-permission-1474651469456 var response = client.AddPermission(new AddPermissionRequest { Action = "lambda:InvokeFunction", FunctionName = "my-function", Principal = "223456789012", StatementId = "xaccount" }); string statement = response.Statement; #endregion } public void LambdaCreateAlias() { #region to-create-an-alias-for-a-lambda-function-1586480324259 var response = client.CreateAlias(new CreateAliasRequest { Description = "alias for live version of function", FunctionName = "my-function", FunctionVersion = "1", Name = "LIVE" }); string aliasArn = response.AliasArn; string description = response.Description; string functionVersion = response.FunctionVersion; string name = response.Name; string revisionId = response.RevisionId; #endregion } public void LambdaCreateEventSourceMapping() { #region to-create-a-mapping-between-an-event-source-and-an-aws-lambda-function-1586480555467 var response = client.CreateEventSourceMapping(new CreateEventSourceMappingRequest { BatchSize = 5, EventSourceArn = "arn:aws:sqs:us-west-2:123456789012:my-queue", FunctionName = "my-function" }); int batchSize = response.BatchSize; string eventSourceArn = response.EventSourceArn; string functionArn = response.FunctionArn; DateTime lastModified = response.LastModified; string state = response.State; string stateTransitionReason = response.StateTransitionReason; string uuid = response.UUID; #endregion } public void LambdaCreateFunction() { #region to-create-a-function-1586492061186 var response = client.CreateFunction(new CreateFunctionRequest { Code = new FunctionCode { S3Bucket = "my-bucket-1xpuxmplzrlbh", S3Key = "function.zip" }, Description = "Process image objects from Amazon S3.", Environment = new Environment { Variables = new Dictionary<string, string> { { "BUCKET", "my-bucket-1xpuxmplzrlbh" }, { "PREFIX", "inbound" } } }, FunctionName = "my-function", Handler = "index.handler", KMSKeyArn = "arn:aws:kms:us-west-2:123456789012:key/b0844d6c-xmpl-4463-97a4-d49f50839966", MemorySize = 256, Publish = true, Role = "arn:aws:iam::123456789012:role/lambda-role", Runtime = "nodejs12.x", Tags = new Dictionary<string, string> { { "DEPARTMENT", "Assets" } }, Timeout = 15, TracingConfig = new TracingConfig { Mode = "Active" } }); string codeSha256 = response.CodeSha256; long codeSize = response.CodeSize; string description = response.Description; EnvironmentResponse environment = response.Environment; string functionArn = response.FunctionArn; string functionName = response.FunctionName; string handler = response.Handler; string kmsKeyArn = response.KMSKeyArn; string lastModified = response.LastModified; string lastUpdateStatus = response.LastUpdateStatus; int memorySize = response.MemorySize; string revisionId = response.RevisionId; string role = response.Role; string runtime = response.Runtime; string state = response.State; int timeout = response.Timeout; TracingConfigResponse tracingConfig = response.TracingConfig; string version = response.Version; #endregion } public void LambdaDeleteAlias() { #region to-delete-a-lambda-function-alias-1481660370804 var response = client.DeleteAlias(new DeleteAliasRequest { FunctionName = "my-function", Name = "BLUE" }); #endregion } public void LambdaDeleteEventSourceMapping() { #region to-delete-a-lambda-function-event-source-mapping-1481658973862 var response = client.DeleteEventSourceMapping(new DeleteEventSourceMappingRequest { UUID = "14e0db71-xmpl-4eb5-b481-8945cf9d10c2" }); int batchSize = response.BatchSize; string eventSourceArn = response.EventSourceArn; string functionArn = response.FunctionArn; DateTime lastModified = response.LastModified; string state = response.State; string stateTransitionReason = response.StateTransitionReason; string uuid = response.UUID; #endregion } public void LambdaDeleteFunction() { #region to-delete-a-lambda-function-1481648553696 var response = client.DeleteFunction(new DeleteFunctionRequest { FunctionName = "my-function", Qualifier = "1" }); #endregion } public void LambdaDeleteFunctionConcurrency() { #region to-remove-the-reserved-concurrent-execution-limit-from-a-function-1586480714680 var response = client.DeleteFunctionConcurrency(new DeleteFunctionConcurrencyRequest { FunctionName = "my-function" }); #endregion } public void LambdaDeleteFunctionEventInvokeConfig() { #region to-delete-an-asynchronous-invocation-configuration-1586481102187 var response = client.DeleteFunctionEventInvokeConfig(new DeleteFunctionEventInvokeConfigRequest { FunctionName = "my-function", Qualifier = "GREEN" }); #endregion } public void LambdaDeleteLayerVersion() { #region to-delete-a-version-of-a-lambda-layer-1586481157547 var response = client.DeleteLayerVersion(new DeleteLayerVersionRequest { LayerName = "my-layer", VersionNumber = 2 }); #endregion } public void LambdaDeleteProvisionedConcurrencyConfig() { #region to-delete-a-provisioned-concurrency-configuration-1586481032551 var response = client.DeleteProvisionedConcurrencyConfig(new DeleteProvisionedConcurrencyConfigRequest { FunctionName = "my-function", Qualifier = "GREEN" }); #endregion } public void LambdaGetAccountSettings() { #region to-get-account-settings-1481657495274 var response = client.GetAccountSettings(new GetAccountSettingsRequest { }); AccountLimit accountLimit = response.AccountLimit; AccountUsage accountUsage = response.AccountUsage; #endregion } public void LambdaGetAlias() { #region to-retrieve-a-lambda-function-alias-1481648742254 var response = client.GetAlias(new GetAliasRequest { FunctionName = "my-function", Name = "BLUE" }); string aliasArn = response.AliasArn; string description = response.Description; string functionVersion = response.FunctionVersion; string name = response.Name; string revisionId = response.RevisionId; #endregion } public void LambdaGetEventSourceMapping() { #region to-get-a-lambda-functions-event-source-mapping-1481661622799 var response = client.GetEventSourceMapping(new GetEventSourceMappingRequest { UUID = "14e0db71-xmpl-4eb5-b481-8945cf9d10c2" }); int batchSize = response.BatchSize; bool bisectBatchOnFunctionError = response.BisectBatchOnFunctionError; DestinationConfig destinationConfig = response.DestinationConfig; string eventSourceArn = response.EventSourceArn; string functionArn = response.FunctionArn; DateTime lastModified = response.LastModified; string lastProcessingResult = response.LastProcessingResult; int maximumRecordAgeInSeconds = response.MaximumRecordAgeInSeconds; int maximumRetryAttempts = response.MaximumRetryAttempts; string state = response.State; string stateTransitionReason = response.StateTransitionReason; string uuid = response.UUID; #endregion } public void LambdaGetFunction() { #region to-get-a-lambda-function-1481661622799 var response = client.GetFunction(new GetFunctionRequest { FunctionName = "my-function", Qualifier = "1" }); FunctionCodeLocation code = response.Code; FunctionConfiguration configuration = response.Configuration; Dictionary<string, string> tags = response.Tags; #endregion } public void LambdaGetFunctionConcurrency() { #region to-get-the-reserved-concurrency-setting-for-a-function-1586481279992 var response = client.GetFunctionConcurrency(new GetFunctionConcurrencyRequest { FunctionName = "my-function" }); int reservedConcurrentExecutions = response.ReservedConcurrentExecutions; #endregion } public void LambdaGetFunctionConfiguration() { #region to-get-a-lambda-functions-event-source-mapping-1481661622799 var response = client.GetFunctionConfiguration(new GetFunctionConfigurationRequest { FunctionName = "my-function", Qualifier = "1" }); string codeSha256 = response.CodeSha256; long codeSize = response.CodeSize; string description = response.Description; EnvironmentResponse environment = response.Environment; string functionArn = response.FunctionArn; string functionName = response.FunctionName; string handler = response.Handler; string kmsKeyArn = response.KMSKeyArn; string lastModified = response.LastModified; string lastUpdateStatus = response.LastUpdateStatus; int memorySize = response.MemorySize; string revisionId = response.RevisionId; string role = response.Role; string runtime = response.Runtime; string state = response.State; int timeout = response.Timeout; TracingConfigResponse tracingConfig = response.TracingConfig; string version = response.Version; #endregion } public void LambdaGetFunctionEventInvokeConfig() { #region to-get-an-asynchronous-invocation-configuration-1586481338463 var response = client.GetFunctionEventInvokeConfig(new GetFunctionEventInvokeConfigRequest { FunctionName = "my-function", Qualifier = "BLUE" }); DestinationConfig destinationConfig = response.DestinationConfig; string functionArn = response.FunctionArn; DateTime lastModified = response.LastModified; int maximumEventAgeInSeconds = response.MaximumEventAgeInSeconds; int maximumRetryAttempts = response.MaximumRetryAttempts; #endregion } public void LambdaGetLayerVersion() { #region to-get-information-about-a-lambda-layer-version-1586481457839 var response = client.GetLayerVersion(new GetLayerVersionRequest { LayerName = "my-layer", VersionNumber = 1 }); List<string> compatibleRuntimes = response.CompatibleRuntimes; LayerVersionContentOutput content = response.Content; string createdDate = response.CreatedDate; string description = response.Description; string layerArn = response.LayerArn; string layerVersionArn = response.LayerVersionArn; string licenseInfo = response.LicenseInfo; long version = response.Version; #endregion } public void LambdaGetLayerVersionByArn() { #region to-get-information-about-a-lambda-layer-version-1586481457839 var response = client.GetLayerVersionByArn(new GetLayerVersionByArnRequest { Arn = "arn:aws:lambda:ca-central-1:123456789012:layer:blank-python-lib:3" }); List<string> compatibleRuntimes = response.CompatibleRuntimes; LayerVersionContentOutput content = response.Content; string createdDate = response.CreatedDate; string description = response.Description; string layerArn = response.LayerArn; string layerVersionArn = response.LayerVersionArn; long version = response.Version; #endregion } public void LambdaGetPolicy() { #region to-retrieve-a-lambda-function-policy-1481649319053 var response = client.GetPolicy(new GetPolicyRequest { FunctionName = "my-function", Qualifier = "1" }); string policy = response.Policy; string revisionId = response.RevisionId; #endregion } public void LambdaGetProvisionedConcurrencyConfig() { #region to-view-a-provisioned-concurrency-configuration-1586490192690 var response = client.GetProvisionedConcurrencyConfig(new GetProvisionedConcurrencyConfigRequest { FunctionName = "my-function", Qualifier = "BLUE" }); int allocatedProvisionedConcurrentExecutions = response.AllocatedProvisionedConcurrentExecutions; int availableProvisionedConcurrentExecutions = response.AvailableProvisionedConcurrentExecutions; string lastModified = response.LastModified; int requestedProvisionedConcurrentExecutions = response.RequestedProvisionedConcurrentExecutions; string status = response.Status; #endregion } public void LambdaGetProvisionedConcurrencyConfig() { #region to-get-a-provisioned-concurrency-configuration-1586490192690 var response = client.GetProvisionedConcurrencyConfig(new GetProvisionedConcurrencyConfigRequest { FunctionName = "my-function", Qualifier = "BLUE" }); int allocatedProvisionedConcurrentExecutions = response.AllocatedProvisionedConcurrentExecutions; int availableProvisionedConcurrentExecutions = response.AvailableProvisionedConcurrentExecutions; string lastModified = response.LastModified; int requestedProvisionedConcurrentExecutions = response.RequestedProvisionedConcurrentExecutions; string status = response.Status; #endregion } public void LambdaInvoke() { #region to-invoke-a-lambda-function-1481659683915 var response = client.Invoke(new InvokeRequest { FunctionName = "my-function", Qualifier = "1" }); MemoryStream payload = response.Payload; int statusCode = response.StatusCode; #endregion } public void LambdaInvoke() { #region to-invoke-a-lambda-function-async-1481659683915 var response = client.Invoke(new InvokeRequest { FunctionName = "my-function", InvocationType = "Event", Qualifier = "1" }); MemoryStream payload = response.Payload; int statusCode = response.StatusCode; #endregion } public void LambdaInvokeAsync() { #region to-invoke-a-lambda-function-asynchronously-1481649694923 var response = client.InvokeAsync(new InvokeAsyncRequest { FunctionName = "my-function", }); int status = response.Status; #endregion } public void LambdaListAliases() { #region to-list-a-functions-aliases-1481650199732 var response = client.ListAliases(new ListAliasesRequest { FunctionName = "my-function" }); List<AliasConfiguration> aliases = response.Aliases; #endregion } public void LambdaListEventSourceMappings() { #region to-list-the-event-source-mappings-for-a-function-1586490285906 var response = client.ListEventSourceMappings(new ListEventSourceMappingsRequest { FunctionName = "my-function" }); List<EventSourceMappingConfiguration> eventSourceMappings = response.EventSourceMappings; #endregion } public void LambdaListFunctionEventInvokeConfigs() { #region to-view-a-list-of-asynchronous-invocation-configurations-1586490355611 var response = client.ListFunctionEventInvokeConfigs(new ListFunctionEventInvokeConfigsRequest { FunctionName = "my-function" }); List<FunctionEventInvokeConfig> functionEventInvokeConfigs = response.FunctionEventInvokeConfigs; #endregion } public void LambdaListFunctions() { #region to-get-a-list-of-lambda-functions-1481650507425 var response = client.ListFunctions(new ListFunctionsRequest { }); List<FunctionConfiguration> functions = response.Functions; string nextMarker = response.NextMarker; #endregion } public void LambdaListLayers() { #region to-list-the-layers-that-are-compatible-with-your-functions-runtime-1586490857297 var response = client.ListLayers(new ListLayersRequest { CompatibleRuntime = "python3.7" }); List<LayersListItem> layers = response.Layers; #endregion } public void LambdaListLayerVersions() { #region to-list-versions-of-a-layer-1586490857297 var response = client.ListLayerVersions(new ListLayerVersionsRequest { LayerName = "blank-java-lib" }); List<LayerVersionsListItem> layerVersions = response.LayerVersions; #endregion } public void LambdaListProvisionedConcurrencyConfigs() { #region to-get-a-list-of-provisioned-concurrency-configurations-1586491032592 var response = client.ListProvisionedConcurrencyConfigs(new ListProvisionedConcurrencyConfigsRequest { FunctionName = "my-function" }); List<ProvisionedConcurrencyConfigListItem> provisionedConcurrencyConfigs = response.ProvisionedConcurrencyConfigs; #endregion } public void LambdaListTags() { #region to-retrieve-the-list-of-tags-for-a-lambda-function-1586491111498 var response = client.ListTags(new ListTagsRequest { Resource = "arn:aws:lambda:us-west-2:123456789012:function:my-function" }); Dictionary<string, string> tags = response.Tags; #endregion } public void LambdaListVersionsByFunction() { #region to-list-versions-1481650603750 var response = client.ListVersionsByFunction(new ListVersionsByFunctionRequest { FunctionName = "my-function" }); List<FunctionConfiguration> versions = response.Versions; #endregion } public void LambdaPublishLayerVersion() { #region to-create-a-lambda-layer-version-1586491213595 var response = client.PublishLayerVersion(new PublishLayerVersionRequest { CompatibleRuntimes = new List<string> { "python3.6", "python3.7" }, Content = new LayerVersionContentInput { S3Bucket = "lambda-layers-us-west-2-123456789012", S3Key = "layer.zip" }, Description = "My Python layer", LayerName = "my-layer", LicenseInfo = "MIT" }); List<string> compatibleRuntimes = response.CompatibleRuntimes; LayerVersionContentOutput content = response.Content; string createdDate = response.CreatedDate; string description = response.Description; string layerArn = response.LayerArn; string layerVersionArn = response.LayerVersionArn; string licenseInfo = response.LicenseInfo; long version = response.Version; #endregion } public void LambdaPublishVersion() { #region to-publish-a-version-of-a-lambda-function-1481650704986 var response = client.PublishVersion(new PublishVersionRequest { CodeSha256 = "", Description = "", FunctionName = "myFunction" }); string codeSha256 = response.CodeSha256; long codeSize = response.CodeSize; string description = response.Description; EnvironmentResponse environment = response.Environment; string functionArn = response.FunctionArn; string functionName = response.FunctionName; string handler = response.Handler; string kmsKeyArn = response.KMSKeyArn; string lastModified = response.LastModified; string lastUpdateStatus = response.LastUpdateStatus; int memorySize = response.MemorySize; string revisionId = response.RevisionId; string role = response.Role; string runtime = response.Runtime; string state = response.State; int timeout = response.Timeout; TracingConfigResponse tracingConfig = response.TracingConfig; string version = response.Version; #endregion } public void LambdaPutFunctionConcurrency() { #region to-configure-a-reserved-concurrency-limit-for-a-function-1586491405956 var response = client.PutFunctionConcurrency(new PutFunctionConcurrencyRequest { FunctionName = "my-function", ReservedConcurrentExecutions = 100 }); int reservedConcurrentExecutions = response.ReservedConcurrentExecutions; #endregion } public void LambdaPutFunctionEventInvokeConfig() { #region to-configure-error-handling-for-asynchronous-invocation-1586491524021 var response = client.PutFunctionEventInvokeConfig(new PutFunctionEventInvokeConfigRequest { FunctionName = "my-function", MaximumEventAgeInSeconds = 3600, MaximumRetryAttempts = 0 }); DestinationConfig destinationConfig = response.DestinationConfig; string functionArn = response.FunctionArn; DateTime lastModified = response.LastModified; int maximumEventAgeInSeconds = response.MaximumEventAgeInSeconds; int maximumRetryAttempts = response.MaximumRetryAttempts; #endregion } public void LambdaPutProvisionedConcurrencyConfig() { #region to-allocate-provisioned-concurrency-1586491651377 var response = client.PutProvisionedConcurrencyConfig(new PutProvisionedConcurrencyConfigRequest { FunctionName = "my-function", ProvisionedConcurrentExecutions = 100, Qualifier = "BLUE" }); int allocatedProvisionedConcurrentExecutions = response.AllocatedProvisionedConcurrentExecutions; string lastModified = response.LastModified; int requestedProvisionedConcurrentExecutions = response.RequestedProvisionedConcurrentExecutions; string status = response.Status; #endregion } public void LambdaRemoveLayerVersionPermission() { #region to-delete-layer-version-permissions-1586491829416 var response = client.RemoveLayerVersionPermission(new RemoveLayerVersionPermissionRequest { LayerName = "my-layer", StatementId = "xaccount", VersionNumber = 1 }); #endregion } public void LambdaRemovePermission() { #region to-remove-a-lambda-functions-permissions-1481661337021 var response = client.RemovePermission(new RemovePermissionRequest { FunctionName = "my-function", Qualifier = "PROD", StatementId = "xaccount" }); #endregion } public void LambdaTagResource() { #region to-add-tags-to-an-existing-lambda-function-1586491890446 var response = client.TagResource(new TagResourceRequest { Resource = "arn:aws:lambda:us-west-2:123456789012:function:my-function", Tags = new Dictionary<string, string> { { "DEPARTMENT", "Department A" } } }); #endregion } public void LambdaUntagResource() { #region to-remove-tags-from-an-existing-lambda-function-1586491956425 var response = client.UntagResource(new UntagResourceRequest { Resource = "arn:aws:lambda:us-west-2:123456789012:function:my-function", TagKeys = new List<string> { "DEPARTMENT" } }); #endregion } public void LambdaUpdateAlias() { #region to-update-a-function-alias-1481650817950 var response = client.UpdateAlias(new UpdateAliasRequest { FunctionName = "my-function", FunctionVersion = "2", Name = "BLUE", RoutingConfig = new AliasRoutingConfiguration { AdditionalVersionWeights = new Dictionary<string, double> { { "1", 0.7 } } } }); string aliasArn = response.AliasArn; string description = response.Description; string functionVersion = response.FunctionVersion; string name = response.Name; string revisionId = response.RevisionId; AliasRoutingConfiguration routingConfig = response.RoutingConfig; #endregion } public void LambdaUpdateEventSourceMapping() { #region to-update-a-lambda-function-event-source-mapping-1481650907413 var response = client.UpdateEventSourceMapping(new UpdateEventSourceMappingRequest { BatchSize = 123, Enabled = true, FunctionName = "myFunction", UUID = "1234xCy789012" }); int batchSize = response.BatchSize; string eventSourceArn = response.EventSourceArn; string functionArn = response.FunctionArn; DateTime lastModified = response.LastModified; string lastProcessingResult = response.LastProcessingResult; string state = response.State; string stateTransitionReason = response.StateTransitionReason; string uuid = response.UUID; #endregion } public void LambdaUpdateFunctionCode() { #region to-update-a-lambda-functions-code-1481650992672 var response = client.UpdateFunctionCode(new UpdateFunctionCodeRequest { FunctionName = "my-function", S3Bucket = "my-bucket-1xpuxmplzrlbh", S3Key = "function.zip" }); string codeSha256 = response.CodeSha256; long codeSize = response.CodeSize; string description = response.Description; string functionArn = response.FunctionArn; string functionName = response.FunctionName; string handler = response.Handler; string lastModified = response.LastModified; int memorySize = response.MemorySize; string revisionId = response.RevisionId; string role = response.Role; string runtime = response.Runtime; int timeout = response.Timeout; TracingConfigResponse tracingConfig = response.TracingConfig; string version = response.Version; #endregion } public void LambdaUpdateFunctionConfiguration() { #region to-update-a-lambda-functions-configuration-1481651096447 var response = client.UpdateFunctionConfiguration(new UpdateFunctionConfigurationRequest { FunctionName = "my-function", MemorySize = 256 }); string codeSha256 = response.CodeSha256; long codeSize = response.CodeSize; string description = response.Description; string functionArn = response.FunctionArn; string functionName = response.FunctionName; string handler = response.Handler; string lastModified = response.LastModified; int memorySize = response.MemorySize; string revisionId = response.RevisionId; string role = response.Role; string runtime = response.Runtime; int timeout = response.Timeout; TracingConfigResponse tracingConfig = response.TracingConfig; string version = response.Version; #endregion } public void LambdaUpdateFunctionEventInvokeConfig() { #region to-update-an-asynchronous-invocation-configuration-1586492061186 var response = client.UpdateFunctionEventInvokeConfig(new UpdateFunctionEventInvokeConfigRequest { DestinationConfig = new DestinationConfig { OnFailure = new OnFailure { Destination = "arn:aws:sqs:us-east-2:123456789012:destination" } }, FunctionName = "my-function" }); DestinationConfig destinationConfig = response.DestinationConfig; string functionArn = response.FunctionArn; DateTime lastModified = response.LastModified; int maximumEventAgeInSeconds = response.MaximumEventAgeInSeconds; int maximumRetryAttempts = response.MaximumRetryAttempts; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
989
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.LexModelBuildingService; using Amazon.LexModelBuildingService.Model; namespace AWSSDKDocSamples.Amazon.LexModelBuildingService.Generated { class LexModelBuildingServiceSamples : ISample { public void LexModelBuildingServiceGetBot() { #region to-get-information-about-a-bot-1494431724188 var client = new AmazonLexModelBuildingServiceClient(); var response = client.GetBot(new GetBotRequest { Name = "DocOrderPizza", VersionOrAlias = "$LATEST" }); string version = response.Version; string name = response.Name; Statement abortStatement = response.AbortStatement; string checksum = response.Checksum; bool childDirected = response.ChildDirected; Prompt clarificationPrompt = response.ClarificationPrompt; DateTime createdDate = response.CreatedDate; string description = response.Description; int idleSessionTTLInSeconds = response.IdleSessionTTLInSeconds; List<Intent> intents = response.Intents; DateTime lastUpdatedDate = response.LastUpdatedDate; string locale = response.Locale; string status = response.Status; #endregion } public void LexModelBuildingServiceGetBots() { #region to-get-a-list-of-bots-1494432220036 var client = new AmazonLexModelBuildingServiceClient(); var response = client.GetBots(new GetBotsRequest { MaxResults = 5, NextToken = "" }); List<BotMetadata> bots = response.Bots; #endregion } public void LexModelBuildingServiceGetIntent() { #region to-get-a-information-about-an-intent-1494432574147 var client = new AmazonLexModelBuildingServiceClient(); var response = client.GetIntent(new GetIntentRequest { Version = "$LATEST", Name = "DocOrderPizza" }); string version = response.Version; string name = response.Name; string checksum = response.Checksum; Statement conclusionStatement = response.ConclusionStatement; Prompt confirmationPrompt = response.ConfirmationPrompt; DateTime createdDate = response.CreatedDate; string description = response.Description; FulfillmentActivity fulfillmentActivity = response.FulfillmentActivity; DateTime lastUpdatedDate = response.LastUpdatedDate; Statement rejectionStatement = response.RejectionStatement; List<string> sampleUtterances = response.SampleUtterances; List<Slot> slots = response.Slots; #endregion } public void LexModelBuildingServiceGetIntents() { #region to-get-a-list-of-intents-1494432416363 var client = new AmazonLexModelBuildingServiceClient(); var response = client.GetIntents(new GetIntentsRequest { MaxResults = 10, NextToken = "" }); List<IntentMetadata> intents = response.Intents; #endregion } public void LexModelBuildingServiceGetSlotType() { #region to-get-information-about-a-slot-type-1494432961004 var client = new AmazonLexModelBuildingServiceClient(); var response = client.GetSlotType(new GetSlotTypeRequest { Version = "$LATEST", Name = "DocPizzaCrustType" }); string version = response.Version; string name = response.Name; string checksum = response.Checksum; DateTime createdDate = response.CreatedDate; string description = response.Description; List<EnumerationValue> enumerationValues = response.EnumerationValues; DateTime lastUpdatedDate = response.LastUpdatedDate; #endregion } public void LexModelBuildingServiceGetSlotTypes() { #region to-get-a-list-of-slot-types-1494432757458 var client = new AmazonLexModelBuildingServiceClient(); var response = client.GetSlotTypes(new GetSlotTypesRequest { MaxResults = 10, NextToken = "" }); List<SlotTypeMetadata> slotTypes = response.SlotTypes; #endregion } public void LexModelBuildingServicePutBot() { #region to-create-a-bot-1494360003886 var client = new AmazonLexModelBuildingServiceClient(); var response = client.PutBot(new PutBotRequest { Name = "DocOrderPizzaBot", AbortStatement = new Statement { Messages = new List<Message> { new Message { Content = "I don't understand. Can you try again?", ContentType = "PlainText" }, new Message { Content = "I'm sorry, I don't understand.", ContentType = "PlainText" } } }, ChildDirected = true, ClarificationPrompt = new Prompt { MaxAttempts = 1, Messages = new List<Message> { new Message { Content = "I'm sorry, I didn't hear that. Can you repeat what you just said?", ContentType = "PlainText" }, new Message { Content = "Can you say that again?", ContentType = "PlainText" } } }, Description = "Orders a pizza from a local pizzeria.", IdleSessionTTLInSeconds = 300, Intents = new List<Intent> { new Intent { IntentName = "DocOrderPizza", IntentVersion = "$LATEST" } }, Locale = "en-US", ProcessBehavior = "SAVE" }); string version = response.Version; string name = response.Name; Statement abortStatement = response.AbortStatement; string checksum = response.Checksum; bool childDirected = response.ChildDirected; Prompt clarificationPrompt = response.ClarificationPrompt; DateTime createdDate = response.CreatedDate; string description = response.Description; int idleSessionTTLInSeconds = response.IdleSessionTTLInSeconds; List<Intent> intents = response.Intents; DateTime lastUpdatedDate = response.LastUpdatedDate; string locale = response.Locale; string status = response.Status; #endregion } public void LexModelBuildingServicePutIntent() { #region to-create-an-intent-1494358144659 var client = new AmazonLexModelBuildingServiceClient(); var response = client.PutIntent(new PutIntentRequest { Name = "DocOrderPizza", ConclusionStatement = new Statement { Messages = new List<Message> { new Message { Content = "All right, I ordered you a {Crust} crust {Type} pizza with {Sauce} sauce.", ContentType = "PlainText" }, new Message { Content = "OK, your {Crust} crust {Type} pizza with {Sauce} sauce is on the way.", ContentType = "PlainText" } }, ResponseCard = "foo" }, ConfirmationPrompt = new Prompt { MaxAttempts = 1, Messages = new List<Message> { new Message { Content = "Should I order your {Crust} crust {Type} pizza with {Sauce} sauce?", ContentType = "PlainText" } } }, Description = "Order a pizza from a local pizzeria.", FulfillmentActivity = new FulfillmentActivity { Type = "ReturnIntent" }, RejectionStatement = new Statement { Messages = new List<Message> { new Message { Content = "Ok, I'll cancel your order.", ContentType = "PlainText" }, new Message { Content = "I cancelled your order.", ContentType = "PlainText" } } }, SampleUtterances = new List<string> { "Order me a pizza.", "Order me a {Type} pizza.", "I want a {Crust} crust {Type} pizza", "I want a {Crust} crust {Type} pizza with {Sauce} sauce." }, Slots = new List<Slot> { new Slot { Name = "Type", Description = "The type of pizza to order.", Priority = 1, SampleUtterances = new List<string> { "Get me a {Type} pizza.", "A {Type} pizza please.", "I'd like a {Type} pizza." }, SlotConstraint = "Required", SlotType = "DocPizzaType", SlotTypeVersion = "$LATEST", ValueElicitationPrompt = new Prompt { MaxAttempts = 1, Messages = new List<Message> { new Message { Content = "What type of pizza would you like?", ContentType = "PlainText" }, new Message { Content = "Vegie or cheese pizza?", ContentType = "PlainText" }, new Message { Content = "I can get you a vegie or a cheese pizza.", ContentType = "PlainText" } } } }, new Slot { Name = "Crust", Description = "The type of pizza crust to order.", Priority = 2, SampleUtterances = new List<string> { "Make it a {Crust} crust.", "I'd like a {Crust} crust." }, SlotConstraint = "Required", SlotType = "DocPizzaCrustType", SlotTypeVersion = "$LATEST", ValueElicitationPrompt = new Prompt { MaxAttempts = 1, Messages = new List<Message> { new Message { Content = "What type of crust would you like?", ContentType = "PlainText" }, new Message { Content = "Thick or thin crust?", ContentType = "PlainText" } } } }, new Slot { Name = "Sauce", Description = "The type of sauce to use on the pizza.", Priority = 3, SampleUtterances = new List<string> { "Make it {Sauce} sauce.", "I'd like {Sauce} sauce." }, SlotConstraint = "Required", SlotType = "DocPizzaSauceType", SlotTypeVersion = "$LATEST", ValueElicitationPrompt = new Prompt { MaxAttempts = 1, Messages = new List<Message> { new Message { Content = "White or red sauce?", ContentType = "PlainText" }, new Message { Content = "Garlic or tomato sauce?", ContentType = "PlainText" } } } } } }); string version = response.Version; string name = response.Name; string checksum = response.Checksum; Statement conclusionStatement = response.ConclusionStatement; Prompt confirmationPrompt = response.ConfirmationPrompt; DateTime createdDate = response.CreatedDate; string description = response.Description; FulfillmentActivity fulfillmentActivity = response.FulfillmentActivity; DateTime lastUpdatedDate = response.LastUpdatedDate; Statement rejectionStatement = response.RejectionStatement; List<string> sampleUtterances = response.SampleUtterances; List<Slot> slots = response.Slots; #endregion } public void LexModelBuildingServicePutSlotType() { #region to-create-a-slot-type-1494357262258 var client = new AmazonLexModelBuildingServiceClient(); var response = client.PutSlotType(new PutSlotTypeRequest { Name = "PizzaSauceType", Description = "Available pizza sauces", EnumerationValues = new List<EnumerationValue> { new EnumerationValue { Value = "red" }, new EnumerationValue { Value = "white" } } }); string version = response.Version; string name = response.Name; string checksum = response.Checksum; DateTime createdDate = response.CreatedDate; string description = response.Description; List<EnumerationValue> enumerationValues = response.EnumerationValues; DateTime lastUpdatedDate = response.LastUpdatedDate; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
383
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.Neptune; using Amazon.Neptune.Model; namespace AWSSDKDocSamples.Amazon.Neptune.Generated { class NeptuneSamples : ISample { static IAmazonNeptune client = new AmazonNeptuneClient(); public void NeptuneAddSourceIdentifierToSubscription() { #region add-source-identifier-to-subscription-93fb6a15-0a59-4577-a7b5-e12db9752c14 var response = client.AddSourceIdentifierToSubscription(new AddSourceIdentifierToSubscriptionRequest { SourceIdentifier = "mymysqlinstance", SubscriptionName = "mymysqleventsubscription" }); EventSubscription eventSubscription = response.EventSubscription; #endregion } public void NeptuneAddTagsToResource() { #region add-tags-to-resource-fa99ef50-228b-449d-b893-ca4d4e9768ab var response = client.AddTagsToResource(new AddTagsToResourceRequest { ResourceName = "arn:aws:rds:us-east-1:992648334831:og:mymysqloptiongroup", Tags = new List<Tag> { new Tag { Key = "Staging", Value = "LocationDB" } } }); #endregion } public void NeptuneApplyPendingMaintenanceAction() { #region apply-pending-maintenance-action-2a026047-8bbb-47fc-b695-abad9f308c24 var response = client.ApplyPendingMaintenanceAction(new ApplyPendingMaintenanceActionRequest { ApplyAction = "system-update", OptInType = "immediate", ResourceIdentifier = "arn:aws:rds:us-east-1:992648334831:db:mymysqlinstance" }); ResourcePendingMaintenanceActions resourcePendingMaintenanceActions = response.ResourcePendingMaintenanceActions; #endregion } public void NeptuneCopyDBClusterParameterGroup() { #region copy-db-cluster-parameter-group-6fefaffe-cde9-4dba-9f0b-d3f593572fe4 var response = client.CopyDBClusterParameterGroup(new CopyDBClusterParameterGroupRequest { SourceDBClusterParameterGroupIdentifier = "mydbclusterparametergroup", TargetDBClusterParameterGroupDescription = "My DB cluster parameter group copy", TargetDBClusterParameterGroupIdentifier = "mydbclusterparametergroup-copy" }); DBClusterParameterGroup dbClusterParameterGroup = response.DBClusterParameterGroup; #endregion } public void NeptuneCopyDBClusterSnapshot() { #region to-copy-a-db-cluster-snapshot-1473879770564 var response = client.CopyDBClusterSnapshot(new CopyDBClusterSnapshotRequest { SourceDBClusterSnapshotIdentifier = "rds:sample-cluster-2016-09-14-10-38", TargetDBClusterSnapshotIdentifier = "cluster-snapshot-copy-1" }); DBClusterSnapshot dbClusterSnapshot = response.DBClusterSnapshot; #endregion } public void NeptuneCopyDBParameterGroup() { #region copy-db-parameter-group-610d4dba-2c87-467f-ae5d-edd7f8e47349 var response = client.CopyDBParameterGroup(new CopyDBParameterGroupRequest { SourceDBParameterGroupIdentifier = "mymysqlparametergroup", TargetDBParameterGroupDescription = "My MySQL parameter group copy", TargetDBParameterGroupIdentifier = "mymysqlparametergroup-copy" }); DBParameterGroup dbParameterGroup = response.DBParameterGroup; #endregion } public void NeptuneCreateDBCluster() { #region create-db-cluster-423b998d-eba9-40dd-8e19-96c5b6e5f31d var response = client.CreateDBCluster(new CreateDBClusterRequest { AvailabilityZones = new List<string> { "us-east-1a" }, BackupRetentionPeriod = 1, DBClusterIdentifier = "mydbcluster", DBClusterParameterGroupName = "mydbclusterparametergroup", DatabaseName = "myauroradb", Engine = "aurora", EngineVersion = "5.6.10a", MasterUserPassword = "mypassword", MasterUsername = "myuser", Port = 3306, StorageEncrypted = true }); DBCluster dbCluster = response.DBCluster; #endregion } public void NeptuneCreateDBClusterParameterGroup() { #region create-db-cluster-parameter-group-8eb1c3ae-1965-4262-afe3-ee134c4430b1 var response = client.CreateDBClusterParameterGroup(new CreateDBClusterParameterGroupRequest { DBClusterParameterGroupName = "mydbclusterparametergroup", DBParameterGroupFamily = "aurora5.6", Description = "My DB cluster parameter group" }); DBClusterParameterGroup dbClusterParameterGroup = response.DBClusterParameterGroup; #endregion } public void NeptuneCreateDBClusterSnapshot() { #region create-db-cluster-snapshot- var response = client.CreateDBClusterSnapshot(new CreateDBClusterSnapshotRequest { DBClusterIdentifier = "mydbcluster", DBClusterSnapshotIdentifier = "mydbclustersnapshot" }); DBClusterSnapshot dbClusterSnapshot = response.DBClusterSnapshot; #endregion } public void NeptuneCreateDBInstance() { #region create-db-instance-57eb5d16-8bf8-4c84-9709-1700322b37b9 var response = client.CreateDBInstance(new CreateDBInstanceRequest { AllocatedStorage = 5, DBInstanceClass = "db.t2.micro", DBInstanceIdentifier = "mymysqlinstance", Engine = "MySQL", MasterUserPassword = "MyPassword", MasterUsername = "MyUser" }); DBInstance dbInstance = response.DBInstance; #endregion } public void NeptuneCreateDBParameterGroup() { #region create-db-parameter-group-42afcc37-12e9-4b6a-a55c-b8a141246e87 var response = client.CreateDBParameterGroup(new CreateDBParameterGroupRequest { DBParameterGroupFamily = "mysql5.6", DBParameterGroupName = "mymysqlparametergroup", Description = "My MySQL parameter group" }); DBParameterGroup dbParameterGroup = response.DBParameterGroup; #endregion } public void NeptuneCreateDBSubnetGroup() { #region create-db-subnet-group-c3d162c2-0ec4-4955-ba89-18967615fdb8 var response = client.CreateDBSubnetGroup(new CreateDBSubnetGroupRequest { DBSubnetGroupDescription = "My DB subnet group", DBSubnetGroupName = "mydbsubnetgroup", SubnetIds = new List<string> { "subnet-1fab8a69", "subnet-d43a468c" } }); DBSubnetGroup dbSubnetGroup = response.DBSubnetGroup; #endregion } public void NeptuneCreateEventSubscription() { #region create-event-subscription-00dd0ee6-0e0f-4a38-ae83-e5f2ded5f69a var response = client.CreateEventSubscription(new CreateEventSubscriptionRequest { Enabled = true, EventCategories = new List<string> { "availability" }, SnsTopicArn = "arn:aws:sns:us-east-1:992648334831:MyDemoSNSTopic", SourceIds = new List<string> { "mymysqlinstance" }, SourceType = "db-instance", SubscriptionName = "mymysqleventsubscription" }); EventSubscription eventSubscription = response.EventSubscription; #endregion } public void NeptuneDeleteDBCluster() { #region delete-db-cluster-927fc2c8-6c67-4075-b1ba-75490be0f7d6 var response = client.DeleteDBCluster(new DeleteDBClusterRequest { DBClusterIdentifier = "mydbcluster", SkipFinalSnapshot = true }); DBCluster dbCluster = response.DBCluster; #endregion } public void NeptuneDeleteDBClusterParameterGroup() { #region delete-db-cluster-parameter-group-364f5555-ba0a-4cc8-979c-e769098924fc var response = client.DeleteDBClusterParameterGroup(new DeleteDBClusterParameterGroupRequest { DBClusterParameterGroupName = "mydbclusterparametergroup" }); #endregion } public void NeptuneDeleteDBClusterSnapshot() { #region delete-db-cluster-snapshot-c67e0d95-670e-4fb5-af90-6d9a70a91b07 var response = client.DeleteDBClusterSnapshot(new DeleteDBClusterSnapshotRequest { DBClusterSnapshotIdentifier = "mydbclustersnapshot" }); DBClusterSnapshot dbClusterSnapshot = response.DBClusterSnapshot; #endregion } public void NeptuneDeleteDBInstance() { #region delete-db-instance-4412e650-949c-488a-b32a-7d3038ebccc4 var response = client.DeleteDBInstance(new DeleteDBInstanceRequest { DBInstanceIdentifier = "mymysqlinstance", SkipFinalSnapshot = true }); DBInstance dbInstance = response.DBInstance; #endregion } public void NeptuneDeleteDBParameterGroup() { #region to-delete-a-db-parameter-group-1473888796509 var response = client.DeleteDBParameterGroup(new DeleteDBParameterGroupRequest { DBParameterGroupName = "mydbparamgroup3" }); #endregion } public void NeptuneDeleteDBSubnetGroup() { #region delete-db-subnet-group-4ae00375-511e-443d-a01d-4b9f552244aa var response = client.DeleteDBSubnetGroup(new DeleteDBSubnetGroupRequest { DBSubnetGroupName = "mydbsubnetgroup" }); #endregion } public void NeptuneDeleteEventSubscription() { #region delete-db-event-subscription-d33567e3-1d5d-48ff-873f-0270453f4a75 var response = client.DeleteEventSubscription(new DeleteEventSubscriptionRequest { SubscriptionName = "myeventsubscription" }); EventSubscription eventSubscription = response.EventSubscription; #endregion } public void NeptuneDescribeDBClusterParameterGroups() { #region describe-db-cluster-parameter-groups-cf9c6e66-664e-4f57-8e29-a9080abfc013 var response = client.DescribeDBClusterParameterGroups(new DescribeDBClusterParameterGroupsRequest { DBClusterParameterGroupName = "mydbclusterparametergroup" }); #endregion } public void NeptuneDescribeDBClusterParameters() { #region describe-db-cluster-parameters-98043c28-e489-41a7-b118-bfd96dc779a1 var response = client.DescribeDBClusterParameters(new DescribeDBClusterParametersRequest { DBClusterParameterGroupName = "mydbclusterparametergroup", Source = "system" }); #endregion } public void NeptuneDescribeDBClusters() { #region describe-db-clusters-7aae8861-cb95-4b3b-9042-f62df7698635 var response = client.DescribeDBClusters(new DescribeDBClustersRequest { DBClusterIdentifier = "mynewdbcluster" }); #endregion } public void NeptuneDescribeDBClusterSnapshotAttributes() { #region describe-db-cluster-snapshot-attributes-6752ade3-0c7b-4b06-a8e4-b76bf4e2d3571 var response = client.DescribeDBClusterSnapshotAttributes(new DescribeDBClusterSnapshotAttributesRequest { DBClusterSnapshotIdentifier = "mydbclustersnapshot" }); DBClusterSnapshotAttributesResult dbClusterSnapshotAttributesResult = response.DBClusterSnapshotAttributesResult; #endregion } public void NeptuneDescribeDBClusterSnapshots() { #region describe-db-cluster-snapshots-52f38af1-3431-4a51-9a6a-e6bb8c961b32 var response = client.DescribeDBClusterSnapshots(new DescribeDBClusterSnapshotsRequest { DBClusterSnapshotIdentifier = "mydbclustersnapshot", SnapshotType = "manual" }); #endregion } public void NeptuneDescribeDBEngineVersions() { #region describe-db-engine-versions-8e698cf2-2162-425a-a854-111cdaceb52b var response = client.DescribeDBEngineVersions(new DescribeDBEngineVersionsRequest { DBParameterGroupFamily = "mysql5.6", DefaultOnly = true, Engine = "mysql", EngineVersion = "5.6", ListSupportedCharacterSets = true }); #endregion } public void NeptuneDescribeDBInstances() { #region describe-db-instances-0e11a8c5-4ec3-4463-8cbf-f7254d04c4fc var response = client.DescribeDBInstances(new DescribeDBInstancesRequest { DBInstanceIdentifier = "mymysqlinstance" }); #endregion } public void NeptuneDescribeDBParameterGroups() { #region describe-db-parameter-groups- var response = client.DescribeDBParameterGroups(new DescribeDBParameterGroupsRequest { DBParameterGroupName = "mymysqlparametergroup" }); #endregion } public void NeptuneDescribeDBParameters() { #region describe-db-parameters-09db4201-ef4f-4d97-a4b5-d71c0715b901 var response = client.DescribeDBParameters(new DescribeDBParametersRequest { DBParameterGroupName = "mymysqlparametergroup", MaxRecords = 20, Source = "system" }); #endregion } public void NeptuneDescribeDBSubnetGroups() { #region describe-db-subnet-groups-1d97b340-682f-4dd6-9653-8ed72a8d1221 var response = client.DescribeDBSubnetGroups(new DescribeDBSubnetGroupsRequest { DBSubnetGroupName = "mydbsubnetgroup" }); #endregion } public void NeptuneDescribeEngineDefaultClusterParameters() { #region describe-engine-default-cluster-parameters-f130374a-7bee-434b-b51d-da20b6e000e0 var response = client.DescribeEngineDefaultClusterParameters(new DescribeEngineDefaultClusterParametersRequest { DBParameterGroupFamily = "aurora5.6" }); EngineDefaults engineDefaults = response.EngineDefaults; #endregion } public void NeptuneDescribeEngineDefaultParameters() { #region describe-engine-default-parameters-35d5108e-1d44-4fac-8aeb-04b8fdfface1 var response = client.DescribeEngineDefaultParameters(new DescribeEngineDefaultParametersRequest { DBParameterGroupFamily = "mysql5.6" }); EngineDefaults engineDefaults = response.EngineDefaults; #endregion } public void NeptuneDescribeEventCategories() { #region describe-event-categories-97bd4c77-12da-4be6-b42f-edf77771428b var response = client.DescribeEventCategories(new DescribeEventCategoriesRequest { SourceType = "db-instance" }); #endregion } public void NeptuneDescribeEvents() { #region describe-events-3836e5ed-3913-4f76-8452-c77fcad5016b var response = client.DescribeEvents(new DescribeEventsRequest { Duration = 10080, EventCategories = new List<string> { "backup" }, SourceIdentifier = "mymysqlinstance", SourceType = "db-instance" }); #endregion } public void NeptuneDescribeEventSubscriptions() { #region describe-event-subscriptions-11184a82-e58a-4d0c-b558-f3a7489e0850 var response = client.DescribeEventSubscriptions(new DescribeEventSubscriptionsRequest { SubscriptionName = "mymysqleventsubscription" }); #endregion } public void NeptuneDescribeOrderableDBInstanceOptions() { #region describe-orderable-db-instance-options-7444d3ed-82eb-42b9-9ed9-896b8c27a782 var response = client.DescribeOrderableDBInstanceOptions(new DescribeOrderableDBInstanceOptionsRequest { DBInstanceClass = "db.t2.micro", Engine = "mysql", EngineVersion = "5.6.27", LicenseModel = "general-public-license", Vpc = true }); #endregion } public void NeptuneDescribePendingMaintenanceActions() { #region describe-pending-maintenance-actions-e6021f7e-58ae-49cc-b874-11996176835c var response = client.DescribePendingMaintenanceActions(new DescribePendingMaintenanceActionsRequest { ResourceIdentifier = "arn:aws:rds:us-east-1:992648334831:db:mymysqlinstance" }); #endregion } public void NeptuneFailoverDBCluster() { #region failover-db-cluster-9e7f2f93-d98c-42c7-bb0e-d6c485c096d6 var response = client.FailoverDBCluster(new FailoverDBClusterRequest { DBClusterIdentifier = "myaurorainstance-cluster", TargetDBInstanceIdentifier = "myaurorareplica" }); DBCluster dbCluster = response.DBCluster; #endregion } public void NeptuneListTagsForResource() { #region list-tags-for-resource-8401f3c2-77cd-4f90-bfd5-b523f0adcc2f var response = client.ListTagsForResource(new ListTagsForResourceRequest { ResourceName = "arn:aws:rds:us-east-1:992648334831:og:mymysqloptiongroup" }); #endregion } public void NeptuneModifyDBCluster() { #region modify-db-cluster-a370ee1b-768d-450a-853b-707cb1ab663d var response = client.ModifyDBCluster(new ModifyDBClusterRequest { ApplyImmediately = true, DBClusterIdentifier = "mydbcluster", MasterUserPassword = "mynewpassword", NewDBClusterIdentifier = "mynewdbcluster", PreferredBackupWindow = "04:00-04:30", PreferredMaintenanceWindow = "Tue:05:00-Tue:05:30" }); DBCluster dbCluster = response.DBCluster; #endregion } public void NeptuneModifyDBClusterParameterGroup() { #region modify-db-cluster-parameter-group-f9156bc9-082a-442e-8d12-239542c1a113 var response = client.ModifyDBClusterParameterGroup(new ModifyDBClusterParameterGroupRequest { DBClusterParameterGroupName = "mydbclusterparametergroup", Parameters = new List<Parameter> { new Parameter { ApplyMethod = "immediate", ParameterName = "time_zone", ParameterValue = "America/Phoenix" } } }); #endregion } public void NeptuneModifyDBClusterSnapshotAttribute() { #region to-add-or-remove-access-to-a-manual-db-cluster-snapshot-1473889426431 var response = client.ModifyDBClusterSnapshotAttribute(new ModifyDBClusterSnapshotAttributeRequest { AttributeName = "restore", DBClusterSnapshotIdentifier = "manual-cluster-snapshot1", ValuesToAdd = new List<string> { "123451234512", "123456789012" }, ValuesToRemove = new List<string> { "all" } }); DBClusterSnapshotAttributesResult dbClusterSnapshotAttributesResult = response.DBClusterSnapshotAttributesResult; #endregion } public void NeptuneModifyDBInstance() { #region modify-db-instance-6979a368-6254-467b-8a8d-61103f4fcde9 var response = client.ModifyDBInstance(new ModifyDBInstanceRequest { AllocatedStorage = 10, ApplyImmediately = true, BackupRetentionPeriod = 1, DBInstanceClass = "db.t2.small", DBInstanceIdentifier = "mymysqlinstance", MasterUserPassword = "mynewpassword", PreferredBackupWindow = "04:00-04:30", PreferredMaintenanceWindow = "Tue:05:00-Tue:05:30" }); DBInstance dbInstance = response.DBInstance; #endregion } public void NeptuneModifyDBParameterGroup() { #region modify-db-parameter-group-f3a4e52a-68e4-4b88-b559-f912d34c457a var response = client.ModifyDBParameterGroup(new ModifyDBParameterGroupRequest { DBParameterGroupName = "mymysqlparametergroup", Parameters = new List<Parameter> { new Parameter { ApplyMethod = "immediate", ParameterName = "time_zone", ParameterValue = "America/Phoenix" } } }); #endregion } public void NeptuneModifyDBSubnetGroup() { #region modify-db-subnet-group-e34a97d9-8fe6-4239-a4ed-ad6e73a956b0 var response = client.ModifyDBSubnetGroup(new ModifyDBSubnetGroupRequest { DBSubnetGroupName = "mydbsubnetgroup", SubnetIds = new List<string> { "subnet-70e1975a", "subnet-747a5c49" } }); DBSubnetGroup dbSubnetGroup = response.DBSubnetGroup; #endregion } public void NeptuneModifyEventSubscription() { #region modify-event-subscription-405ac869-1f02-42cd-b8f4-6950a435f30e var response = client.ModifyEventSubscription(new ModifyEventSubscriptionRequest { Enabled = true, EventCategories = new List<string> { "deletion", "low storage" }, SourceType = "db-instance", SubscriptionName = "mymysqleventsubscription" }); EventSubscription eventSubscription = response.EventSubscription; #endregion } public void NeptuneRebootDBInstance() { #region reboot-db-instance-b9ce8a0a-2920-451d-a1f3-01d288aa7366 var response = client.RebootDBInstance(new RebootDBInstanceRequest { DBInstanceIdentifier = "mymysqlinstance", ForceFailover = false }); DBInstance dbInstance = response.DBInstance; #endregion } public void NeptuneRemoveSourceIdentifierFromSubscription() { #region remove-source-identifier-from-subscription-30d25493-c19d-4cf7-b4e5-68371d0d8770 var response = client.RemoveSourceIdentifierFromSubscription(new RemoveSourceIdentifierFromSubscriptionRequest { SourceIdentifier = "mymysqlinstance", SubscriptionName = "myeventsubscription" }); EventSubscription eventSubscription = response.EventSubscription; #endregion } public void NeptuneRemoveTagsFromResource() { #region remove-tags-from-resource-49f00574-38f6-4d01-ac89-d3c668449ce3 var response = client.RemoveTagsFromResource(new RemoveTagsFromResourceRequest { ResourceName = "arn:aws:rds:us-east-1:992648334831:og:mydboptiongroup", TagKeys = new List<string> { "MyKey" } }); #endregion } public void NeptuneResetDBClusterParameterGroup() { #region reset-db-cluster-parameter-group-b04aeaf7-7f73-49e1-9bb4-857573ea3ee4 var response = client.ResetDBClusterParameterGroup(new ResetDBClusterParameterGroupRequest { DBClusterParameterGroupName = "mydbclusterparametergroup", ResetAllParameters = true }); #endregion } public void NeptuneResetDBParameterGroup() { #region reset-db-parameter-group-ed2ed723-de0d-4824-8af5-3c65fa130abf var response = client.ResetDBParameterGroup(new ResetDBParameterGroupRequest { DBParameterGroupName = "mydbparametergroup", ResetAllParameters = true }); #endregion } public void NeptuneRestoreDBClusterFromSnapshot() { #region to-restore-an-amazon-aurora-db-cluster-from-a-db-cluster-snapshot-1473958144325 var response = client.RestoreDBClusterFromSnapshot(new RestoreDBClusterFromSnapshotRequest { DBClusterIdentifier = "restored-cluster1", Engine = "aurora", SnapshotIdentifier = "sample-cluster-snapshot1" }); DBCluster dbCluster = response.DBCluster; #endregion } public void NeptuneRestoreDBClusterToPointInTime() { #region to-restore-a-db-cluster-to-a-point-in-time-1473962082214 var response = client.RestoreDBClusterToPointInTime(new RestoreDBClusterToPointInTimeRequest { DBClusterIdentifier = "sample-restored-cluster1", RestoreToTime = new DateTime(2016, 9, 13, 11, 45, 0), SourceDBClusterIdentifier = "sample-cluster1" }); DBCluster dbCluster = response.DBCluster; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
867
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.Organizations; using Amazon.Organizations.Model; namespace AWSSDKDocSamples.Amazon.Organizations.Generated { class OrganizationsSamples : ISample { public void OrganizationsAcceptHandshake() { #region to-accept-a-handshake-from-another-account-1472500561150 var client = new AmazonOrganizationsClient(); var response = client.AcceptHandshake(new AcceptHandshakeRequest { HandshakeId = "h-examplehandshakeid111" }); Handshake handshake = response.Handshake; #endregion } public void OrganizationsAttachPolicy() { #region to-attach-a-policy-to-an-ou var client = new AmazonOrganizationsClient(); var response = client.AttachPolicy(new AttachPolicyRequest { PolicyId = "p-examplepolicyid111", TargetId = "ou-examplerootid111-exampleouid111" }); #endregion } public void OrganizationsAttachPolicy() { #region to-attach-a-policy-to-an-account var client = new AmazonOrganizationsClient(); var response = client.AttachPolicy(new AttachPolicyRequest { PolicyId = "p-examplepolicyid111", TargetId = "333333333333" }); #endregion } public void OrganizationsCancelHandshake() { #region to-cancel-a-handshake-sent-to-a-member-account-1472501320506 var client = new AmazonOrganizationsClient(); var response = client.CancelHandshake(new CancelHandshakeRequest { HandshakeId = "h-examplehandshakeid111" }); Handshake handshake = response.Handshake; #endregion } public void OrganizationsCreateAccount() { #region to-create-a-new-account-that-is-automatically-part-of-the-organization-1472501463507 var client = new AmazonOrganizationsClient(); var response = client.CreateAccount(new CreateAccountRequest { AccountName = "Production Account", Email = "[email protected]" }); CreateAccountStatus createAccountStatus = response.CreateAccountStatus; #endregion } public void OrganizationsCreateOrganization() { #region to-create-a-new-organization-with-all-features enabled var client = new AmazonOrganizationsClient(); var response = client.CreateOrganization(new CreateOrganizationRequest { }); Organization organization = response.Organization; #endregion } public void OrganizationsCreateOrganization() { #region to-create-a-new-organization-with-consolidated-billing-features-only var client = new AmazonOrganizationsClient(); var response = client.CreateOrganization(new CreateOrganizationRequest { FeatureSet = "CONSOLIDATED_BILLING" }); Organization organization = response.Organization; #endregion } public void OrganizationsCreateOrganizationalUnit() { #region to-create-a-new-organizational-unit var client = new AmazonOrganizationsClient(); var response = client.CreateOrganizationalUnit(new CreateOrganizationalUnitRequest { Name = "AccountingOU", ParentId = "r-examplerootid111" }); OrganizationalUnit organizationalUnit = response.OrganizationalUnit; #endregion } public void OrganizationsCreatePolicy() { #region to-create-a-service-control-policy var client = new AmazonOrganizationsClient(); var response = client.CreatePolicy(new CreatePolicyRequest { Content = "{\\"Version\\":\\"2012-10-17\\",\\"Statement\\":{\\"Effect\\":\\"Allow\\",\\"Action\\":\\"s3:*\\"}}", Description = "Enables admins of attached accounts to delegate all S3 permissions", Name = "AllowAllS3Actions", Type = "SERVICE_CONTROL_POLICY" }); Policy policy = response.Policy; #endregion } public void OrganizationsDeclineHandshake() { #region to-decline-a-handshake-sent-from-the-master-account-1472502666967 var client = new AmazonOrganizationsClient(); var response = client.DeclineHandshake(new DeclineHandshakeRequest { HandshakeId = "h-examplehandshakeid111" }); Handshake handshake = response.Handshake; #endregion } public void OrganizationsDeleteOrganizationalUnit() { #region to-delete-an-organizational-unit var client = new AmazonOrganizationsClient(); var response = client.DeleteOrganizationalUnit(new DeleteOrganizationalUnitRequest { OrganizationalUnitId = "ou-examplerootid111-exampleouid111" }); #endregion } public void OrganizationsDeletePolicy() { #region to-delete-a-policy var client = new AmazonOrganizationsClient(); var response = client.DeletePolicy(new DeletePolicyRequest { PolicyId = "p-examplepolicyid111" }); #endregion } public void OrganizationsDescribeAccount() { #region to-get-the-details-about-an-account-1472503166868 var client = new AmazonOrganizationsClient(); var response = client.DescribeAccount(new DescribeAccountRequest { AccountId = "555555555555" }); Account account = response.Account; #endregion } public void OrganizationsDescribeCreateAccountStatus() { #region to-get-information-about-a-request-to-create-an-account-1472503727223 var client = new AmazonOrganizationsClient(); var response = client.DescribeCreateAccountStatus(new DescribeCreateAccountStatusRequest { CreateAccountRequestId = "car-exampleaccountcreationrequestid" }); CreateAccountStatus createAccountStatus = response.CreateAccountStatus; #endregion } public void OrganizationsDescribeHandshake() { #region to-get-information-about-a-handshake-1472503400505 var client = new AmazonOrganizationsClient(); var response = client.DescribeHandshake(new DescribeHandshakeRequest { HandshakeId = "h-examplehandshakeid111" }); Handshake handshake = response.Handshake; #endregion } public void OrganizationsDescribeOrganization() { #region to-get-information-about-an-organization-1472503400505 var client = new AmazonOrganizationsClient(); var response = client.DescribeOrganization(new DescribeOrganizationRequest { }); Organization organization = response.Organization; #endregion } public void OrganizationsDescribeOrganizationalUnit() { #region to-get-information-about-an-organizational-unit var client = new AmazonOrganizationsClient(); var response = client.DescribeOrganizationalUnit(new DescribeOrganizationalUnitRequest { OrganizationalUnitId = "ou-examplerootid111-exampleouid111" }); OrganizationalUnit organizationalUnit = response.OrganizationalUnit; #endregion } public void OrganizationsDescribePolicy() { #region to-get-information-about-a-policy var client = new AmazonOrganizationsClient(); var response = client.DescribePolicy(new DescribePolicyRequest { PolicyId = "p-examplepolicyid111" }); Policy policy = response.Policy; #endregion } public void OrganizationsDetachPolicy() { #region to-detach-a-policy-from-a-root-ou-or-account var client = new AmazonOrganizationsClient(); var response = client.DetachPolicy(new DetachPolicyRequest { PolicyId = "p-examplepolicyid111", TargetId = "ou-examplerootid111-exampleouid111" }); #endregion } public void OrganizationsDisablePolicyType() { #region to-disable-a-policy-type-in-a-root var client = new AmazonOrganizationsClient(); var response = client.DisablePolicyType(new DisablePolicyTypeRequest { PolicyType = "SERVICE_CONTROL_POLICY", RootId = "r-examplerootid111" }); Root root = response.Root; #endregion } public void OrganizationsEnableAllFeatures() { #region to-enable-all-features-in-an-organization var client = new AmazonOrganizationsClient(); var response = client.EnableAllFeatures(new EnableAllFeaturesRequest { }); Handshake handshake = response.Handshake; #endregion } public void OrganizationsEnablePolicyType() { #region to-enable-a-policy-type-in-a-root var client = new AmazonOrganizationsClient(); var response = client.EnablePolicyType(new EnablePolicyTypeRequest { PolicyType = "SERVICE_CONTROL_POLICY", RootId = "r-examplerootid111" }); Root root = response.Root; #endregion } public void OrganizationsInviteAccountToOrganization() { #region to-invite-an-account-to-join-an-organization-1472508594110 var client = new AmazonOrganizationsClient(); var response = client.InviteAccountToOrganization(new InviteAccountToOrganizationRequest { Notes = "This is a request for Juan's account to join Bill's organization", Target = new HandshakeParty { Id = "[email protected]", Type = "EMAIL" } }); Handshake handshake = response.Handshake; #endregion } public void OrganizationsLeaveOrganization() { #region to-leave-an-organization-as-a-member-account-1472508784736 var client = new AmazonOrganizationsClient(); var response = client.LeaveOrganization(new LeaveOrganizationRequest { }); #endregion } public void OrganizationsListAccounts() { #region to-retrieve-a-list-of-all-of-the-accounts-in-an-organization-1472509590974 var client = new AmazonOrganizationsClient(); var response = client.ListAccounts(new ListAccountsRequest { }); List<Account> accounts = response.Accounts; #endregion } public void OrganizationsListAccountsForParent() { #region to-retrieve-a-list-of-all-of-the-accounts-in-a-root-or-ou-1472509590974 var client = new AmazonOrganizationsClient(); var response = client.ListAccountsForParent(new ListAccountsForParentRequest { ParentId = "ou-examplerootid111-exampleouid111" }); List<Account> accounts = response.Accounts; #endregion } public void OrganizationsListChildren() { #region to-retrieve-a-list-of-all-of-the-child-accounts-and-OUs-in-a-parent-container var client = new AmazonOrganizationsClient(); var response = client.ListChildren(new ListChildrenRequest { ChildType = "ORGANIZATIONAL_UNIT", ParentId = "ou-examplerootid111-exampleouid111" }); List<Child> children = response.Children; #endregion } public void OrganizationsListCreateAccountStatus() { #region to-get-a-list-of-completed-account-creation-requests-made-in-the-organization var client = new AmazonOrganizationsClient(); var response = client.ListCreateAccountStatus(new ListCreateAccountStatusRequest { States = new List<string> { "SUCCEEDED" } }); List<CreateAccountStatus> createAccountStatuses = response.CreateAccountStatuses; #endregion } public void OrganizationsListCreateAccountStatus() { #region to-get-a-list-of-all-account-creation-requests-made-in-the-organization-1472509174532 var client = new AmazonOrganizationsClient(); var response = client.ListCreateAccountStatus(new ListCreateAccountStatusRequest { States = new List<string> { "IN_PROGRESS" } }); List<CreateAccountStatus> createAccountStatuses = response.CreateAccountStatuses; #endregion } public void OrganizationsListHandshakesForAccount() { #region to-retrieve-a-list-of-the-handshakes-sent-to-an-account-1472510214747 var client = new AmazonOrganizationsClient(); var response = client.ListHandshakesForAccount(new ListHandshakesForAccountRequest { }); List<Handshake> handshakes = response.Handshakes; #endregion } public void OrganizationsListHandshakesForOrganization() { #region to-retrieve-a-list-of-the-handshakes-associated-with-an-organization-1472511206653 var client = new AmazonOrganizationsClient(); var response = client.ListHandshakesForOrganization(new ListHandshakesForOrganizationRequest { }); List<Handshake> handshakes = response.Handshakes; #endregion } public void OrganizationsListOrganizationalUnitsForParent() { #region to-retrieve-a-list-of-all-of-the-OUs-in-a-parent-container var client = new AmazonOrganizationsClient(); var response = client.ListOrganizationalUnitsForParent(new ListOrganizationalUnitsForParentRequest { ParentId = "r-examplerootid111" }); List<OrganizationalUnit> organizationalUnits = response.OrganizationalUnits; #endregion } public void OrganizationsListParents() { #region to-retrieve-a-list-of-all-of-the-parents-of-a-child-ou-or-account var client = new AmazonOrganizationsClient(); var response = client.ListParents(new ListParentsRequest { ChildId = "444444444444" }); List<Parent> parents = response.Parents; #endregion } public void OrganizationsListPolicies() { #region to-retrieve-a-list-of--policies-in-the-organization var client = new AmazonOrganizationsClient(); var response = client.ListPolicies(new ListPoliciesRequest { Filter = "SERVICE_CONTROL_POLICY" }); List<PolicySummary> policies = response.Policies; #endregion } public void OrganizationsListPoliciesForTarget() { #region to-retrieve-a-list-of-policies-attached-to-a-root-ou-or-account var client = new AmazonOrganizationsClient(); var response = client.ListPoliciesForTarget(new ListPoliciesForTargetRequest { Filter = "SERVICE_CONTROL_POLICY", TargetId = "444444444444" }); List<PolicySummary> policies = response.Policies; #endregion } public void OrganizationsListRoots() { #region to-retrieve-a-list-of-roots-in-the-organization var client = new AmazonOrganizationsClient(); var response = client.ListRoots(new ListRootsRequest { }); List<Root> roots = response.Roots; #endregion } public void OrganizationsListTargetsForPolicy() { #region to-retrieve-a-list-of-roots-ous-and-accounts-to-which-a-policy-is-attached var client = new AmazonOrganizationsClient(); var response = client.ListTargetsForPolicy(new ListTargetsForPolicyRequest { PolicyId = "p-FullAWSAccess" }); List<PolicyTargetSummary> targets = response.Targets; #endregion } public void OrganizationsMoveAccount() { #region to-move-an-ou-or-account-to-another-ou-or-the-root var client = new AmazonOrganizationsClient(); var response = client.MoveAccount(new MoveAccountRequest { AccountId = "333333333333", DestinationParentId = "ou-examplerootid111-exampleouid111", SourceParentId = "r-examplerootid111" }); #endregion } public void OrganizationsRemoveAccountFromOrganization() { #region to-remove-an-account-from-an-organization-as-the-master-account var client = new AmazonOrganizationsClient(); var response = client.RemoveAccountFromOrganization(new RemoveAccountFromOrganizationRequest { AccountId = "333333333333" }); #endregion } public void OrganizationsUpdateOrganizationalUnit() { #region to-rename-an-organizational-unit var client = new AmazonOrganizationsClient(); var response = client.UpdateOrganizationalUnit(new UpdateOrganizationalUnitRequest { Name = "AccountingOU", OrganizationalUnitId = "ou-examplerootid111-exampleouid111" }); OrganizationalUnit organizationalUnit = response.OrganizationalUnit; #endregion } public void OrganizationsUpdatePolicy() { #region to-update-the-details-of-a-policy var client = new AmazonOrganizationsClient(); var response = client.UpdatePolicy(new UpdatePolicyRequest { Description = "This description replaces the original.", Name = "Renamed-Policy", PolicyId = "p-examplepolicyid111" }); Policy policy = response.Policy; #endregion } public void OrganizationsUpdatePolicy() { #region to-update-the-content-of-a-policy var client = new AmazonOrganizationsClient(); var response = client.UpdatePolicy(new UpdatePolicyRequest { Content = "{ \\"Version\\": \\"2012-10-17\\", \\"Statement\\": {\\"Effect\\": \\"Allow\\", \\"Action\\": \\"s3:*\\", \\"Resource\\": \\"*\\" } }", PolicyId = "p-examplepolicyid111" }); Policy policy = response.Policy; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
663
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.Pinpoint; using Amazon.Pinpoint.Model; namespace AWSSDKDocSamples.Amazon.Pinpoint.Generated { class PinpointSamples : ISample { public void PinpointGetJourneyRunExecutionActivityMetrics() { #region to-get-the-activity-execution-metrics-for-a-journey-run var client = new AmazonPinpointClient(); var response = client.GetJourneyRunExecutionActivityMetrics(new GetJourneyRunExecutionActivityMetricsRequest { ApplicationId = "11111111112222222222333333333344", JourneyId = "aaaaaaaaaabbbbbbbbbbccccccccccdd", RunId = "99999999998888888888777777777766", JourneyActivityId = "AAAAAAAAAA" }); JourneyRunExecutionActivityMetricsResponse journeyRunExecutionActivityMetricsResponse = response.JourneyRunExecutionActivityMetricsResponse; #endregion } public void PinpointGetJourneyRunExecutionMetrics() { #region to-get-the-execution-metrics-for-a-journey-run var client = new AmazonPinpointClient(); var response = client.GetJourneyRunExecutionMetrics(new GetJourneyRunExecutionMetricsRequest { ApplicationId = "11111111112222222222333333333344", JourneyId = "aaaaaaaaaabbbbbbbbbbccccccccccdd", RunId = "99999999998888888888777777777766" }); JourneyRunExecutionMetricsResponse journeyRunExecutionMetricsResponse = response.JourneyRunExecutionMetricsResponse; #endregion } public void PinpointGetJourneyRuns() { #region to-get-the-runs-of-a-journey var client = new AmazonPinpointClient(); var response = client.GetJourneyRuns(new GetJourneyRunsRequest { ApplicationId = "11111111112222222222333333333344", JourneyId = "aaaaaaaaaabbbbbbbbbbccccccccccdd" }); JourneyRunsResponse journeyRunsResponse = response.JourneyRunsResponse; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
74
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.Polly; using Amazon.Polly.Model; namespace AWSSDKDocSamples.Amazon.Polly.Generated { class PollySamples : ISample { public void PollyDeleteLexicon() { #region to-delete-a-lexicon-1481922498332 var client = new AmazonPollyClient(); var response = client.DeleteLexicon(new DeleteLexiconRequest { Name = "example" }); #endregion } public void PollyDescribeVoices() { #region to-describe-available-voices-1482180557753 var client = new AmazonPollyClient(); var response = client.DescribeVoices(new DescribeVoicesRequest { LanguageCode = "en-GB" }); List<Voice> voices = response.Voices; #endregion } public void PollyGetLexicon() { #region to-retrieve-a-lexicon-1481912870836 var client = new AmazonPollyClient(); var response = client.GetLexicon(new GetLexiconRequest { Name = "" }); Lexicon lexicon = response.Lexicon; LexiconAttributes lexiconAttributes = response.LexiconAttributes; #endregion } public void PollyListLexicons() { #region to-list-all-lexicons-in-a-region-1481842106487 var client = new AmazonPollyClient(); var response = client.ListLexicons(new ListLexiconsRequest { }); List<LexiconDescription> lexicons = response.Lexicons; #endregion } public void PollyPutLexicon() { #region to-save-a-lexicon-1482272584088 var client = new AmazonPollyClient(); var response = client.PutLexicon(new PutLexiconRequest { Content = "file://example.pls", Name = "W3C" }); #endregion } public void PollySynthesizeSpeech() { #region to-synthesize-speech-1482186064046 var client = new AmazonPollyClient(); var response = client.SynthesizeSpeech(new SynthesizeSpeechRequest { LexiconNames = new List<string> { "example" }, OutputFormat = "mp3", SampleRate = "8000", Text = "All Gaul is divided into three parts", TextType = "text", VoiceId = "Joanna" }); MemoryStream audioStream = response.AudioStream; string contentType = response.ContentType; int requestCharacters = response.RequestCharacters; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
121
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.Pricing; using Amazon.Pricing.Model; namespace AWSSDKDocSamples.Amazon.Pricing.Generated { class PricingSamples : ISample { public void PricingDescribeServices() { #region to-retrieve-service-metadata var client = new AmazonPricingClient(); var response = client.DescribeServices(new DescribeServicesRequest { FormatVersion = "aws_v1", MaxResults = 1, ServiceCode = "AmazonEC2" }); string formatVersion = response.FormatVersion; string nextToken = response.NextToken; List<Service> services = response.Services; #endregion } public void PricingGetAttributeValues() { #region to-retreive-attribute-values var client = new AmazonPricingClient(); var response = client.GetAttributeValues(new GetAttributeValuesRequest { AttributeName = "volumeType", MaxResults = 2, ServiceCode = "AmazonEC2" }); List<AttributeValue> attributeValues = response.AttributeValues; string nextToken = response.NextToken; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
60
aws-sdk-net
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDKDocSamples")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyProduct("AWSSDKDocSamples")] [assembly: AssemblyCopyright("Copyright © 2012-2013 Amazon, Inc")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cbf79c1b-8abf-4557-8aba-e24e63b2fc5e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.Redshift; using Amazon.Redshift.Model; namespace AWSSDKDocSamples.Amazon.Redshift.Generated { class RedshiftSamples : ISample { public void RedshiftAuthorizeClusterSecurityGroupIngress() { #region authorizing-access-to-an-ec2-security-group-1481675923213 var client = new AmazonRedshiftClient(); var response = client.AuthorizeClusterSecurityGroupIngress(new AuthorizeClusterSecurityGroupIngressRequest { ClusterSecurityGroupName = "mysecuritygroup", EC2SecurityGroupName = "myec2securitygroup", EC2SecurityGroupOwnerId = "123445677890" }); #endregion } public void RedshiftAuthorizeSnapshotAccess() { #region to-authorize-an-aws-account-to-restore-from-snapshot-1482368189016 var client = new AmazonRedshiftClient(); var response = client.AuthorizeSnapshotAccess(new AuthorizeSnapshotAccessRequest { AccountWithRestoreAccess = "444455556666", SnapshotIdentifier = "my-snapshot-id" }); #endregion } public void RedshiftCopyClusterSnapshot() { #region to--creates-a-copy-of-a-snapshot-1482357194074 var client = new AmazonRedshiftClient(); var response = client.CopyClusterSnapshot(new CopyClusterSnapshotRequest { SourceSnapshotIdentifier = "rs:mycluster-2016-12-21-20-40-51", TargetSnapshotIdentifier = "my-saved-snapshot-cop" }); #endregion } public void RedshiftCreateCluster() { #region to-create-a-cluster-with-minimal-parameters-1481678090203 var client = new AmazonRedshiftClient(); var response = client.CreateCluster(new CreateClusterRequest { ClusterIdentifier = "mycluster", MasterUserPassword = "TopSecret1", MasterUsername = "adminuser ", NodeType = "dw.hs1.xlarge" }); #endregion } public void RedshiftCreateClusterParameterGroup() { #region to-create-a-cluster-snapshot-1481844657333 var client = new AmazonRedshiftClient(); var response = client.CreateClusterParameterGroup(new CreateClusterParameterGroupRequest { Description = "My first cluster parameter group", ParameterGroupFamily = "redshift-1.0", ParameterGroupName = "myclusterparametergroup" }); #endregion } public void RedshiftCreateClusterSecurityGroup() { #region to-create-a-new-cluster-security-group-1481844171608 var client = new AmazonRedshiftClient(); var response = client.CreateClusterSecurityGroup(new CreateClusterSecurityGroupRequest { ClusterSecurityGroupName = "mysecuritygroup", Description = "This is my cluster security group" }); #endregion } public void RedshiftCreateClusterSnapshot() { #region to-create-a-new-cluster-snapshot-1482180269983 var client = new AmazonRedshiftClient(); var response = client.CreateClusterSnapshot(new CreateClusterSnapshotRequest { ClusterIdentifier = "mycluster", SnapshotIdentifier = "my-snapshot-id" }); #endregion } public void RedshiftCreateClusterSubnetGroup() { #region to-create-a-new-cluster-subnet-group-1482357950701 var client = new AmazonRedshiftClient(); var response = client.CreateClusterSubnetGroup(new CreateClusterSubnetGroupRequest { ClusterSubnetGroupName = "mysubnetgroup", Description = "My subnet group", SubnetIds = new List<string> { "subnet-abc12345" } }); #endregion } public void RedshiftCreateEventSubscription() { #region to-create-an-event-subscription-1483132129428 var client = new AmazonRedshiftClient(); var response = client.CreateEventSubscription(new CreateEventSubscriptionRequest { SnsTopicArn = "arn:aws:sns:us-west-2:123456789101:my-sns-topic", SubscriptionName = "mysubscription" }); #endregion } public void RedshiftCreateHsmClientCertificate() { #region to-create-a-new-hsm-certificate-1482359863292 var client = new AmazonRedshiftClient(); var response = client.CreateHsmClientCertificate(new CreateHsmClientCertificateRequest { HsmClientCertificateIdentifier = "my-hsm" }); #endregion } public void RedshiftCreateSnapshotCopyGrant() { #region to-create-a-snapshot-copy-grant-1482180728699 var client = new AmazonRedshiftClient(); var response = client.CreateSnapshotCopyGrant(new CreateSnapshotCopyGrantRequest { SnapshotCopyGrantName = "mycopygrant" }); #endregion } public void RedshiftCreateTags() { #region to-create-tags--1482440094007 var client = new AmazonRedshiftClient(); var response = client.CreateTags(new CreateTagsRequest { ResourceName = "arn:aws:redshift:us-west-2:644653688104:cluster:mycluster", Tags = new List<Tag> { new Tag { Key = "owner", Value = "admin" }, new Tag { Key = "test", Value = "environment" } } }); #endregion } public void RedshiftDeleteEventSubscription() { #region to-delete-an-event-subscription-1483134357677 var client = new AmazonRedshiftClient(); var response = client.DeleteEventSubscription(new DeleteEventSubscriptionRequest { SubscriptionName = "mysubscription" }); #endregion } public void RedshiftDescribeClusterParameterGroups() { #region to-get-a-description-of-cluster-parameter-groups-1482361865953 var client = new AmazonRedshiftClient(); var response = client.DescribeClusterParameterGroups(new DescribeClusterParameterGroupsRequest { Marker = "", MaxRecords = 123, ParameterGroupName = "", TagKeys = new List<string> { }, TagValues = new List<string> { } }); List<ClusterParameterGroup> parameterGroups = response.ParameterGroups; #endregion } public void RedshiftDescribeClusterParameters() { #region to-get-the-parameters-for-a-parameter-group-1482362769122 var client = new AmazonRedshiftClient(); var response = client.DescribeClusterParameters(new DescribeClusterParametersRequest { ParameterGroupName = "myclusterparametergroup" }); List<Parameter> parameters = response.Parameters; #endregion } public void RedshiftDescribeClusters() { #region to-get-a-description-of-all-clusters-1475865512651 var client = new AmazonRedshiftClient(); var response = client.DescribeClusters(new DescribeClustersRequest { }); List<Cluster> clusters = response.Clusters; #endregion } public void RedshiftDescribeClusterSecurityGroups() { #region to-get-a-description-of-cluster-security-groups-for-the-account-1482363060704 var client = new AmazonRedshiftClient(); var response = client.DescribeClusterSecurityGroups(new DescribeClusterSecurityGroupsRequest { }); List<ClusterSecurityGroup> clusterSecurityGroups = response.ClusterSecurityGroups; #endregion } public void RedshiftDescribeClusterSnapshots() { #region to-get-a-description-of-all-cluster-snapshots-1482181325771 var client = new AmazonRedshiftClient(); var response = client.DescribeClusterSnapshots(new DescribeClusterSnapshotsRequest { }); List<Snapshot> snapshots = response.Snapshots; #endregion } public void RedshiftDescribeClusterSubnetGroups() { #region to-get-a-description-of-all-cluster-subnet-groups-1481847412769 var client = new AmazonRedshiftClient(); var response = client.DescribeClusterSubnetGroups(new DescribeClusterSubnetGroupsRequest { }); List<ClusterSubnetGroup> clusterSubnetGroups = response.ClusterSubnetGroups; #endregion } public void RedshiftDescribeClusterVersions() { #region to-get-a-description-of-cluster-versions-1482363389639 var client = new AmazonRedshiftClient(); var response = client.DescribeClusterVersions(new DescribeClusterVersionsRequest { }); List<ClusterVersion> clusterVersions = response.ClusterVersions; #endregion } public void RedshiftDescribeDefaultClusterParameters() { #region to-get-a-description-of-cluster-default-parameters-1482365915635 var client = new AmazonRedshiftClient(); var response = client.DescribeDefaultClusterParameters(new DescribeDefaultClusterParametersRequest { ParameterGroupFamily = "redshift-1.0" }); #endregion } public void RedshiftDescribeEventCategories() { #region to-get-a-description-of-event-categories-1482366442369 var client = new AmazonRedshiftClient(); var response = client.DescribeEventCategories(new DescribeEventCategoriesRequest { SourceType = "cluster" }); List<EventCategoriesMap> eventCategoriesMapList = response.EventCategoriesMapList; #endregion } public void RedshiftDescribeEvents() { #region to-get-a-description-of-events-1482367106459 var client = new AmazonRedshiftClient(); var response = client.DescribeEvents(new DescribeEventsRequest { Duration = 600 }); List<Event> events = response.Events; #endregion } public void RedshiftDescribeEventSubscriptions() { #region to-describe-an-event-subscription-1483133239054 var client = new AmazonRedshiftClient(); var response = client.DescribeEventSubscriptions(new DescribeEventSubscriptionsRequest { SubscriptionName = "mysubscription" }); List<EventSubscription> eventSubscriptionsList = response.EventSubscriptionsList; #endregion } public void RedshiftDescribeHsmClientCertificates() { #region to-get-a-description-of-hsm-certificates-1482367536680 var client = new AmazonRedshiftClient(); var response = client.DescribeHsmClientCertificates(new DescribeHsmClientCertificatesRequest { }); List<HsmClientCertificate> hsmClientCertificates = response.HsmClientCertificates; #endregion } public void RedshiftDescribeLoggingStatus() { #region to-describe-logging-status-1483134803712 var client = new AmazonRedshiftClient(); var response = client.DescribeLoggingStatus(new DescribeLoggingStatusRequest { ClusterIdentifier = "mycluster" }); string bucketName = response.BucketName; DateTime lastSuccessfulDeliveryTime = response.LastSuccessfulDeliveryTime; bool loggingEnabled = response.LoggingEnabled; #endregion } public void RedshiftDescribeTags() { #region to-get-tags-for-a-resource-1482438593642 var client = new AmazonRedshiftClient(); var response = client.DescribeTags(new DescribeTagsRequest { }); List<TaggedResource> taggedResources = response.TaggedResources; #endregion } public void RedshiftDisableLogging() { #region to-disable-logging-1483135106459 var client = new AmazonRedshiftClient(); var response = client.DisableLogging(new DisableLoggingRequest { ClusterIdentifier = "mycluster" }); string bucketName = response.BucketName; DateTime lastSuccessfulDeliveryTime = response.LastSuccessfulDeliveryTime; bool loggingEnabled = response.LoggingEnabled; #endregion } public void RedshiftDisableSnapshotCopy() { #region to-disable-snapshot-copy-1482435501112 var client = new AmazonRedshiftClient(); var response = client.DisableSnapshotCopy(new DisableSnapshotCopyRequest { ClusterIdentifier = "mycluster" }); #endregion } public void RedshiftEnableLogging() { #region to-enable-logging-1482434657633 var client = new AmazonRedshiftClient(); var response = client.EnableLogging(new EnableLoggingRequest { BucketName = "aws-logs-112233445566-us-west-2", ClusterIdentifier = "mycluster" }); string bucketName = response.BucketName; bool loggingEnabled = response.LoggingEnabled; #endregion } public void RedshiftEnableSnapshotCopy() { #region to-enable-snapshot-copy-1482435074072 var client = new AmazonRedshiftClient(); var response = client.EnableSnapshotCopy(new EnableSnapshotCopyRequest { ClusterIdentifier = "mycluster", DestinationRegion = "us-east-1" }); #endregion } public void RedshiftModifyCluster() { #region to-modify-a-cluster-1482436093526 var client = new AmazonRedshiftClient(); var response = client.ModifyCluster(new ModifyClusterRequest { ClusterIdentifier = "mycluster", ClusterSecurityGroups = new List<string> { "mysecuritygroup" } }); #endregion } public void RedshiftModifyClusterIamRoles() { #region to-modify-a-cluster-iam-roles-1482436895837 var client = new AmazonRedshiftClient(); var response = client.ModifyClusterIamRoles(new ModifyClusterIamRolesRequest { AddIamRoles = new List<string> { "arn:aws:iam::112233445566:role/myRedshiftRole" }, ClusterIdentifier = "mycluster" }); #endregion } public void RedshiftModifyClusterParameterGroup() { #region to-modify-a-paramter-group-1483130143433 var client = new AmazonRedshiftClient(); var response = client.ModifyClusterParameterGroup(new ModifyClusterParameterGroupRequest { ParameterGroupName = "myclusterparametergroup", Parameters = new List<Parameter> { new Parameter { ApplyType = "dynamic", ParameterName = "wlm_json_configuration", ParameterValue = "[{\"query_group\":[\"report\"], \"query_group_wild_card\":1, \"query_concurrency\":4, \"max_execution_time\":20000, \"memory_percent_to_use\":25, \"rules\": [{\"rule_name\": \"rule_1\", \"predicate\": [{\"metric_name\": \"query_cpu_time\", \"operator\": \">\", \"value\": 1000000}, {\"metric_name\": \"query_blocks_read\", \"operator\": \">\", \"value\": 1000}], \"action\": \"log\"}] }, {\"user_group\":[\"admin\",\"dba\"], \"user_group_wild_card\":0, \"query_concurrency\":5, \"memory_percent_to_use\":40, \"rules\": [{\"rule_name\": \"rule_2\", \"predicate\": [{\"metric_name\": \"query_execution_time\", \"operator\": \">\", \"value\": 10000}, {\"metric_name\": \"scan_row_count\", \"operator\": \">\", \"value\": 1000000000}], \"action\": \"hop\"}] }, {\"query_concurrency\":5, \"memory_percent_to_use\":35 } ]" } } }); string parameterGroupName = response.ParameterGroupName; string parameterGroupStatus = response.ParameterGroupStatus; #endregion } public void RedshiftModifyClusterSubnetGroup() { #region to-modify-a-paramter-group-1483130143433 var client = new AmazonRedshiftClient(); var response = client.ModifyClusterSubnetGroup(new ModifyClusterSubnetGroupRequest { ClusterSubnetGroupName = "mysubnetgroup", Description = "My subnet group", SubnetIds = new List<string> { "subnet-4632f321", "subnet-11312a67" } }); #endregion } public void RedshiftModifyEventSubscription() { #region to-modify-an-event-subscription-1483132220470 var client = new AmazonRedshiftClient(); var response = client.ModifyEventSubscription(new ModifyEventSubscriptionRequest { SourceType = "cluster", SubscriptionName = "mysubscription" }); #endregion } # region ISample Members public virtual void Run() { } # endregion } }
597
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.Rekognition; using Amazon.Rekognition.Model; namespace AWSSDKDocSamples.Amazon.Rekognition.Generated { class RekognitionSamples : ISample { public void RekognitionAssociateFaces() { #region associatefaces-1686181269281 var client = new AmazonRekognitionClient(); var response = client.AssociateFaces(new AssociateFacesRequest { ClientRequestToken = "550e8400-e29b-41d4-a716-446655440002", CollectionId = "MyCollection", FaceIds = new List<string> { "f5817d37-94f6-4335-bfee-6cf79a3d806e", "851cb847-dccc-4fea-9309-9f4805967855", "35ebbb41-7f67-4263-908d-dd0ecba05ab9" }, UserId = "DemoUser", UserMatchThreshold = 70 }); List<AssociatedFace> associatedFaces = response.AssociatedFaces; List<UnsuccessfulFaceAssociation> unsuccessfulFaceAssociations = response.UnsuccessfulFaceAssociations; string userStatus = response.UserStatus; #endregion } public void RekognitionCompareFaces() { #region to-compare-two-images-1482181985581 var client = new AmazonRekognitionClient(); var response = client.CompareFaces(new CompareFacesRequest { SimilarityThreshold = 90, SourceImage = new Image { S3Object = new S3Object { Bucket = "mybucket", Name = "mysourceimage" } }, TargetImage = new Image { S3Object = new S3Object { Bucket = "mybucket", Name = "mytargetimage" } } }); List<CompareFacesMatch> faceMatches = response.FaceMatches; ComparedSourceImageFace sourceImageFace = response.SourceImageFace; #endregion } public void RekognitionCopyProjectVersion() { #region copyprojectversion-1658203943815 var client = new AmazonRekognitionClient(); var response = client.CopyProjectVersion(new CopyProjectVersionRequest { DestinationProjectArn = "arn:aws:rekognition:us-east-1:555555555555:project/DestinationProject/1656705098765", KmsKeyId = "arn:1234abcd-12ab-34cd-56ef-1234567890ab", OutputConfig = new OutputConfig { S3Bucket = "bucket-name", S3KeyPrefix = "path_to_folder" }, SourceProjectArn = "arn:aws:rekognition:us-east-1:111122223333:project/SourceProject/16565123456", SourceProjectVersionArn = "arn:aws:rekognition:us-east-1:111122223333:project/SourceProject/version/model_1/1656611123456", Tags = new Dictionary<string, string> { { "key1", "val1" } }, VersionName = "DestinationVersionName_cross_account" }); string projectVersionArn = response.ProjectVersionArn; #endregion } public void RekognitionCreateCollection() { #region to-create-a-collection-1481833313674 var client = new AmazonRekognitionClient(); var response = client.CreateCollection(new CreateCollectionRequest { CollectionId = "myphotos" }); string collectionArn = response.CollectionArn; int statusCode = response.StatusCode; #endregion } public void RekognitionCreateUser() { #region createuser-1686181562299 var client = new AmazonRekognitionClient(); var response = client.CreateUser(new CreateUserRequest { CollectionId = "MyCollection", UserId = "DemoUser" }); #endregion } public void RekognitionDeleteCollection() { #region to-delete-a-collection-1481838179973 var client = new AmazonRekognitionClient(); var response = client.DeleteCollection(new DeleteCollectionRequest { CollectionId = "myphotos" }); int statusCode = response.StatusCode; #endregion } public void RekognitionDeleteFaces() { #region to-delete-a-face-1482182799377 var client = new AmazonRekognitionClient(); var response = client.DeleteFaces(new DeleteFacesRequest { CollectionId = "myphotos", FaceIds = new List<string> { "ff43d742-0c13-5d16-a3e8-03d3f58e980b" } }); List<string> deletedFaces = response.DeletedFaces; #endregion } public void RekognitionDeleteProjectPolicy() { #region deleteprojectpolicy-1658204413810 var client = new AmazonRekognitionClient(); var response = client.DeleteProjectPolicy(new DeleteProjectPolicyRequest { PolicyName = "testPolicy1", PolicyRevisionId = "3b274c25e9203a56a99e00e3ff205fbc", ProjectArn = "arn:aws:rekognition:us-east-1:111122223333:project/SourceProject/1656557123456" }); #endregion } public void RekognitionDeleteUser() { #region deleteuser-1686181913475 var client = new AmazonRekognitionClient(); var response = client.DeleteUser(new DeleteUserRequest { ClientRequestToken = "550e8400-e29b-41d4-a716-446655440001", CollectionId = "MyCollection", UserId = "DemoUser" }); #endregion } public void RekognitionDetectFaces() { #region to-detect-faces-in-an-image-1481841782793 var client = new AmazonRekognitionClient(); var response = client.DetectFaces(new DetectFacesRequest { Image = new Image { S3Object = new S3Object { Bucket = "mybucket", Name = "myphoto" } } }); List<FaceDetail> faceDetails = response.FaceDetails; string orientationCorrection = response.OrientationCorrection; #endregion } public void RekognitionDetectLabels() { #region to-detect-labels-1481834255770 var client = new AmazonRekognitionClient(); var response = client.DetectLabels(new DetectLabelsRequest { Image = new Image { S3Object = new S3Object { Bucket = "mybucket", Name = "myphoto" } }, MaxLabels = 123, MinConfidence = 70 }); List<Label> labels = response.Labels; #endregion } public void RekognitionDisassociateFaces() { #region disassociatefaces-1686182627295 var client = new AmazonRekognitionClient(); var response = client.DisassociateFaces(new DisassociateFacesRequest { ClientRequestToken = "550e8400-e29b-41d4-a716-446655440003", CollectionId = "MyCollection", FaceIds = new List<string> { "f5817d37-94f6-4335-bfee-6cf79a3d806e", "c92265d4-5f9c-43af-a58e-12be0ce02bc3" }, UserId = "DemoUser" }); List<DisassociatedFace> disassociatedFaces = response.DisassociatedFaces; List<UnsuccessfulFaceDisassociation> unsuccessfulFaceDisassociations = response.UnsuccessfulFaceDisassociations; string userStatus = response.UserStatus; #endregion } public void RekognitionIndexFaces() { #region to-add-a-face-to-a-collection-1482179542923 var client = new AmazonRekognitionClient(); var response = client.IndexFaces(new IndexFacesRequest { CollectionId = "myphotos", DetectionAttributes = new List<string> { }, ExternalImageId = "myphotoid", Image = new Image { S3Object = new S3Object { Bucket = "mybucket", Name = "myphoto" } } }); List<FaceRecord> faceRecords = response.FaceRecords; string orientationCorrection = response.OrientationCorrection; #endregion } public void RekognitionListCollections() { #region to-list-the-collections-1482179199088 var client = new AmazonRekognitionClient(); var response = client.ListCollections(new ListCollectionsRequest { }); List<string> collectionIds = response.CollectionIds; #endregion } public void RekognitionListFaces() { #region to-list-the-faces-in-a-collection-1482181416530 var client = new AmazonRekognitionClient(); var response = client.ListFaces(new ListFacesRequest { CollectionId = "myphotos", MaxResults = 20 }); string faceModelVersion = response.FaceModelVersion; List<Face> faces = response.Faces; #endregion } public void RekognitionListProjectPolicies() { #region listprojectpolicies-1658202290173 var client = new AmazonRekognitionClient(); var response = client.ListProjectPolicies(new ListProjectPoliciesRequest { MaxResults = 5, NextToken = "", ProjectArn = "arn:aws:rekognition:us-east-1:111122223333:project/my-sdk-project/1656557051929" }); string nextToken = response.NextToken; List<ProjectPolicy> projectPolicies = response.ProjectPolicies; #endregion } public void RekognitionListUsers() { #region listusers-1686182360075 var client = new AmazonRekognitionClient(); var response = client.ListUsers(new ListUsersRequest { CollectionId = "MyCollection" }); string nextToken = response.NextToken; List<User> users = response.Users; #endregion } public void RekognitionPutProjectPolicy() { #region putprojectpolicy-1658201727623 var client = new AmazonRekognitionClient(); var response = client.PutProjectPolicy(new PutProjectPolicyRequest { PolicyDocument = "'{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"ALLOW\",\"Principal\":{\"AWS\":\"principal\"},\"Action\":\"rekognition:CopyProjectVersion\",\"Resource\":\"arn:aws:rekognition:us-east-1:123456789012:project/my-sdk-project/version/DestinationVersionName/1627045542080\"}]}'", PolicyName = "SamplePolicy", PolicyRevisionId = "0123456789abcdef", ProjectArn = "arn:aws:rekognition:us-east-1:111122223333:project/my-sdk-project/1656557051929" }); string policyRevisionId = response.PolicyRevisionId; #endregion } public void RekognitionSearchFaces() { #region to-delete-a-face-1482182799377 var client = new AmazonRekognitionClient(); var response = client.SearchFaces(new SearchFacesRequest { CollectionId = "myphotos", FaceId = "70008e50-75e4-55d0-8e80-363fb73b3a14", FaceMatchThreshold = 90, MaxFaces = 10 }); List<FaceMatch> faceMatches = response.FaceMatches; string searchedFaceId = response.SearchedFaceId; #endregion } public void RekognitionSearchFacesByImage() { #region to-search-for-faces-matching-a-supplied-image-1482175994491 var client = new AmazonRekognitionClient(); var response = client.SearchFacesByImage(new SearchFacesByImageRequest { CollectionId = "myphotos", FaceMatchThreshold = 95, Image = new Image { S3Object = new S3Object { Bucket = "mybucket", Name = "myphoto" } }, MaxFaces = 5 }); List<FaceMatch> faceMatches = response.FaceMatches; BoundingBox searchedFaceBoundingBox = response.SearchedFaceBoundingBox; float searchedFaceConfidence = response.SearchedFaceConfidence; #endregion } public void RekognitionSearchUsers() { #region searchusers-1686182912030 var client = new AmazonRekognitionClient(); var response = client.SearchUsers(new SearchUsersRequest { CollectionId = "MyCollection", MaxUsers = 2, UserId = "DemoUser", UserMatchThreshold = 70 }); string faceModelVersion = response.FaceModelVersion; SearchedUser searchedUser = response.SearchedUser; List<UserMatch> userMatches = response.UserMatches; #endregion } public void RekognitionSearchUsersByImage() { #region searchusersbyimage-1686183178610 var client = new AmazonRekognitionClient(); var response = client.SearchUsersByImage(new SearchUsersByImageRequest { CollectionId = "MyCollection", Image = new Image { S3Object = new S3Object { Bucket = "bucket", Name = "input.jpg" } }, MaxUsers = 2, QualityFilter = "MEDIUM", UserMatchThreshold = 70 }); string faceModelVersion = response.FaceModelVersion; SearchedFaceDetails searchedFace = response.SearchedFace; List<UnsearchedFace> unsearchedFaces = response.UnsearchedFaces; List<UserMatch> userMatches = response.UserMatches; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
450
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Threading; using Amazon; using Amazon.Route53; using Amazon.Route53.Model; namespace AWSSDKDocSamples.Route53 { //Create a hosted zone and add a basic record set to it class route53samples : ISample { public static void Route53CreateAdd(string[] args) { #region Route53CreateAdd string domainName = "www.example.org"; IAmazonRoute53 route53Client = new AmazonRoute53Client(); CreateHostedZoneRequest zoneRequest = new CreateHostedZoneRequest { Name = domainName, CallerReference = "my_change_request" }; CreateHostedZoneResponse zoneResponse = route53Client.CreateHostedZone(zoneRequest); ResourceRecordSet recordSet = new ResourceRecordSet { Name = domainName, TTL = 60, Type = RRType.A, ResourceRecords = new List<ResourceRecord> { new ResourceRecord { Value = "192.0.2.235" } } }; Change change1 = new Change { ResourceRecordSet = recordSet, Action = ChangeAction.CREATE }; ChangeBatch changeBatch = new ChangeBatch { Changes = new List<Change> { change1 } }; ChangeResourceRecordSetsRequest recordsetRequest = new ChangeResourceRecordSetsRequest { HostedZoneId = zoneResponse.HostedZone.Id, ChangeBatch = changeBatch }; ChangeResourceRecordSetsResponse recordsetResponse = route53Client.ChangeResourceRecordSets(recordsetRequest); GetChangeRequest changeRequest = new GetChangeRequest { Id = recordsetResponse.ChangeInfo.Id }; while (route53Client.GetChange(changeRequest).ChangeInfo.Status == ChangeStatus.PENDING) { Console.WriteLine("Change is pending."); Thread.Sleep(TimeSpan.FromSeconds(15)); } #endregion Console.WriteLine("Change is complete."); Console.ReadKey(); } #region ISample Members public virtual void Run() { } #endregion } }
78
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.Route53; using Amazon.Route53.Model; namespace AWSSDKDocSamples.Amazon.Route53.Generated { class Route53Samples : ISample { public void Route53AssociateVPCWithHostedZone() { #region to-associate-a-vpc-with-a-hosted-zone-1484069228699 var client = new AmazonRoute53Client(); var response = client.AssociateVPCWithHostedZone(new AssociateVPCWithHostedZoneRequest { Comment = "", HostedZoneId = "Z3M3LMPEXAMPLE", VPC = new VPC { VPCId = "vpc-1a2b3c4d", VPCRegion = "us-east-2" } }); ChangeInfo changeInfo = response.ChangeInfo; #endregion } public void Route53ChangeResourceRecordSets() { #region to-create-update-or-delete-resource-record-sets-1484344703668 var client = new AmazonRoute53Client(); var response = client.ChangeResourceRecordSets(new ChangeResourceRecordSetsRequest { ChangeBatch = new ChangeBatch { Changes = new List<Change> { new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { Name = "example.com", ResourceRecords = new List<ResourceRecord> { new ResourceRecord { Value = "192.0.2.44" } }, TTL = 60, Type = "A" } } }, Comment = "Web server for example.com" }, HostedZoneId = "Z3M3LMPEXAMPLE" }); ChangeInfo changeInfo = response.ChangeInfo; #endregion } public void Route53ChangeResourceRecordSets() { #region to-create-weighted-resource-record-sets-1484348208522 var client = new AmazonRoute53Client(); var response = client.ChangeResourceRecordSets(new ChangeResourceRecordSetsRequest { ChangeBatch = new ChangeBatch { Changes = new List<Change> { new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { HealthCheckId = "abcdef11-2222-3333-4444-555555fedcba", Name = "example.com", ResourceRecords = new List<ResourceRecord> { new ResourceRecord { Value = "192.0.2.44" } }, SetIdentifier = "Seattle data center", TTL = 60, Type = "A", Weight = 100 } }, new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { HealthCheckId = "abcdef66-7777-8888-9999-000000fedcba", Name = "example.com", ResourceRecords = new List<ResourceRecord> { new ResourceRecord { Value = "192.0.2.45" } }, SetIdentifier = "Portland data center", TTL = 60, Type = "A", Weight = 200 } } }, Comment = "Web servers for example.com" }, HostedZoneId = "Z3M3LMPEXAMPLE" }); ChangeInfo changeInfo = response.ChangeInfo; #endregion } public void Route53ChangeResourceRecordSets() { #region to-create-an-alias-resource-record-set-1484348404062 var client = new AmazonRoute53Client(); var response = client.ChangeResourceRecordSets(new ChangeResourceRecordSetsRequest { ChangeBatch = new ChangeBatch { Changes = new List<Change> { new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { AliasTarget = new AliasTarget { DNSName = "d123rk29d0stfj.cloudfront.net", EvaluateTargetHealth = false, HostedZoneId = "Z2FDTNDATAQYW2" }, Name = "example.com", Type = "A" } } }, Comment = "CloudFront distribution for example.com" }, HostedZoneId = "Z3M3LMPEXAMPLE" // Depends on the type of resource that you want to route traffic to }); ChangeInfo changeInfo = response.ChangeInfo; #endregion } public void Route53ChangeResourceRecordSets() { #region to-create-weighted-alias-resource-record-sets-1484349467416 var client = new AmazonRoute53Client(); var response = client.ChangeResourceRecordSets(new ChangeResourceRecordSetsRequest { ChangeBatch = new ChangeBatch { Changes = new List<Change> { new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { AliasTarget = new AliasTarget { DNSName = "example-com-123456789.us-east-2.elb.amazonaws.com ", EvaluateTargetHealth = true, HostedZoneId = "Z3AADJGX6KTTL2" }, Name = "example.com", SetIdentifier = "Ohio region", Type = "A", Weight = 100 } }, new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { AliasTarget = new AliasTarget { DNSName = "example-com-987654321.us-west-2.elb.amazonaws.com ", EvaluateTargetHealth = true, HostedZoneId = "Z1H1FL5HABSF5" }, Name = "example.com", SetIdentifier = "Oregon region", Type = "A", Weight = 200 } } }, Comment = "ELB load balancers for example.com" }, HostedZoneId = "Z3M3LMPEXAMPLE" // Depends on the type of resource that you want to route traffic to }); ChangeInfo changeInfo = response.ChangeInfo; #endregion } public void Route53ChangeResourceRecordSets() { #region to-create-latency-resource-record-sets-1484350219917 var client = new AmazonRoute53Client(); var response = client.ChangeResourceRecordSets(new ChangeResourceRecordSetsRequest { ChangeBatch = new ChangeBatch { Changes = new List<Change> { new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { HealthCheckId = "abcdef11-2222-3333-4444-555555fedcba", Name = "example.com", Region = "us-east-2", ResourceRecords = new List<ResourceRecord> { new ResourceRecord { Value = "192.0.2.44" } }, SetIdentifier = "Ohio region", TTL = 60, Type = "A" } }, new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { HealthCheckId = "abcdef66-7777-8888-9999-000000fedcba", Name = "example.com", Region = "us-west-2", ResourceRecords = new List<ResourceRecord> { new ResourceRecord { Value = "192.0.2.45" } }, SetIdentifier = "Oregon region", TTL = 60, Type = "A" } } }, Comment = "EC2 instances for example.com" }, HostedZoneId = "Z3M3LMPEXAMPLE" }); ChangeInfo changeInfo = response.ChangeInfo; #endregion } public void Route53ChangeResourceRecordSets() { #region to-create-latency-alias-resource-record-sets-1484601774179 var client = new AmazonRoute53Client(); var response = client.ChangeResourceRecordSets(new ChangeResourceRecordSetsRequest { ChangeBatch = new ChangeBatch { Changes = new List<Change> { new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { AliasTarget = new AliasTarget { DNSName = "example-com-123456789.us-east-2.elb.amazonaws.com ", EvaluateTargetHealth = true, HostedZoneId = "Z3AADJGX6KTTL2" }, Name = "example.com", Region = "us-east-2", SetIdentifier = "Ohio region", Type = "A" } }, new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { AliasTarget = new AliasTarget { DNSName = "example-com-987654321.us-west-2.elb.amazonaws.com ", EvaluateTargetHealth = true, HostedZoneId = "Z1H1FL5HABSF5" }, Name = "example.com", Region = "us-west-2", SetIdentifier = "Oregon region", Type = "A" } } }, Comment = "ELB load balancers for example.com" }, HostedZoneId = "Z3M3LMPEXAMPLE" // Depends on the type of resource that you want to route traffic to }); ChangeInfo changeInfo = response.ChangeInfo; #endregion } public void Route53ChangeResourceRecordSets() { #region to-create-failover-resource-record-sets-1484604541740 var client = new AmazonRoute53Client(); var response = client.ChangeResourceRecordSets(new ChangeResourceRecordSetsRequest { ChangeBatch = new ChangeBatch { Changes = new List<Change> { new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { Failover = "PRIMARY", HealthCheckId = "abcdef11-2222-3333-4444-555555fedcba", Name = "example.com", ResourceRecords = new List<ResourceRecord> { new ResourceRecord { Value = "192.0.2.44" } }, SetIdentifier = "Ohio region", TTL = 60, Type = "A" } }, new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { Failover = "SECONDARY", HealthCheckId = "abcdef66-7777-8888-9999-000000fedcba", Name = "example.com", ResourceRecords = new List<ResourceRecord> { new ResourceRecord { Value = "192.0.2.45" } }, SetIdentifier = "Oregon region", TTL = 60, Type = "A" } } }, Comment = "Failover configuration for example.com" }, HostedZoneId = "Z3M3LMPEXAMPLE" }); ChangeInfo changeInfo = response.ChangeInfo; #endregion } public void Route53ChangeResourceRecordSets() { #region to-create-failover-alias-resource-record-sets-1484607497724 var client = new AmazonRoute53Client(); var response = client.ChangeResourceRecordSets(new ChangeResourceRecordSetsRequest { ChangeBatch = new ChangeBatch { Changes = new List<Change> { new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { AliasTarget = new AliasTarget { DNSName = "example-com-123456789.us-east-2.elb.amazonaws.com ", EvaluateTargetHealth = true, HostedZoneId = "Z3AADJGX6KTTL2" }, Failover = "PRIMARY", Name = "example.com", SetIdentifier = "Ohio region", Type = "A" } }, new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { AliasTarget = new AliasTarget { DNSName = "example-com-987654321.us-west-2.elb.amazonaws.com ", EvaluateTargetHealth = true, HostedZoneId = "Z1H1FL5HABSF5" }, Failover = "SECONDARY", Name = "example.com", SetIdentifier = "Oregon region", Type = "A" } } }, Comment = "Failover alias configuration for example.com" }, HostedZoneId = "Z3M3LMPEXAMPLE" // Depends on the type of resource that you want to route traffic to }); ChangeInfo changeInfo = response.ChangeInfo; #endregion } public void Route53ChangeResourceRecordSets() { #region to-create-geolocation-resource-record-sets-1484612462466 var client = new AmazonRoute53Client(); var response = client.ChangeResourceRecordSets(new ChangeResourceRecordSetsRequest { ChangeBatch = new ChangeBatch { Changes = new List<Change> { new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { GeoLocation = new GeoLocation { ContinentCode = "NA" }, Name = "example.com", ResourceRecords = new List<ResourceRecord> { new ResourceRecord { Value = "192.0.2.44" } }, SetIdentifier = "North America", TTL = 60, Type = "A" } }, new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { GeoLocation = new GeoLocation { ContinentCode = "SA" }, Name = "example.com", ResourceRecords = new List<ResourceRecord> { new ResourceRecord { Value = "192.0.2.45" } }, SetIdentifier = "South America", TTL = 60, Type = "A" } }, new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { GeoLocation = new GeoLocation { ContinentCode = "EU" }, Name = "example.com", ResourceRecords = new List<ResourceRecord> { new ResourceRecord { Value = "192.0.2.46" } }, SetIdentifier = "Europe", TTL = 60, Type = "A" } }, new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { GeoLocation = new GeoLocation { CountryCode = "*" }, Name = "example.com", ResourceRecords = new List<ResourceRecord> { new ResourceRecord { Value = "192.0.2.47" } }, SetIdentifier = "Other locations", TTL = 60, Type = "A" } } }, Comment = "Geolocation configuration for example.com" }, HostedZoneId = "Z3M3LMPEXAMPLE" }); ChangeInfo changeInfo = response.ChangeInfo; #endregion } public void Route53ChangeResourceRecordSets() { #region to-create-geolocation-alias-resource-record-sets-1484612871203 var client = new AmazonRoute53Client(); var response = client.ChangeResourceRecordSets(new ChangeResourceRecordSetsRequest { ChangeBatch = new ChangeBatch { Changes = new List<Change> { new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { AliasTarget = new AliasTarget { DNSName = "example-com-123456789.us-east-2.elb.amazonaws.com ", EvaluateTargetHealth = true, HostedZoneId = "Z3AADJGX6KTTL2" }, GeoLocation = new GeoLocation { ContinentCode = "NA" }, Name = "example.com", SetIdentifier = "North America", Type = "A" } }, new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { AliasTarget = new AliasTarget { DNSName = "example-com-234567890.sa-east-1.elb.amazonaws.com ", EvaluateTargetHealth = true, HostedZoneId = "Z2P70J7HTTTPLU" }, GeoLocation = new GeoLocation { ContinentCode = "SA" }, Name = "example.com", SetIdentifier = "South America", Type = "A" } }, new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { AliasTarget = new AliasTarget { DNSName = "example-com-234567890.eu-central-1.elb.amazonaws.com ", EvaluateTargetHealth = true, HostedZoneId = "Z215JYRZR1TBD5" }, GeoLocation = new GeoLocation { ContinentCode = "EU" }, Name = "example.com", SetIdentifier = "Europe", Type = "A" } }, new Change { Action = "CREATE", ResourceRecordSet = new ResourceRecordSet { AliasTarget = new AliasTarget { DNSName = "example-com-234567890.ap-southeast-1.elb.amazonaws.com ", EvaluateTargetHealth = true, HostedZoneId = "Z1LMS91P8CMLE5" }, GeoLocation = new GeoLocation { CountryCode = "*" }, Name = "example.com", SetIdentifier = "Other locations", Type = "A" } } }, Comment = "Geolocation alias configuration for example.com" }, HostedZoneId = "Z3M3LMPEXAMPLE" // Depends on the type of resource that you want to route traffic to }); ChangeInfo changeInfo = response.ChangeInfo; #endregion } public void Route53ChangeTagsForResource() { #region to-add-or-remove-tags-from-a-hosted-zone-or-health-check-1484084752409 var client = new AmazonRoute53Client(); var response = client.ChangeTagsForResource(new ChangeTagsForResourceRequest { AddTags = new List<Tag> { new Tag { Key = "apex", Value = "3874" }, new Tag { Key = "acme", Value = "4938" } }, RemoveTagKeys = new List<string> { "Nadir" }, ResourceId = "Z3M3LMPEXAMPLE", ResourceType = "hostedzone" // Valid values are healthcheck and hostedzone. }); #endregion } public void Route53GetHostedZone() { #region to-get-information-about-a-hosted-zone-1481752361124 var client = new AmazonRoute53Client(); var response = client.GetHostedZone(new GetHostedZoneRequest { Id = "Z3M3LMPEXAMPLE" }); DelegationSet delegationSet = response.DelegationSet; HostedZone hostedZone = response.HostedZone; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
586
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Amazon.S3; using Amazon.S3.Model; using System.Diagnostics; using System.IO; using System.Net; namespace AWSSDKDocSamples.S3 { public class BaseS3Samples : ISample { public void BucketSamples() { { #region ListBuckets Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Issue call ListBucketsResponse response = client.ListBuckets(); // View response data Console.WriteLine("Buckets owner - {0}", response.Owner.DisplayName); foreach (S3Bucket bucket in response.Buckets) { Console.WriteLine("Bucket {0}, Created on {1}", bucket.BucketName, bucket.CreationDate); } #endregion } { #region BucketPolicy Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Put sample bucket policy (overwrite an existing policy) string newPolicy = @"{ ""Statement"":[{ ""Sid"":""BasicPerms"", ""Effect"":""Allow"", ""Principal"": ""*"", ""Action"":[""s3:PutObject"",""s3:GetObject""], ""Resource"":[""arn:aws:s3:::samplebucketname/*""] }]}"; PutBucketPolicyRequest putRequest = new PutBucketPolicyRequest { BucketName = "SampleBucket", Policy = newPolicy }; client.PutBucketPolicy(putRequest); // Retrieve current policy GetBucketPolicyRequest getRequest = new GetBucketPolicyRequest { BucketName = "SampleBucket" }; string policy = client.GetBucketPolicy(getRequest).Policy; Console.WriteLine(policy); Debug.Assert(policy.Contains("BasicPerms")); // Delete current policy DeleteBucketPolicyRequest deleteRequest = new DeleteBucketPolicyRequest { BucketName = "SampleBucket" }; client.DeleteBucketPolicy(deleteRequest); // Retrieve current policy and verify that it is null policy = client.GetBucketPolicy(getRequest).Policy; Debug.Assert(policy == null); #endregion } { #region GetBucketLocation Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Construct request GetBucketLocationRequest request = new GetBucketLocationRequest { BucketName = "SampleBucket" }; // Issue call GetBucketLocationResponse response = client.GetBucketLocation(request); // View response data Console.WriteLine("Bucket location - {0}", response.Location); #endregion } { #region PutBucket Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Construct request PutBucketRequest request = new PutBucketRequest { BucketName = "SampleBucket", BucketRegion = S3Region.EU, // set region to EU CannedACL = S3CannedACL.PublicRead // make bucket publicly readable }; // Issue call PutBucketResponse response = client.PutBucket(request); #endregion } { #region DeleteBucket Sample 1 // Create a client AmazonS3Client client = new AmazonS3Client(); // Construct request DeleteBucketRequest request = new DeleteBucketRequest { BucketName = "SampleBucket" }; // Issue call DeleteBucketResponse response = client.DeleteBucket(request); #endregion } { #region DeleteBucket Sample 2 // Create a client AmazonS3Client client = new AmazonS3Client(); // List and delete all objects ListObjectsRequest listRequest = new ListObjectsRequest { BucketName = "SampleBucket" }; ListObjectsResponse listResponse; do { // Get a list of objects listResponse = client.ListObjects(listRequest); foreach (S3Object obj in listResponse.S3Objects) { // Delete each object client.DeleteObject(new DeleteObjectRequest { BucketName = "SampleBucket", Key = obj.Key }); } // Set the marker property listRequest.Marker = listResponse.NextMarker; } while (listResponse.IsTruncated); // Construct DeleteBucket request DeleteBucketRequest request = new DeleteBucketRequest { BucketName = "SampleBucket" }; // Issue call DeleteBucketResponse response = client.DeleteBucket(request); #endregion } { #region LifecycleConfiguration Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Put sample lifecycle configuration (overwrite an existing configuration) LifecycleConfiguration newConfiguration = new LifecycleConfiguration { Rules = new List<LifecycleRule> { // Rule to delete keys with prefix "Test-" after 5 days new LifecycleRule { Prefix = "Test-", Expiration = new LifecycleRuleExpiration { Days = 5 } }, // Rule to delete keys in subdirectory "Logs" after 2 days new LifecycleRule { Prefix = "Logs/", Expiration = new LifecycleRuleExpiration { Days = 2 }, Id = "log-file-removal" } } }; PutLifecycleConfigurationRequest putRequest = new PutLifecycleConfigurationRequest { BucketName = "SampleBucket", Configuration = newConfiguration }; client.PutLifecycleConfiguration(putRequest); // Retrieve current configuration GetLifecycleConfigurationRequest getRequest = new GetLifecycleConfigurationRequest { BucketName = "SampleBucket" }; LifecycleConfiguration configuration = client.GetLifecycleConfiguration(getRequest).Configuration; Console.WriteLine("Configuration contains {0} rules", configuration.Rules.Count); foreach (LifecycleRule rule in configuration.Rules) { Console.WriteLine("Rule"); Console.WriteLine(" Prefix = " + rule.Prefix); Console.WriteLine(" Expiration (days) = " + rule.Expiration.Days); Console.WriteLine(" Id = " + rule.Id); Console.WriteLine(" Status = " + rule.Status); } // Put a new configuration and overwrite the existing configuration configuration.Rules.RemoveAt(0); // remove first rule client.PutLifecycleConfiguration(putRequest); // Delete current configuration DeleteLifecycleConfigurationRequest deleteRequest = new DeleteLifecycleConfigurationRequest { BucketName = "SampleBucket" }; client.DeleteLifecycleConfiguration(deleteRequest); // Retrieve current configuration and verify that it is null configuration = client.GetLifecycleConfiguration(getRequest).Configuration; Debug.Assert(configuration == null); #endregion } } public void ObjectSamples() { { #region ListObjects Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // List all objects ListObjectsRequest listRequest = new ListObjectsRequest { BucketName = "SampleBucket", }; ListObjectsResponse listResponse; do { // Get a list of objects listResponse = client.ListObjects(listRequest); foreach (S3Object obj in listResponse.S3Objects) { Console.WriteLine("Object - " + obj.Key); Console.WriteLine(" Size - " + obj.Size); Console.WriteLine(" LastModified - " + obj.LastModified); Console.WriteLine(" Storage class - " + obj.StorageClass); } // Set the marker property listRequest.Marker = listResponse.NextMarker; } while (listResponse.IsTruncated); #endregion } { #region GetObject Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a GetObject request GetObjectRequest request = new GetObjectRequest { BucketName = "SampleBucket", Key = "Item1" }; // Issue request and remember to dispose of the response using (GetObjectResponse response = client.GetObject(request)) { using (StreamReader reader = new StreamReader(response.ResponseStream)) { string contents = reader.ReadToEnd(); Console.WriteLine("Object - " + response.Key); Console.WriteLine(" Version Id - " + response.VersionId); Console.WriteLine(" Contents - " + contents); } } #endregion } { #region GetObject WriteResponseStreamToFile Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a GetObject request GetObjectRequest request = new GetObjectRequest { BucketName = "SampleBucket", Key = "Item1" }; // Issue request and remember to dispose of the response using (GetObjectResponse response = client.GetObject(request)) { // Save object to local file response.WriteResponseStreamToFile("Item1.txt"); } #endregion } { #region GetObjectMetadata Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a GetObjectMetadata request GetObjectMetadataRequest request = new GetObjectMetadataRequest { BucketName = "SampleBucket", Key = "Item1" }; // Issue request and view the response GetObjectMetadataResponse response = client.GetObjectMetadata(request); Console.WriteLine("Content Length - " + response.ContentLength); Console.WriteLine("Content Type - " + response.Headers.ContentType); if (response.Expiration != null) { Console.WriteLine("Expiration Date - " + response.Expiration.ExpiryDate); Console.WriteLine("Expiration Rule Id - " + response.Expiration.RuleId); } #endregion } { #region PutObject Sample 1 // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a PutObject request PutObjectRequest request = new PutObjectRequest { BucketName = "SampleBucket", Key = "Item1", ContentBody = "This is sample content..." }; // Put object PutObjectResponse response = client.PutObject(request); #endregion } { #region PutObject Sample 2 // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a PutObject request PutObjectRequest request = new PutObjectRequest { BucketName = "SampleBucket", Key = "Item1", FilePath = "contents.txt" }; // Put object PutObjectResponse response = client.PutObject(request); #endregion } { #region PutObject Sample 3 // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a PutObject request PutObjectRequest request = new PutObjectRequest { BucketName = "SampleBucket", Key = "Item1", }; using (FileStream stream = new FileStream("contents.txt", FileMode.Open)) { request.InputStream = stream; // Put object PutObjectResponse response = client.PutObject(request); } #endregion } { #region DeleteObject Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a DeleteObject request DeleteObjectRequest request = new DeleteObjectRequest { BucketName = "SampleBucket", Key = "Item1" }; // Issue request client.DeleteObject(request); #endregion } { #region DeleteObjects Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a DeleteObject request DeleteObjectsRequest request = new DeleteObjectsRequest { BucketName = "SampleBucket", Objects = new List<KeyVersion> { new KeyVersion() {Key = "Item1"}, // Versioned item new KeyVersion() { Key = "Item2", VersionId = "Rej8CiBxcZKVK81cLr39j27Y5FVXghDK", }, // Item in subdirectory new KeyVersion() { Key = "Logs/error.txt"} } }; try { // Issue request DeleteObjectsResponse response = client.DeleteObjects(request); } catch (DeleteObjectsException doe) { // Catch error and list error details DeleteObjectsResponse errorResponse = doe.Response; foreach (DeletedObject deletedObject in errorResponse.DeletedObjects) { Console.WriteLine("Deleted item " + deletedObject.Key); } foreach (DeleteError deleteError in errorResponse.DeleteErrors) { Console.WriteLine("Error deleting item " + deleteError.Key); Console.WriteLine(" Code - " + deleteError.Code); Console.WriteLine(" Message - " + deleteError.Message); } } #endregion } { #region CopyObject Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a CopyObject request CopyObjectRequest request = new CopyObjectRequest { SourceBucket = "SampleBucket", SourceKey = "Item1", DestinationBucket = "AnotherBucket", DestinationKey = "Copy1", CannedACL = S3CannedACL.PublicRead }; // Issue request client.CopyObject(request); #endregion } { #region CopyObject Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a CopyObject request CopyObjectRequest request = new CopyObjectRequest { SourceBucket = "SampleBucket", SourceKey = "Item1", DestinationBucket = "AnotherBucket", DestinationKey = "Copy1", CannedACL = S3CannedACL.PublicRead }; // Issue request client.CopyObject(request); #endregion } { #region ListVersions Sample // Create a client AmazonS3Client client = new AmazonS3Client(); // Turn versioning on for a bucket client.PutBucketVersioning(new PutBucketVersioningRequest { BucketName = "SampleBucket", VersioningConfig = new S3BucketVersioningConfig { Status = "Enable" } }); // Populate bucket with multiple items, each with multiple versions PopulateBucket(client, "SampleBucket"); // Get versions ListVersionsRequest request = new ListVersionsRequest { BucketName = "SampleBucket" }; // Make paged ListVersions calls ListVersionsResponse response; do { response = client.ListVersions(request); // View information about versions foreach (var version in response.Versions) { Console.WriteLine("Key = {0}, Version = {1}, IsLatest = {2}, LastModified = {3}, Size = {4}", version.Key, version.VersionId, version.IsLatest, version.LastModified, version.Size); } request.KeyMarker = response.NextKeyMarker; request.VersionIdMarker = response.NextVersionIdMarker; } while (response.IsTruncated); #endregion } { #region Multipart Upload Sample int MB = (int)Math.Pow(2, 20); // Create a client AmazonS3Client client = new AmazonS3Client(); // Define input stream Stream inputStream = Create13MBDataStream(); // Initiate multipart upload InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest { BucketName = "SampleBucket", Key = "Item1" }; InitiateMultipartUploadResponse initResponse = client.InitiateMultipartUpload(initRequest); // Upload part 1 UploadPartRequest uploadRequest = new UploadPartRequest { BucketName = "SampleBucket", Key = "Item1", UploadId = initResponse.UploadId, PartNumber = 1, PartSize = 5 * MB, InputStream = inputStream }; UploadPartResponse up1Response = client.UploadPart(uploadRequest); // Upload part 2 uploadRequest = new UploadPartRequest { BucketName = "SampleBucket", Key = "Item1", UploadId = initResponse.UploadId, PartNumber = 2, PartSize = 5 * MB, InputStream = inputStream }; UploadPartResponse up2Response = client.UploadPart(uploadRequest); // Upload part 3 uploadRequest = new UploadPartRequest { BucketName = "SampleBucket", Key = "Item1", UploadId = initResponse.UploadId, PartNumber = 3, InputStream = inputStream }; UploadPartResponse up3Response = client.UploadPart(uploadRequest); // List parts for current upload ListPartsRequest listPartRequest = new ListPartsRequest { BucketName = "SampleBucket", Key = "Item1", UploadId = initResponse.UploadId }; ListPartsResponse listPartResponse = client.ListParts(listPartRequest); Debug.Assert(listPartResponse.Parts.Count == 3); // Complete the multipart upload CompleteMultipartUploadRequest compRequest = new CompleteMultipartUploadRequest { BucketName = "SampleBucket", Key = "Item1", UploadId = initResponse.UploadId, PartETags = new List<PartETag> { new PartETag { ETag = up1Response.ETag, PartNumber = 1 }, new PartETag { ETag = up2Response.ETag, PartNumber = 2 }, new PartETag { ETag = up3Response.ETag, PartNumber = 3 } } }; CompleteMultipartUploadResponse compResponse = client.CompleteMultipartUpload(compRequest); #endregion } } private Stream Create13MBDataStream() { return null; } private void PopulateBucket(IAmazonS3 client, string bucketName) { client.PutObject(new PutObjectRequest() { BucketName = bucketName, Key = "Item", ContentBody = "Attempt number one" }); for (int i = 0; i < 20; i++) { client.PutObject(new PutObjectRequest() { BucketName = bucketName, Key = "Item", ContentBody = "Atempt " + i }); } } public void PresignedURLSamples() { { #region GetPreSignedURL Sample 1 // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a CopyObject request GetPreSignedUrlRequest request = new GetPreSignedUrlRequest { BucketName = "SampleBucket", Key = "Item1", Expires = DateTime.UtcNow.AddMinutes(5) }; // Get path for request string path = client.GetPreSignedURL(request); // Test by getting contents string contents = GetContents(path); #endregion } { #region GetPreSignedURL Sample 2 // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a CopyObject request GetPreSignedUrlRequest request = new GetPreSignedUrlRequest { BucketName = "SampleBucket", Key = "Item1", Expires = DateTime.UtcNow.AddMinutes(5) }; request.ResponseHeaderOverrides.ContentType = "text/xml+zip"; request.ResponseHeaderOverrides.ContentDisposition = "attachment; filename=dispName.pdf"; request.ResponseHeaderOverrides.CacheControl = "No-cache"; request.ResponseHeaderOverrides.ContentLanguage = "mi, en"; request.ResponseHeaderOverrides.Expires = "Thu, 01 Dec 1994 16:00:00 GMT"; request.ResponseHeaderOverrides.ContentEncoding = "x-gzip"; // Get path for request string path = client.GetPreSignedURL(request); // Test by getting contents string contents = GetContents(path); #endregion } { #region GetPreSignedURL Sample 3 // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a CopyObject request GetPreSignedUrlRequest request = new GetPreSignedUrlRequest { BucketName = "SampleBucket", Expires = DateTime.UtcNow.AddMinutes(5) }; // Get path for request string path = client.GetPreSignedURL(request); // Retrieve objects string allObjects = GetContents(path); #endregion } { #region GetPreSignedURL Sample 4 // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a CopyObject request GetPreSignedUrlRequest request = new GetPreSignedUrlRequest { Expires = DateTime.UtcNow.AddMinutes(5) }; // Get path for request string path = client.GetPreSignedURL(request); // Retrieve buckets string allBuckets = GetContents(path); #endregion } { #region GetPreSignedURL Sample 5 // Create a client AmazonS3Client client = new AmazonS3Client(); // Create a CopyObject request GetPreSignedUrlRequest request = new GetPreSignedUrlRequest { BucketName = "SampleBucket", Key = "Item1", Verb = HttpVerb.PUT, Expires = DateTime.UtcNow.AddDays(10) }; // Get path for request string path = client.GetPreSignedURL(request); // Prepare data byte[] data = UTF8Encoding.UTF8.GetBytes("Sample text."); // Configure request HttpWebRequest httpRequest = WebRequest.Create(path) as HttpWebRequest; httpRequest.Method = "PUT"; httpRequest.ContentLength = data.Length; // Write data to stream Stream requestStream = httpRequest.GetRequestStream(); requestStream.Write(data, 0, data.Length); requestStream.Close(); // Issue request HttpWebResponse response = httpRequest.GetResponse() as HttpWebResponse; #endregion } } public void AclSamples() { { #region PutACL Sample 1 // Create a client AmazonS3Client client = new AmazonS3Client(); // Set Canned ACL (PublicRead) for an existing item client.PutACL(new PutACLRequest { BucketName = "SampleBucket", Key = "Item1", CannedACL = S3CannedACL.PublicRead }); // Set Canned ACL (PublicRead) for an existing item // (This reverts ACL back to default for object) client.PutACL(new PutACLRequest { BucketName = "SampleBucket", Key = "Item1", CannedACL = S3CannedACL.Private }); #endregion } { #region GetACL\PutACL Samples // Create a client AmazonS3Client client = new AmazonS3Client(); // Retrieve ACL for object S3AccessControlList acl = client.GetACL(new GetACLRequest { BucketName = "SampleBucket", Key = "Item1", }).AccessControlList; // Retrieve owner Owner owner = acl.Owner; // Describe grant S3Grant grant = new S3Grant { Grantee = new S3Grantee { EmailAddress = "[email protected]" }, Permission = S3Permission.WRITE_ACP }; // Create new ACL S3AccessControlList newAcl = new S3AccessControlList { Grants = new List<S3Grant> { grant }, Owner = owner }; // Set new ACL PutACLResponse response = client.PutACL(new PutACLRequest { BucketName = "SampleBucket", Key = "Item1", AccessControlList = acl }); #endregion } } #region GetContents function public static string GetContents(string path) { HttpWebRequest request = HttpWebRequest.Create(path) as HttpWebRequest; HttpWebResponse response = request.GetResponse() as HttpWebResponse; using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } #endregion #region ISample Members public void Run() { } #endregion } }
927
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.SecretsManager; using Amazon.SecretsManager.Model; namespace AWSSDKDocSamples.Amazon.SecretsManager.Generated { class SecretsManagerSamples : ISample { public void SecretsManagerCancelRotateSecret() { #region to-cancel-scheduled-rotation-for-a-secret-1523996016032 var client = new AmazonSecretsManagerClient(); var response = client.CancelRotateSecret(new CancelRotateSecretRequest { SecretId = "MyTestDatabaseSecret" }); string arn = response.ARN; string name = response.Name; #endregion } public void SecretsManagerCreateSecret() { #region to-create-a-basic-secret-1523996473658 var client = new AmazonSecretsManagerClient(); var response = client.CreateSecret(new CreateSecretRequest { ClientRequestToken = "EXAMPLE1-90ab-cdef-fedc-ba987SECRET1", Description = "My test database secret created with the CLI", Name = "MyTestDatabaseSecret", SecretString = "{\"username\":\"david\",\"password\":\"EXAMPLE-PASSWORD\"}" }); string arn = response.ARN; string name = response.Name; string versionId = response.VersionId; #endregion } public void SecretsManagerDeleteResourcePolicy() { #region to-delete-the-resource-based-policy-attached-to-a-secret-1530209419204 var client = new AmazonSecretsManagerClient(); var response = client.DeleteResourcePolicy(new DeleteResourcePolicyRequest { SecretId = "MyTestDatabaseSecret" }); string arn = response.ARN; string name = response.Name; #endregion } public void SecretsManagerDeleteSecret() { #region to-delete-a-secret-1523996905092 var client = new AmazonSecretsManagerClient(); var response = client.DeleteSecret(new DeleteSecretRequest { RecoveryWindowInDays = 7, SecretId = "MyTestDatabaseSecret1" }); string arn = response.ARN; DateTime deletionDate = response.DeletionDate; string name = response.Name; #endregion } public void SecretsManagerDescribeSecret() { #region to-retrieve-the-details-of-a-secret-1524000138629 var client = new AmazonSecretsManagerClient(); var response = client.DescribeSecret(new DescribeSecretRequest { SecretId = "MyTestDatabaseSecret" }); string arn = response.ARN; string description = response.Description; string kmsKeyId = response.KmsKeyId; DateTime lastAccessedDate = response.LastAccessedDate; DateTime lastChangedDate = response.LastChangedDate; DateTime lastRotatedDate = response.LastRotatedDate; string name = response.Name; DateTime nextRotationDate = response.NextRotationDate; bool rotationEnabled = response.RotationEnabled; string rotationLambdaARN = response.RotationLambdaARN; RotationRulesType rotationRules = response.RotationRules; List<Tag> tags = response.Tags; Dictionary<string, List<string>> versionIdsToStages = response.VersionIdsToStages; #endregion } public void SecretsManagerGetRandomPassword() { #region to-generate-a-random-password-1524000546092 var client = new AmazonSecretsManagerClient(); var response = client.GetRandomPassword(new GetRandomPasswordRequest { IncludeSpace = true, PasswordLength = 20, RequireEachIncludedType = true }); string randomPassword = response.RandomPassword; #endregion } public void SecretsManagerGetResourcePolicy() { #region to-retrieve-the-resource-based-policy-attached-to-a-secret-1530209677536 var client = new AmazonSecretsManagerClient(); var response = client.GetResourcePolicy(new GetResourcePolicyRequest { SecretId = "MyTestDatabaseSecret" }); string arn = response.ARN; string name = response.Name; string resourcePolicy = response.ResourcePolicy; #endregion } public void SecretsManagerGetSecretValue() { #region to-retrieve-the-encrypted-secret-value-of-a-secret-1524000702484 var client = new AmazonSecretsManagerClient(); var response = client.GetSecretValue(new GetSecretValueRequest { SecretId = "MyTestDatabaseSecret" }); string arn = response.ARN; DateTime createdDate = response.CreatedDate; string name = response.Name; string secretString = response.SecretString; string versionId = response.VersionId; List<string> versionStages = response.VersionStages; #endregion } public void SecretsManagerListSecrets() { #region to-list-the-secrets-in-your-account-1524001246087 var client = new AmazonSecretsManagerClient(); var response = client.ListSecrets(new ListSecretsRequest { }); List<SecretListEntry> secretList = response.SecretList; #endregion } public void SecretsManagerListSecretVersionIds() { #region to-list-all-of-the-secret-versions-associated-with-a-secret-1524000999164 var client = new AmazonSecretsManagerClient(); var response = client.ListSecretVersionIds(new ListSecretVersionIdsRequest { IncludeDeprecated = true, SecretId = "MyTestDatabaseSecret" }); string arn = response.ARN; string name = response.Name; List<SecretVersionsListEntry> versions = response.Versions; #endregion } public void SecretsManagerPutResourcePolicy() { #region to-add-a-resource-based-policy-to-a-secret-1530209881839 var client = new AmazonSecretsManagerClient(); var response = client.PutResourcePolicy(new PutResourcePolicyRequest { ResourcePolicy = "{ \"Version\":\"2012-10-17\", \"Statement\":[{ \"Effect\":\"Allow\", \"Principal\":{ \"AWS\":\"arn:aws:iam::123456789012:root\" }, \"Action\":\"secretsmanager:GetSecretValue\", \"Resource\":\"*\" }] }", SecretId = "MyTestDatabaseSecret" }); string arn = response.ARN; string name = response.Name; #endregion } public void SecretsManagerPutSecretValue() { #region to-store-a-secret-value-in-a-new-version-of-a-secret-1524001393971 var client = new AmazonSecretsManagerClient(); var response = client.PutSecretValue(new PutSecretValueRequest { ClientRequestToken = "EXAMPLE2-90ab-cdef-fedc-ba987EXAMPLE", SecretId = "MyTestDatabaseSecret", SecretString = "{\"username\":\"david\",\"password\":\"EXAMPLE-PASSWORD\"}" }); string arn = response.ARN; string name = response.Name; string versionId = response.VersionId; List<string> versionStages = response.VersionStages; #endregion } public void SecretsManagerReplicateSecretToRegions() { #region example-1679591984774 var client = new AmazonSecretsManagerClient(); var response = client.ReplicateSecretToRegions(new ReplicateSecretToRegionsRequest { AddReplicaRegions = new List<ReplicaRegionType> { new ReplicaRegionType { Region = "eu-west-3" } }, ForceOverwriteReplicaSecret = true, SecretId = "MyTestSecret" }); string arn = response.ARN; List<ReplicationStatusType> replicationStatus = response.ReplicationStatus; #endregion } public void SecretsManagerRestoreSecret() { #region to-restore-a-previously-deleted-secret-1524001513930 var client = new AmazonSecretsManagerClient(); var response = client.RestoreSecret(new RestoreSecretRequest { SecretId = "MyTestDatabaseSecret" }); string arn = response.ARN; string name = response.Name; #endregion } public void SecretsManagerRotateSecret() { #region to-configure-rotation-for-a-secret-1524001629475 var client = new AmazonSecretsManagerClient(); var response = client.RotateSecret(new RotateSecretRequest { RotationLambdaARN = "arn:aws:lambda:us-west-2:123456789012:function:MyTestDatabaseRotationLambda", RotationRules = new RotationRulesType { Duration = "2h", ScheduleExpression = "cron(0 16 1,15 * ? *)" }, SecretId = "MyTestDatabaseSecret" }); string arn = response.ARN; string name = response.Name; string versionId = response.VersionId; #endregion } public void SecretsManagerRotateSecret() { #region to-request-an-immediate-rotation-for-a-secret-1524001949004 var client = new AmazonSecretsManagerClient(); var response = client.RotateSecret(new RotateSecretRequest { SecretId = "MyTestDatabaseSecret" }); string arn = response.ARN; string name = response.Name; string versionId = response.VersionId; #endregion } public void SecretsManagerTagResource() { #region to-add-tags-to-a-secret-1524002106718 var client = new AmazonSecretsManagerClient(); var response = client.TagResource(new TagResourceRequest { SecretId = "MyExampleSecret", Tags = new List<Tag> { new Tag { Key = "FirstTag", Value = "SomeValue" }, new Tag { Key = "SecondTag", Value = "AnotherValue" } } }); #endregion } public void SecretsManagerUntagResource() { #region to-remove-tags-from-a-secret-1524002239065 var client = new AmazonSecretsManagerClient(); var response = client.UntagResource(new UntagResourceRequest { SecretId = "MyTestDatabaseSecret", TagKeys = new List<string> { "FirstTag", "SecondTag" } }); #endregion } public void SecretsManagerUpdateSecret() { #region to-update-the-description-of-a-secret-1524002349094 var client = new AmazonSecretsManagerClient(); var response = client.UpdateSecret(new UpdateSecretRequest { ClientRequestToken = "EXAMPLE1-90ab-cdef-fedc-ba987EXAMPLE", Description = "This is a new description for the secret.", SecretId = "MyTestDatabaseSecret" }); string arn = response.ARN; string name = response.Name; #endregion } public void SecretsManagerUpdateSecret() { #region to-update-the-kms-key-associated-with-a-secret-1524002421563 var client = new AmazonSecretsManagerClient(); var response = client.UpdateSecret(new UpdateSecretRequest { KmsKeyId = "arn:aws:kms:us-west-2:123456789012:key/EXAMPLE2-90ab-cdef-fedc-ba987EXAMPLE", SecretId = "MyTestDatabaseSecret" }); string arn = response.ARN; string name = response.Name; #endregion } public void SecretsManagerUpdateSecret() { #region to-create-a-new-version-of-the-encrypted-secret-value-1524004651836 var client = new AmazonSecretsManagerClient(); var response = client.UpdateSecret(new UpdateSecretRequest { SecretId = "MyTestDatabaseSecret", SecretString = "{JSON STRING WITH CREDENTIALS}" }); string arn = response.ARN; string name = response.Name; string versionId = response.VersionId; #endregion } public void SecretsManagerUpdateSecretVersionStage() { #region to-add-a-staging-label-attached-to-a-version-of-a-secret-1524004783841 var client = new AmazonSecretsManagerClient(); var response = client.UpdateSecretVersionStage(new UpdateSecretVersionStageRequest { MoveToVersionId = "EXAMPLE1-90ab-cdef-fedc-ba987SECRET1", SecretId = "MyTestDatabaseSecret", VersionStage = "STAGINGLABEL1" }); string arn = response.ARN; string name = response.Name; #endregion } public void SecretsManagerUpdateSecretVersionStage() { #region to-delete-a-staging-label-attached-to-a-version-of-a-secret-1524004862181 var client = new AmazonSecretsManagerClient(); var response = client.UpdateSecretVersionStage(new UpdateSecretVersionStageRequest { RemoveFromVersionId = "EXAMPLE1-90ab-cdef-fedc-ba987SECRET1", SecretId = "MyTestDatabaseSecret", VersionStage = "STAGINGLABEL1" }); string arn = response.ARN; string name = response.Name; #endregion } public void SecretsManagerUpdateSecretVersionStage() { #region to-move-a-staging-label-from-one-version-of-a-secret-to-another-1524004963841 var client = new AmazonSecretsManagerClient(); var response = client.UpdateSecretVersionStage(new UpdateSecretVersionStageRequest { MoveToVersionId = "EXAMPLE2-90ab-cdef-fedc-ba987SECRET2", RemoveFromVersionId = "EXAMPLE1-90ab-cdef-fedc-ba987SECRET1", SecretId = "MyTestDatabaseSecret", VersionStage = "AWSCURRENT" }); string arn = response.ARN; string name = response.Name; #endregion } public void SecretsManagerValidateResourcePolicy() { #region to-validate-the-resource-policy-of-a-secret-1524000138629 var client = new AmazonSecretsManagerClient(); var response = client.ValidateResourcePolicy(new ValidateResourcePolicyRequest { ResourcePolicy = "{ \"Version\":\"2012-10-17\", \"Statement\":[{ \"Effect\":\"Allow\", \"Principal\":{ \"AWS\":\"arn:aws:iam::123456789012:root\" }, \"Action\":\"secretsmanager:GetSecretValue\", \"Resource\":\"*\" }] }", SecretId = "MyTestDatabaseSecret" }); bool policyValidationPassed = response.PolicyValidationPassed; List<ValidationErrorsEntry> validationErrors = response.ValidationErrors; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
505
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.SecurityHub; using Amazon.SecurityHub.Model; namespace AWSSDKDocSamples.Amazon.SecurityHub.Generated { class SecurityHubSamples : ISample { public void SecurityHubAcceptAdministratorInvitation() { #region to-accept-an-invitation-be-a-member-account-1674849870467 var client = new AmazonSecurityHubClient(); var response = client.AcceptAdministratorInvitation(new AcceptAdministratorInvitationRequest { AdministratorId = "123456789012", InvitationId = "7ab938c5d52d7904ad09f9e7c20cc4eb" }); #endregion } public void SecurityHubBatchDeleteAutomationRules() { #region to-delete-one-or-more-automation-rules-1684769550318 var client = new AmazonSecurityHubClient(); var response = client.BatchDeleteAutomationRules(new BatchDeleteAutomationRulesRequest { AutomationRulesArns = new List<string> { "arn:aws:securityhub:us-east-1:123456789012:automation-rule/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "arn:aws:securityhub:us-east-1:123456789012:automation-rule/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222" } }); List<string> processedAutomationRules = response.ProcessedAutomationRules; List<UnprocessedAutomationRule> unprocessedAutomationRules = response.UnprocessedAutomationRules; #endregion } public void SecurityHubBatchDisableStandards() { #region to-disable-one-or-more-security-standards-1674851507200 var client = new AmazonSecurityHubClient(); var response = client.BatchDisableStandards(new BatchDisableStandardsRequest { StandardsSubscriptionArns = new List<string> { "arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1" } }); List<StandardsSubscription> standardsSubscriptions = response.StandardsSubscriptions; #endregion } public void SecurityHubBatchEnableStandards() { #region to-enable-security-standards-1683233792239 var client = new AmazonSecurityHubClient(); var response = client.BatchEnableStandards(new BatchEnableStandardsRequest { StandardsSubscriptionRequests = new List<StandardsSubscriptionRequest> { new StandardsSubscriptionRequest { StandardsArn = "arn:aws:securityhub:us-west-1::standards/pci-dss/v/3.2.1" } } }); List<StandardsSubscription> standardsSubscriptions = response.StandardsSubscriptions; #endregion } public void SecurityHubBatchGetAutomationRules() { #region to-update-one-ore-more-automation-rules-1684771025347 var client = new AmazonSecurityHubClient(); var response = client.BatchGetAutomationRules(new BatchGetAutomationRulesRequest { AutomationRulesArns = new List<string> { "arn:aws:securityhub:us-east-1:123456789012:automation-rule/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "arn:aws:securityhub:us-east-1:123456789012:automation-rule/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222" } }); List<AutomationRulesConfig> rules = response.Rules; #endregion } public void SecurityHubBatchGetSecurityControls() { #region to-get-security-control-details--1683234478355 var client = new AmazonSecurityHubClient(); var response = client.BatchGetSecurityControls(new BatchGetSecurityControlsRequest { SecurityControlIds = new List<string> { "ACM.1", "APIGateway.1" } }); List<SecurityControl> securityControls = response.SecurityControls; #endregion } public void SecurityHubBatchGetStandardsControlAssociations() { #region to-get-enablement-status-of-a-batch-of-controls-1683301618357 var client = new AmazonSecurityHubClient(); var response = client.BatchGetStandardsControlAssociations(new BatchGetStandardsControlAssociationsRequest { StandardsControlAssociationIds = new List<StandardsControlAssociationId> { new StandardsControlAssociationId { SecurityControlId = "CloudTrail.1", StandardsArn = "arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0" }, new StandardsControlAssociationId { SecurityControlId = "CloudWatch.12", StandardsArn = "arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0" } } }); List<StandardsControlAssociationDetail> standardsControlAssociationDetails = response.StandardsControlAssociationDetails; #endregion } public void SecurityHubBatchImportFindings() { #region to-import-security-findings-from-a-third-party-provider-to-security-hub-1675090935260 var client = new AmazonSecurityHubClient(); var response = client.BatchImportFindings(new BatchImportFindingsRequest { Findings = new List<AwsSecurityFinding> { new AwsSecurityFinding { AwsAccountId = "123456789012", CreatedAt = "2020-05-27T17:05:54.832Z", Description = "Vulnerability in a CloudTrail trail", FindingProviderFields = new FindingProviderFields { Severity = new FindingProviderSeverity { Label = "LOW", Original = "10" }, Types = new List<string> { "Software and Configuration Checks/Vulnerabilities/CVE" } }, GeneratorId = "TestGeneratorId", Id = "Id1", ProductArn = "arn:aws:securityhub:us-west-1:123456789012:product/123456789012/default", Resources = new List<Resource> { new Resource { Id = "arn:aws:cloudtrail:us-west-1:123456789012:trail/TrailName", Partition = "aws", Region = "us-west-1", Type = "AwsCloudTrailTrail" } }, SchemaVersion = "2018-10-08", Title = "CloudTrail trail vulnerability", UpdatedAt = "2020-06-02T16:05:54.832Z" } } }); int failedCount = response.FailedCount; List<ImportFindingsError> failedFindings = response.FailedFindings; int successCount = response.SuccessCount; #endregion } public void SecurityHubBatchUpdateAutomationRules() { #region to-update-one-ore-more-automation-rules-1684771025347 var client = new AmazonSecurityHubClient(); var response = client.BatchUpdateAutomationRules(new BatchUpdateAutomationRulesRequest { UpdateAutomationRulesRequestItems = new List<UpdateAutomationRulesRequestItem> { new UpdateAutomationRulesRequestItem { RuleArn = "arn:aws:securityhub:us-east-1:123456789012:automation-rule/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", RuleOrder = 15, RuleStatus = "ENABLED" }, new UpdateAutomationRulesRequestItem { RuleArn = "arn:aws:securityhub:us-east-1:123456789012:automation-rule/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222", RuleStatus = "DISABLED" } } }); List<string> processedAutomationRules = response.ProcessedAutomationRules; #endregion } public void SecurityHubBatchUpdateFindings() { #region to-update-security-hub-findings-1675183938248 var client = new AmazonSecurityHubClient(); var response = client.BatchUpdateFindings(new BatchUpdateFindingsRequest { Confidence = 80, Criticality = 80, FindingIdentifiers = new List<AwsSecurityFindingIdentifier> { new AwsSecurityFindingIdentifier { Id = "arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1/PCI.Lambda.2/finding/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", ProductArn = "arn:aws:securityhub:us-west-1::product/aws/securityhub" }, new AwsSecurityFindingIdentifier { Id = "arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1/PCI.Lambda.2/finding/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222", ProductArn = "arn:aws:securityhub:us-west-1::product/aws/securityhub" } }, Note = new NoteUpdate { Text = "Known issue that is not a risk.", UpdatedBy = "user1" }, RelatedFindings = new List<RelatedFinding> { new RelatedFinding { Id = "arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1/PCI.Lambda.2/finding/a1b2c3d4-5678-90ab-cdef-EXAMPLE33333", ProductArn = "arn:aws:securityhub:us-west-1::product/aws/securityhub" } }, Severity = new SeverityUpdate { Label = "LOW" }, Types = new List<string> { "Software and Configuration Checks/Vulnerabilities/CVE" }, UserDefinedFields = new Dictionary<string, string> { { "reviewedByCio", "true" } }, VerificationState = "TRUE_POSITIVE", Workflow = new WorkflowUpdate { Status = "RESOLVED" } }); List<AwsSecurityFindingIdentifier> processedFindings = response.ProcessedFindings; List<BatchUpdateFindingsUnprocessedFinding> unprocessedFindings = response.UnprocessedFindings; #endregion } public void SecurityHubBatchUpdateStandardsControlAssociations() { #region to-update-enablement-status-of-a-batch-of-controls-1683300378416 var client = new AmazonSecurityHubClient(); var response = client.BatchUpdateStandardsControlAssociations(new BatchUpdateStandardsControlAssociationsRequest { StandardsControlAssociationUpdates = new List<StandardsControlAssociationUpdate> { new StandardsControlAssociationUpdate { AssociationStatus = "DISABLED", SecurityControlId = "CloudTrail.1", StandardsArn = "arn:aws:securityhub:::ruleset/sample-standard/v/1.1.0", UpdatedReason = "Not relevant to environment" }, new StandardsControlAssociationUpdate { AssociationStatus = "DISABLED", SecurityControlId = "CloudWatch.12", StandardsArn = "arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0", UpdatedReason = "Not relevant to environment" } } }); List<UnprocessedStandardsControlAssociationUpdate> unprocessedAssociationUpdates = response.UnprocessedAssociationUpdates; #endregion } public void SecurityHubCreateActionTarget() { #region to-create-a-custom-action-target-1675184966299 var client = new AmazonSecurityHubClient(); var response = client.CreateActionTarget(new CreateActionTargetRequest { Description = "Action to send the finding for remediation tracking", Id = "Remediation", Name = "Send to remediation" }); string actionTargetArn = response.ActionTargetArn; #endregion } public void SecurityHubCreateAutomationRule() { #region to-create-an-automation-rule-1684768393507 var client = new AmazonSecurityHubClient(); var response = client.CreateAutomationRule(new CreateAutomationRuleRequest { Actions = new List<AutomationRulesAction> { new AutomationRulesAction { FindingFieldsUpdate = new AutomationRulesFindingFieldsUpdate { Note = new NoteUpdate { Text = "This is a critical S3 bucket, please look into this ASAP", UpdatedBy = "test-user" }, Severity = new SeverityUpdate { Label = "CRITICAL" } }, Type = "FINDING_FIELDS_UPDATE" } }, Criteria = new AutomationRulesFindingFilters { ComplianceStatus = new List<StringFilter> { new StringFilter { Comparison = "EQUALS", Value = "FAILED" } }, ProductName = new List<StringFilter> { new StringFilter { Comparison = "EQUALS", Value = "Security Hub" } }, RecordState = new List<StringFilter> { new StringFilter { Comparison = "EQUALS", Value = "ACTIVE" } }, ResourceId = new List<StringFilter> { new StringFilter { Comparison = "EQUALS", Value = "arn:aws:s3:::examplebucket/developers/design_info.doc" } }, WorkflowStatus = new List<StringFilter> { new StringFilter { Comparison = "EQUALS", Value = "NEW" } } }, Description = "Elevate finding severity to Critical for important resources", IsTerminal = false, RuleName = "Elevate severity for important resources", RuleOrder = 1, RuleStatus = "ENABLED", Tags = new Dictionary<string, string> { { "important-resources-rule", "s3-bucket" } } }); string ruleArn = response.RuleArn; #endregion } public void SecurityHubCreateFindingAggregator() { #region to-enable-cross-region-aggregation-1674766716226 var client = new AmazonSecurityHubClient(); var response = client.CreateFindingAggregator(new CreateFindingAggregatorRequest { RegionLinkingMode = "SPECIFIED_REGIONS", Regions = new List<string> { "us-west-1", "us-west-2" } }); string findingAggregationRegion = response.FindingAggregationRegion; string findingAggregatorArn = response.FindingAggregatorArn; string regionLinkingMode = response.RegionLinkingMode; List<string> regions = response.Regions; #endregion } public void SecurityHubCreateInsight() { #region to-create-a-custom-insight-1675354046628 var client = new AmazonSecurityHubClient(); var response = client.CreateInsight(new CreateInsightRequest { Filters = new AwsSecurityFindingFilters { ResourceType = new List<StringFilter> { new StringFilter { Comparison = "EQUALS", Value = "AwsIamRole" } }, SeverityLabel = new List<StringFilter> { new StringFilter { Comparison = "EQUALS", Value = "CRITICAL" } } }, GroupByAttribute = "ResourceId", Name = "Critical role findings" }); string insightArn = response.InsightArn; #endregion } public void SecurityHubCreateMembers() { #region to-add-a-member-account-1675354709996 var client = new AmazonSecurityHubClient(); var response = client.CreateMembers(new CreateMembersRequest { AccountDetails = new List<AccountDetails> { new AccountDetails { AccountId = "123456789012" }, new AccountDetails { AccountId = "111122223333" } } }); List<Result> unprocessedAccounts = response.UnprocessedAccounts; #endregion } public void SecurityHubDeclineInvitations() { #region to-decline-invitation-to-become-a-member-account-1675448487605 var client = new AmazonSecurityHubClient(); var response = client.DeclineInvitations(new DeclineInvitationsRequest { AccountIds = new List<string> { "123456789012", "111122223333" } }); List<Result> unprocessedAccounts = response.UnprocessedAccounts; #endregion } public void SecurityHubDeleteActionTarget() { #region to-delete-a-custom-action-target-1675449272793 var client = new AmazonSecurityHubClient(); var response = client.DeleteActionTarget(new DeleteActionTargetRequest { ActionTargetArn = "arn:aws:securityhub:us-west-1:123456789012:action/custom/Remediation" }); string actionTargetArn = response.ActionTargetArn; #endregion } public void SecurityHubDeleteFindingAggregator() { #region to-delete-a-finding-aggregator-1675701750629 var client = new AmazonSecurityHubClient(); var response = client.DeleteFindingAggregator(new DeleteFindingAggregatorRequest { FindingAggregatorArn = "arn:aws:securityhub:us-east-1:123456789012:finding-aggregator/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111" }); #endregion } public void SecurityHubDeleteInsight() { #region to-delete-a-custom-insight-1675702697204 var client = new AmazonSecurityHubClient(); var response = client.DeleteInsight(new DeleteInsightRequest { InsightArn = "arn:aws:securityhub:us-west-1:123456789012:insight/123456789012/custom/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111" }); string insightArn = response.InsightArn; #endregion } public void SecurityHubDeleteInvitations() { #region to-delete-a-custom-insight-1675702697204 var client = new AmazonSecurityHubClient(); var response = client.DeleteInvitations(new DeleteInvitationsRequest { AccountIds = new List<string> { "123456789012" } }); List<Result> unprocessedAccounts = response.UnprocessedAccounts; #endregion } public void SecurityHubDeleteMembers() { #region to-delete-a-member-account-1675883040513 var client = new AmazonSecurityHubClient(); var response = client.DeleteMembers(new DeleteMembersRequest { AccountIds = new List<string> { "123456789111", "123456789222" } }); List<Result> unprocessedAccounts = response.UnprocessedAccounts; #endregion } public void SecurityHubDescribeActionTargets() { #region to-return-custom-action-targets-1675883682038 var client = new AmazonSecurityHubClient(); var response = client.DescribeActionTargets(new DescribeActionTargetsRequest { ActionTargetArns = new List<string> { "arn:aws:securityhub:us-west-1:123456789012:action/custom/Remediation" } }); List<ActionTarget> actionTargets = response.ActionTargets; #endregion } public void SecurityHubDescribeHub() { #region to-return-details-about-hub-resource-1675884542597 var client = new AmazonSecurityHubClient(); var response = client.DescribeHub(new DescribeHubRequest { HubArn = "arn:aws:securityhub:us-west-1:123456789012:hub/default" }); bool autoEnableControls = response.AutoEnableControls; string controlFindingGenerator = response.ControlFindingGenerator; string hubArn = response.HubArn; string subscribedAt = response.SubscribedAt; #endregion } public void SecurityHubDescribeOrganizationConfiguration() { #region to-get-information-about-organizations-configuration-1676059786304 var client = new AmazonSecurityHubClient(); var response = client.DescribeOrganizationConfiguration(new DescribeOrganizationConfigurationRequest { }); bool autoEnable = response.AutoEnable; string autoEnableStandards = response.AutoEnableStandards; bool memberAccountLimitReached = response.MemberAccountLimitReached; #endregion } public void SecurityHubDescribeProducts() { #region to-get-information-about-security-hub-integrations-1676061228533 var client = new AmazonSecurityHubClient(); var response = client.DescribeProducts(new DescribeProductsRequest { MaxResults = 1, NextToken = "NULL", ProductArn = "arn:aws:securityhub:us-east-1:517716713836:product/crowdstrike/crowdstrike-falcon" }); string nextToken = response.NextToken; List<Product> products = response.Products; #endregion } public void SecurityHubDescribeStandards() { #region to-get-available-security-hub-standards-1676307464661 var client = new AmazonSecurityHubClient(); var response = client.DescribeStandards(new DescribeStandardsRequest { }); List<Standard> standards = response.Standards; #endregion } public void SecurityHubDescribeStandardsControls() { #region to-get-a-list-of-controls-for-a-security-standard-1676308027759 var client = new AmazonSecurityHubClient(); var response = client.DescribeStandardsControls(new DescribeStandardsControlsRequest { MaxResults = 2, NextToken = "NULL", StandardsSubscriptionArn = "arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1" }); List<StandardsControl> controls = response.Controls; string nextToken = response.NextToken; #endregion } public void SecurityHubDisableImportFindingsForProduct() { #region to-end-a-security-hub-integration-1676480035650 var client = new AmazonSecurityHubClient(); var response = client.DisableImportFindingsForProduct(new DisableImportFindingsForProductRequest { ProductSubscriptionArn = "arn:aws:securityhub:us-east-1:517716713836:product/crowdstrike/crowdstrike-falcon" }); #endregion } public void SecurityHubDisableOrganizationAdminAccount() { #region to-remove-a-security-hub-administrator-account-1676480521876 var client = new AmazonSecurityHubClient(); var response = client.DisableOrganizationAdminAccount(new DisableOrganizationAdminAccountRequest { AdminAccountId = "123456789012" }); #endregion } public void SecurityHubDisableSecurityHub() { #region to-deactivate-security-hub-1676583894245 var client = new AmazonSecurityHubClient(); var response = client.DisableSecurityHub(new DisableSecurityHubRequest { }); #endregion } public void SecurityHubDisassociateFromAdministratorAccount() { #region to-disassociate-requesting-account-from-administrator-account-1676584168509 var client = new AmazonSecurityHubClient(); var response = client.DisassociateFromAdministratorAccount(new DisassociateFromAdministratorAccountRequest { }); #endregion } public void SecurityHubDisassociateMembers() { #region to-disassociate-member-accounts-from-administrator-account-1676918349164 var client = new AmazonSecurityHubClient(); var response = client.DisassociateMembers(new DisassociateMembersRequest { AccountIds = new List<string> { "123456789012", "111122223333" } }); #endregion } public void SecurityHubEnableImportFindingsForProduct() { #region to-activate-an-integration-1676918918114 var client = new AmazonSecurityHubClient(); var response = client.EnableImportFindingsForProduct(new EnableImportFindingsForProductRequest { ProductArn = "arn:aws:securityhub:us-east-1:517716713836:product/crowdstrike/crowdstrike-falcon" }); string productSubscriptionArn = response.ProductSubscriptionArn; #endregion } public void SecurityHubEnableOrganizationAdminAccount() { #region to-designate-a-security-hub-administrator-1676998319851 var client = new AmazonSecurityHubClient(); var response = client.EnableOrganizationAdminAccount(new EnableOrganizationAdminAccountRequest { AdminAccountId = "123456789012" }); #endregion } public void SecurityHubEnableSecurityHub() { #region to-activate-security-hub-1676998538599 var client = new AmazonSecurityHubClient(); var response = client.EnableSecurityHub(new EnableSecurityHubRequest { EnableDefaultStandards = true, Tags = new Dictionary<string, string> { { "Department", "Security" } } }); #endregion } public void SecurityHubGetAdministratorAccount() { #region to-get-details-about-the-security-hub-administrator-account-1676998997182 var client = new AmazonSecurityHubClient(); var response = client.GetAdministratorAccount(new GetAdministratorAccountRequest { }); Invitation administrator = response.Administrator; #endregion } public void SecurityHubGetEnabledStandards() { #region to-return-a-list-of-enabled-standards-1677090731129 var client = new AmazonSecurityHubClient(); var response = client.GetEnabledStandards(new GetEnabledStandardsRequest { StandardsSubscriptionArns = new List<string> { "arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1" } }); List<StandardsSubscription> standardsSubscriptions = response.StandardsSubscriptions; #endregion } public void SecurityHubGetFindingAggregator() { #region to-get-cross-region-aggregation-details-1677091474868 var client = new AmazonSecurityHubClient(); var response = client.GetFindingAggregator(new GetFindingAggregatorRequest { FindingAggregatorArn = "arn:aws:securityhub:us-east-1:123456789012:finding-aggregator/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111" }); string findingAggregationRegion = response.FindingAggregationRegion; string findingAggregatorArn = response.FindingAggregatorArn; string regionLinkingMode = response.RegionLinkingMode; List<string> regions = response.Regions; #endregion } public void SecurityHubGetFindingHistory() { #region to-get-finding-history-1680270012186 var client = new AmazonSecurityHubClient(); var response = client.GetFindingHistory(new GetFindingHistoryRequest { EndTime = DateTime.UtcNow, FindingIdentifier = new AwsSecurityFindingIdentifier { Id = "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", ProductArn = "arn:aws:securityhub:us-west-2:123456789012:product/123456789012/default" }, MaxResults = 2, StartTime = new DateTime(2021, 9, 30, 8, 53, 35, DateTimeKind.Utc) }); List<FindingHistoryRecord> records = response.Records; #endregion } public void SecurityHubGetFindings() { #region to-get-a-list-of-findings-1677181069931 var client = new AmazonSecurityHubClient(); var response = client.GetFindings(new GetFindingsRequest { Filters = new AwsSecurityFindingFilters { AwsAccountId = new List<StringFilter> { new StringFilter { Comparison = "PREFIX", Value = "123456789012" } } }, MaxResults = 1 }); List<AwsSecurityFinding> findings = response.Findings; #endregion } public void SecurityHubGetInsightResults() { #region to-get-the-results-of-a-security-hub-insight-1677182822019 var client = new AmazonSecurityHubClient(); var response = client.GetInsightResults(new GetInsightResultsRequest { InsightArn = "arn:aws:securityhub:us-west-1:123456789012:insight/123456789012/custom/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111" }); InsightResults insightResults = response.InsightResults; #endregion } public void SecurityHubGetInsights() { #region to-get-details-of-a-security-hub-insight-1677774127203 var client = new AmazonSecurityHubClient(); var response = client.GetInsights(new GetInsightsRequest { InsightArns = new List<string> { "arn:aws:securityhub:us-west-1:123456789012:insight/123456789012/custom/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111" } }); List<Insight> insights = response.Insights; #endregion } public void SecurityHubGetInvitationsCount() { #region to-get-a-count-of-membership-invitations-1677774568793 var client = new AmazonSecurityHubClient(); var response = client.GetInvitationsCount(new GetInvitationsCountRequest { }); int invitationsCount = response.InvitationsCount; #endregion } public void SecurityHubGetMembers() { #region to-get-member-account-details-1677774956489 var client = new AmazonSecurityHubClient(); var response = client.GetMembers(new GetMembersRequest { AccountIds = new List<string> { "444455556666", "777788889999" } }); List<Member> members = response.Members; List<Result> unprocessedAccounts = response.UnprocessedAccounts; #endregion } public void SecurityHubInviteMembers() { #region to-invite-accounts-to-become-members-1677775500860 var client = new AmazonSecurityHubClient(); var response = client.InviteMembers(new InviteMembersRequest { AccountIds = new List<string> { "111122223333", "444455556666" } }); List<Result> unprocessedAccounts = response.UnprocessedAccounts; #endregion } public void SecurityHubListAutomationRules() { #region to-list-automation-rules-1684770582059 var client = new AmazonSecurityHubClient(); var response = client.ListAutomationRules(new ListAutomationRulesRequest { MaxResults = 2, NextToken = "example-token" }); List<AutomationRulesMetadata> automationRulesMetadata = response.AutomationRulesMetadata; string nextToken = response.NextToken; #endregion } public void SecurityHubListEnabledProductsForImport() { #region to-list-arns-for-enabled-integrations-1678294870020 var client = new AmazonSecurityHubClient(); var response = client.ListEnabledProductsForImport(new ListEnabledProductsForImportRequest { }); List<string> productSubscriptions = response.ProductSubscriptions; #endregion } public void SecurityHubListFindingAggregators() { #region to-update-the-enablement-status-of-a-standard-control-1678912506444 var client = new AmazonSecurityHubClient(); var response = client.ListFindingAggregators(new ListFindingAggregatorsRequest { }); List<FindingAggregator> findingAggregators = response.FindingAggregators; #endregion } public void SecurityHubListInvitations() { #region to-list-membership-invitations-to-calling-account-1678295758285 var client = new AmazonSecurityHubClient(); var response = client.ListInvitations(new ListInvitationsRequest { }); List<Invitation> invitations = response.Invitations; #endregion } public void SecurityHubListMembers() { #region to-list-member-account-details-1678385639113 var client = new AmazonSecurityHubClient(); var response = client.ListMembers(new ListMembersRequest { }); List<Member> members = response.Members; #endregion } public void SecurityHubListOrganizationAdminAccounts() { #region to-list-administrator-acccounts-for-an-organization-1678386548110 var client = new AmazonSecurityHubClient(); var response = client.ListOrganizationAdminAccounts(new ListOrganizationAdminAccountsRequest { }); List<AdminAccount> adminAccounts = response.AdminAccounts; #endregion } public void SecurityHubListSecurityControlDefinitions() { #region to-list-security-controls-that-apply-to-a-standard-1678386912894 var client = new AmazonSecurityHubClient(); var response = client.ListSecurityControlDefinitions(new ListSecurityControlDefinitionsRequest { MaxResults = 3, NextToken = "NULL", StandardsArn = "arn:aws:securityhub:::standards/aws-foundational-security-best-practices/v/1.0.0" }); string nextToken = response.NextToken; List<SecurityControlDefinition> securityControlDefinitions = response.SecurityControlDefinitions; #endregion } public void SecurityHubListStandardsControlAssociations() { #region to-say-whether-standard-1678389297986 var client = new AmazonSecurityHubClient(); var response = client.ListStandardsControlAssociations(new ListStandardsControlAssociationsRequest { SecurityControlId = "S3.1" }); List<StandardsControlAssociationSummary> standardsControlAssociationSummaries = response.StandardsControlAssociationSummaries; #endregion } public void SecurityHubListTagsForResource() { #region to-get-a-list-of-tags-for-a-resource-1678477883796 var client = new AmazonSecurityHubClient(); var response = client.ListTagsForResource(new ListTagsForResourceRequest { ResourceArn = "arn:aws:securityhub:us-west-1:123456789012:hub/default" }); Dictionary<string, string> tags = response.Tags; #endregion } public void SecurityHubTagResource() { #region to-tag-a-resource-1678478687320 var client = new AmazonSecurityHubClient(); var response = client.TagResource(new TagResourceRequest { ResourceArn = "arn:aws:securityhub:us-west-1:123456789012:hub/default", Tags = new Dictionary<string, string> { { "Area", "USMidwest" }, { "Department", "Operations" } } }); #endregion } public void SecurityHubUntagResource() { #region to-remove-tags-from-a-resource-1678478903748 var client = new AmazonSecurityHubClient(); var response = client.UntagResource(new UntagResourceRequest { ResourceArn = "arn:aws:securityhub:us-west-1:123456789012:hub/default", TagKeys = new List<string> { "Department" } }); #endregion } public void SecurityHubUpdateActionTarget() { #region to-update-the-name-and-description-of-a-custom-action-target-1678814873015 var client = new AmazonSecurityHubClient(); var response = client.UpdateActionTarget(new UpdateActionTargetRequest { ActionTargetArn = "arn:aws:securityhub:us-west-1:123456789012:action/custom/Remediation", Description = "Sends specified findings to customer service chat", Name = "Chat custom action" }); #endregion } public void SecurityHubUpdateFindingAggregator() { #region to-update-cross-region-aggregation-settings-1678815536396 var client = new AmazonSecurityHubClient(); var response = client.UpdateFindingAggregator(new UpdateFindingAggregatorRequest { FindingAggregatorArn = "arn:aws:securityhub:us-east-1:123456789012:finding-aggregator/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", RegionLinkingMode = "SPECIFIED_REGIONS", Regions = new List<string> { "us-west-1", "us-west-2" } }); string findingAggregationRegion = response.FindingAggregationRegion; string findingAggregatorArn = response.FindingAggregatorArn; string regionLinkingMode = response.RegionLinkingMode; List<string> regions = response.Regions; #endregion } public void SecurityHubUpdateInsight() { #region to-update-an-insight-1678816280498 var client = new AmazonSecurityHubClient(); var response = client.UpdateInsight(new UpdateInsightRequest { Filters = new AwsSecurityFindingFilters { ResourceType = new List<StringFilter> { new StringFilter { Comparison = "EQUALS", Value = "AwsIamRole" } }, SeverityLabel = new List<StringFilter> { new StringFilter { Comparison = "EQUALS", Value = "HIGH" } } }, InsightArn = "arn:aws:securityhub:us-west-1:123456789012:insight/123456789012/custom/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", Name = "High severity role findings" }); #endregion } public void SecurityHubUpdateOrganizationConfiguration() { #region to-update-organization-configuration-1678911630846 var client = new AmazonSecurityHubClient(); var response = client.UpdateOrganizationConfiguration(new UpdateOrganizationConfigurationRequest { AutoEnable = true }); #endregion } public void SecurityHubUpdateSecurityHubConfiguration() { #region to-update-security-hub-settings-1678912194496 var client = new AmazonSecurityHubClient(); var response = client.UpdateSecurityHubConfiguration(new UpdateSecurityHubConfigurationRequest { AutoEnableControls = true, ControlFindingGenerator = "SECURITY_CONTROL" }); #endregion } public void SecurityHubUpdateStandardsControl() { #region to-update-the-enablement-status-of-a-standard-control-1678912506444 var client = new AmazonSecurityHubClient(); var response = client.UpdateStandardsControl(new UpdateStandardsControlRequest { ControlStatus = "DISABLED", DisabledReason = "Not applicable to my service", StandardsControlArn = "arn:aws:securityhub:us-west-1:123456789012:control/pci-dss/v/3.2.1/PCI.AutoScaling.1" }); #endregion } # region ISample Members public virtual void Run() { } # endregion } }
1,221
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Amazon.SecurityToken; using AWSSDKDocSamples.Util; using Amazon.SecurityToken.Model; namespace AWSSDKDocSamples.SecurityToken { public class StsSamplesBase : ISample { private AmazonSecurityTokenServiceClient client = null; public AmazonSecurityTokenServiceClient Client { get { if (client == null) { client = new AmazonSecurityTokenServiceClient(); } return client; } } #region ISample Members public virtual void Run() { } #endregion } public class BasicSamples : StsSamplesBase { public override void Run() { BasicStsSample(); } private void BasicStsSample() { { #region Sample 1 GetSessionTokenResponse response = Client.GetSessionToken(); Credentials credentials = response.Credentials; Console.WriteLine("Access Key = {0}", credentials.AccessKeyId); Console.WriteLine("Secret Key = {0}", credentials.SecretAccessKey); Console.WriteLine("Session Token = {0}", credentials.SessionToken); Console.WriteLine("Expiration = {0}", credentials.Expiration); #endregion } { #region Sample 2 GetSessionTokenResponse response = Client.GetSessionToken(new GetSessionTokenRequest { DurationSeconds = (int)TimeSpan.FromHours(8).TotalSeconds }); Credentials credentials = response.Credentials; Console.WriteLine("Access Key = {0}", credentials.AccessKeyId); Console.WriteLine("Secret Key = {0}", credentials.SecretAccessKey); Console.WriteLine("Session Token = {0}", credentials.SessionToken); Console.WriteLine("Expiration = {0}", credentials.Expiration); #endregion } } } }
74
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.SecurityToken; using Amazon.SecurityToken.Model; namespace AWSSDKDocSamples.Amazon.SecurityToken.Generated { class SecurityTokenServiceSamples : ISample { public void SecurityTokenServiceAssumeRole() { #region to-assume-a-role-1480532402212 var client = new AmazonSecurityTokenServiceClient(); var response = client.AssumeRole(new AssumeRoleRequest { ExternalId = "123ABC", Policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Stmt1\",\"Effect\":\"Allow\",\"Action\":\"s3:ListAllMyBuckets\",\"Resource\":\"*\"}]}", RoleArn = "arn:aws:iam::123456789012:role/demo", RoleSessionName = "testAssumeRoleSession", Tags = new List<Tag> { new Tag { Key = "Project", Value = "Unicorn" }, new Tag { Key = "Team", Value = "Automation" }, new Tag { Key = "Cost-Center", Value = "12345" } }, TransitiveTagKeys = new List<string> { "Project", "Cost-Center" } }); AssumedRoleUser assumedRoleUser = response.AssumedRoleUser; Credentials credentials = response.Credentials; int packedPolicySize = response.PackedPolicySize; #endregion } public void SecurityTokenServiceAssumeRoleWithSAML() { #region to-assume-role-with-saml-14882749597814 var client = new AmazonSecurityTokenServiceClient(); var response = client.AssumeRoleWithSAML(new AssumeRoleWithSAMLRequest { DurationSeconds = 3600, PrincipalArn = "arn:aws:iam::123456789012:saml-provider/SAML-test", RoleArn = "arn:aws:iam::123456789012:role/TestSaml", SAMLAssertion = "VERYLONGENCODEDASSERTIONEXAMPLExzYW1sOkF1ZGllbmNlPmJsYW5rPC9zYW1sOkF1ZGllbmNlPjwvc2FtbDpBdWRpZW5jZVJlc3RyaWN0aW9uPjwvc2FtbDpDb25kaXRpb25zPjxzYW1sOlN1YmplY3Q+PHNhbWw6TmFtZUlEIEZvcm1hdD0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOm5hbWVpZC1mb3JtYXQ6dHJhbnNpZW50Ij5TYW1sRXhhbXBsZTwvc2FtbDpOYW1lSUQ+PHNhbWw6U3ViamVjdENvbmZpcm1hdGlvbiBNZXRob2Q9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDpjbTpiZWFyZXIiPjxzYW1sOlN1YmplY3RDb25maXJtYXRpb25EYXRhIE5vdE9uT3JBZnRlcj0iMjAxOS0xMS0wMVQyMDoyNTowNS4xNDVaIiBSZWNpcGllbnQ9Imh0dHBzOi8vc2lnbmluLmF3cy5hbWF6b24uY29tL3NhbWwiLz48L3NhbWw6U3ViamVjdENvbmZpcm1hdGlvbj48L3NhbWw6U3ViamVjdD48c2FtbDpBdXRoblN0YXRlbWVudCBBdXRoPD94bWwgdmpSZXNwb25zZT4=" }); AssumedRoleUser assumedRoleUser = response.AssumedRoleUser; string audience = response.Audience; Credentials credentials = response.Credentials; string issuer = response.Issuer; string nameQualifier = response.NameQualifier; int packedPolicySize = response.PackedPolicySize; string subject = response.Subject; string subjectType = response.SubjectType; #endregion } public void SecurityTokenServiceAssumeRoleWithWebIdentity() { #region to-assume-a-role-as-an-openid-connect-federated-user-1480533445696 var client = new AmazonSecurityTokenServiceClient(); var response = client.AssumeRoleWithWebIdentity(new AssumeRoleWithWebIdentityRequest { DurationSeconds = 3600, Policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Stmt1\",\"Effect\":\"Allow\",\"Action\":\"s3:ListAllMyBuckets\",\"Resource\":\"*\"}]}", ProviderId = "www.amazon.com", RoleArn = "arn:aws:iam::123456789012:role/FederatedWebIdentityRole", RoleSessionName = "app1", WebIdentityToken = "Atza%7CIQEBLjAsAhRFiXuWpUXuRvQ9PZL3GMFcYevydwIUFAHZwXZXXXXXXXXJnrulxKDHwy87oGKPznh0D6bEQZTSCzyoCtL_8S07pLpr0zMbn6w1lfVZKNTBdDansFBmtGnIsIapjI6xKR02Yc_2bQ8LZbUXSGm6Ry6_BG7PrtLZtj_dfCTj92xNGed-CrKqjG7nPBjNIL016GGvuS5gSvPRUxWES3VYfm1wl7WTI7jn-Pcb6M-buCgHhFOzTQxod27L9CqnOLio7N3gZAGpsp6n1-AJBOCJckcyXe2c6uD0srOJeZlKUm2eTDVMf8IehDVI0r1QOnTV6KzzAI3OY87Vd_cVMQ" }); AssumedRoleUser assumedRoleUser = response.AssumedRoleUser; string audience = response.Audience; Credentials credentials = response.Credentials; int packedPolicySize = response.PackedPolicySize; string provider = response.Provider; string subjectFromWebIdentityToken = response.SubjectFromWebIdentityToken; #endregion } public void SecurityTokenServiceDecodeAuthorizationMessage() { #region to-decode-information-about-an-authorization-status-of-a-request-1480533854499 var client = new AmazonSecurityTokenServiceClient(); var response = client.DecodeAuthorizationMessage(new DecodeAuthorizationMessageRequest { EncodedMessage = "<encoded-message>" }); string decodedMessage = response.DecodedMessage; #endregion } public void SecurityTokenServiceGetCallerIdentity() { #region to-get-details-about-a-calling-iam-user-1480540050376 var client = new AmazonSecurityTokenServiceClient(); var response = client.GetCallerIdentity(new GetCallerIdentityRequest { }); string account = response.Account; string arn = response.Arn; string userId = response.UserId; #endregion } public void SecurityTokenServiceGetCallerIdentity() { #region to-get-details-about-a-calling-user-federated-with-assumerole-1480540158545 var client = new AmazonSecurityTokenServiceClient(); var response = client.GetCallerIdentity(new GetCallerIdentityRequest { }); string account = response.Account; string arn = response.Arn; string userId = response.UserId; #endregion } public void SecurityTokenServiceGetCallerIdentity() { #region to-get-details-about-a-calling-user-federated-with-getfederationtoken-1480540231316 var client = new AmazonSecurityTokenServiceClient(); var response = client.GetCallerIdentity(new GetCallerIdentityRequest { }); string account = response.Account; string arn = response.Arn; string userId = response.UserId; #endregion } public void SecurityTokenServiceGetFederationToken() { #region to-get-temporary-credentials-for-a-role-by-using-getfederationtoken-1480540749900 var client = new AmazonSecurityTokenServiceClient(); var response = client.GetFederationToken(new GetFederationTokenRequest { DurationSeconds = 3600, Name = "testFedUserSession", Policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Stmt1\",\"Effect\":\"Allow\",\"Action\":\"s3:ListAllMyBuckets\",\"Resource\":\"*\"}]}", Tags = new List<Tag> { new Tag { Key = "Project", Value = "Pegasus" }, new Tag { Key = "Cost-Center", Value = "98765" } } }); Credentials credentials = response.Credentials; FederatedUser federatedUser = response.FederatedUser; int packedPolicySize = response.PackedPolicySize; #endregion } public void SecurityTokenServiceGetSessionToken() { #region to-get-temporary-credentials-for-an-iam-user-or-an-aws-account-1480540814038 var client = new AmazonSecurityTokenServiceClient(); var response = client.GetSessionToken(new GetSessionTokenRequest { DurationSeconds = 3600, SerialNumber = "YourMFASerialNumber", TokenCode = "123456" }); Credentials credentials = response.Credentials; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
220
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.ServiceDiscovery; using Amazon.ServiceDiscovery.Model; namespace AWSSDKDocSamples.Amazon.ServiceDiscovery.Generated { class ServiceDiscoverySamples : ISample { public void ServiceDiscoveryCreateHttpNamespace() { #region createhttpnamespace-example-1590114811304 var client = new AmazonServiceDiscoveryClient(); var response = client.CreateHttpNamespace(new CreateHttpNamespaceRequest { CreatorRequestId = "example-creator-request-id-0001", Description = "Example.com AWS Cloud Map HTTP Namespace", Name = "example-http.com" }); string operationId = response.OperationId; #endregion } public void ServiceDiscoveryCreatePrivateDnsNamespace() { #region example-create-private-dns-namespace-1587058592930 var client = new AmazonServiceDiscoveryClient(); var response = client.CreatePrivateDnsNamespace(new CreatePrivateDnsNamespaceRequest { CreatorRequestId = "eedd6892-50f3-41b2-8af9-611d6e1d1a8c", Name = "example.com", Vpc = "vpc-1c56417b" }); string operationId = response.OperationId; #endregion } public void ServiceDiscoveryCreatePublicDnsNamespace() { #region createpublicdnsnamespace-example-1590114940910 var client = new AmazonServiceDiscoveryClient(); var response = client.CreatePublicDnsNamespace(new CreatePublicDnsNamespaceRequest { CreatorRequestId = "example-creator-request-id-0003", Description = "Example.com AWS Cloud Map Public DNS Namespace", Name = "example-public-dns.com" }); string operationId = response.OperationId; #endregion } public void ServiceDiscoveryCreateService() { #region example-create-service-1587235913584 var client = new AmazonServiceDiscoveryClient(); var response = client.CreateService(new CreateServiceRequest { CreatorRequestId = "567c1193-6b00-4308-bd57-ad38a8822d25", DnsConfig = new DnsConfig { DnsRecords = new List<DnsRecord> { new DnsRecord { TTL = 60, Type = "A" } }, NamespaceId = "ns-ylexjili4cdxy3xm", RoutingPolicy = "MULTIVALUE" }, Name = "myservice", NamespaceId = "ns-ylexjili4cdxy3xm" }); Service service = response.Service; #endregion } public void ServiceDiscoveryDeleteNamespace() { #region example-delete-namespace-1587416093508 var client = new AmazonServiceDiscoveryClient(); var response = client.DeleteNamespace(new DeleteNamespaceRequest { Id = "ns-ylexjili4cdxy3xm" }); string operationId = response.OperationId; #endregion } public void ServiceDiscoveryDeleteService() { #region example-delete-service-1587416462902 var client = new AmazonServiceDiscoveryClient(); var response = client.DeleteService(new DeleteServiceRequest { Id = "srv-p5zdwlg5uvvzjita" }); #endregion } public void ServiceDiscoveryDeregisterInstance() { #region example-deregister-a-service-instance-1587416305738 var client = new AmazonServiceDiscoveryClient(); var response = client.DeregisterInstance(new DeregisterInstanceRequest { InstanceId = "myservice-53", ServiceId = "srv-p5zdwlg5uvvzjita" }); string operationId = response.OperationId; #endregion } public void ServiceDiscoveryDiscoverInstances() { #region example-discover-registered-instances-1587236343568 var client = new AmazonServiceDiscoveryClient(); var response = client.DiscoverInstances(new DiscoverInstancesRequest { HealthStatus = "ALL", MaxResults = 10, NamespaceName = "example.com", ServiceName = "myservice" }); List<HttpInstanceSummary> instances = response.Instances; #endregion } public void ServiceDiscoveryGetInstance() { #region getinstance-example-1590115065598 var client = new AmazonServiceDiscoveryClient(); var response = client.GetInstance(new GetInstanceRequest { InstanceId = "i-abcd1234", ServiceId = "srv-e4anhexample0004" }); Instance instance = response.Instance; #endregion } public void ServiceDiscoveryGetInstancesHealthStatus() { #region getinstanceshealthstatus-example-1590115176146 var client = new AmazonServiceDiscoveryClient(); var response = client.GetInstancesHealthStatus(new GetInstancesHealthStatusRequest { ServiceId = "srv-e4anhexample0004" }); Dictionary<string, string> status = response.Status; #endregion } public void ServiceDiscoveryGetNamespace() { #region getnamespace-example-1590115383708 var client = new AmazonServiceDiscoveryClient(); var response = client.GetNamespace(new GetNamespaceRequest { Id = "ns-e4anhexample0004" }); Namespace awsNamespace = response.Namespace; #endregion } public void ServiceDiscoveryGetOperation() { #region example-get-operation-result-1587073807124 var client = new AmazonServiceDiscoveryClient(); var response = client.GetOperation(new GetOperationRequest { OperationId = "gv4g5meo7ndmeh4fqskygvk23d2fijwa-k9302yzd" }); Operation operation = response.Operation; #endregion } public void ServiceDiscoveryGetService() { #region getservice-example-1590117234294 var client = new AmazonServiceDiscoveryClient(); var response = client.GetService(new GetServiceRequest { Id = "srv-e4anhexample0004" }); Service service = response.Service; #endregion } public void ServiceDiscoveryListInstances() { #region example-list-service-instances-1587236237008 var client = new AmazonServiceDiscoveryClient(); var response = client.ListInstances(new ListInstancesRequest { ServiceId = "srv-qzpwvt2tfqcegapy" }); List<InstanceSummary> instances = response.Instances; #endregion } public void ServiceDiscoveryListNamespaces() { #region example-list-namespaces-1587401553154 var client = new AmazonServiceDiscoveryClient(); var response = client.ListNamespaces(new ListNamespacesRequest { }); List<NamespaceSummary> namespaces = response.Namespaces; #endregion } public void ServiceDiscoveryListOperations() { #region listoperations-example-1590117354396 var client = new AmazonServiceDiscoveryClient(); var response = client.ListOperations(new ListOperationsRequest { Filters = new List<OperationFilter> { new OperationFilter { Condition = "IN", Name = "STATUS", Values = new List<string> { "PENDING", "SUCCESS" } } } }); List<OperationSummary> operations = response.Operations; #endregion } public void ServiceDiscoveryListServices() { #region example-list-services-1587236889840 var client = new AmazonServiceDiscoveryClient(); var response = client.ListServices(new ListServicesRequest { }); List<ServiceSummary> services = response.Services; #endregion } public void ServiceDiscoveryListTagsForResource() { #region listtagsforresource-example-1590093928416 var client = new AmazonServiceDiscoveryClient(); var response = client.ListTagsForResource(new ListTagsForResourceRequest { ResourceARN = "arn:aws:servicediscovery:us-east-1:123456789012:namespace/ns-ylexjili4cdxy3xm" }); List<Tag> tags = response.Tags; #endregion } public void ServiceDiscoveryRegisterInstance() { #region example-register-instance-1587236116314 var client = new AmazonServiceDiscoveryClient(); var response = client.RegisterInstance(new RegisterInstanceRequest { Attributes = new Dictionary<string, string> { { "AWS_INSTANCE_IPV4", "172.2.1.3" }, { "AWS_INSTANCE_PORT", "808" } }, CreatorRequestId = "7a48a98a-72e6-4849-bfa7-1a458e030d7b", InstanceId = "myservice-53", ServiceId = "srv-p5zdwlg5uvvzjita" }); string operationId = response.OperationId; #endregion } public void ServiceDiscoveryTagResource() { #region tagresource-example-1590093532240 var client = new AmazonServiceDiscoveryClient(); var response = client.TagResource(new TagResourceRequest { ResourceARN = "arn:aws:servicediscovery:us-east-1:123456789012:namespace/ns-ylexjili4cdxy3xm", Tags = new List<Tag> { new Tag { Key = "Department", Value = "Engineering" }, new Tag { Key = "Project", Value = "Zeta" } } }); #endregion } public void ServiceDiscoveryUntagResource() { #region untagresource-example-1590094024672 var client = new AmazonServiceDiscoveryClient(); var response = client.UntagResource(new UntagResourceRequest { ResourceARN = "arn:aws:servicediscovery:us-east-1:123456789012:namespace/ns-ylexjili4cdxy3xm", TagKeys = new List<string> { "Project", "Department" } }); #endregion } public void ServiceDiscoveryUpdateInstanceCustomHealthStatus() { #region updateinstancecustomhealthstatus-example-1590118408574 var client = new AmazonServiceDiscoveryClient(); var response = client.UpdateInstanceCustomHealthStatus(new UpdateInstanceCustomHealthStatusRequest { InstanceId = "i-abcd1234", ServiceId = "srv-e4anhexample0004", Status = "HEALTHY" }); #endregion } public void ServiceDiscoveryUpdateService() { #region updateservice-example-1590117830880 var client = new AmazonServiceDiscoveryClient(); var response = client.UpdateService(new UpdateServiceRequest { Id = "srv-e4anhexample0004", Service = new ServiceChange { DnsConfig = new DnsConfigChange { DnsRecords = new List<DnsRecord> { new DnsRecord { TTL = 60, Type = "A" } } }, HealthCheckConfig = new HealthCheckConfig { FailureThreshold = 2, ResourcePath = "/", Type = "HTTP" } } }); string operationId = response.OperationId; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
429
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.SimpleEmail; using Amazon.SimpleEmail.Model; using System.IO; namespace AWSSDKDocSamples.SES { class SESSamples : ISample { public static void SESSendEmail() { #region SESSendEmail var sesClient = new AmazonSimpleEmailServiceClient(); var dest = new Destination { ToAddresses = new List<string>() { "[email protected]" }, CcAddresses = new List<string>() { "[email protected]" } }; var from = "[email protected]"; var subject = new Content("You're invited to the meeting"); var body = new Body(new Content("Please join us Monday at 7:00 PM.")); var msg = new Message(subject, body); var request = new SendEmailRequest { Destination = dest, Message = msg, Source = from }; sesClient.SendEmail(request); #endregion } public static void SESSendRawEmail() { #region SESSendRawEmail // using System.IO; var sesClient = new AmazonSimpleEmailServiceClient(); var stream = new MemoryStream( Encoding.UTF8.GetBytes("From: [email protected]\n" + "To: [email protected]\n" + "Subject: You're invited to the meeting\n" + "Content-Type: text/plain\n\n" + "Please join us Monday at 7:00 PM.") ); var raw = new RawMessage { Data = stream }; var to = new List<string>() { "[email protected]" }; var from = "[email protected]"; var request = new SendRawEmailRequest { Destinations = to, RawMessage = raw, Source = from }; sesClient.SendRawEmail(request); #endregion } public static void SESGetSendQuota() { #region SESGetSendQuota var sesClient = new AmazonSimpleEmailServiceClient(); var response = sesClient.GetSendQuota(); Console.WriteLine("Maximum emails that can be sent each 24 hours: " + response.Max24HourSend); Console.WriteLine("Maximum emails that can be sent per second: " + response.MaxSendRate); Console.WriteLine("Number of emails sent in last 24 hours: " + response.SentLast24Hours); #endregion Console.ReadLine(); } public static void SESSetIdentityFeedbackForwardingEnabled() { #region SESSetIdentityFeedbackForwardingEnabled var sesClient = new AmazonSimpleEmailServiceClient(); var request = new SetIdentityFeedbackForwardingEnabledRequest { ForwardingEnabled = true, Identity = "[email protected]" }; sesClient.SetIdentityFeedbackForwardingEnabled(request); #endregion } public static void SESListIdentities() { #region SESListIdentities var sesClient = new AmazonSimpleEmailServiceClient(); var response = sesClient.ListIdentities(); if (response.Identities.Count > 0) { Console.WriteLine("Identities:"); foreach (var identity in response.Identities) { Console.WriteLine(" " + identity); } } #endregion Console.ReadLine(); } public static void SESListVerifiedEmailAddresses() { #region SESListVerifiedEmailAddresses var sesClient = new AmazonSimpleEmailServiceClient(); var response = sesClient.ListVerifiedEmailAddresses(); if (response.VerifiedEmailAddresses.Count > 0) { Console.WriteLine("Verified email addresses:"); foreach (var address in response.VerifiedEmailAddresses) { Console.WriteLine(" " + address); } } #endregion Console.ReadLine(); } public static void SESGetSendStatistics() { #region SESGetSendStatistics var sesClient = new AmazonSimpleEmailServiceClient(); var response = sesClient.GetSendStatistics(); Console.WriteLine("For request " + response.ResponseMetadata.RequestId + ":"); if (response.SendDataPoints.Count > 0) { foreach (var point in response.SendDataPoints) { Console.WriteLine(); Console.WriteLine("Data points for " + point.Timestamp + ":"); Console.WriteLine(" Bounces: " + point.Bounces); Console.WriteLine(" Complaints: " + point.Complaints); Console.WriteLine(" Delivery Attempts: " + point.DeliveryAttempts); Console.WriteLine(" Rejects: " + point.Rejects); } } else { Console.WriteLine("No data points."); } #endregion Console.ReadLine(); } public static void SESGetIdentityNotificationAttributes() { #region SESGetIdentityNotificationAttributes var sesClient = new AmazonSimpleEmailServiceClient(); var idsResponse = sesClient.ListIdentities(); if (idsResponse.Identities.Count > 0) { var request = new GetIdentityNotificationAttributesRequest { Identities = idsResponse.Identities }; var response = sesClient.GetIdentityNotificationAttributes(request); foreach (var attr in response.NotificationAttributes) { Console.WriteLine(attr.Key); Console.WriteLine(" Bounce Topic: " + attr.Value.BounceTopic); Console.WriteLine(" Complaint Topic: " + attr.Value.ComplaintTopic); Console.WriteLine(" Forwarding Enabled: " + attr.Value.ForwardingEnabled); Console.WriteLine(); } } #endregion Console.ReadLine(); } public static void SESSetIdentityDkimEnabled() { #region SESSetIdentityDkimEnabled var sesClient = new AmazonSimpleEmailServiceClient(); var request = new SetIdentityDkimEnabledRequest { DkimEnabled = false, Identity = "[email protected]" }; sesClient.SetIdentityDkimEnabled(request); #endregion } public static void SESGetIdentityVerificationAttributes() { #region SESGetIdentityVerificationAttributes var sesClient = new AmazonSimpleEmailServiceClient(); var idsResponse = sesClient.ListIdentities(); if (idsResponse.Identities.Count > 0) { var request = new GetIdentityVerificationAttributesRequest { Identities = idsResponse.Identities }; var response = sesClient.GetIdentityVerificationAttributes(request); foreach (var attr in response.VerificationAttributes) { Console.WriteLine(attr.Key); Console.WriteLine(" Verification Status: " + attr.Value.VerificationStatus.Value); Console.WriteLine(" Verification Token: " + attr.Value.VerificationToken); Console.WriteLine(); } }; #endregion Console.ReadLine(); } public static void SESVerifyEmailAddress() { #region SESVerifyEmailAddress var sesClient = new AmazonSimpleEmailServiceClient(); var request = new VerifyEmailAddressRequest { EmailAddress = "[email protected]" }; sesClient.VerifyEmailAddress(request); #endregion } public static void SESVerifyEmailIdentity() { #region SESVerifyEmailIdentity var sesClient = new AmazonSimpleEmailServiceClient(); var request = new VerifyEmailIdentityRequest { EmailAddress = "[email protected]" }; sesClient.VerifyEmailIdentity(request); #endregion } public static void SESGetIdentityDkimAttributes() { #region SESGetIdentityDkimAttributes var sesClient = new AmazonSimpleEmailServiceClient(); var idsResponse = sesClient.ListIdentities(); if (idsResponse.Identities.Count > 0) { var request = new GetIdentityDkimAttributesRequest { Identities = idsResponse.Identities }; var response = sesClient.GetIdentityDkimAttributes(request); foreach (var attr in response.DkimAttributes) { Console.WriteLine(attr.Key); Console.WriteLine(" DKIM Enabled: " + attr.Value.DkimEnabled); Console.WriteLine(" DKIM Verification Status: " + attr.Value.DkimVerificationStatus.Value); if (attr.Value.DkimTokens.Count > 0) { Console.WriteLine(" DKIM Tokens: "); foreach (var token in attr.Value.DkimTokens) { Console.WriteLine(" " + token); } } Console.WriteLine(); } }; #endregion Console.ReadLine(); } public static void SESSetIdentityNotificationTopic() { #region SESSetIdentityNotificationTopic var sesClient = new AmazonSimpleEmailServiceClient(); var bounceRequest = new SetIdentityNotificationTopicRequest { Identity = "[email protected]", NotificationType = NotificationType.Bounce, SnsTopic = "arn:aws:sns:us-east-1:80398EXAMPLE:CodingTestResults" }; sesClient.SetIdentityNotificationTopic(bounceRequest); var complaintRequest = new SetIdentityNotificationTopicRequest { Identity = "[email protected]", NotificationType = NotificationType.Complaint, SnsTopic = "arn:aws:sns:us-east-1:80398EXAMPLE:CodingTestResults" }; sesClient.SetIdentityNotificationTopic(complaintRequest); #endregion } public static void SESDeleteVerifiedEmailAddress() { #region SESDeleteVerifiedEmailAddress var sesClient = new AmazonSimpleEmailServiceClient(); var request = new DeleteVerifiedEmailAddressRequest { EmailAddress = "[email protected]" }; sesClient.DeleteVerifiedEmailAddress(request); #endregion } public static void SESVerifyDomainIdentity() { #region SESVerifyDomainIdentity var sesClient = new AmazonSimpleEmailServiceClient(); var request = new VerifyDomainIdentityRequest { Domain = "example.com" }; var response = sesClient.VerifyDomainIdentity(request); Console.WriteLine("Verification token: " + response.VerificationToken); #endregion Console.ReadLine(); } public static void SESVerifyDomainDkim() { #region SESVerifyDomainDkim var sesClient = new AmazonSimpleEmailServiceClient(); var request = new VerifyDomainDkimRequest { Domain = "example.com" }; var response = sesClient.VerifyDomainDkim(request); Console.WriteLine("DKIM tokens:"); foreach (var token in response.DkimTokens) { Console.WriteLine(" " + token); } #endregion Console.ReadLine(); } public static void SESDeleteIdentity() { #region SESDeleteIdentity var sesClient = new AmazonSimpleEmailServiceClient(); var request = new DeleteIdentityRequest { Identity = "[email protected]" }; sesClient.DeleteIdentity(request); #endregion } #region ISample Members public virtual void Run() { } #endregion } }
429
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.SimpleEmail; using Amazon.SimpleEmail.Model; namespace AWSSDKDocSamples.Amazon.SimpleEmail.Generated { class SimpleEmailServiceSamples : ISample { public void SimpleEmailServiceCloneReceiptRuleSet() { #region clonereceiptruleset-1469055039770 var client = new AmazonSimpleEmailServiceClient(); var response = client.CloneReceiptRuleSet(new CloneReceiptRuleSetRequest { OriginalRuleSetName = "RuleSetToClone", RuleSetName = "RuleSetToCreate" }); #endregion } public void SimpleEmailServiceCreateReceiptFilter() { #region createreceiptfilter-1469122681253 var client = new AmazonSimpleEmailServiceClient(); var response = client.CreateReceiptFilter(new CreateReceiptFilterRequest { Filter = new ReceiptFilter { IpFilter = new ReceiptIpFilter { Cidr = "1.2.3.4/24", Policy = "Allow" }, Name = "MyFilter" } }); #endregion } public void SimpleEmailServiceCreateReceiptRule() { #region createreceiptrule-1469122946515 var client = new AmazonSimpleEmailServiceClient(); var response = client.CreateReceiptRule(new CreateReceiptRuleRequest { After = "", Rule = new ReceiptRule { Actions = new List<ReceiptAction> { new ReceiptAction { S3Action = new S3Action { BucketName = "MyBucket", ObjectKeyPrefix = "email" } } }, Enabled = true, Name = "MyRule", ScanEnabled = true, TlsPolicy = "Optional" }, RuleSetName = "MyRuleSet" }); #endregion } public void SimpleEmailServiceCreateReceiptRuleSet() { #region createreceiptruleset-1469058761646 var client = new AmazonSimpleEmailServiceClient(); var response = client.CreateReceiptRuleSet(new CreateReceiptRuleSetRequest { RuleSetName = "MyRuleSet" }); #endregion } public void SimpleEmailServiceDeleteIdentity() { #region deleteidentity-1469047858906 var client = new AmazonSimpleEmailServiceClient(); var response = client.DeleteIdentity(new DeleteIdentityRequest { Identity = "[email protected]" }); #endregion } public void SimpleEmailServiceDeleteIdentityPolicy() { #region deleteidentitypolicy-1469055282499 var client = new AmazonSimpleEmailServiceClient(); var response = client.DeleteIdentityPolicy(new DeleteIdentityPolicyRequest { Identity = "[email protected]", PolicyName = "MyPolicy" }); #endregion } public void SimpleEmailServiceDeleteReceiptFilter() { #region deletereceiptfilter-1469055456835 var client = new AmazonSimpleEmailServiceClient(); var response = client.DeleteReceiptFilter(new DeleteReceiptFilterRequest { FilterName = "MyFilter" }); #endregion } public void SimpleEmailServiceDeleteReceiptRule() { #region deletereceiptrule-1469055563599 var client = new AmazonSimpleEmailServiceClient(); var response = client.DeleteReceiptRule(new DeleteReceiptRuleRequest { RuleName = "MyRule", RuleSetName = "MyRuleSet" }); #endregion } public void SimpleEmailServiceDeleteReceiptRuleSet() { #region deletereceiptruleset-1469055713690 var client = new AmazonSimpleEmailServiceClient(); var response = client.DeleteReceiptRuleSet(new DeleteReceiptRuleSetRequest { RuleSetName = "MyRuleSet" }); #endregion } public void SimpleEmailServiceDeleteVerifiedEmailAddress() { #region deleteverifiedemailaddress-1469051086444 var client = new AmazonSimpleEmailServiceClient(); var response = client.DeleteVerifiedEmailAddress(new DeleteVerifiedEmailAddressRequest { EmailAddress = "[email protected]" }); #endregion } public void SimpleEmailServiceDescribeActiveReceiptRuleSet() { #region describeactivereceiptruleset-1469121611502 var client = new AmazonSimpleEmailServiceClient(); var response = client.DescribeActiveReceiptRuleSet(new DescribeActiveReceiptRuleSetRequest { }); ReceiptRuleSetMetadata metadata = response.Metadata; List<ReceiptRule> rules = response.Rules; #endregion } public void SimpleEmailServiceDescribeReceiptRule() { #region describereceiptrule-1469055813118 var client = new AmazonSimpleEmailServiceClient(); var response = client.DescribeReceiptRule(new DescribeReceiptRuleRequest { RuleName = "MyRule", RuleSetName = "MyRuleSet" }); ReceiptRule rule = response.Rule; #endregion } public void SimpleEmailServiceDescribeReceiptRuleSet() { #region describereceiptruleset-1469121240385 var client = new AmazonSimpleEmailServiceClient(); var response = client.DescribeReceiptRuleSet(new DescribeReceiptRuleSetRequest { RuleSetName = "MyRuleSet" }); ReceiptRuleSetMetadata metadata = response.Metadata; List<ReceiptRule> rules = response.Rules; #endregion } public void SimpleEmailServiceGetAccountSendingEnabled() { #region getaccountsendingenabled-1469047741333 var client = new AmazonSimpleEmailServiceClient(); var response = client.GetAccountSendingEnabled(new GetAccountSendingEnabledRequest { }); bool enabled = response.Enabled; #endregion } public void SimpleEmailServiceGetIdentityDkimAttributes() { #region getidentitydkimattributes-1469050695628 var client = new AmazonSimpleEmailServiceClient(); var response = client.GetIdentityDkimAttributes(new GetIdentityDkimAttributesRequest { Identities = new List<string> { "example.com", "[email protected]" } }); Dictionary<string, IdentityDkimAttributes> dkimAttributes = response.DkimAttributes; #endregion } public void SimpleEmailServiceGetIdentityMailFromDomainAttributes() { #region getidentitymailfromdomainattributes-1469123114860 var client = new AmazonSimpleEmailServiceClient(); var response = client.GetIdentityMailFromDomainAttributes(new GetIdentityMailFromDomainAttributesRequest { Identities = new List<string> { "example.com" } }); Dictionary<string, IdentityMailFromDomainAttributes> mailFromDomainAttributes = response.MailFromDomainAttributes; #endregion } public void SimpleEmailServiceGetIdentityNotificationAttributes() { #region getidentitynotificationattributes-1469123466947 var client = new AmazonSimpleEmailServiceClient(); var response = client.GetIdentityNotificationAttributes(new GetIdentityNotificationAttributesRequest { Identities = new List<string> { "example.com" } }); Dictionary<string, IdentityNotificationAttributes> notificationAttributes = response.NotificationAttributes; #endregion } public void SimpleEmailServiceGetIdentityPolicies() { #region getidentitypolicies-1469123949351 var client = new AmazonSimpleEmailServiceClient(); var response = client.GetIdentityPolicies(new GetIdentityPoliciesRequest { Identity = "example.com", PolicyNames = new List<string> { "MyPolicy" } }); Dictionary<string, string> policies = response.Policies; #endregion } public void SimpleEmailServiceGetIdentityVerificationAttributes() { #region getidentityverificationattributes-1469124205897 var client = new AmazonSimpleEmailServiceClient(); var response = client.GetIdentityVerificationAttributes(new GetIdentityVerificationAttributesRequest { Identities = new List<string> { "example.com" } }); Dictionary<string, IdentityVerificationAttributes> verificationAttributes = response.VerificationAttributes; #endregion } public void SimpleEmailServiceGetSendQuota() { #region getsendquota-1469047324508 var client = new AmazonSimpleEmailServiceClient(); var response = client.GetSendQuota(new GetSendQuotaRequest { }); double max24HourSend = response.Max24HourSend; double maxSendRate = response.MaxSendRate; double sentLast24Hours = response.SentLast24Hours; #endregion } public void SimpleEmailServiceGetSendStatistics() { #region getsendstatistics-1469047741329 var client = new AmazonSimpleEmailServiceClient(); var response = client.GetSendStatistics(new GetSendStatisticsRequest { }); List<SendDataPoint> sendDataPoints = response.SendDataPoints; #endregion } public void SimpleEmailServiceListIdentities() { #region listidentities-1469048638493 var client = new AmazonSimpleEmailServiceClient(); var response = client.ListIdentities(new ListIdentitiesRequest { IdentityType = "EmailAddress", MaxItems = 123, NextToken = "" }); List<string> identities = response.Identities; string nextToken = response.NextToken; #endregion } public void SimpleEmailServiceListIdentityPolicies() { #region listidentitypolicies-1469124417674 var client = new AmazonSimpleEmailServiceClient(); var response = client.ListIdentityPolicies(new ListIdentityPoliciesRequest { Identity = "example.com" }); List<string> policyNames = response.PolicyNames; #endregion } public void SimpleEmailServiceListReceiptFilters() { #region listreceiptfilters-1469120786789 var client = new AmazonSimpleEmailServiceClient(); var response = client.ListReceiptFilters(new ListReceiptFiltersRequest { }); List<ReceiptFilter> filters = response.Filters; #endregion } public void SimpleEmailServiceListReceiptRuleSets() { #region listreceiptrulesets-1469121037235 var client = new AmazonSimpleEmailServiceClient(); var response = client.ListReceiptRuleSets(new ListReceiptRuleSetsRequest { NextToken = "" }); string nextToken = response.NextToken; List<ReceiptRuleSetMetadata> ruleSets = response.RuleSets; #endregion } public void SimpleEmailServiceListVerifiedEmailAddresses() { #region listverifiedemailaddresses-1469051402570 var client = new AmazonSimpleEmailServiceClient(); var response = client.ListVerifiedEmailAddresses(new ListVerifiedEmailAddressesRequest { }); List<string> verifiedEmailAddresses = response.VerifiedEmailAddresses; #endregion } public void SimpleEmailServicePutIdentityPolicy() { #region putidentitypolicy-1469124560016 var client = new AmazonSimpleEmailServiceClient(); var response = client.PutIdentityPolicy(new PutIdentityPolicyRequest { Identity = "example.com", Policy = "{\"Version\":\"2008-10-17\",\"Statement\":[{\"Sid\":\"stmt1469123904194\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::123456789012:root\"},\"Action\":[\"ses:SendEmail\",\"ses:SendRawEmail\"],\"Resource\":\"arn:aws:ses:us-east-1:EXAMPLE65304:identity/example.com\"}]}", PolicyName = "MyPolicy" }); #endregion } public void SimpleEmailServiceReorderReceiptRuleSet() { #region reorderreceiptruleset-1469058156806 var client = new AmazonSimpleEmailServiceClient(); var response = client.ReorderReceiptRuleSet(new ReorderReceiptRuleSetRequest { RuleNames = new List<string> { "MyRule", "MyOtherRule" }, RuleSetName = "MyRuleSet" }); #endregion } public void SimpleEmailServiceSendEmail() { #region sendemail-1469049656296 var client = new AmazonSimpleEmailServiceClient(); var response = client.SendEmail(new SendEmailRequest { Destination = new Destination { BccAddresses = new List<string> { }, CcAddresses = new List<string> { "[email protected]" }, ToAddresses = new List<string> { "[email protected]", "[email protected]" } }, Message = new Message { Body = new Body { Html = new Content { Charset = "UTF-8", Data = "This message body contains HTML formatting. It can, for example, contain links like this one: <a class=\"ulink\" href=\"http://docs.aws.amazon.com/ses/latest/DeveloperGuide\" target=\"_blank\">Amazon SES Developer Guide</a>." }, Text = new Content { Charset = "UTF-8", Data = "This is the message body in text format." } }, Subject = new Content { Charset = "UTF-8", Data = "Test email" } }, ReplyToAddresses = new List<string> { }, ReturnPath = "", ReturnPathArn = "", Source = "[email protected]", SourceArn = "" }); string messageId = response.MessageId; #endregion } public void SimpleEmailServiceSendRawEmail() { #region sendrawemail-1469118548649 var client = new AmazonSimpleEmailServiceClient(); var response = client.SendRawEmail(new SendRawEmailRequest { Destinations = new List<string> { }, FromArn = "", RawMessage = new RawMessage { Data = new MemoryStream(From: [email protected]\nTo: [email protected]\nSubject: Test email (contains an attachment)\nMIME-Version: 1.0\nContent-type: Multipart/Mixed; boundary="NextPart"\n\n--NextPart\nContent-Type: text/plain\n\nThis is the message body.\n\n--NextPart\nContent-Type: text/plain;\nContent-Disposition: attachment; filename="attachment.txt"\n\nThis is the text in the attachment.\n\n--NextPart--) }, ReturnPathArn = "", Source = "", SourceArn = "" }); string messageId = response.MessageId; #endregion } public void SimpleEmailServiceSetActiveReceiptRuleSet() { #region setactivereceiptruleset-1469058391329 var client = new AmazonSimpleEmailServiceClient(); var response = client.SetActiveReceiptRuleSet(new SetActiveReceiptRuleSetRequest { RuleSetName = "RuleSetToActivate" }); #endregion } public void SimpleEmailServiceSetIdentityDkimEnabled() { #region setidentitydkimenabled-1469057485202 var client = new AmazonSimpleEmailServiceClient(); var response = client.SetIdentityDkimEnabled(new SetIdentityDkimEnabledRequest { DkimEnabled = true, Identity = "[email protected]" }); #endregion } public void SimpleEmailServiceSetIdentityFeedbackForwardingEnabled() { #region setidentityfeedbackforwardingenabled-1469056811329 var client = new AmazonSimpleEmailServiceClient(); var response = client.SetIdentityFeedbackForwardingEnabled(new SetIdentityFeedbackForwardingEnabledRequest { ForwardingEnabled = true, Identity = "[email protected]" }); #endregion } public void SimpleEmailServiceSetIdentityHeadersInNotificationsEnabled() { #region setidentityheadersinnotificationsenabled-1469057295001 var client = new AmazonSimpleEmailServiceClient(); var response = client.SetIdentityHeadersInNotificationsEnabled(new SetIdentityHeadersInNotificationsEnabledRequest { Enabled = true, Identity = "[email protected]", NotificationType = "Bounce" }); #endregion } public void SimpleEmailServiceSetIdentityMailFromDomain() { #region setidentitymailfromdomain-1469057693908 var client = new AmazonSimpleEmailServiceClient(); var response = client.SetIdentityMailFromDomain(new SetIdentityMailFromDomainRequest { BehaviorOnMXFailure = "UseDefaultValue", Identity = "[email protected]", MailFromDomain = "bounces.example.com" }); #endregion } public void SimpleEmailServiceSetIdentityNotificationTopic() { #region setidentitynotificationtopic-1469057854966 var client = new AmazonSimpleEmailServiceClient(); var response = client.SetIdentityNotificationTopic(new SetIdentityNotificationTopicRequest { Identity = "[email protected]", NotificationType = "Bounce", SnsTopic = "arn:aws:sns:us-west-2:111122223333:MyTopic" }); #endregion } public void SimpleEmailServiceSetReceiptRulePosition() { #region setreceiptruleposition-1469058530550 var client = new AmazonSimpleEmailServiceClient(); var response = client.SetReceiptRulePosition(new SetReceiptRulePositionRequest { After = "PutRuleAfterThisRule", RuleName = "RuleToReposition", RuleSetName = "MyRuleSet" }); #endregion } public void SimpleEmailServiceUpdateAccountSendingEnabled() { #region updateaccountsendingenabled-1469047741333 var client = new AmazonSimpleEmailServiceClient(); var response = client.UpdateAccountSendingEnabled(new UpdateAccountSendingEnabledRequest { Enabled = true }); #endregion } public void SimpleEmailServiceUpdateConfigurationSetReputationMetricsEnabled() { #region updateconfigurationsetreputationmetricsenabled-2362747741333 var client = new AmazonSimpleEmailServiceClient(); var response = client.UpdateConfigurationSetReputationMetricsEnabled(new UpdateConfigurationSetReputationMetricsEnabledRequest { ConfigurationSetName = "foo", Enabled = true }); #endregion } public void SimpleEmailServiceUpdateConfigurationSetSendingEnabled() { #region updateconfigurationsetsendingenabled-2362747741333 var client = new AmazonSimpleEmailServiceClient(); var response = client.UpdateConfigurationSetSendingEnabled(new UpdateConfigurationSetSendingEnabledRequest { ConfigurationSetName = "foo", Enabled = true }); #endregion } public void SimpleEmailServiceUpdateReceiptRule() { #region updatereceiptrule-1469051756940 var client = new AmazonSimpleEmailServiceClient(); var response = client.UpdateReceiptRule(new UpdateReceiptRuleRequest { Rule = new ReceiptRule { Actions = new List<ReceiptAction> { new ReceiptAction { S3Action = new S3Action { BucketName = "MyBucket", ObjectKeyPrefix = "email" } } }, Enabled = true, Name = "MyRule", ScanEnabled = true, TlsPolicy = "Optional" }, RuleSetName = "MyRuleSet" }); #endregion } public void SimpleEmailServiceVerifyDomainDkim() { #region verifydomaindkim-1469049503083 var client = new AmazonSimpleEmailServiceClient(); var response = client.VerifyDomainDkim(new VerifyDomainDkimRequest { Domain = "example.com" }); List<string> dkimTokens = response.DkimTokens; #endregion } public void SimpleEmailServiceVerifyDomainIdentity() { #region verifydomainidentity-1469049165936 var client = new AmazonSimpleEmailServiceClient(); var response = client.VerifyDomainIdentity(new VerifyDomainIdentityRequest { Domain = "example.com" }); string verificationToken = response.VerificationToken; #endregion } public void SimpleEmailServiceVerifyEmailAddress() { #region verifyemailaddress-1469048849187 var client = new AmazonSimpleEmailServiceClient(); var response = client.VerifyEmailAddress(new VerifyEmailAddressRequest { EmailAddress = "[email protected]" }); #endregion } public void SimpleEmailServiceVerifyEmailIdentity() { #region verifyemailidentity-1469049068623 var client = new AmazonSimpleEmailServiceClient(); var response = client.VerifyEmailIdentity(new VerifyEmailIdentityRequest { EmailAddress = "[email protected]" }); #endregion } # region ISample Members public virtual void Run() { } # endregion } }
781
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.SimpleEmailV2; using Amazon.SimpleEmailV2.Model; namespace AWSSDKDocSamples.Amazon.SimpleEmailV2.Generated { class SimpleEmailServiceV2Samples : ISample { public void SimpleEmailServiceV2PutDedicatedIpPoolScalingAttributes() { #region put-dedicated-ip-pool-scaling-attributes-example-1683639172 var client = new AmazonSimpleEmailServiceV2Client(); var response = client.PutDedicatedIpPoolScalingAttributes(new PutDedicatedIpPoolScalingAttributesRequest { PoolName = "sample-ses-pool", ScalingMode = "MANAGED" }); #endregion } # region ISample Members public virtual void Run() { } # endregion } }
38
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.Snowball; using Amazon.Snowball.Model; namespace AWSSDKDocSamples.Amazon.Snowball.Generated { class SnowballSamples : ISample { public void SnowballCancelCluster() { #region to-cancel-a-cluster-job-1482533760554 var client = new AmazonSnowballClient(); var response = client.CancelCluster(new CancelClusterRequest { ClusterId = "CID123e4567-e89b-12d3-a456-426655440000" }); #endregion } public void SnowballCancelJob() { #region to-cancel-a-job-for-a-snowball-device-1482534699477 var client = new AmazonSnowballClient(); var response = client.CancelJob(new CancelJobRequest { JobId = "JID123e4567-e89b-12d3-a456-426655440000" }); #endregion } public void SnowballCreateAddress() { #region to-create-an-address-for-a-job-1482535416294 var client = new AmazonSnowballClient(); var response = client.CreateAddress(new CreateAddressRequest { Address = new Address { City = "Seattle", Company = "My Company's Name", Country = "USA", Name = "My Name", PhoneNumber = "425-555-5555", PostalCode = "98101", StateOrProvince = "WA", Street1 = "123 Main Street" } }); string addressId = response.AddressId; #endregion } public void SnowballCreateCluster() { #region to-create-a-cluster-1482864724077 var client = new AmazonSnowballClient(); var response = client.CreateCluster(new CreateClusterRequest { AddressId = "ADID1234ab12-3eec-4eb3-9be6-9374c10eb51b", Description = "MyCluster", JobType = "LOCAL_USE", KmsKeyARN = "arn:aws:kms:us-east-1:123456789012:key/abcd1234-12ab-34cd-56ef-123456123456", Notification = new Notification { JobStatesToNotify = new List<string> { }, NotifyAll = false }, Resources = new JobResource { S3Resources = new List<S3Resource> { new S3Resource { BucketArn = "arn:aws:s3:::MyBucket", KeyRange = new KeyRange { } } } }, RoleARN = "arn:aws:iam::123456789012:role/snowball-import-S3-role", ShippingOption = "SECOND_DAY", SnowballType = "EDGE" }); string clusterId = response.ClusterId; #endregion } public void SnowballCreateJob() { #region to-create-a-job-1482864834886 var client = new AmazonSnowballClient(); var response = client.CreateJob(new CreateJobRequest { AddressId = "ADID1234ab12-3eec-4eb3-9be6-9374c10eb51b", Description = "My Job", JobType = "IMPORT", KmsKeyARN = "arn:aws:kms:us-east-1:123456789012:key/abcd1234-12ab-34cd-56ef-123456123456", Notification = new Notification { JobStatesToNotify = new List<string> { }, NotifyAll = false }, Resources = new JobResource { S3Resources = new List<S3Resource> { new S3Resource { BucketArn = "arn:aws:s3:::MyBucket", KeyRange = new KeyRange { } } } }, RoleARN = "arn:aws:iam::123456789012:role/snowball-import-S3-role", ShippingOption = "SECOND_DAY", SnowballCapacityPreference = "T80", SnowballType = "STANDARD" }); string jobId = response.JobId; #endregion } public void SnowballDescribeAddress() { #region to-describe-an-address-for-a-job-1482538608745 var client = new AmazonSnowballClient(); var response = client.DescribeAddress(new DescribeAddressRequest { AddressId = "ADID1234ab12-3eec-4eb3-9be6-9374c10eb51b" }); Address address = response.Address; #endregion } public void SnowballDescribeAddresses() { #region to-describe-all-the-addresses-youve-created-for-aws-snowball-1482538936603 var client = new AmazonSnowballClient(); var response = client.DescribeAddresses(new DescribeAddressesRequest { }); List<Address> addresses = response.Addresses; #endregion } public void SnowballDescribeCluster() { #region to-describe-a-cluster-1482864218396 var client = new AmazonSnowballClient(); var response = client.DescribeCluster(new DescribeClusterRequest { ClusterId = "CID123e4567-e89b-12d3-a456-426655440000" }); ClusterMetadata clusterMetadata = response.ClusterMetadata; #endregion } public void SnowballDescribeJob() { #region to-describe-a-job-youve-created-for-aws-snowball-1482539500180 var client = new AmazonSnowballClient(); var response = client.DescribeJob(new DescribeJobRequest { JobId = "JID123e4567-e89b-12d3-a456-426655440000" }); JobMetadata jobMetadata = response.JobMetadata; #endregion } public void SnowballGetJobManifest() { #region to-get-the-manifest-for-a-job-youve-created-for-aws-snowball-1482540389246 var client = new AmazonSnowballClient(); var response = client.GetJobManifest(new GetJobManifestRequest { JobId = "JID123e4567-e89b-12d3-a456-426655440000" }); string manifestURI = response.ManifestURI; #endregion } public void SnowballGetJobUnlockCode() { #region to-get-the-unlock-code-for-a-job-youve-created-for-aws-snowball-1482541987286 var client = new AmazonSnowballClient(); var response = client.GetJobUnlockCode(new GetJobUnlockCodeRequest { JobId = "JID123e4567-e89b-12d3-a456-426655440000" }); string unlockCode = response.UnlockCode; #endregion } public void SnowballGetSnowballUsage() { #region to-see-your-snowball-service-limit-and-the-number-of-snowballs-you-have-in-use-1482863394588 var client = new AmazonSnowballClient(); var response = client.GetSnowballUsage(new GetSnowballUsageRequest { }); int snowballLimit = response.SnowballLimit; int snowballsInUse = response.SnowballsInUse; #endregion } public void SnowballListClusterJobs() { #region to-get-a-list-of-jobs-in-a-cluster-that-youve-created-for-aws-snowball-1482863105773 var client = new AmazonSnowballClient(); var response = client.ListClusterJobs(new ListClusterJobsRequest { ClusterId = "CID123e4567-e89b-12d3-a456-426655440000" }); List<JobListEntry> jobListEntries = response.JobListEntries; #endregion } public void SnowballListClusters() { #region to-get-a-list-of-clusters-that-youve-created-for-aws-snowball-1482862223003 var client = new AmazonSnowballClient(); var response = client.ListClusters(new ListClustersRequest { }); List<ClusterListEntry> clusterListEntries = response.ClusterListEntries; #endregion } public void SnowballListJobs() { #region to-get-a-list-of-jobs-that-youve-created-for-aws-snowball-1482542167627 var client = new AmazonSnowballClient(); var response = client.ListJobs(new ListJobsRequest { }); List<JobListEntry> jobListEntries = response.JobListEntries; #endregion } public void SnowballUpdateCluster() { #region to-update-a-cluster-1482863900595 var client = new AmazonSnowballClient(); var response = client.UpdateCluster(new UpdateClusterRequest { AddressId = "ADID1234ab12-3eec-4eb3-9be6-9374c10eb51b", ClusterId = "CID123e4567-e89b-12d3-a456-426655440000", Description = "updated-cluster-name" }); #endregion } public void SnowballUpdateJob() { #region to-update-a-job-1482863556886 var client = new AmazonSnowballClient(); var response = client.UpdateJob(new UpdateJobRequest { AddressId = "ADID1234ab12-3eec-4eb3-9be6-9374c10eb51b", Description = "updated-job-name", JobId = "JID123e4567-e89b-12d3-a456-426655440000", ShippingOption = "NEXT_DAY", SnowballCapacityPreference = "T100" }); #endregion } # region ISample Members public virtual void Run() { } # endregion } }
323
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; namespace AWSSDKDocSamples.SNS { class SNSSamples : ISample { public static void SNSCreateSubscribePublish() { #region SNSCreateSubscribePublish var snsClient = new AmazonSimpleNotificationServiceClient(); var topicRequest = new CreateTopicRequest { Name = "CodingTestResults" }; var topicResponse = snsClient.CreateTopic(topicRequest); var topicAttrRequest = new SetTopicAttributesRequest { TopicArn = topicResponse.TopicArn, AttributeName = "DisplayName", AttributeValue = "Coding Test Results" }; snsClient.SetTopicAttributes(topicAttrRequest); snsClient.Subscribe(new SubscribeRequest { Endpoint = "[email protected]", Protocol = "email", TopicArn = topicResponse.TopicArn }); // Wait for up to 2 minutes for the user to confirm the subscription. DateTime latest = DateTime.Now + TimeSpan.FromMinutes(2); while (DateTime.Now < latest) { var subsRequest = new ListSubscriptionsByTopicRequest { TopicArn = topicResponse.TopicArn }; var subs = snsClient.ListSubscriptionsByTopic(subsRequest).Subscriptions; var sub = subs[0]; if (!string.Equals(sub.SubscriptionArn, "PendingConfirmation", StringComparison.Ordinal)) { break; } // Wait 15 seconds before trying again. System.Threading.Thread.Sleep(TimeSpan.FromSeconds(15)); } snsClient.Publish(new PublishRequest { Subject = "Coding Test Results for " + DateTime.Today.ToShortDateString(), Message = "All of today's coding tests passed.", TopicArn = topicResponse.TopicArn }); #endregion } public static void SNSListTopics() { #region SNSListTopics var snsClient = new AmazonSimpleNotificationServiceClient(); var request = new ListTopicsRequest(); var response = new ListTopicsResponse(); do { response = snsClient.ListTopics(request); foreach (var topic in response.Topics) { Console.WriteLine("Topic: {0}", topic.TopicArn); var attrs = snsClient.GetTopicAttributes( new GetTopicAttributesRequest { TopicArn = topic.TopicArn }).Attributes; if (attrs.Count > 0) { foreach (var attr in attrs) { Console.WriteLine(" -{0} : {1}", attr.Key, attr.Value); } } Console.WriteLine(); } request.NextToken = response.NextToken; } while (!string.IsNullOrEmpty(response.NextToken)); #endregion Console.ReadLine(); } public static void SNSListSubscriptionsByTopic() { #region SNSListSubscriptionsByTopic var snsClient = new AmazonSimpleNotificationServiceClient(); var request = new ListSubscriptionsByTopicRequest(); var response = new ListSubscriptionsByTopicResponse(); request.TopicArn = "arn:aws:sns:us-east-1:80398EXAMPLE:CodingTestResults"; do { response = snsClient.ListSubscriptionsByTopic(request); foreach (var sub in response.Subscriptions) { Console.WriteLine("Subscription: {0}", sub.SubscriptionArn); var subAttrs = snsClient.GetSubscriptionAttributes( new GetSubscriptionAttributesRequest { SubscriptionArn = sub.SubscriptionArn }).Attributes; if (subAttrs.Count > 0) { foreach (var subAttr in subAttrs) { Console.WriteLine(" -{0} : {1}", subAttr.Key, subAttr.Value); } } Console.WriteLine(); } request.NextToken = response.NextToken; } while (!string.IsNullOrEmpty(response.NextToken)); #endregion Console.ReadLine(); } public static void SNSListSubscriptions() { #region SNSListSubscriptions var snsClient = new AmazonSimpleNotificationServiceClient(); var request = new ListSubscriptionsRequest(); var response = new ListSubscriptionsResponse(); do { response = snsClient.ListSubscriptions(request); foreach (var sub in response.Subscriptions) { Console.WriteLine("Subscription: {0}", sub.SubscriptionArn); } request.NextToken = response.NextToken; } while (!string.IsNullOrEmpty(response.NextToken)); #endregion Console.ReadLine(); } public static void SNSUnsubscribe() { #region SNSUnsubscribe var snsClient = new AmazonSimpleNotificationServiceClient(); var request = new UnsubscribeRequest(); request.SubscriptionArn = "arn:aws:sns:us-east-1:80398EXAMPLE:CodingTestResults:" + "2f5671ba-c68e-4231-a94a-e82d3EXAMPLE"; snsClient.Unsubscribe(request); #endregion } public static void SNSAddPermission() { #region SNSAddPermission var snsClient = new AmazonSimpleNotificationServiceClient(); var request = new AddPermissionRequest { TopicArn = "arn:aws:sns:us-east-1:80398EXAMPLE:CodingTestResults", ActionName = new List<string>() { "Subscribe" }, AWSAccountId = new List<string>() { "80398EXAMPLE" }, Label = "SubscribePolicy" }; snsClient.AddPermission(request); #endregion } public static void SNSDeleteTopic() { #region SNSDeleteTopic var snsClient = new AmazonSimpleNotificationServiceClient(); var request = new DeleteTopicRequest { TopicArn = "arn:aws:sns:us-east-1:80398EXAMPLE:CodingTestResults" }; snsClient.DeleteTopic(request); #endregion } public static void SNSConfirmSubscription() { #region SNSConfirmSubscription var snsClient = new AmazonSimpleNotificationServiceClient(); var request = new ConfirmSubscriptionRequest { TopicArn = "arn:aws:sns:us-east-1:80398EXAMPLE:CodingTestResults", Token = "2336412f37fb687f5d51e6e241d638b059833563d4ff1b6f50a3be00e3a" + "ff3a5f486f64ab082b19d3b9a6e569ea3f6acb10d944314fc3af72ebc36085519" + "3a02f5a8631552643b8089c751cb8343d581231fb631f34783e30fd2d959dd5bb" + "ea7b11ef09dbd06023af5de4d390d53a10dc9652c01983b028206a1b3e00EXAMPLE" }; snsClient.ConfirmSubscription(request); #endregion } public static void SNSMobilePushAPIsCreatePlatformApplication() { #region SNSMobilePushAPIsCreatePlatformApplication var snsClient = new AmazonSimpleNotificationServiceClient(); var request = new CreatePlatformApplicationRequest { Attributes = new Dictionary<string, string>() { { "PlatformCredential", "AIzaSyDM1GHqKEdVg1pVFTXPReFT7UdGEXAMPLE" } }, Name = "TimeCardProcessingApplication", Platform = "GCM" }; snsClient.CreatePlatformApplication(request); #endregion } public static void SNSMobilePushAPIsSetPlatformApplicationAttributes() { #region SNSMobilePushAPIsSetPlatformApplicationAttributes var snsClient = new AmazonSimpleNotificationServiceClient(); var request = new SetPlatformApplicationAttributesRequest { Attributes = new Dictionary<string, string>() { { "EventDeliveryFailure", "arn:aws:sns:us-east-1:80398EXAMPLE:CodingTestResults" } }, PlatformApplicationArn = "arn:aws:sns:us-east-1:80398EXAMPLE:" + "app/GCM/TimeCardProcessingApplication" }; snsClient.SetPlatformApplicationAttributes(request); #endregion } public static void SNSMobilePushAPIsCreatePlatformEndpoint() { #region SNSMobilePushAPIsCreatePlatformEndpoint var snsClient = new AmazonSimpleNotificationServiceClient(); var request = new CreatePlatformEndpointRequest { CustomUserData = "Any arbitrary data can go here", PlatformApplicationArn = "arn:aws:sns:us-east-1:80398EXAMPLE:" + "app/GCM/TimeCardProcessingApplication", Token = "APBTKzPGlCyT6E6oOfpdwLpcRNxQp5vCPFiF" + "eru9oZylc22HvZSwQTDgmmw9WdNlXMerUPEXAMPLE" }; snsClient.CreatePlatformEndpoint(request); #endregion } public static void SNSMobilePushAPIsSetEndpointAttributes() { #region SNSMobilePushAPIsSetEndpointAttributes var snsClient = new AmazonSimpleNotificationServiceClient(); var request = new SetEndpointAttributesRequest { EndpointArn = "arn:aws:sns:us-east-1:80398EXAMPLE:" + "endpoint/GCM/TimeCardProcessingApplication/" + "d84b5f0d-7136-3bbe-9b42-4e001EXAMPLE", Attributes = new Dictionary<string, string>() { { "Enabled", "true" } } }; snsClient.SetEndpointAttributes(request); #endregion } public static void SNSMobilePushAPIsListApplicationsEndpoints() { #region SNSMobilePushAPIsListApplicationsEndpoints var snsClient = new AmazonSimpleNotificationServiceClient(); var appsResponse = snsClient.ListPlatformApplications(); foreach (var app in appsResponse.PlatformApplications) { Console.WriteLine(); var appAttrsRequest = new GetPlatformApplicationAttributesRequest { PlatformApplicationArn = app.PlatformApplicationArn }; var appAttrsResponse = snsClient.GetPlatformApplicationAttributes(appAttrsRequest); var endpointsByAppRequest = new ListEndpointsByPlatformApplicationRequest { PlatformApplicationArn = app.PlatformApplicationArn }; var endpointsByAppResponse = snsClient.ListEndpointsByPlatformApplication( endpointsByAppRequest); Console.WriteLine("Application: " + app.PlatformApplicationArn); Console.WriteLine(" Properties: "); foreach (var attr in appAttrsResponse.Attributes) { Console.WriteLine(" " + attr.Key + ": " + attr.Value); } Console.WriteLine(" Endpoints: "); foreach (var endpoint in endpointsByAppResponse.Endpoints) { Console.WriteLine(" ARN: " + endpoint.EndpointArn); Console.WriteLine(" Attributes: "); foreach (var attr in endpoint.Attributes) { Console.WriteLine(" " + attr.Key + ": " + attr.Value); } } } #endregion Console.ReadLine(); } public static void SNSMobilePushAPIsDeletePlatformEndpoint() { #region SNSMobilePushAPIsDeletePlatformEndpoint var snsClient = new AmazonSimpleNotificationServiceClient(); var request = new DeleteEndpointRequest { EndpointArn = "arn:aws:sns:us-east-1:80398EXAMPLE:" + "endpoint/GCM/TimeCardProcessingApplication/" + "d84b5f0d-7136-3bbe-9b42-4e001EXAMPLE" }; snsClient.DeleteEndpoint(request); #endregion } public static void SNSMobilePushAPIsDeletePlatformApplication() { #region SNSMobilePushAPIsDeletePlatformApplication var snsClient = new AmazonSimpleNotificationServiceClient(); var request = new DeletePlatformApplicationRequest { PlatformApplicationArn = "arn:aws:sns:us-east-1:80398EXAMPLE:" + "app/GCM/TimeCardProcessingApplication" }; snsClient.DeletePlatformApplication(request); #endregion } #region ISample Members public virtual void Run() { } #endregion } }
410
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.SQS; using Amazon.SQS.Model; namespace AWSSDKDocSamples.Amazon.SQS.Generated { class SQSSamples : ISample { static IAmazonSQS client = new AmazonSQSClient(); public void SQSCreateQueue() { #region create-an-sqs-queue-1445915686197 var response = client.CreateQueue(new CreateQueueRequest { QueueName = "MyQueue", // The Name for the new queue Attributes = new Dictionary<string, string> { { "foo", "bar" }, { "ghoti", "fish" } } }); string queueUrl = response.QueueUrl; // The URL of the new queue #endregion } public void SQSGetQueueUrl() { #region retrieve-queue-attributes-from-an-sqs-queue-1445915930574 var response = client.GetQueueUrl(new GetQueueUrlRequest { QueueName = "MyQueue", QueueOwnerAWSAccountId = "12345678910" }); string queueUrl = response.QueueUrl; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
57
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.SQS; using Amazon.SQS.Model; namespace AWSSDKDocSamples.SQS { class SQSSamples : ISample { public static void SQSReceiveMessage() { #region SQSReceiveMessage var client = new AmazonSQSClient(); var request = new ReceiveMessageRequest { AttributeNames = new List<string>() { "All" }, MaxNumberOfMessages = 5, QueueUrl = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue", VisibilityTimeout = (int)TimeSpan.FromMinutes(10).TotalSeconds, WaitTimeSeconds = (int)TimeSpan.FromSeconds(5).TotalSeconds }; var response = client.ReceiveMessage(request); if (response.Messages.Count > 0) { foreach (var message in response.Messages) { Console.WriteLine("For message ID '" + message.MessageId + "':"); Console.WriteLine(" Body: " + message.Body); Console.WriteLine(" Receipt handle: " + message.ReceiptHandle); Console.WriteLine(" MD5 of body: " + message.MD5OfBody); Console.WriteLine(" MD5 of message attributes: " + message.MD5OfMessageAttributes); Console.WriteLine(" Attributes:"); foreach (var attr in message.Attributes) { Console.WriteLine(" " + attr.Key + ": " + attr.Value); } } } else { Console.WriteLine("No messages received."); } #endregion Console.ReadLine(); } public static void SQSSendMessage() { #region SQSSendMessage var client = new AmazonSQSClient(); var request = new SendMessageRequest { DelaySeconds = (int)TimeSpan.FromSeconds(5).TotalSeconds, MessageAttributes = new Dictionary<string, MessageAttributeValue> { { "MyNameAttribute", new MessageAttributeValue { DataType = "String", StringValue = "John Doe" } }, { "MyAddressAttribute", new MessageAttributeValue { DataType = "String", StringValue = "123 Main St." } }, { "MyRegionAttribute", new MessageAttributeValue { DataType = "String", StringValue = "Any Town, United States" } } }, MessageBody = "John Doe customer information.", QueueUrl = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue" }; var response = client.SendMessage(request); Console.WriteLine("For message ID '" + response.MessageId + "':"); Console.WriteLine(" MD5 of message attributes: " + response.MD5OfMessageAttributes); Console.WriteLine(" MD5 of message body: " + response.MD5OfMessageBody); #endregion Console.ReadLine(); } public static void SQSDeleteMessage() { #region SQSDeleteMessage var client = new AmazonSQSClient(); var request = new ReceiveMessageRequest { AttributeNames = new List<string>() { "All" }, MaxNumberOfMessages = 5, QueueUrl = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue", VisibilityTimeout = (int)TimeSpan.FromMinutes(10).TotalSeconds, WaitTimeSeconds = (int)TimeSpan.FromSeconds(5).TotalSeconds }; var response = client.ReceiveMessage(request); if (response.Messages.Count > 0) { foreach (var message in response.Messages) { Console.Write("Message ID '" + message.MessageId + "' "); var delRequest = new DeleteMessageRequest { QueueUrl = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue", ReceiptHandle = message.ReceiptHandle }; var delResponse = client.DeleteMessage(delRequest); } } else { Console.WriteLine("No messages to delete."); } #endregion Console.ReadLine(); } public static void SQSDeleteMessageBatch() { #region SQSDeleteMessageBatch var client = new AmazonSQSClient(); var request = new ReceiveMessageRequest { AttributeNames = new List<string>() { "All" }, MaxNumberOfMessages = 5, QueueUrl = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue", VisibilityTimeout = (int)TimeSpan.FromMinutes(10).TotalSeconds, WaitTimeSeconds = (int)TimeSpan.FromSeconds(5).TotalSeconds }; var response = client.ReceiveMessage(request); var batchEntries = new List<DeleteMessageBatchRequestEntry>(); if (response.Messages.Count > 0) { foreach (var message in response.Messages) { var batchEntry = new DeleteMessageBatchRequestEntry { Id = message.MessageId, ReceiptHandle = message.ReceiptHandle }; batchEntries.Add(batchEntry); } var delRequest = new DeleteMessageBatchRequest { Entries = batchEntries, QueueUrl = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue" }; var delResponse = client.DeleteMessageBatch(delRequest); if (delResponse.Failed.Count > 0) { Console.WriteLine("Failed deletions:"); foreach (var failure in delResponse.Failed) { Console.WriteLine(" For ID '" + failure.Id + "': "); Console.WriteLine(" Code = " + failure.Code); Console.WriteLine(" Message = " + failure.Message); Console.WriteLine(" Sender's fault? = " + failure.SenderFault); } } if (delResponse.Successful.Count > 0) { Console.WriteLine("Successful deletions:"); foreach (var success in delResponse.Successful) { Console.WriteLine(" ID '" + success.Id + "'"); } } } else { Console.WriteLine("No messages to delete."); } #endregion Console.ReadLine(); } public static void SQSCreateQueue() { #region SQSCreateQueue var client = new AmazonSQSClient(); var attrs = new Dictionary<string, string>(); // Maximum message size of 256 KiB (1,024 bytes * 256 KiB = 262,144 bytes). int maxMessage = 256 * 1024; attrs.Add(QueueAttributeName.DelaySeconds, TimeSpan.FromSeconds(5).TotalSeconds.ToString()); attrs.Add(QueueAttributeName.MaximumMessageSize, maxMessage.ToString()); attrs.Add(QueueAttributeName.MessageRetentionPeriod, TimeSpan.FromDays(4).TotalSeconds.ToString()); attrs.Add(QueueAttributeName.ReceiveMessageWaitTimeSeconds, TimeSpan.FromSeconds(5).TotalSeconds.ToString()); attrs.Add(QueueAttributeName.VisibilityTimeout, TimeSpan.FromHours(12).TotalSeconds.ToString()); var request = new CreateQueueRequest { Attributes = attrs, QueueName = "MyTestQueue" }; var response = client.CreateQueue(request); Console.WriteLine("Queue URL: " + response.QueueUrl); #endregion Console.ReadLine(); } public static void SQSGetQueueUrl() { #region SQSGetQueueUrl var client = new AmazonSQSClient(); var request = new GetQueueUrlRequest { QueueName = "MyTestQueue", QueueOwnerAWSAccountId = "80398EXAMPLE" }; var response = client.GetQueueUrl(request); Console.WriteLine("Queue URL: " + response.QueueUrl); #endregion Console.ReadLine(); } public static void SQSListQueues() { #region SQSListQueues var client = new AmazonSQSClient(); // List all queues that start with "My". var request = new ListQueuesRequest { QueueNamePrefix = "My" }; var response = client.ListQueues(request); if (response.QueueUrls.Count > 0) { Console.WriteLine("Queue URLs:"); foreach (var url in response.QueueUrls) { Console.WriteLine(" " + url); } } else { Console.WriteLine("No matching queues."); } #endregion Console.ReadLine(); } public static void SQSSendMessageBatch() { #region SQSSendMessageBatch var client = new AmazonSQSClient(); var entry1 = new SendMessageBatchRequestEntry { DelaySeconds = 0, Id = "Entry1", MessageAttributes = new Dictionary<string, MessageAttributeValue> { { "MyNameAttribute", new MessageAttributeValue { DataType = "String", StringValue = "John Doe" } }, { "MyAddressAttribute", new MessageAttributeValue { DataType = "String", StringValue = "123 Main St." } }, { "MyRegionAttribute", new MessageAttributeValue { DataType = "String", StringValue = "Any Town, United States" } } }, MessageBody = "John Doe customer information." }; var entry2 = new SendMessageBatchRequestEntry { DelaySeconds = 0, Id = "Entry2", MessageAttributes = new Dictionary<string, MessageAttributeValue> { { "MyNameAttribute", new MessageAttributeValue { DataType = "String", StringValue = "Jane Doe" } }, { "MyAddressAttribute", new MessageAttributeValue { DataType = "String", StringValue = "456 Center Road" } }, { "MyRegionAttribute", new MessageAttributeValue { DataType = "String", StringValue = "Any City, United States" } } }, MessageBody = "Jane Doe customer information." }; var entry3 = new SendMessageBatchRequestEntry { DelaySeconds = 0, Id = "Entry3", MessageAttributes = new Dictionary<string, MessageAttributeValue> { { "MyNameAttribute", new MessageAttributeValue { DataType = "String", StringValue = "Richard Doe" } }, { "MyAddressAttribute", new MessageAttributeValue { DataType = "String", StringValue = "789 East Blvd." } }, { "MyRegionAttribute", new MessageAttributeValue { DataType = "String", StringValue = "Anywhere, United States" } } }, MessageBody = "Richard Doe customer information." }; var request = new SendMessageBatchRequest { Entries = new List<SendMessageBatchRequestEntry>() { entry1, entry2, entry3 }, QueueUrl = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue" }; var response = client.SendMessageBatch(request); if (response.Successful.Count > 0) { Console.WriteLine("Successfully sent:"); foreach (var success in response.Successful) { Console.WriteLine(" For ID: '" + success.Id + "':"); Console.WriteLine(" Message ID = " + success.MessageId); Console.WriteLine(" MD5 of message attributes = " + success.MD5OfMessageAttributes); Console.WriteLine(" MD5 of message body = " + success.MD5OfMessageBody); } } if (response.Failed.Count > 0) { Console.WriteLine("Failed to be sent:"); foreach (var fail in response.Failed) { Console.WriteLine(" For ID '" + fail.Id + "':"); Console.WriteLine(" Code = " + fail.Code); Console.WriteLine(" Message = " + fail.Message); Console.WriteLine(" Sender's fault? = " + fail.SenderFault); } } #endregion Console.ReadLine(); } public static void SQSGetQueueAttributes() { #region SQSGetQueueAttributes var client = new AmazonSQSClient(); var request = new GetQueueAttributesRequest { QueueUrl = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue", AttributeNames = new List<string>() { "All" } }; var response = client.GetQueueAttributes(request); Console.WriteLine("Attributes for queue ARN '" + response.QueueARN + "':"); Console.WriteLine(" Approximate number of messages:" + response.ApproximateNumberOfMessages); Console.WriteLine(" Approximate number of messages delayed: " + response.ApproximateNumberOfMessagesDelayed); Console.WriteLine(" Approximate number of messages not visible: " + response.ApproximateNumberOfMessagesNotVisible); Console.WriteLine(" Queue created on: " + response.CreatedTimestamp); Console.WriteLine(" Delay seconds: " + response.DelaySeconds); Console.WriteLine(" Queue last modified on: " + response.LastModifiedTimestamp); Console.WriteLine(" Maximum message size: " + response.MaximumMessageSize); Console.WriteLine(" Message retention period: " + response.MessageRetentionPeriod); Console.WriteLine(" Visibility timeout: " + response.VisibilityTimeout); Console.WriteLine(" Policy: " + response.Policy); Console.WriteLine(" Attributes:"); foreach (var attr in response.Attributes) { Console.WriteLine(" " + attr.Key + ": " + attr.Value); } #endregion Console.ReadLine(); } public static void SQSChangeMessageVisibility() { #region SQSChangeMessageVisibility var client = new AmazonSQSClient(); var url = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue"; // Receive messages. var rcvRequest = new ReceiveMessageRequest { AttributeNames = new List<string>() { "All" }, QueueUrl = url }; var rcvResponse = client.ReceiveMessage(rcvRequest); // Change visibility timeout for each message. if (rcvResponse.Messages.Count > 0) { foreach (var message in rcvResponse.Messages) { var visRequest = new ChangeMessageVisibilityRequest { QueueUrl = url, ReceiptHandle = message.ReceiptHandle, VisibilityTimeout = (int)TimeSpan.FromMinutes(10).TotalSeconds }; client.ChangeMessageVisibility(visRequest); } } else { Console.WriteLine("No messages to change visibility for."); } #endregion } public static void SQSSetQueueAttributes() { #region SQSSetQueueAttributes var client = new AmazonSQSClient(); var attrs = new Dictionary<string, string>(); // Maximum message size of 128 KiB (1,024 bytes * 128 KiB = 131,072 bytes). int maxMessage = 128 * 1024; attrs.Add(QueueAttributeName.DelaySeconds, TimeSpan.FromSeconds(5).TotalSeconds.ToString()); attrs.Add(QueueAttributeName.MaximumMessageSize, maxMessage.ToString()); attrs.Add(QueueAttributeName.MessageRetentionPeriod, TimeSpan.FromDays(1).TotalSeconds.ToString()); attrs.Add(QueueAttributeName.ReceiveMessageWaitTimeSeconds, TimeSpan.FromSeconds(5).TotalSeconds.ToString()); attrs.Add(QueueAttributeName.VisibilityTimeout, TimeSpan.FromHours(1).TotalSeconds.ToString()); // Dead-letter queue attributes. attrs.Add(QueueAttributeName.RedrivePolicy, "{\"maxReceiveCount\":" + "\"5\"," + "\"deadLetterTargetArn\":" + "\"arn:aws:sqs:us-east-1:80398EXAMPLE:MyTestDeadLetterQueue\"}"); var request = new SetQueueAttributesRequest { Attributes = attrs, QueueUrl = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue" }; client.SetQueueAttributes(request); #endregion } public static void SQSChangeMessageVisibilityBatch() { #region SQSChangeMessageVisibilityBatch var client = new AmazonSQSClient(); var url = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue"; // Receive messages. var msgRequest = new ReceiveMessageRequest { AttributeNames = new List<string>() { "All" }, QueueUrl = url }; var msgResponse = client.ReceiveMessage(msgRequest); // Change visibility timeout for each message. if (msgResponse.Messages.Count > 0) { var entries = new List<ChangeMessageVisibilityBatchRequestEntry>(); int numMessages = 0; foreach (var message in msgResponse.Messages) { numMessages += 1; var entry = new ChangeMessageVisibilityBatchRequestEntry { Id = "Entry" + numMessages.ToString(), ReceiptHandle = message.ReceiptHandle, VisibilityTimeout = (int)TimeSpan.FromMinutes(10).TotalSeconds }; entries.Add(entry); } var batRequest = new ChangeMessageVisibilityBatchRequest { Entries = entries, QueueUrl = url }; var batResponse = client.ChangeMessageVisibilityBatch(batRequest); Console.WriteLine("Successes: " + batResponse.Successful.Count + ", Failures: " + batResponse.Failed.Count); if (batResponse.Successful.Count > 0) { foreach (var success in batResponse.Successful) { Console.WriteLine(" Success ID " + success.Id); } } if (batResponse.Failed.Count > 0) { foreach (var fail in batResponse.Failed) { Console.WriteLine(" Failure ID " + fail.Id + ":"); Console.WriteLine(" Code: " + fail.Code); Console.WriteLine(" Message: " + fail.Message); Console.WriteLine(" Sender's fault?: " + fail.SenderFault); } } } #endregion Console.ReadLine(); } public static void SQSDeleteQueue() { #region SQSDeleteQueue var client = new AmazonSQSClient(); var request = new DeleteQueueRequest { QueueUrl = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue" }; client.DeleteQueue(request); #endregion } public static void SQSAddPermission() { #region SQSAddPermission var client = new AmazonSQSClient(); var request = new AddPermissionRequest { Actions = new List<string>() { "GetQueueAttributes", "GetQueueUrl" }, AWSAccountIds = new List<string>() { "80398EXAMPLE" }, Label = "JohnDoeCanAccessQueues", QueueUrl = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue" }; client.AddPermission(request); #endregion } public static void SQSListDeadLetterSourceQueues() { #region SQSListDeadLetterSourceQueues var client = new AmazonSQSClient(); var request = new ListDeadLetterSourceQueuesRequest { QueueUrl = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestDeadLetterQueue" }; var response = client.ListDeadLetterSourceQueues(request); if (response.QueueUrls.Count > 0) { Console.WriteLine("Dead letter source queues:"); foreach (var url in response.QueueUrls) { Console.WriteLine(" " + url); } } else { Console.WriteLine("No dead letter source queues."); } #endregion Console.ReadLine(); } public static void SQSRemovePermission() { #region SQSRemovePermission var client = new AmazonSQSClient(); var request = new RemovePermissionRequest { Label = "JohnDoeCanAccessQueues", QueueUrl = "https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyTestQueue" }; client.RemovePermission(request); #endregion } #region ISample Members public virtual void Run() { } #endregion } }
672
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.SSMContacts; using Amazon.SSMContacts.Model; namespace AWSSDKDocSamples.Amazon.SSMContacts.Generated { class SSMContactsSamples : ISample { public void SSMContactsAcceptPage() { #region to-accept-a-page-during-and-engagement-1630357840187 var client = new AmazonSSMContactsClient(); var response = client.AcceptPage(new AcceptPageRequest { AcceptCode = "425440", AcceptType = "READ", PageId = "arn:aws:ssm-contacts:us-east-2:682428703967:page/akuam/94ea0c7b-56d9-46c3-b84a-a37c8b067ad3" }); #endregion } public void SSMContactsActivateContactChannel() { #region activate-a-contacts-contact-channel-1630359780075 var client = new AmazonSSMContactsClient(); var response = client.ActivateContactChannel(new ActivateContactChannelRequest { ActivationCode = "466136", ContactChannelId = "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/fc7405c4-46b2-48b7-87b2-93e2f225b90d" }); #endregion } public void SSMContactsCreateContact() { #region to-create-a-contact-1630360152750 var client = new AmazonSSMContactsClient(); var response = client.CreateContact(new CreateContactRequest { Alias = "akuam", DisplayName = "Akua Mansa", Plan = new Plan { Stages = new List<Stage> { } }, Type = "PERSONAL" }); string contactArn = response.ContactArn; #endregion } public void SSMContactsCreateContactChannel() { #region to-create-a-contact-channel-1630360447010 var client = new AmazonSSMContactsClient(); var response = client.CreateContactChannel(new CreateContactChannelRequest { ContactId = "arn:aws:ssm-contacts:us-east-1:111122223333:contact/akuam", DeliveryAddress = new ContactChannelAddress { SimpleAddress = "+15005550199" }, Name = "akuas sms-test", Type = "SMS" }); string contactChannelArn = response.ContactChannelArn; #endregion } public void SSMContactsDeactivateContactChannel() { #region to-deactivate-a-contact-channel-1630360853894 var client = new AmazonSSMContactsClient(); var response = client.DeactivateContactChannel(new DeactivateContactChannelRequest { ContactChannelId = "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/fc7405c4-46b2-48b7-87b2-93e2f225b90d" }); #endregion } public void SSMContactsDeleteContact() { #region to-delete-a-contact-1630361093863 var client = new AmazonSSMContactsClient(); var response = client.DeleteContact(new DeleteContactRequest { ContactId = "arn:aws:ssm-contacts:us-east-1:111122223333:contact/alejr" }); #endregion } public void SSMContactsDeleteContactChannel() { #region to-delete-a-contact-channel-1630364616682 var client = new AmazonSSMContactsClient(); var response = client.DeleteContactChannel(new DeleteContactChannelRequest { ContactChannelId = "arn:aws:ssm-contacts:us-east-1:111122223333:contact-channel/akuam/13149bad-52ee-45ea-ae1e-45857f78f9b2" }); #endregion } public void SSMContactsDescribeEngagement() { #region to-describe-the-details-of-an-engagement-1630364719475 var client = new AmazonSSMContactsClient(); var response = client.DescribeEngagement(new DescribeEngagementRequest { EngagementId = "arn:aws:ssm-contacts:us-east-2:111122223333:engagement/example_escalation/69e40ce1-8dbb-4d57-8962-5fbe7fc53356" }); string contactArn = response.ContactArn; string content = response.Content; string engagementArn = response.EngagementArn; string publicContent = response.PublicContent; string publicSubject = response.PublicSubject; string sender = response.Sender; DateTime startTime = response.StartTime; string subject = response.Subject; #endregion } public void SSMContactsDescribePage() { #region to-list-the-details-of-a-page-to-a-contact-channel-1630364907282 var client = new AmazonSSMContactsClient(); var response = client.DescribePage(new DescribePageRequest { PageId = "arn:aws:ssm-contacts:us-east-2:111122223333:page/akuam/ad0052bd-e606-498a-861b-25726292eb93" }); string contactArn = response.ContactArn; string content = response.Content; DateTime deliveryTime = response.DeliveryTime; string engagementArn = response.EngagementArn; string pageArn = response.PageArn; string publicContent = response.PublicContent; string publicSubject = response.PublicSubject; DateTime readTime = response.ReadTime; string sender = response.Sender; DateTime sentTime = response.SentTime; string subject = response.Subject; #endregion } public void SSMContactsGetContact() { #region example-1-to-describe-a-contact-plan-1630365360005 var client = new AmazonSSMContactsClient(); var response = client.GetContact(new GetContactRequest { ContactId = "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam" }); string alias = response.Alias; string contactArn = response.ContactArn; string displayName = response.DisplayName; Plan plan = response.Plan; string type = response.Type; #endregion } public void SSMContactsGetContact() { #region example-2-to-describe-an-escalation-plan-1630365515731 var client = new AmazonSSMContactsClient(); var response = client.GetContact(new GetContactRequest { ContactId = "arn:aws:ssm-contacts:us-east-2:111122223333:contact/example_escalation" }); string alias = response.Alias; string contactArn = response.ContactArn; string displayName = response.DisplayName; Plan plan = response.Plan; string type = response.Type; #endregion } public void SSMContactsGetContactChannel() { #region to-list-the-details-of-a-contact-channel-1630365682730 var client = new AmazonSSMContactsClient(); var response = client.GetContactChannel(new GetContactChannelRequest { ContactChannelId = "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/fc7405c4-46b2-48b7-87b2-93e2f225b90d" }); string activationStatus = response.ActivationStatus; string contactArn = response.ContactArn; string contactChannelArn = response.ContactChannelArn; ContactChannelAddress deliveryAddress = response.DeliveryAddress; string name = response.Name; string type = response.Type; #endregion } public void SSMContactsGetContactPolicy() { #region to-list-the-details-of-a-contact-channel-1630365682730 var client = new AmazonSSMContactsClient(); var response = client.GetContactPolicy(new GetContactPolicyRequest { ContactArn = "arn:aws:ssm-contacts:us-east-1:111122223333:contact/akuam" }); string contactArn = response.ContactArn; string policy = response.Policy; #endregion } public void SSMContactsListContactChannels() { #region to-list-the-contact-channels-of-a-contact-1630366544252 var client = new AmazonSSMContactsClient(); var response = client.ListContactChannels(new ListContactChannelsRequest { ContactId = "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam" }); List<ContactChannel> contactChannels = response.ContactChannels; #endregion } public void SSMContactsListContacts() { #region to-list-all-escalation-plans-and-contacts-1630367103082 var client = new AmazonSSMContactsClient(); var response = client.ListContacts(new ListContactsRequest { }); List<Contact> contacts = response.Contacts; #endregion } public void SSMContactsListEngagements() { #region to-list-all-engagements-1630367432635 var client = new AmazonSSMContactsClient(); var response = client.ListEngagements(new ListEngagementsRequest { }); List<Engagement> engagements = response.Engagements; #endregion } public void SSMContactsListPageReceipts() { #region to-list-page-receipts-1630367706869 var client = new AmazonSSMContactsClient(); var response = client.ListPageReceipts(new ListPageReceiptsRequest { PageId = "arn:aws:ssm-contacts:us-east-2:111122223333:page/akuam/94ea0c7b-56d9-46c3-b84a-a37c8b067ad3" }); List<Receipt> receipts = response.Receipts; #endregion } public void SSMContactsListPagesByContact() { #region to-list-pages-by-contact-1630435789132 var client = new AmazonSSMContactsClient(); var response = client.ListPagesByContact(new ListPagesByContactRequest { ContactId = "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam" }); List<Page> pages = response.Pages; #endregion } public void SSMContactsListPagesByEngagement() { #region to-list-pages-to-contact-channels-started-from-an-engagement-1630435864674 var client = new AmazonSSMContactsClient(); var response = client.ListPagesByEngagement(new ListPagesByEngagementRequest { EngagementId = "arn:aws:ssm-contacts:us-east-2:111122223333:engagement/akuam/78a29753-3674-4ac5-9f83-0468563567f0" }); List<Page> pages = response.Pages; #endregion } public void SSMContactsListTagsForResource() { #region to-list-tags-for-a-contact-1630436051681 var client = new AmazonSSMContactsClient(); var response = client.ListTagsForResource(new ListTagsForResourceRequest { ResourceARN = "arn:aws:ssm-contacts:us-east-1:111122223333:contact/akuam" }); List<Tag> tags = response.Tags; #endregion } public void SSMContactsPutContactPolicy() { #region to-share-a-contact-and-engagements-1630436278898 var client = new AmazonSSMContactsClient(); var response = client.PutContactPolicy(new PutContactPolicyRequest { ContactArn = "arn:aws:ssm-contacts:us-east-1:111122223333:contact/akuam", Policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"ExampleResourcePolicy\",\"Action\":[\"ssm-contacts:GetContact\",\"ssm-contacts:StartEngagement\",\"ssm-contacts:DescribeEngagement\",\"ssm-contacts:ListPagesByEngagement\",\"ssm-contacts:StopEngagement\"],\"Principal\":{\"AWS\":\"222233334444\"},\"Effect\":\"Allow\",\"Resource\":[\"arn:aws:ssm-contacts:*:111122223333:contact/akuam\",\"arn:aws:ssm-contacts:*:111122223333:engagement/akuam/*\"]}]}" }); #endregion } public void SSMContactsSendActivationCode() { #region to-send-an-activation-code-1630436453574 var client = new AmazonSSMContactsClient(); var response = client.SendActivationCode(new SendActivationCodeRequest { ContactChannelId = "arn:aws:ssm-contacts:us-east-1:111122223333:contact-channel/akuam/8ddae2d1-12c8-4e45-b852-c8587266c400" }); #endregion } public void SSMContactsStartEngagement() { #region example-1-to-page-a-contacts-contact-channels-1630436634872 var client = new AmazonSSMContactsClient(); var response = client.StartEngagement(new StartEngagementRequest { ContactId = "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam", Content = "Testing engagements", PublicContent = "Testing engagements", PublicSubject = "test", Sender = "tester", Subject = "test" }); string engagementArn = response.EngagementArn; #endregion } public void SSMContactsStartEngagement() { #region example-2-to-page-a-contact-in-the-provided-escalation-plan-1630436808480 var client = new AmazonSSMContactsClient(); var response = client.StartEngagement(new StartEngagementRequest { ContactId = "arn:aws:ssm-contacts:us-east-2:111122223333:contact/example_escalation", Content = "Testing engagements", PublicContent = "Testing engagements", PublicSubject = "test", Sender = "tester", Subject = "test" }); string engagementArn = response.EngagementArn; #endregion } public void SSMContactsStopEngagement() { #region to-stop-an-engagement-1630436882864 var client = new AmazonSSMContactsClient(); var response = client.StopEngagement(new StopEngagementRequest { EngagementId = "arn:aws:ssm-contacts:us-east-2:111122223333:engagement/example_escalation/69e40ce1-8dbb-4d57-8962-5fbe7fc53356" }); #endregion } public void SSMContactsTagResource() { #region to-tag-a-contact-1630437124572 var client = new AmazonSSMContactsClient(); var response = client.TagResource(new TagResourceRequest { ResourceARN = "arn:aws:ssm-contacts:us-east-1:111122223333:contact/akuam", Tags = new List<Tag> { new Tag { Key = "group1", Value = "1" } } }); #endregion } public void SSMContactsUntagResource() { #region to-remove-tags-from-a-contact-1630437251110 var client = new AmazonSSMContactsClient(); var response = client.UntagResource(new UntagResourceRequest { ResourceARN = "arn:aws:ssm-contacts:us-east-1:111122223333:contact/akuam", TagKeys = new List<string> { "group1" } }); #endregion } public void SSMContactsUpdateContact() { #region to-update-the-engagement-plan-of-contact-1630437436599 var client = new AmazonSSMContactsClient(); var response = client.UpdateContact(new UpdateContactRequest { ContactId = "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam", Plan = new Plan { Stages = new List<Stage> { new Stage { DurationInMinutes = 5, Targets = new List<Target> { new Target { ChannelTargetInfo = new ChannelTargetInfo { ContactChannelId = "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/beb25840-5ac8-4644-95cc-7a8de390fa65", RetryIntervalInMinutes = 1 } } } }, new Stage { DurationInMinutes = 5, Targets = new List<Target> { new Target { ChannelTargetInfo = new ChannelTargetInfo { ContactChannelId = "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/49f3c24d-5f9f-4638-ae25-3f49e04229ad", RetryIntervalInMinutes = 1 } } } }, new Stage { DurationInMinutes = 5, Targets = new List<Target> { new Target { ChannelTargetInfo = new ChannelTargetInfo { ContactChannelId = "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/77d4f447-f619-4954-afff-85551e369c2a", RetryIntervalInMinutes = 1 } } } } } } }); #endregion } public void SSMContactsUpdateContactChannel() { #region to-update-a-contact-channel-1630437610256 var client = new AmazonSSMContactsClient(); var response = client.UpdateContactChannel(new UpdateContactChannelRequest { ContactChannelId = "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/49f3c24d-5f9f-4638-ae25-3f49e04229ad", DeliveryAddress = new ContactChannelAddress { SimpleAddress = "+15005550198" }, Name = "akuas voice channel" }); #endregion } # region ISample Members public virtual void Run() { } # endregion } }
537
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.StorageGateway; using Amazon.StorageGateway.Model; namespace AWSSDKDocSamples.Amazon.StorageGateway.Generated { class StorageGatewaySamples : ISample { public void StorageGatewayActivateGateway() { #region to-activate-the-gateway-1471281611207 var client = new AmazonStorageGatewayClient(); var response = client.ActivateGateway(new ActivateGatewayRequest { ActivationKey = "29AV1-3OFV9-VVIUB-NKT0I-LRO6V", GatewayName = "My_Gateway", GatewayRegion = "us-east-1", GatewayTimezone = "GMT-12:00", GatewayType = "STORED", MediumChangerType = "AWS-Gateway-VTL", TapeDriveType = "IBM-ULT3580-TD5" }); string gatewayARN = response.GatewayARN; #endregion } public void StorageGatewayAddCache() { #region to-add-a-cache-1471043606854 var client = new AmazonStorageGatewayClient(); var response = client.AddCache(new AddCacheRequest { DiskIds = new List<string> { "pci-0000:03:00.0-scsi-0:0:0:0", "pci-0000:03:00.0-scsi-0:0:1:0" }, GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B" }); string gatewayARN = response.GatewayARN; #endregion } public void StorageGatewayAddTagsToResource() { #region to-add-tags-to-resource-1471283689460 var client = new AmazonStorageGatewayClient(); var response = client.AddTagsToResource(new AddTagsToResourceRequest { ResourceARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-11A2222B", Tags = new List<Tag> { new Tag { Key = "Dev Gatgeway Region", Value = "East Coast" } } }); string resourceARN = response.ResourceARN; #endregion } public void StorageGatewayAddUploadBuffer() { #region to-add-upload-buffer-on-local-disk-1471293902847 var client = new AmazonStorageGatewayClient(); var response = client.AddUploadBuffer(new AddUploadBufferRequest { DiskIds = new List<string> { "pci-0000:03:00.0-scsi-0:0:0:0", "pci-0000:03:00.0-scsi-0:0:1:0" }, GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B" }); string gatewayARN = response.GatewayARN; #endregion } public void StorageGatewayAddWorkingStorage() { #region to-add-storage-on-local-disk-1471294305401 var client = new AmazonStorageGatewayClient(); var response = client.AddWorkingStorage(new AddWorkingStorageRequest { DiskIds = new List<string> { "pci-0000:03:00.0-scsi-0:0:0:0", "pci-0000:03:00.0-scsi-0:0:1:0" }, GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B" }); string gatewayARN = response.GatewayARN; #endregion } public void StorageGatewayCancelArchival() { #region to-cancel-virtual-tape-archiving-1471294865203 var client = new AmazonStorageGatewayClient(); var response = client.CancelArchival(new CancelArchivalRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B", TapeARN = "arn:aws:storagegateway:us-east-1:999999999999:tape/AMZN01A2A4" }); string tapeARN = response.TapeARN; #endregion } public void StorageGatewayCancelRetrieval() { #region to-cancel-virtual-tape-retrieval-1471295704491 var client = new AmazonStorageGatewayClient(); var response = client.CancelRetrieval(new CancelRetrievalRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B", TapeARN = "arn:aws:storagegateway:us-east-1:999999999999:tape/AMZN01A2A4" }); string tapeARN = response.TapeARN; #endregion } public void StorageGatewayCreateCachediSCSIVolume() { #region to-create-a-cached-iscsi-volume-1471296661787 var client = new AmazonStorageGatewayClient(); var response = client.CreateCachediSCSIVolume(new CreateCachediSCSIVolumeRequest { ClientToken = "cachedvol112233", GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B", NetworkInterfaceId = "10.1.1.1", SnapshotId = "snap-f47b7b94", TargetName = "my-volume", VolumeSizeInBytes = 536870912000 }); string targetARN = response.TargetARN; string volumeARN = response.VolumeARN; #endregion } public void StorageGatewayCreateSnapshot() { #region to-create-a-snapshot-of-a-gateway-volume-1471301469561 var client = new AmazonStorageGatewayClient(); var response = client.CreateSnapshot(new CreateSnapshotRequest { SnapshotDescription = "My root volume snapshot as of 10/03/2017", VolumeARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B/volume/vol-1122AABB" }); string snapshotId = response.SnapshotId; string volumeARN = response.VolumeARN; #endregion } public void StorageGatewayCreateSnapshotFromVolumeRecoveryPoint() { #region to-create-a-snapshot-of-a-gateway-volume-1471301469561 var client = new AmazonStorageGatewayClient(); var response = client.CreateSnapshotFromVolumeRecoveryPoint(new CreateSnapshotFromVolumeRecoveryPointRequest { SnapshotDescription = "My root volume snapshot as of 2017-06-30T10:10:10.000Z", VolumeARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B/volume/vol-1122AABB" }); string snapshotId = response.SnapshotId; string volumeARN = response.VolumeARN; string volumeRecoveryPointTime = response.VolumeRecoveryPointTime; #endregion } public void StorageGatewayCreateStorediSCSIVolume() { #region to-create-a-stored-iscsi-volume-1471367662813 var client = new AmazonStorageGatewayClient(); var response = client.CreateStorediSCSIVolume(new CreateStorediSCSIVolumeRequest { DiskId = "pci-0000:03:00.0-scsi-0:0:0:0", GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B", NetworkInterfaceId = "10.1.1.1", PreserveExistingData = true, SnapshotId = "snap-f47b7b94", TargetName = "my-volume" }); string targetARN = response.TargetARN; string volumeARN = response.VolumeARN; long volumeSizeInBytes = response.VolumeSizeInBytes; #endregion } public void StorageGatewayCreateTapes() { #region to-create-a-virtual-tape-1471372061659 var client = new AmazonStorageGatewayClient(); var response = client.CreateTapes(new CreateTapesRequest { ClientToken = "77777", GatewayARN = "arn:aws:storagegateway:us-east-1:999999999999:gateway/sgw-12A3456B", NumTapesToCreate = 3, TapeBarcodePrefix = "TEST", TapeSizeInBytes = 107374182400 }); List<string> tapeARNs = response.TapeARNs; #endregion } public void StorageGatewayCreateTapeWithBarcode() { #region to-create-a-virtual-tape-using-a-barcode-1471371842452 var client = new AmazonStorageGatewayClient(); var response = client.CreateTapeWithBarcode(new CreateTapeWithBarcodeRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:999999999999:gateway/sgw-12A3456B", TapeBarcode = "TEST12345", TapeSizeInBytes = 107374182400 }); string tapeARN = response.TapeARN; #endregion } public void StorageGatewayDeleteBandwidthRateLimit() { #region to-delete-bandwidth-rate-limits-of-gateway-1471373225520 var client = new AmazonStorageGatewayClient(); var response = client.DeleteBandwidthRateLimit(new DeleteBandwidthRateLimitRequest { BandwidthType = "All", GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B" }); string gatewayARN = response.GatewayARN; #endregion } public void StorageGatewayDeleteChapCredentials() { #region to-delete-chap-credentials-1471375025612 var client = new AmazonStorageGatewayClient(); var response = client.DeleteChapCredentials(new DeleteChapCredentialsRequest { InitiatorName = "iqn.1991-05.com.microsoft:computername.domain.example.com", TargetARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B/target/iqn.1997-05.com.amazon:myvolume" }); string initiatorName = response.InitiatorName; string targetARN = response.TargetARN; #endregion } public void StorageGatewayDeleteGateway() { #region to-delete-a-gatgeway-1471381697333 var client = new AmazonStorageGatewayClient(); var response = client.DeleteGateway(new DeleteGatewayRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B" }); string gatewayARN = response.GatewayARN; #endregion } public void StorageGatewayDeleteSnapshotSchedule() { #region to-delete-a-snapshot-of-a-volume-1471382234377 var client = new AmazonStorageGatewayClient(); var response = client.DeleteSnapshotSchedule(new DeleteSnapshotScheduleRequest { VolumeARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B/volume/vol-1122AABB" }); string volumeARN = response.VolumeARN; #endregion } public void StorageGatewayDeleteTape() { #region to-delete-a-virtual-tape-1471382444157 var client = new AmazonStorageGatewayClient(); var response = client.DeleteTape(new DeleteTapeRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:204469490176:gateway/sgw-12A3456B", TapeARN = "arn:aws:storagegateway:us-east-1:204469490176:tape/TEST05A2A0" }); string tapeARN = response.TapeARN; #endregion } public void StorageGatewayDeleteTapeArchive() { #region to-delete-a-virtual-tape-from-the-shelf-vts-1471383964329 var client = new AmazonStorageGatewayClient(); var response = client.DeleteTapeArchive(new DeleteTapeArchiveRequest { TapeARN = "arn:aws:storagegateway:us-east-1:204469490176:tape/TEST05A2A0" }); string tapeARN = response.TapeARN; #endregion } public void StorageGatewayDeleteVolume() { #region to-delete-a-gateway-volume-1471384418416 var client = new AmazonStorageGatewayClient(); var response = client.DeleteVolume(new DeleteVolumeRequest { VolumeARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B/volume/vol-1122AABB" }); string volumeARN = response.VolumeARN; #endregion } public void StorageGatewayDescribeBandwidthRateLimit() { #region to-describe-the-bandwidth-rate-limits-of-a-gateway-1471384826404 var client = new AmazonStorageGatewayClient(); var response = client.DescribeBandwidthRateLimit(new DescribeBandwidthRateLimitRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B" }); long averageDownloadRateLimitInBitsPerSec = response.AverageDownloadRateLimitInBitsPerSec; long averageUploadRateLimitInBitsPerSec = response.AverageUploadRateLimitInBitsPerSec; string gatewayARN = response.GatewayARN; #endregion } public void StorageGatewayDescribeCache() { #region to-describe-cache-information-1471385756036 var client = new AmazonStorageGatewayClient(); var response = client.DescribeCache(new DescribeCacheRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B" }); long cacheAllocatedInBytes = response.CacheAllocatedInBytes; double cacheDirtyPercentage = response.CacheDirtyPercentage; double cacheHitPercentage = response.CacheHitPercentage; double cacheMissPercentage = response.CacheMissPercentage; double cacheUsedPercentage = response.CacheUsedPercentage; List<string> diskIds = response.DiskIds; string gatewayARN = response.GatewayARN; #endregion } public void StorageGatewayDescribeCachediSCSIVolumes() { #region to-describe-gateway-cached-iscsi-volumes-1471458094649 var client = new AmazonStorageGatewayClient(); var response = client.DescribeCachediSCSIVolumes(new DescribeCachediSCSIVolumesRequest { VolumeARNs = new List<string> { "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B/volume/vol-1122AABB" } }); List<CachediSCSIVolume> cachediSCSIVolumes = response.CachediSCSIVolumes; #endregion } public void StorageGatewayDescribeChapCredentials() { #region to-describe-chap-credetnitals-for-an-iscsi-1471467462967 var client = new AmazonStorageGatewayClient(); var response = client.DescribeChapCredentials(new DescribeChapCredentialsRequest { TargetARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B/target/iqn.1997-05.com.amazon:myvolume" }); List<ChapInfo> chapCredentials = response.ChapCredentials; #endregion } public void StorageGatewayDescribeGatewayInformation() { #region to-describe-metadata-about-the-gateway-1471467849079 var client = new AmazonStorageGatewayClient(); var response = client.DescribeGatewayInformation(new DescribeGatewayInformationRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B" }); string gatewayARN = response.GatewayARN; string gatewayId = response.GatewayId; string gatewayName = response.GatewayName; List<NetworkInterface> gatewayNetworkInterfaces = response.GatewayNetworkInterfaces; string gatewayState = response.GatewayState; string gatewayTimezone = response.GatewayTimezone; string gatewayType = response.GatewayType; string lastSoftwareUpdate = response.LastSoftwareUpdate; string nextUpdateAvailabilityDate = response.NextUpdateAvailabilityDate; #endregion } public void StorageGatewayDescribeMaintenanceStartTime() { #region to-describe-gateways-maintenance-start-time-1471470727387 var client = new AmazonStorageGatewayClient(); var response = client.DescribeMaintenanceStartTime(new DescribeMaintenanceStartTimeRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B" }); int dayOfWeek = response.DayOfWeek; string gatewayARN = response.GatewayARN; int hourOfDay = response.HourOfDay; int minuteOfHour = response.MinuteOfHour; string timezone = response.Timezone; #endregion } public void StorageGatewayDescribeSnapshotSchedule() { #region to-describe-snapshot-schedule-for-gateway-volume-1471471139538 var client = new AmazonStorageGatewayClient(); var response = client.DescribeSnapshotSchedule(new DescribeSnapshotScheduleRequest { VolumeARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B/volume/vol-1122AABB" }); string description = response.Description; int recurrenceInHours = response.RecurrenceInHours; int startAt = response.StartAt; string timezone = response.Timezone; string volumeARN = response.VolumeARN; #endregion } public void StorageGatewayDescribeStorediSCSIVolumes() { #region to-describe-the-volumes-of-a-gateway-1471472640660 var client = new AmazonStorageGatewayClient(); var response = client.DescribeStorediSCSIVolumes(new DescribeStorediSCSIVolumesRequest { VolumeARNs = new List<string> { "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B/volume/vol-1122AABB" } }); List<StorediSCSIVolume> storediSCSIVolumes = response.StorediSCSIVolumes; #endregion } public void StorageGatewayDescribeTapeArchives() { #region to-describe-virtual-tapes-in-the-vts-1471473188198 var client = new AmazonStorageGatewayClient(); var response = client.DescribeTapeArchives(new DescribeTapeArchivesRequest { Limit = 123, Marker = "1", TapeARNs = new List<string> { "arn:aws:storagegateway:us-east-1:999999999999:tape/AM08A1AD", "arn:aws:storagegateway:us-east-1:999999999999:tape/AMZN01A2A4" } }); string marker = response.Marker; List<TapeArchive> tapeArchives = response.TapeArchives; #endregion } public void StorageGatewayDescribeTapeRecoveryPoints() { #region to-describe-virtual-tape-recovery-points-1471542042026 var client = new AmazonStorageGatewayClient(); var response = client.DescribeTapeRecoveryPoints(new DescribeTapeRecoveryPointsRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B", Limit = 1, Marker = "1" }); string gatewayARN = response.GatewayARN; string marker = response.Marker; List<TapeRecoveryPointInfo> tapeRecoveryPointInfos = response.TapeRecoveryPointInfos; #endregion } public void StorageGatewayDescribeTapes() { #region to-describe-virtual-tapes-associated-with-gateway-1471629287727 var client = new AmazonStorageGatewayClient(); var response = client.DescribeTapes(new DescribeTapesRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:999999999999:gateway/sgw-12A3456B", Limit = 2, Marker = "1", TapeARNs = new List<string> { "arn:aws:storagegateway:us-east-1:999999999999:tape/TEST04A2A1", "arn:aws:storagegateway:us-east-1:999999999999:tape/TEST05A2A0" } }); string marker = response.Marker; List<Tape> tapes = response.Tapes; #endregion } public void StorageGatewayDescribeUploadBuffer() { #region to-describe-upload-buffer-of-gateway-1471631099003 var client = new AmazonStorageGatewayClient(); var response = client.DescribeUploadBuffer(new DescribeUploadBufferRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B" }); List<string> diskIds = response.DiskIds; string gatewayARN = response.GatewayARN; long uploadBufferAllocatedInBytes = response.UploadBufferAllocatedInBytes; long uploadBufferUsedInBytes = response.UploadBufferUsedInBytes; #endregion } public void StorageGatewayDescribeUploadBuffer() { #region to-describe-upload-buffer-of-a-gateway--1471904566370 var client = new AmazonStorageGatewayClient(); var response = client.DescribeUploadBuffer(new DescribeUploadBufferRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B" }); List<string> diskIds = response.DiskIds; string gatewayARN = response.GatewayARN; long uploadBufferAllocatedInBytes = response.UploadBufferAllocatedInBytes; long uploadBufferUsedInBytes = response.UploadBufferUsedInBytes; #endregion } public void StorageGatewayDescribeVTLDevices() { #region to-describe-virtual-tape-library-vtl-devices-of-a-single-gateway-1471906071410 var client = new AmazonStorageGatewayClient(); var response = client.DescribeVTLDevices(new DescribeVTLDevicesRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:999999999999:gateway/sgw-12A3456B", Limit = 123, Marker = "1", VTLDeviceARNs = new List<string> { } }); string gatewayARN = response.GatewayARN; string marker = response.Marker; List<VTLDevice> vtlDevices = response.VTLDevices; #endregion } public void StorageGatewayDescribeWorkingStorage() { #region to-describe-the-working-storage-of-a-gateway-depreciated-1472070842332 var client = new AmazonStorageGatewayClient(); var response = client.DescribeWorkingStorage(new DescribeWorkingStorageRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B" }); List<string> diskIds = response.DiskIds; string gatewayARN = response.GatewayARN; long workingStorageAllocatedInBytes = response.WorkingStorageAllocatedInBytes; long workingStorageUsedInBytes = response.WorkingStorageUsedInBytes; #endregion } public void StorageGatewayDisableGateway() { #region to-disable-a-gateway-when-it-is-no-longer-functioning-1472076046936 var client = new AmazonStorageGatewayClient(); var response = client.DisableGateway(new DisableGatewayRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B" }); string gatewayARN = response.GatewayARN; #endregion } public void StorageGatewayListGateways() { #region to-lists-region-specific-gateways-per-aws-account-1472077860657 var client = new AmazonStorageGatewayClient(); var response = client.ListGateways(new ListGatewaysRequest { Limit = 2, Marker = "1" }); List<GatewayInfo> gateways = response.Gateways; string marker = response.Marker; #endregion } public void StorageGatewayListLocalDisks() { #region to-list-the-gateways-local-disks-1472079564618 var client = new AmazonStorageGatewayClient(); var response = client.ListLocalDisks(new ListLocalDisksRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B" }); List<Disk> disks = response.Disks; string gatewayARN = response.GatewayARN; #endregion } public void StorageGatewayListTagsForResource() { #region to-list-tags-that-have-been-added-to-a-resource-1472080268972 var client = new AmazonStorageGatewayClient(); var response = client.ListTagsForResource(new ListTagsForResourceRequest { Limit = 1, Marker = "1", ResourceARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-11A2222B" }); string marker = response.Marker; string resourceARN = response.ResourceARN; List<Tag> tags = response.Tags; #endregion } public void StorageGatewayListVolumeRecoveryPoints() { #region to-list-recovery-points-for-a-gateway-1472143015088 var client = new AmazonStorageGatewayClient(); var response = client.ListVolumeRecoveryPoints(new ListVolumeRecoveryPointsRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B" }); string gatewayARN = response.GatewayARN; List<VolumeRecoveryPointInfo> volumeRecoveryPointInfos = response.VolumeRecoveryPointInfos; #endregion } public void StorageGatewayListVolumes() { #region to-list-the-iscsi-stored-volumes-of-a-gateway-1472145723653 var client = new AmazonStorageGatewayClient(); var response = client.ListVolumes(new ListVolumesRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B", Limit = 2, Marker = "1" }); string gatewayARN = response.GatewayARN; string marker = response.Marker; List<VolumeInfo> volumeInfos = response.VolumeInfos; #endregion } public void StorageGatewayRemoveTagsFromResource() { #region to-remove-tags-from-a-resource-1472147210553 var client = new AmazonStorageGatewayClient(); var response = client.RemoveTagsFromResource(new RemoveTagsFromResourceRequest { ResourceARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-11A2222B", TagKeys = new List<string> { "Dev Gatgeway Region", "East Coast" } }); string resourceARN = response.ResourceARN; #endregion } public void StorageGatewayResetCache() { #region to-reset-cache-disks-in-error-status-1472148909807 var client = new AmazonStorageGatewayClient(); var response = client.ResetCache(new ResetCacheRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-13B4567C" }); string gatewayARN = response.GatewayARN; #endregion } public void StorageGatewayRetrieveTapeArchive() { #region to-retrieve-an-archived-tape-from-the-vts-1472149812358 var client = new AmazonStorageGatewayClient(); var response = client.RetrieveTapeArchive(new RetrieveTapeArchiveRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:999999999999:gateway/sgw-12A3456B", TapeARN = "arn:aws:storagegateway:us-east-1:999999999999:tape/TEST0AA2AF" }); string tapeARN = response.TapeARN; #endregion } public void StorageGatewayRetrieveTapeRecoveryPoint() { #region to-retrieve-the-recovery-point-of-a-virtual-tape-1472150014805 var client = new AmazonStorageGatewayClient(); var response = client.RetrieveTapeRecoveryPoint(new RetrieveTapeRecoveryPointRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:999999999999:gateway/sgw-12A3456B", TapeARN = "arn:aws:storagegateway:us-east-1:999999999999:tape/TEST0AA2AF" }); string tapeARN = response.TapeARN; #endregion } public void StorageGatewaySetLocalConsolePassword() { #region to-set-a-password-for-your-vm-1472150202632 var client = new AmazonStorageGatewayClient(); var response = client.SetLocalConsolePassword(new SetLocalConsolePasswordRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:999999999999:gateway/sgw-12A3456B", LocalConsolePassword = "PassWordMustBeAtLeast6Chars." }); string gatewayARN = response.GatewayARN; #endregion } public void StorageGatewayShutdownGateway() { #region to-shut-down-a-gateway-service-1472150508835 var client = new AmazonStorageGatewayClient(); var response = client.ShutdownGateway(new ShutdownGatewayRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:999999999999:gateway/sgw-12A3456B" }); string gatewayARN = response.GatewayARN; #endregion } public void StorageGatewayStartGateway() { #region to-start-a-gateway-service-1472150722315 var client = new AmazonStorageGatewayClient(); var response = client.StartGateway(new StartGatewayRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:999999999999:gateway/sgw-12A3456B" }); string gatewayARN = response.GatewayARN; #endregion } public void StorageGatewayUpdateBandwidthRateLimit() { #region to-update-the-bandwidth-rate-limits-of-a-gateway-1472151016202 var client = new AmazonStorageGatewayClient(); var response = client.UpdateBandwidthRateLimit(new UpdateBandwidthRateLimitRequest { AverageDownloadRateLimitInBitsPerSec = 102400, AverageUploadRateLimitInBitsPerSec = 51200, GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B" }); string gatewayARN = response.GatewayARN; #endregion } public void StorageGatewayUpdateChapCredentials() { #region to-update-chap-credentials-for-an-iscsi-target-1472151325795 var client = new AmazonStorageGatewayClient(); var response = client.UpdateChapCredentials(new UpdateChapCredentialsRequest { InitiatorName = "iqn.1991-05.com.microsoft:computername.domain.example.com", SecretToAuthenticateInitiator = "111111111111", SecretToAuthenticateTarget = "222222222222", TargetARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B/target/iqn.1997-05.com.amazon:myvolume" }); string initiatorName = response.InitiatorName; string targetARN = response.TargetARN; #endregion } public void StorageGatewayUpdateGatewayInformation() { #region to-update-a-gateways-metadata-1472151688693 var client = new AmazonStorageGatewayClient(); var response = client.UpdateGatewayInformation(new UpdateGatewayInformationRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B", GatewayName = "MyGateway2", GatewayTimezone = "GMT-12:00" }); string gatewayARN = response.GatewayARN; string gatewayName = response.GatewayName; #endregion } public void StorageGatewayUpdateGatewaySoftwareNow() { #region to-update-a-gateways-vm-software-1472152020929 var client = new AmazonStorageGatewayClient(); var response = client.UpdateGatewaySoftwareNow(new UpdateGatewaySoftwareNowRequest { GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B" }); string gatewayARN = response.GatewayARN; #endregion } public void StorageGatewayUpdateMaintenanceStartTime() { #region to-update-a-gateways-maintenance-start-time-1472152552031 var client = new AmazonStorageGatewayClient(); var response = client.UpdateMaintenanceStartTime(new UpdateMaintenanceStartTimeRequest { DayOfWeek = 2, GatewayARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B", HourOfDay = 0, MinuteOfHour = 30 }); string gatewayARN = response.GatewayARN; #endregion } public void StorageGatewayUpdateSnapshotSchedule() { #region to-update-a-volume-snapshot-schedule-1472152757068 var client = new AmazonStorageGatewayClient(); var response = client.UpdateSnapshotSchedule(new UpdateSnapshotScheduleRequest { Description = "Hourly snapshot", RecurrenceInHours = 1, StartAt = 0, VolumeARN = "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-12A3456B/volume/vol-1122AABB" }); string volumeARN = response.VolumeARN; #endregion } public void StorageGatewayUpdateVTLDeviceType() { #region to-update-a-vtl-device-type-1472153012967 var client = new AmazonStorageGatewayClient(); var response = client.UpdateVTLDeviceType(new UpdateVTLDeviceTypeRequest { DeviceType = "Medium Changer", VTLDeviceARN = "arn:aws:storagegateway:us-east-1:999999999999:gateway/sgw-12A3456B/device/AMZN_SGW-1FAD4876_MEDIACHANGER_00001" }); string vtlDeviceARN = response.VTLDeviceARN; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
998
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Amazon.Runtime; using System.Threading; namespace AWSSDKDocSamples.Util { public static class Common { public static void WaitUntil(Func<bool> isDoneFunc) { WaitUntil(isDoneFunc, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(10)); } public static void WaitUntil(Func<bool> isDoneFunc, TimeSpan checkPeriod) { WaitUntil(isDoneFunc, checkPeriod, TimeSpan.FromMinutes(10)); } public static void WaitUntil(Func<bool> isDoneFunc, TimeSpan checkPeriod, TimeSpan maxTotalWaitTime) { if (isDoneFunc == null) throw new ArgumentNullException("isDoneFunc"); if (checkPeriod.Ticks <= 0) throw new ArgumentOutOfRangeException("checkPeriod"); if (maxTotalWaitTime.Ticks < 0) throw new ArgumentOutOfRangeException("maxTotalWaitTime"); DateTime startTime = DateTime.Now; while (true) { // check if exit criteria is reached if (isDoneFunc()) break; // check if maximum alotted time is reached if (maxTotalWaitTime.Ticks > 0 && (startTime + maxTotalWaitTime < DateTime.Now)) break; Thread.Sleep(checkPeriod); } } } }
40
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.WAF; using Amazon.WAF.Model; namespace AWSSDKDocSamples.Amazon.WAF.Generated { class WAFSamples : ISample { public void WAFCreateIPSet() { #region createipset-1472501003122 var client = new AmazonWAFClient(); var response = client.CreateIPSet(new CreateIPSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", Name = "MyIPSetFriendlyName" }); string changeToken = response.ChangeToken; IPSet ipSet = response.IPSet; #endregion } public void WAFCreateRule() { #region createrule-1474072675555 var client = new AmazonWAFClient(); var response = client.CreateRule(new CreateRuleRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", MetricName = "WAFByteHeaderRule", Name = "WAFByteHeaderRule" }); string changeToken = response.ChangeToken; Rule rule = response.Rule; #endregion } public void WAFCreateSizeConstraintSet() { #region createsizeconstraint-1474299140754 var client = new AmazonWAFClient(); var response = client.CreateSizeConstraintSet(new CreateSizeConstraintSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", Name = "MySampleSizeConstraintSet" }); string changeToken = response.ChangeToken; SizeConstraintSet sizeConstraintSet = response.SizeConstraintSet; #endregion } public void WAFCreateSqlInjectionMatchSet() { #region createsqlinjectionmatchset-1474492796105 var client = new AmazonWAFClient(); var response = client.CreateSqlInjectionMatchSet(new CreateSqlInjectionMatchSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", Name = "MySQLInjectionMatchSet" }); string changeToken = response.ChangeToken; SqlInjectionMatchSet sqlInjectionMatchSet = response.SqlInjectionMatchSet; #endregion } public void WAFCreateWebACL() { #region createwebacl-1472061481310 var client = new AmazonWAFClient(); var response = client.CreateWebACL(new CreateWebACLRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", DefaultAction = new WafAction { Type = "ALLOW" }, MetricName = "CreateExample", Name = "CreateExample" }); string changeToken = response.ChangeToken; WebACL webACL = response.WebACL; #endregion } public void WAFCreateXssMatchSet() { #region createxssmatchset-1474560868500 var client = new AmazonWAFClient(); var response = client.CreateXssMatchSet(new CreateXssMatchSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", Name = "MySampleXssMatchSet" }); string changeToken = response.ChangeToken; XssMatchSet xssMatchSet = response.XssMatchSet; #endregion } public void WAFDeleteByteMatchSet() { #region deletebytematchset-1473367566229 var client = new AmazonWAFClient(); var response = client.DeleteByteMatchSet(new DeleteByteMatchSetRequest { ByteMatchSetId = "exampleIDs3t-46da-4fdb-b8d5-abc321j569j5", ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f" }); string changeToken = response.ChangeToken; #endregion } public void WAFDeleteIPSet() { #region deleteipset-1472767434306 var client = new AmazonWAFClient(); var response = client.DeleteIPSet(new DeleteIPSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", IPSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); string changeToken = response.ChangeToken; #endregion } public void WAFDeleteRule() { #region deleterule-1474073108749 var client = new AmazonWAFClient(); var response = client.DeleteRule(new DeleteRuleRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", RuleId = "WAFRule-1-Example" }); string changeToken = response.ChangeToken; #endregion } public void WAFDeleteSizeConstraintSet() { #region deletesizeconstraintset-1474299857905 var client = new AmazonWAFClient(); var response = client.DeleteSizeConstraintSet(new DeleteSizeConstraintSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", SizeConstraintSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); string changeToken = response.ChangeToken; #endregion } public void WAFDeleteSqlInjectionMatchSet() { #region deletesqlinjectionmatchset-1474493373197 var client = new AmazonWAFClient(); var response = client.DeleteSqlInjectionMatchSet(new DeleteSqlInjectionMatchSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", SqlInjectionMatchSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); string changeToken = response.ChangeToken; #endregion } public void WAFDeleteWebACL() { #region deletewebacl-1472767755931 var client = new AmazonWAFClient(); var response = client.DeleteWebACL(new DeleteWebACLRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", WebACLId = "example-46da-4444-5555-example" }); string changeToken = response.ChangeToken; #endregion } public void WAFDeleteXssMatchSet() { #region deletexssmatchset-1474561302618 var client = new AmazonWAFClient(); var response = client.DeleteXssMatchSet(new DeleteXssMatchSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", XssMatchSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); string changeToken = response.ChangeToken; #endregion } public void WAFGetByteMatchSet() { #region getbytematchset-1473273311532 var client = new AmazonWAFClient(); var response = client.GetByteMatchSet(new GetByteMatchSetRequest { ByteMatchSetId = "exampleIDs3t-46da-4fdb-b8d5-abc321j569j5" }); ByteMatchSet byteMatchSet = response.ByteMatchSet; #endregion } public void WAFGetChangeToken() { #region get-change-token-example-1471635120794 var client = new AmazonWAFClient(); var response = client.GetChangeToken(new GetChangeTokenRequest { }); string changeToken = response.ChangeToken; #endregion } public void WAFGetChangeTokenStatus() { #region getchangetokenstatus-1474658417107 var client = new AmazonWAFClient(); var response = client.GetChangeTokenStatus(new GetChangeTokenStatusRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f" }); string changeTokenStatus = response.ChangeTokenStatus; #endregion } public void WAFGetIPSet() { #region getipset-1474658688675 var client = new AmazonWAFClient(); var response = client.GetIPSet(new GetIPSetRequest { IPSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); IPSet ipSet = response.IPSet; #endregion } public void WAFGetRule() { #region getrule-1474659238790 var client = new AmazonWAFClient(); var response = client.GetRule(new GetRuleRequest { RuleId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); Rule rule = response.Rule; #endregion } public void WAFGetSampledRequests() { #region getsampledrequests-1474927997195 var client = new AmazonWAFClient(); var response = client.GetSampledRequests(new GetSampledRequestsRequest { MaxItems = 100, RuleId = "WAFRule-1-Example", TimeWindow = new TimeWindow { EndTime = new DateTime(2016, 9, 27, 8, 50, 0, DateTimeKind.Utc), StartTime = new DateTime(2016, 9, 27, 8, 50, 0, DateTimeKind.Utc) }, WebAclId = "createwebacl-1472061481310" }); long populationSize = response.PopulationSize; List<SampledHTTPRequest> sampledRequests = response.SampledRequests; TimeWindow timeWindow = response.TimeWindow; #endregion } public void WAFGetSizeConstraintSet() { #region getsizeconstraintset-1475005422493 var client = new AmazonWAFClient(); var response = client.GetSizeConstraintSet(new GetSizeConstraintSetRequest { SizeConstraintSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); SizeConstraintSet sizeConstraintSet = response.SizeConstraintSet; #endregion } public void WAFGetSqlInjectionMatchSet() { #region getsqlinjectionmatchset-1475005940137 var client = new AmazonWAFClient(); var response = client.GetSqlInjectionMatchSet(new GetSqlInjectionMatchSetRequest { SqlInjectionMatchSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); SqlInjectionMatchSet sqlInjectionMatchSet = response.SqlInjectionMatchSet; #endregion } public void WAFGetWebACL() { #region getwebacl-1475006348525 var client = new AmazonWAFClient(); var response = client.GetWebACL(new GetWebACLRequest { WebACLId = "createwebacl-1472061481310" }); WebACL webACL = response.WebACL; #endregion } public void WAFGetXssMatchSet() { #region getxssmatchset-1475187879017 var client = new AmazonWAFClient(); var response = client.GetXssMatchSet(new GetXssMatchSetRequest { XssMatchSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); XssMatchSet xssMatchSet = response.XssMatchSet; #endregion } public void WAFListIPSets() { #region listipsets-1472235676229 var client = new AmazonWAFClient(); var response = client.ListIPSets(new ListIPSetsRequest { Limit = 100 }); List<IPSetSummary> ipSets = response.IPSets; #endregion } public void WAFListRules() { #region listrules-1475258406433 var client = new AmazonWAFClient(); var response = client.ListRules(new ListRulesRequest { Limit = 100 }); List<RuleSummary> rules = response.Rules; #endregion } public void WAFListSizeConstraintSets() { #region listsizeconstraintsets-1474300067597 var client = new AmazonWAFClient(); var response = client.ListSizeConstraintSets(new ListSizeConstraintSetsRequest { Limit = 100 }); List<SizeConstraintSetSummary> sizeConstraintSets = response.SizeConstraintSets; #endregion } public void WAFListSqlInjectionMatchSets() { #region listsqlinjectionmatchset-1474493560103 var client = new AmazonWAFClient(); var response = client.ListSqlInjectionMatchSets(new ListSqlInjectionMatchSetsRequest { Limit = 100 }); List<SqlInjectionMatchSetSummary> sqlInjectionMatchSets = response.SqlInjectionMatchSets; #endregion } public void WAFListWebACLs() { #region listwebacls-1475258732691 var client = new AmazonWAFClient(); var response = client.ListWebACLs(new ListWebACLsRequest { Limit = 100 }); List<WebACLSummary> webACLs = response.WebACLs; #endregion } public void WAFListXssMatchSets() { #region listxssmatchsets-1474561481168 var client = new AmazonWAFClient(); var response = client.ListXssMatchSets(new ListXssMatchSetsRequest { Limit = 100 }); List<XssMatchSetSummary> xssMatchSets = response.XssMatchSets; #endregion } public void WAFUpdateByteMatchSet() { #region updatebytematchset-1475259074558 var client = new AmazonWAFClient(); var response = client.UpdateByteMatchSet(new UpdateByteMatchSetRequest { ByteMatchSetId = "exampleIDs3t-46da-4fdb-b8d5-abc321j569j5", ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", Updates = new List<ByteMatchSetUpdate> { new ByteMatchSetUpdate { Action = "DELETE", ByteMatchTuple = new ByteMatchTuple { FieldToMatch = new FieldToMatch { Data = "referer", Type = "HEADER" }, PositionalConstraint = "CONTAINS", TextTransformation = "NONE" } } } }); string changeToken = response.ChangeToken; #endregion } public void WAFUpdateIPSet() { #region updateipset-1475259733625 var client = new AmazonWAFClient(); var response = client.UpdateIPSet(new UpdateIPSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", IPSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5", Updates = new List<IPSetUpdate> { new IPSetUpdate { Action = "DELETE", IPSetDescriptor = new IPSetDescriptor { Type = "IPV4", Value = "192.0.2.44/32" } } } }); string changeToken = response.ChangeToken; #endregion } public void WAFUpdateRule() { #region updaterule-1475260064720 var client = new AmazonWAFClient(); var response = client.UpdateRule(new UpdateRuleRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", RuleId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5", Updates = new List<RuleUpdate> { new RuleUpdate { Action = "DELETE", Predicate = new Predicate { DataId = "MyByteMatchSetID", Negated = false, Type = "ByteMatch" } } } }); string changeToken = response.ChangeToken; #endregion } public void WAFUpdateSizeConstraintSet() { #region updatesizeconstraintset-1475531697891 var client = new AmazonWAFClient(); var response = client.UpdateSizeConstraintSet(new UpdateSizeConstraintSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", SizeConstraintSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5", Updates = new List<SizeConstraintSetUpdate> { new SizeConstraintSetUpdate { Action = "DELETE", SizeConstraint = new SizeConstraint { ComparisonOperator = "GT", FieldToMatch = new FieldToMatch { Type = "QUERY_STRING" }, Size = 0, TextTransformation = "NONE" } } } }); string changeToken = response.ChangeToken; #endregion } public void WAFUpdateSqlInjectionMatchSet() { #region updatesqlinjectionmatchset-1475532094686 var client = new AmazonWAFClient(); var response = client.UpdateSqlInjectionMatchSet(new UpdateSqlInjectionMatchSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", SqlInjectionMatchSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5", Updates = new List<SqlInjectionMatchSetUpdate> { new SqlInjectionMatchSetUpdate { Action = "DELETE", SqlInjectionMatchTuple = new SqlInjectionMatchTuple { FieldToMatch = new FieldToMatch { Type = "QUERY_STRING" }, TextTransformation = "URL_DECODE" } } } }); string changeToken = response.ChangeToken; #endregion } public void WAFUpdateWebACL() { #region updatewebacl-1475533627385 var client = new AmazonWAFClient(); var response = client.UpdateWebACL(new UpdateWebACLRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", DefaultAction = new WafAction { Type = "ALLOW" }, Updates = new List<WebACLUpdate> { new WebACLUpdate { Action = "DELETE", ActivatedRule = new ActivatedRule { Action = new WafAction { Type = "ALLOW" }, Priority = 1, RuleId = "WAFRule-1-Example" } } }, WebACLId = "webacl-1472061481310" }); string changeToken = response.ChangeToken; #endregion } public void WAFUpdateXssMatchSet() { #region updatexssmatchset-1475534098881 var client = new AmazonWAFClient(); var response = client.UpdateXssMatchSet(new UpdateXssMatchSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", Updates = new List<XssMatchSetUpdate> { new XssMatchSetUpdate { Action = "DELETE", XssMatchTuple = new XssMatchTuple { FieldToMatch = new FieldToMatch { Type = "QUERY_STRING" }, TextTransformation = "URL_DECODE" } } }, XssMatchSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); string changeToken = response.ChangeToken; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
671
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.WAFRegional; using Amazon.WAFRegional.Model; namespace AWSSDKDocSamples.Amazon.WAFRegional.Generated { class WAFRegionalSamples : ISample { public void WAFRegionalCreateIPSet() { #region createipset-1472501003122 var client = new AmazonWAFRegionalClient(); var response = client.CreateIPSet(new CreateIPSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", Name = "MyIPSetFriendlyName" }); string changeToken = response.ChangeToken; IPSet ipSet = response.IPSet; #endregion } public void WAFRegionalCreateRule() { #region createrule-1474072675555 var client = new AmazonWAFRegionalClient(); var response = client.CreateRule(new CreateRuleRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", MetricName = "WAFByteHeaderRule", Name = "WAFByteHeaderRule" }); string changeToken = response.ChangeToken; Rule rule = response.Rule; #endregion } public void WAFRegionalCreateSizeConstraintSet() { #region createsizeconstraint-1474299140754 var client = new AmazonWAFRegionalClient(); var response = client.CreateSizeConstraintSet(new CreateSizeConstraintSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", Name = "MySampleSizeConstraintSet" }); string changeToken = response.ChangeToken; SizeConstraintSet sizeConstraintSet = response.SizeConstraintSet; #endregion } public void WAFRegionalCreateSqlInjectionMatchSet() { #region createsqlinjectionmatchset-1474492796105 var client = new AmazonWAFRegionalClient(); var response = client.CreateSqlInjectionMatchSet(new CreateSqlInjectionMatchSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", Name = "MySQLInjectionMatchSet" }); string changeToken = response.ChangeToken; SqlInjectionMatchSet sqlInjectionMatchSet = response.SqlInjectionMatchSet; #endregion } public void WAFRegionalCreateWebACL() { #region createwebacl-1472061481310 var client = new AmazonWAFRegionalClient(); var response = client.CreateWebACL(new CreateWebACLRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", DefaultAction = new WafAction { Type = "ALLOW" }, MetricName = "CreateExample", Name = "CreateExample" }); string changeToken = response.ChangeToken; WebACL webACL = response.WebACL; #endregion } public void WAFRegionalCreateXssMatchSet() { #region createxssmatchset-1474560868500 var client = new AmazonWAFRegionalClient(); var response = client.CreateXssMatchSet(new CreateXssMatchSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", Name = "MySampleXssMatchSet" }); string changeToken = response.ChangeToken; XssMatchSet xssMatchSet = response.XssMatchSet; #endregion } public void WAFRegionalDeleteByteMatchSet() { #region deletebytematchset-1473367566229 var client = new AmazonWAFRegionalClient(); var response = client.DeleteByteMatchSet(new DeleteByteMatchSetRequest { ByteMatchSetId = "exampleIDs3t-46da-4fdb-b8d5-abc321j569j5", ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f" }); string changeToken = response.ChangeToken; #endregion } public void WAFRegionalDeleteIPSet() { #region deleteipset-1472767434306 var client = new AmazonWAFRegionalClient(); var response = client.DeleteIPSet(new DeleteIPSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", IPSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); string changeToken = response.ChangeToken; #endregion } public void WAFRegionalDeleteRule() { #region deleterule-1474073108749 var client = new AmazonWAFRegionalClient(); var response = client.DeleteRule(new DeleteRuleRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", RuleId = "WAFRule-1-Example" }); string changeToken = response.ChangeToken; #endregion } public void WAFRegionalDeleteSizeConstraintSet() { #region deletesizeconstraintset-1474299857905 var client = new AmazonWAFRegionalClient(); var response = client.DeleteSizeConstraintSet(new DeleteSizeConstraintSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", SizeConstraintSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); string changeToken = response.ChangeToken; #endregion } public void WAFRegionalDeleteSqlInjectionMatchSet() { #region deletesqlinjectionmatchset-1474493373197 var client = new AmazonWAFRegionalClient(); var response = client.DeleteSqlInjectionMatchSet(new DeleteSqlInjectionMatchSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", SqlInjectionMatchSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); string changeToken = response.ChangeToken; #endregion } public void WAFRegionalDeleteWebACL() { #region deletewebacl-1472767755931 var client = new AmazonWAFRegionalClient(); var response = client.DeleteWebACL(new DeleteWebACLRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", WebACLId = "example-46da-4444-5555-example" }); string changeToken = response.ChangeToken; #endregion } public void WAFRegionalDeleteXssMatchSet() { #region deletexssmatchset-1474561302618 var client = new AmazonWAFRegionalClient(); var response = client.DeleteXssMatchSet(new DeleteXssMatchSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", XssMatchSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); string changeToken = response.ChangeToken; #endregion } public void WAFRegionalGetByteMatchSet() { #region getbytematchset-1473273311532 var client = new AmazonWAFRegionalClient(); var response = client.GetByteMatchSet(new GetByteMatchSetRequest { ByteMatchSetId = "exampleIDs3t-46da-4fdb-b8d5-abc321j569j5" }); ByteMatchSet byteMatchSet = response.ByteMatchSet; #endregion } public void WAFRegionalGetChangeToken() { #region get-change-token-example-1471635120794 var client = new AmazonWAFRegionalClient(); var response = client.GetChangeToken(new GetChangeTokenRequest { }); string changeToken = response.ChangeToken; #endregion } public void WAFRegionalGetChangeTokenStatus() { #region getchangetokenstatus-1474658417107 var client = new AmazonWAFRegionalClient(); var response = client.GetChangeTokenStatus(new GetChangeTokenStatusRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f" }); string changeTokenStatus = response.ChangeTokenStatus; #endregion } public void WAFRegionalGetIPSet() { #region getipset-1474658688675 var client = new AmazonWAFRegionalClient(); var response = client.GetIPSet(new GetIPSetRequest { IPSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); IPSet ipSet = response.IPSet; #endregion } public void WAFRegionalGetRule() { #region getrule-1474659238790 var client = new AmazonWAFRegionalClient(); var response = client.GetRule(new GetRuleRequest { RuleId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); Rule rule = response.Rule; #endregion } public void WAFRegionalGetSampledRequests() { #region getsampledrequests-1474927997195 var client = new AmazonWAFRegionalClient(); var response = client.GetSampledRequests(new GetSampledRequestsRequest { MaxItems = 100, RuleId = "WAFRule-1-Example", TimeWindow = new TimeWindow { EndTime = new DateTime(2016, 9, 27, 8, 50, 0, DateTimeKind.Utc), StartTime = new DateTime(2016, 9, 27, 8, 50, 0, DateTimeKind.Utc) }, WebAclId = "createwebacl-1472061481310" }); long populationSize = response.PopulationSize; List<SampledHTTPRequest> sampledRequests = response.SampledRequests; TimeWindow timeWindow = response.TimeWindow; #endregion } public void WAFRegionalGetSizeConstraintSet() { #region getsizeconstraintset-1475005422493 var client = new AmazonWAFRegionalClient(); var response = client.GetSizeConstraintSet(new GetSizeConstraintSetRequest { SizeConstraintSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); SizeConstraintSet sizeConstraintSet = response.SizeConstraintSet; #endregion } public void WAFRegionalGetSqlInjectionMatchSet() { #region getsqlinjectionmatchset-1475005940137 var client = new AmazonWAFRegionalClient(); var response = client.GetSqlInjectionMatchSet(new GetSqlInjectionMatchSetRequest { SqlInjectionMatchSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); SqlInjectionMatchSet sqlInjectionMatchSet = response.SqlInjectionMatchSet; #endregion } public void WAFRegionalGetWebACL() { #region getwebacl-1475006348525 var client = new AmazonWAFRegionalClient(); var response = client.GetWebACL(new GetWebACLRequest { WebACLId = "createwebacl-1472061481310" }); WebACL webACL = response.WebACL; #endregion } public void WAFRegionalGetXssMatchSet() { #region getxssmatchset-1475187879017 var client = new AmazonWAFRegionalClient(); var response = client.GetXssMatchSet(new GetXssMatchSetRequest { XssMatchSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); XssMatchSet xssMatchSet = response.XssMatchSet; #endregion } public void WAFRegionalListIPSets() { #region listipsets-1472235676229 var client = new AmazonWAFRegionalClient(); var response = client.ListIPSets(new ListIPSetsRequest { Limit = 100 }); List<IPSetSummary> ipSets = response.IPSets; #endregion } public void WAFRegionalListRules() { #region listrules-1475258406433 var client = new AmazonWAFRegionalClient(); var response = client.ListRules(new ListRulesRequest { Limit = 100 }); List<RuleSummary> rules = response.Rules; #endregion } public void WAFRegionalListSizeConstraintSets() { #region listsizeconstraintsets-1474300067597 var client = new AmazonWAFRegionalClient(); var response = client.ListSizeConstraintSets(new ListSizeConstraintSetsRequest { Limit = 100 }); List<SizeConstraintSetSummary> sizeConstraintSets = response.SizeConstraintSets; #endregion } public void WAFRegionalListSqlInjectionMatchSets() { #region listsqlinjectionmatchset-1474493560103 var client = new AmazonWAFRegionalClient(); var response = client.ListSqlInjectionMatchSets(new ListSqlInjectionMatchSetsRequest { Limit = 100 }); List<SqlInjectionMatchSetSummary> sqlInjectionMatchSets = response.SqlInjectionMatchSets; #endregion } public void WAFRegionalListWebACLs() { #region listwebacls-1475258732691 var client = new AmazonWAFRegionalClient(); var response = client.ListWebACLs(new ListWebACLsRequest { Limit = 100 }); List<WebACLSummary> webACLs = response.WebACLs; #endregion } public void WAFRegionalListXssMatchSets() { #region listxssmatchsets-1474561481168 var client = new AmazonWAFRegionalClient(); var response = client.ListXssMatchSets(new ListXssMatchSetsRequest { Limit = 100 }); List<XssMatchSetSummary> xssMatchSets = response.XssMatchSets; #endregion } public void WAFRegionalUpdateByteMatchSet() { #region updatebytematchset-1475259074558 var client = new AmazonWAFRegionalClient(); var response = client.UpdateByteMatchSet(new UpdateByteMatchSetRequest { ByteMatchSetId = "exampleIDs3t-46da-4fdb-b8d5-abc321j569j5", ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", Updates = new List<ByteMatchSetUpdate> { new ByteMatchSetUpdate { Action = "DELETE", ByteMatchTuple = new ByteMatchTuple { FieldToMatch = new FieldToMatch { Data = "referer", Type = "HEADER" }, PositionalConstraint = "CONTAINS", TextTransformation = "NONE" } } } }); string changeToken = response.ChangeToken; #endregion } public void WAFRegionalUpdateIPSet() { #region updateipset-1475259733625 var client = new AmazonWAFRegionalClient(); var response = client.UpdateIPSet(new UpdateIPSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", IPSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5", Updates = new List<IPSetUpdate> { new IPSetUpdate { Action = "DELETE", IPSetDescriptor = new IPSetDescriptor { Type = "IPV4", Value = "192.0.2.44/32" } } } }); string changeToken = response.ChangeToken; #endregion } public void WAFRegionalUpdateRule() { #region updaterule-1475260064720 var client = new AmazonWAFRegionalClient(); var response = client.UpdateRule(new UpdateRuleRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", RuleId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5", Updates = new List<RuleUpdate> { new RuleUpdate { Action = "DELETE", Predicate = new Predicate { DataId = "MyByteMatchSetID", Negated = false, Type = "ByteMatch" } } } }); string changeToken = response.ChangeToken; #endregion } public void WAFRegionalUpdateSizeConstraintSet() { #region updatesizeconstraintset-1475531697891 var client = new AmazonWAFRegionalClient(); var response = client.UpdateSizeConstraintSet(new UpdateSizeConstraintSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", SizeConstraintSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5", Updates = new List<SizeConstraintSetUpdate> { new SizeConstraintSetUpdate { Action = "DELETE", SizeConstraint = new SizeConstraint { ComparisonOperator = "GT", FieldToMatch = new FieldToMatch { Type = "QUERY_STRING" }, Size = 0, TextTransformation = "NONE" } } } }); string changeToken = response.ChangeToken; #endregion } public void WAFRegionalUpdateSqlInjectionMatchSet() { #region updatesqlinjectionmatchset-1475532094686 var client = new AmazonWAFRegionalClient(); var response = client.UpdateSqlInjectionMatchSet(new UpdateSqlInjectionMatchSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", SqlInjectionMatchSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5", Updates = new List<SqlInjectionMatchSetUpdate> { new SqlInjectionMatchSetUpdate { Action = "DELETE", SqlInjectionMatchTuple = new SqlInjectionMatchTuple { FieldToMatch = new FieldToMatch { Type = "QUERY_STRING" }, TextTransformation = "URL_DECODE" } } } }); string changeToken = response.ChangeToken; #endregion } public void WAFRegionalUpdateWebACL() { #region updatewebacl-1475533627385 var client = new AmazonWAFRegionalClient(); var response = client.UpdateWebACL(new UpdateWebACLRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", DefaultAction = new WafAction { Type = "ALLOW" }, Updates = new List<WebACLUpdate> { new WebACLUpdate { Action = "DELETE", ActivatedRule = new ActivatedRule { Action = new WafAction { Type = "ALLOW" }, Priority = 1, RuleId = "WAFRule-1-Example" } } }, WebACLId = "webacl-1472061481310" }); string changeToken = response.ChangeToken; #endregion } public void WAFRegionalUpdateXssMatchSet() { #region updatexssmatchset-1475534098881 var client = new AmazonWAFRegionalClient(); var response = client.UpdateXssMatchSet(new UpdateXssMatchSetRequest { ChangeToken = "abcd12f2-46da-4fdb-b8d5-fbd4c466928f", Updates = new List<XssMatchSetUpdate> { new XssMatchSetUpdate { Action = "DELETE", XssMatchTuple = new XssMatchTuple { FieldToMatch = new FieldToMatch { Type = "QUERY_STRING" }, TextTransformation = "URL_DECODE" } } }, XssMatchSetId = "example1ds3t-46da-4fdb-b8d5-abc321j569j5" }); string changeToken = response.ChangeToken; #endregion } # region ISample Members public virtual void Run() { } # endregion } }
671
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SDKDocGenerator { /// <summary> /// Parses the command line into argument settings controlling the documentation /// generator. /// </summary> internal class CommandArguments { /// <summary> /// Takes the command line arguments, fuses them with any response file that may also have /// been specified, and parses them. /// </summary> /// <param name="cmdlineArgs">The set of arguments supplied to the program</param> /// <returns></returns> public static CommandArguments Parse(string[] cmdlineArgs) { var arguments = new CommandArguments(); arguments.Process(cmdlineArgs); return arguments; } /// <summary> /// Set if an error is encountered whilst parsing arguments. /// </summary> public string Error { get; private set; } /// <summary> /// <para> /// The collection of options parsed from the command line. /// These arguments exist on the command line as individual entries /// prefixed with '-' or '/'. Options can be set in a response file /// and indicated with a '@' prefix, in which case the contents /// of the file will be read and inserted into the same relative /// location in the arguments to parse (allowing for later /// arguments to override). /// </para> /// <para> /// Options not specified on the command line are set from internal /// defaults. /// </para> /// </summary> public GeneratorOptions ParsedOptions { get; private set; } private CommandArguments() { ParsedOptions = new GeneratorOptions(); } private void Process(IEnumerable<string> cmdlineArgs) { // walk the supplied command line looking for any response file(s), indicated using // @filename, and fuse into one logical set of arguments we can parse var argsToParse = new List<string>(); foreach (var a in cmdlineArgs) { if (a.StartsWith("@", StringComparison.OrdinalIgnoreCase)) AddResponseFileArguments(a.Substring(1), argsToParse); else argsToParse.Add(a); } if (string.IsNullOrEmpty(Error)) { for (var argIndex = 0; argIndex < argsToParse.Count; argIndex++) { if (!IsSwitch(argsToParse[argIndex])) continue; var argDeclaration = FindArgDeclaration(argsToParse[argIndex]); if (argDeclaration != null) { if (argDeclaration.HasValue) argIndex++; if (argIndex < argsToParse.Count) argDeclaration.Parse(this, argsToParse[argIndex]); else Error = "Expected value for argument: " + argDeclaration.OptionName; } else Error = "Unrecognised argument: " + argsToParse[argIndex]; if (!string.IsNullOrEmpty(Error)) break; } } } private void AddResponseFileArguments(string responseFile, ICollection<string> args) { try { // Response file format is one argument (plus optional value) // per line. Comments can be used by putting # as the first char. using (var s = new StreamReader(ResolvePath(responseFile))) { var line = s.ReadLine(); while (line != null) { if (line.Length != 0 && line[0] != '#') { // trying to be flexible here and allow for lines with or without keyword // prefix in the response file var keywordEnd = line.IndexOf(' '); var keyword = keywordEnd > 0 ? line.Substring(0, keywordEnd) : line; if (ArgumentPrefixes.Any(prefix => keyword.StartsWith(prefix.ToString(CultureInfo.InvariantCulture)))) args.Add(keyword); else args.Add(ArgumentPrefixes[0] + keyword); if (keywordEnd > 0) { keywordEnd++; if (keywordEnd < line.Length) { var value = line.Substring(keywordEnd).Trim(' '); if (!string.IsNullOrEmpty(value)) args.Add(value); } } } line = s.ReadLine(); } } } catch (Exception e) { Error = string.Format("Caught exception processing response file {0} - {1}", responseFile, e.Message); } } delegate void ParseArgument(CommandArguments arguments, string argValue = null); class ArgDeclaration { public string OptionName { get; set; } public string ShortName { get; set; } public bool HasValue { get; set; } public ParseArgument Parse { get; set; } public string HelpText { get; set; } public string HelpExample { get; set; } } static readonly ArgDeclaration[] ArgumentsTable = { new ArgDeclaration { OptionName = "verbose", ShortName = "v", Parse = (arguments, argValue) => arguments.ParsedOptions.Verbose = true, HelpText = "Enable verbose output." }, new ArgDeclaration { OptionName = "waitonexit", ShortName = "w", Parse = (arguments, argValue) => arguments.ParsedOptions.WaitOnExit = true, HelpText = "Pauses waiting for a keypress after code generation completes." }, new ArgDeclaration { OptionName = "clean", ShortName = "c", Parse = (arguments, argValue) => arguments.ParsedOptions.Clean = true, HelpText = "Deletes all content in the specified out folder prior to generation.\n" + "The default behavior is to keep existing generated content and overwrite only changed items." }, new ArgDeclaration { OptionName = "testmode", ShortName = "t", Parse = (arguments, argValue) => arguments.ParsedOptions.TestMode = true, HelpText = "If set, generates a subset of the documentation for a predefined set of assemblies. Use for testing generator code changes." }, new ArgDeclaration { OptionName = "writestaticcontent", ShortName = "wsc", Parse = (arguments, argValue) => arguments.ParsedOptions.WriteStaticContent = true, HelpText = "If set, also generates the static content of the documentation framework." }, new ArgDeclaration { OptionName = "sdkassembliesroot", ShortName = "sdk", HasValue = true, Parse = (arguments, argValue) => arguments.ParsedOptions.SDKAssembliesRoot = argValue, HelpText = "The folder containing the version info manifest file (_sdk-versions.json) and the built SDK assemblies, organized into per-platform subfolders." }, new ArgDeclaration { OptionName = "sdkversionfile", ShortName = "sdkversion", HasValue = true, Parse = (arguments, argValue) => arguments.ParsedOptions.SDKVersionFilePath = argValue, HelpText = "The path to the _sdk-versions.json." }, new ArgDeclaration { OptionName = "platform", ShortName = "p", HasValue = true, Parse = (arguments, argValue) => arguments.ParsedOptions.Platform = argValue, HelpText = "The primary platform subfolder used for assembly discovery, controlling which assemblies get used in doc generation. " + "'net45', or the first available subfolder, is used if not specified." }, new ArgDeclaration { OptionName = "services", ShortName = "svc", HasValue = true, Parse = (arguments, argValue) => { var services = argValue.Split(',').ToList(); if (!services.Contains("Core")) services.Add("Core"); arguments.ParsedOptions.Services = services.ToArray(); }, HelpText = "Comma-delimited set of service names to process. If not specified all assemblies within the primary platform folder matching the SDK naming pattern are used." }, new ArgDeclaration { OptionName = "samplesfolder", ShortName = "sf", HasValue = true, Parse = (arguments, argValue) => arguments.ParsedOptions.CodeSamplesRootFolder = argValue, HelpText = "The root folder containing the SDK code samples." }, new ArgDeclaration { OptionName = "outputfolder", ShortName = "o", HasValue = true, Parse = (arguments, argValue) => arguments.ParsedOptions.OutputFolder = argValue, HelpText = "The root folder beneath which the generated documentation will be placed." } }; static readonly char[] ArgumentPrefixes = { '-', '/' }; /// <summary> /// Returns true if the supplied value has a argument prefix indicator, marking it as /// an argumentkeyword. /// </summary> /// <param name="argument"></param> /// <returns></returns> static bool IsSwitch(string argument) { return ArgumentPrefixes.Any(c => argument.StartsWith(c.ToString(CultureInfo.InvariantCulture))); } /// <summary> /// Scans the argument declaration table to find a matching entry for a token from the command line /// that is potentially an option keyword. /// </summary> /// <param name="argument">Keyword found on the command line. Any prefixes will be removed before attempting to match.</param> /// <returns>Matching declaration or null if keyword not recognised</returns> static ArgDeclaration FindArgDeclaration(string argument) { var keyword = argument.TrimStart(ArgumentPrefixes); return ArgumentsTable.FirstOrDefault(argDeclation => keyword.Equals(argDeclation.ShortName, StringComparison.OrdinalIgnoreCase) || keyword.Equals(argDeclation.OptionName, StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Resolves any relatively pathed filename. /// </summary> /// <param name="filePath"></param> /// <returns></returns> static string ResolvePath(string filePath) { if (Path.IsPathRooted(filePath)) return filePath; return Path.GetFullPath(filePath); } } }
285
aws-sdk-net
aws
C#
using System; namespace SDKDocGenerator { class Program { static int Main(string[] args) { var returnCode = -1; var commandArguments = CommandArguments.Parse(args); if (!string.IsNullOrEmpty(commandArguments.Error)) { Console.WriteLine(commandArguments.Error); return returnCode; } try { var docGenerator = new SdkDocGenerator(); returnCode = docGenerator.Execute(commandArguments.ParsedOptions); Console.WriteLine("Documentation generation completed in {0} minute {1} seconds", docGenerator.Duration.Minutes, docGenerator.Duration.Seconds); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); Console.WriteLine(e.StackTrace); } if (commandArguments.ParsedOptions.WaitOnExit) { Console.WriteLine("Press Enter to exit..."); Console.ReadLine(); } return returnCode; } } }
39
aws-sdk-net
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SDKDocGenerator")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SDKDocGenerator")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("99a5dc39-a447-45c7-be0f-fc87b464b252")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; using SDKDocGenerator; namespace SDKDocGenerator.UnitTests { public class NDocMethodSignatureTests { [Fact] public void GenericReturnMethod() { var methodInfo = typeof(TestMethods).GetMethod("Query", new Type[] { typeof(string) }); var signature = NDocUtilities.DetermineNDocNameLookupSignature(methodInfo, ""); Assert.Equal("M:SDKDocGenerator.UnitTests.TestMethods.Query``1(System.String)", signature); } [Fact] public void CollectionTestMethod() { var methodInfo = typeof(TestMethods).GetMethods().First(x => x.Name == "CollectionTest"); var signature = NDocUtilities.DetermineNDocNameLookupSignature(methodInfo, ""); Assert.Equal( "M:SDKDocGenerator.UnitTests.TestMethods.CollectionTest(System.Collections.Generic.IList{System.Collections.Generic.IDictionary{System.String,SDKDocGenerator.UnitTests.TestMethods}})", signature); } [Fact] public void MultiOutTestMethod() { var methodInfo = typeof(TestMethods).GetMethods().First(x => x.Name == "MultiOutTest"); var signature = NDocUtilities.DetermineNDocNameLookupSignature(methodInfo, ""); Assert.Equal( "M:SDKDocGenerator.UnitTests.TestMethods.MultiOutTest(System.Int32@,System.String@)", signature); } [Fact] public void CollectionOutTestMethod() { var methodInfo = typeof(TestMethods).GetMethods().First(x => x.Name == "CollectionOutTest"); var signature = NDocUtilities.DetermineNDocNameLookupSignature(methodInfo, ""); Assert.Equal( "M:SDKDocGenerator.UnitTests.TestMethods.CollectionOutTest(System.Collections.Generic.IList{System.String}@)", signature); } } public class TestMethods { /// <summary> /// Test Method /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <returns></returns> public T Query<T>(string name) { return default(T); } /// <summary> /// Test Method /// </summary> /// <param name="param"></param> public void CollectionTest(IList<IDictionary<string, TestMethods>> param) { } /// <summary> /// Test Method /// </summary> /// <param name="s1"></param> /// <param name="s2"></param> public void MultiOutTest(out int s1, out string s2) { s1 = 1; s2 = "Test"; } /// <summary> /// Test Method /// </summary> /// <param name="param"></param> public void CollectionOutTest(out IList<string> param) { param = new List<string>(); } } }
99
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace SDKDocGenerator.UnitTests { public class RedirectWriterTest { [Fact] public void ExtractFromUrlTest() { string serviceId; string shape; Assert.True(SDKDocRedirectWriter.ExtractServiceIDAndShapeFromUrl("https://docs.aws.amazon.com/goto/WebAPI/streams-dynamodb-2012-08-10/DescribeStream", out serviceId, out shape)); Assert.Equal("streams-dynamodb-2012-08-10", serviceId); Assert.Equal("DescribeStream", shape); Assert.True(SDKDocRedirectWriter.ExtractServiceIDAndShapeFromUrl("https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ResetImageAttribute", out serviceId, out shape)); Assert.Equal("ec2-2016-11-15", serviceId); Assert.Equal("ResetImageAttribute", shape); } } }
29
aws-sdk-net
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SDKDocGenerator.UnitTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SDKDocGenerator.UnitTests")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("884c59bf-05f7-49da-bf20-6bc6de5c737d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace SDKDocGenerator { public class FilenameGenerator { private const int MAX_FILE_SIZE = 160; // we shorten some namespaces to avoid hitting folder name limits in Windows. We need // to know this info when generating filenames as well as generating cross-service // urls public static Dictionary<string, string> ServiceNamespaceContractions = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase) { {"ElasticLoadBalancing", "ELB"}, {"ElasticBeanstalk", "EB"}, {"ElasticMapReduce", "EMR"}, {"ElasticTranscoder", "ETS"}, {"SimpleNotificationService", "SNS"}, {"IdentityManagement", "IAM"}, {"DatabaseMigrationService", "DMS"}, {"ApplicationDiscoveryService", "ADS"}, {"SimpleSystemsManagement", "SSM"}, }; // Where possible we use a fully namespaced name as key to avoid confusing same-named // shapes from different services that may or may not differ in casing only, eg // HttpHeader in CognitoIdentityProvider vs HTTPHeader in WAF/WAFRegional. We also use // case sensitive comparison in the unlikely event a service introduces shapes with // the same name differing only in case. private static readonly Dictionary<string, string> FixedupNameDictionary = new Dictionary<string, string>(StringComparer.Ordinal); private static string Fixup(string name, TypeWrapper type = null) { var lookupKey = type == null ? name : string.Concat(type.Namespace, ".", name); string fixedUpName; if (FixedupNameDictionary.TryGetValue(lookupKey, out fixedUpName)) { return fixedUpName; } var sb = new StringBuilder(name); // don't use encoded <> in filename, as browsers re-encode it in links to %3C // and the link fails sb.Replace('.', '_') .Replace("&lt;", "!") .Replace("&gt;", "!") .Replace("Amazon", "") .Replace("_Model_", "") .Replace("_Begin", "") .Replace("_End", "") .Replace("Client_", "") .Replace("+", "") .Replace("_", ""); foreach (var k in ServiceNamespaceContractions.Keys) { sb.Replace(k, ServiceNamespaceContractions[k]); } if (sb.Length > MAX_FILE_SIZE) { throw new ApplicationException(string.Format("Filename: {0} is too long", sb)); } fixedUpName = sb.ToString(); FixedupNameDictionary[lookupKey] = fixedUpName; return fixedUpName; } public static string GenerateParametersTail(IList<ParameterInfoWrapper> parameters) { var sb = new StringBuilder(); foreach (var parameter in parameters) { if (sb.Length > 0) sb.Append("_"); sb.AppendFormat("{0}", Fixup(parameter.ParameterType.GetDisplayName(false), parameter.ParameterType)); } return sb.ToString(); } public static string GenerateFilename(TypeWrapper type) { return Fixup(string.Format("T_{0}", type.Name), type) + ".html"; } public static string GenerateFilename(PropertyInfoWrapper info) { return Fixup(string.Format("P_{0}_{1}", info.DeclaringType.Name, info.Name), info.DeclaringType) + ".html"; } public static string GenerateFilename(MethodInfoWrapper info) { return Fixup(string.Format("M_{0}_{1}_{2}", info.DeclaringType.Name, info.Name, GenerateParametersTail(info.GetParameters())), info.DeclaringType) + ".html"; } public static string GenerateFilename(ConstructorInfoWrapper info) { return Fixup(string.Format("M_{0}_{1}_{2}", info.DeclaringType.Name, info.Name, GenerateParametersTail(info.GetParameters())), info.DeclaringType) + ".html"; } public static string GenerateFilename(FieldInfoWrapper info) { return Fixup(string.Format("F_{0}_{1}", info.DeclaringType.Name, info.Name), info.DeclaringType) + ".html"; } public static string GenerateFilename(EventInfoWrapper info) { return Fixup(string.Format("E_{0}_{1}", info.DeclaringType.Name, info.Name), info.DeclaringType) + ".html"; } public static string GenerateNamespaceFilename(string namespaceName) { return Fixup(string.Format("N_{0}", namespaceName)) + ".html"; } public static string Escape(string url) { return url.Replace("`", "&#96;"); } } }
127
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SDKDocGenerator { public abstract class FileUtilties { /// <summary> /// Copies one folder's content to another, optionally recursing the source hierarchy. /// </summary> /// <param name="sourceFolder">The source path to copy content from.</param> /// <param name="destinationFolder">The target folder to receive the content. It will be created if it does not exist.</param> /// <param name="recurse">True to recurse the source to copy the entire hierarchy.</param> public static void FolderCopy(string sourceFolder, string destinationFolder, bool recurse) { var dir = new DirectoryInfo(sourceFolder); var dirs = dir.GetDirectories(); if (!dir.Exists) throw new DirectoryNotFoundException("Source directory does not exist or could not be found: " + sourceFolder); if (!Directory.Exists(destinationFolder)) Directory.CreateDirectory(destinationFolder); // Get the files in the directory and copy them to the new location. var files = dir.GetFiles(); foreach (var file in files) { var temppath = Path.Combine(destinationFolder, file.Name); file.CopyTo(temppath, true); } // If copying subdirectories, copy them and their contents to new location. if (recurse) { foreach (var subdir in dirs) { var temppath = Path.Combine(destinationFolder, subdir.Name); FolderCopy(subdir.FullName, temppath, true); } } } /// <summary> /// Removes all files in the specified folder. If the recurse option /// is set the entire folder tree is removed. /// </summary> /// <param name="folder">The folder to clean.</param> /// <param name="recurse">If true, </param> public static void CleanFolder(string folder, bool recurse) { if (!Directory.Exists(folder)) return; if (recurse) { Directory.Delete(folder, true); return; } var files = Directory.GetFiles(folder); foreach (var f in files) { File.Delete(f); } } } }
73
aws-sdk-net
aws
C#
using System; namespace SDKDocGenerator { /// <summary> /// Abstracts the .Net version from the platform folder. /// </summary> public class FrameworkVersion : MarshalByRefObject { public readonly static FrameworkVersion DotNet35 = new FrameworkVersion(".NET Framework 3.5", "NET3_5"); public readonly static FrameworkVersion DotNet45 = new FrameworkVersion(".NET Framework 4.5", "NET4_5"); public FrameworkVersion(string displayName, string shortName) { this.DisplayName = displayName; this.ShortName = shortName; } public string DisplayName { get; private set; } public string ShortName { get; private set; } public override string ToString() { return this.DisplayName; } public static FrameworkVersion FromPlatformFolder(string platformFolder) { if (platformFolder.Equals("net35", StringComparison.OrdinalIgnoreCase)) return DotNet35; return DotNet45; } } }
45
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using System.Xml.XPath; using SDKDocGenerator.Writers; using System.Diagnostics; using System.Reflection; namespace SDKDocGenerator { /// <summary> /// Wraps the generation information required to emit documentation for /// a service, which may have assemblies in all or some of the platforms /// subfolders. /// </summary> public class GenerationManifest { /// <summary> /// The expected naming pattern of AWS generated assemblies is 'awssdk.*.dll' with /// the variable part being the service name (long or short form). /// </summary> public const string AWSAssemblyNamePrefix = "AWSSDK"; /// <summary> /// The preferred platform against which we generate documentation, if it's available. /// </summary> public const string PreferredPlatform = "net45"; /// <summary> /// Represents a single service, supported on one or more platforms, that we will be /// generating documentation for. /// </summary> /// <param name="assemblyPath"> /// The full path and filename of the assembly. The .Net platform for the assembly /// is assumed to be the name of the folder containing the assembly. The name of the /// service will be inferred from the name pattern of the assembly. /// </param> /// <param name="outputFolderRoot"> /// The root output folder that the artifacts should be placed in. A further subfolder /// representing the service (or 'core' if the assembly is the runtime) is added. /// </param> /// <param name="allPlatforms">The set of platform subfolders to use to discover ndoc tables</param> /// <param name="options">The user options governing doc generation</param> /// <param name="useAppDomain"></param> public GenerationManifest(string assemblyPath, string outputFolderRoot, IEnumerable<string> allPlatforms, GeneratorOptions options, bool useAppDomain) { AssemblyPath = Path.GetFullPath(assemblyPath); AssemblyName = Path.GetFileNameWithoutExtension(AssemblyPath); ServiceName = AssemblyName.StartsWith(AWSAssemblyNamePrefix + ".", StringComparison.OrdinalIgnoreCase) ? AssemblyName.Substring(AWSAssemblyNamePrefix.Length + 1) : AssemblyName; Options = options; OutputFolder = Path.GetFullPath(outputFolderRoot); AllPlatforms = allPlatforms; UseAppDomain = useAppDomain; if (Options.Verbose) { Trace.WriteLine("\tConstructed GenerationManifest:"); Trace.WriteLine($"\t...AssemblyPath: {AssemblyPath}"); Trace.WriteLine($"\t...ServiceName: {ServiceName}"); Trace.WriteLine($"\t...OutputFolder: {OutputFolder}"); } } /// <summary> /// The path and filename to the assembly represented by this set of artifacts /// </summary> public string AssemblyPath { get; } /// <summary> /// The basename of the sdk assembly we're generating docs for, less extension. /// </summary> public string AssemblyName { get; } public IEnumerable<string> AllPlatforms { get; } /// <summary> /// The root output folder; the artifacts will be placed under /// here in their top-level namespace subfolders (less the Amazon. /// part). So Amazon.DynamoDBv2.* types get emitted to 'dynamodbv2' /// underneath this root. /// </summary> public string OutputFolder { get; } /// <summary> /// The generation options specified by the user /// </summary> public GeneratorOptions Options { get; } /// <summary> /// If true, sdk assemblies are loaded into a separate app domain prior to doc /// generation. /// </summary> public bool UseAppDomain { get; } /// <summary> /// Returns the discovered NDoc table for a given platform, if it existed. If platform /// is not specified, we attempt to return the NDoc for the primary platform specified /// in the generator options. /// </summary> /// <param name="platform"></param> /// <returns></returns> public IDictionary<string, XElement> NDocForPlatform(string platform = null) { if (string.IsNullOrEmpty(platform)) { platform = Options.Platform; } return NDocUtilities.GetDocumentationInstance(ServiceName, platform); } /// <summary> /// The logical name of the service. This is assumed to exist /// in the assembly name after 'awssdk.' and before the extension. /// </summary> public string ServiceName { get; } private ManifestAssemblyWrapper _manifestAssemblyWrapper; /// <summary> /// Contains the wrapped sdk assembly and the app domain we loaded it /// into, if so configured. Dispose of this when processing of the /// assembly is complete if the assembly contained no types that need /// deferred processing alongside the core sdk assembly. /// </summary> public ManifestAssemblyWrapper ManifestAssemblyContext { get { if (_manifestAssemblyWrapper == null) { _manifestAssemblyWrapper = new ManifestAssemblyWrapper(ServiceName, Options.Platform, AssemblyPath, UseAppDomain); } return _manifestAssemblyWrapper; } private set { if (value == null) { _manifestAssemblyWrapper?.Dispose(); } _manifestAssemblyWrapper = value; } } /// <summary> /// Returns the subfolder name that should be used for Amazon artifacts /// belonging to the specified namespace. Typically we use the service /// root level (the second part) in the namespace. If the namespace is /// not recognized as belonging to Amazon, an empty string is returned. /// </summary> /// <param name="ns">The namespace of a discovered type (Amazon or 3rd party)</param> /// <returns></returns> public static string OutputSubFolderFromNamespace(string ns) { if (ns.IndexOf('.') == -1) return ns; if (!ns.StartsWith("Amazon.")) return string.Empty; var nsParts = ns.Split('.'); string nsPart; switch (nsParts.Length) { case 0: nsPart = ns; break; case 1: nsPart = nsParts[0]; break; default: nsPart = nsParts[1]; break; } if (FilenameGenerator.ServiceNamespaceContractions.ContainsKey(nsPart)) return FilenameGenerator.ServiceNamespaceContractions[nsPart]; return nsPart; } /// <summary> /// Generates the documentation for the artifacts represented by this /// manifest, starting at the namespace(s) in the assembly and working /// down through the type hierarchy. Types that exist in the deferable /// namespaces will be processed later in generation, when the awssdk.core /// assembly is processed. /// </summary> /// <param name="deferrableTypes"> /// Collection for types in service assemblies that we want to defer processing /// on until we process awssdk.core. /// </param> /// <param name="tocWriter"> /// Toc generation handler to which each processed namespace is registered /// </param> public void Generate(DeferredTypesProvider deferrableTypes, TOCWriter tocWriter) { Trace.WriteLine($"\tgenerating from {Options.Platform}/{Path.GetFileName(AssemblyPath)}"); // load the assembly and ndoc dataset for the service we're about to generate; assuming // they contain no deferrable types we'll release them when done var discardAssemblyOnExit = true; foreach (var platform in AllPlatforms) { NDocUtilities.LoadDocumentation(AssemblyName, ServiceName, platform, Options); } var namespaceNames = ManifestAssemblyContext.SdkAssembly.GetNamespaces(); var frameworkVersion = FrameworkVersion.FromPlatformFolder(Options.Platform); var processed = 0; foreach (var namespaceName in namespaceNames) { // when processing awssdk.core, we don't get handed a collection to hold // deferrable types if (deferrableTypes != null) { if (deferrableTypes.Namespaces.Contains(namespaceName)) { var types = ManifestAssemblyContext.SdkAssembly.GetTypesForNamespace(namespaceName); if (types.Any()) { Trace.WriteLine($"\t\tdeferring processing of types in namespace {namespaceName} for {Path.GetFileName(AssemblyPath)}"); deferrableTypes.AddTypes(types); discardAssemblyOnExit = false; } continue; } } WriteNamespace(frameworkVersion, namespaceName); tocWriter.BuildNamespaceToc(namespaceName, ManifestAssemblyContext.SdkAssembly); Trace.WriteLine($"\t\t{namespaceName} processed ({++processed} of {namespaceNames.Count()})"); } if (discardAssemblyOnExit) { // release artifact roots for future GC collections to operate on foreach (var platform in AllPlatforms) { NDocUtilities.UnloadDocumentation(ServiceName, platform); } ManifestAssemblyContext.Dispose(); ManifestAssemblyContext = null; } } void WriteNamespace(FrameworkVersion version, string namespaceName) { var writer = new NamespaceWriter(this, version, namespaceName); writer.Write(); foreach (var type in ManifestAssemblyContext.SdkAssembly.GetTypesForNamespace(namespaceName)) { WriteType(version, type); } } void WriteType(FrameworkVersion version, TypeWrapper type) { var writer = new ClassWriter(this, version, type); writer.Write(); foreach (var item in type.GetConstructors().Where(x => x.IsPublic)) { var itemWriter = new ConstructorWriter(this, version, item); itemWriter.Write(); } foreach (var item in type.GetMethodsToDocument()) { // If a method is in another namespace, it is inherited and should not be overwritten if (item.DeclaringType.Namespace == type.Namespace) { var itemWriter = new MethodWriter(this, version, item); itemWriter.Write(); } } foreach (var item in type.GetEvents()) { // If an event is in another namespace, it is inherited and should not be overwritten if (item.DeclaringType.Namespace == type.Namespace) { var itemWriter = new EventWriter(this, version, item); itemWriter.Write(); } } } public class ManifestAssemblyWrapper : IDisposable { public AssemblyWrapper SdkAssembly { get; private set; } public AppDomain Domain { get; private set; } public ManifestAssemblyWrapper(string serviceName, string platform, string assemblyPath, bool useNewAppDomain) { var docId = NDocUtilities.GenerateDocId(serviceName, platform); if (useNewAppDomain) { Domain = AppDomain.CreateDomain(assemblyPath); var inst = Domain.CreateInstance(this.GetType().Assembly.FullName, typeof(AssemblyWrapper).FullName, true, BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance, null, new object[] { docId }, null, null); SdkAssembly = (AssemblyWrapper)inst.Unwrap(); SdkAssembly.LoadAssembly(assemblyPath); } else { SdkAssembly = new AssemblyWrapper(docId); SdkAssembly.LoadAssembly(assemblyPath); } } #region IDisposable Support private bool _disposedValue; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { // unlink roots, then drop the domain if we used one SdkAssembly = null; if (Domain != null) { AppDomain.Unload(Domain); Domain = null; } } _disposedValue = true; } } public void Dispose() { // we have no finalizer and/or unmanaged resources, so no need to use GC.SuppressFinalize() Dispose(true); } #endregion } } }
364
aws-sdk-net
aws
C#
using System.IO; namespace SDKDocGenerator { /// <summary> /// Command line options for the AWS SDK for .NET documentation generator /// </summary> public class GeneratorOptions { /// <summary> /// If set, causes the generator to emit additional diagnostic messages /// whilst running. /// </summary> public bool Verbose { get; set; } /// <summary> /// If set, waits for keypress before exiting generation. /// </summary> public bool WaitOnExit { get; set; } /// <summary> /// If set, the contents of the generated subfolder hierarchy are deleted prior /// to code generation. The default behavior is to leave existing generated /// content in-place and perform a cumulative generation pass. /// </summary> public bool Clean { get; set; } /// <summary> /// If set, the generator runs against a predefined set of assemblies to /// generate a documentation subset. Use this mode when working on the generator /// code to test changes. /// </summary> public bool TestMode { get; set; } /// <summary> /// If set the static content forming the docset framework is also generated into /// the output folder. To generate framework only, and no service documentation, /// use this switch and omit -AssembliesFolder. /// </summary> public bool WriteStaticContent { get; set; } /// <summary> /// The root folder containing the per-platform subfolders of SDK assemblies. /// </summary> public string SDKAssembliesRoot { get; set; } /// <summary> /// The path to _sdk-versions.json /// </summary> string _sdkVersionFilePath; public string SDKVersionFilePath { get { if (string.IsNullOrWhiteSpace(this._sdkVersionFilePath)) return Path.Combine(Directory.GetParent(this.SDKAssembliesRoot).FullName, "_sdk-versions.json"); return this._sdkVersionFilePath; } set { this._sdkVersionFilePath = value; } } /// <summary> /// The platform subfolder considered to be hosting the primary source of /// assemblies for doc generation. If not specified, we attempt to use 'net45'. /// If that subfolder platform does not exist, we'll use the first subfolder /// under the SDKAssembliesRoot that we find. /// </summary> public string Platform { get; set; } /// <summary> /// The names of one or more services to limit the generation to. If not specified /// all assemblies matching the SDK naming pattern with SDKAssembliesRoot\PrimaryPlatform /// are used. /// </summary> public string[] Services { get; set; } /// <summary> /// The root folder beneath which the generated documentation will be placed. /// </summary> public string OutputFolder { get; set; } /// <summary> /// The subfolder where the dynamically generated content is placed (beneath /// output root). This defaults to "items". /// </summary> public string ContentSubFolderName { get; set; } /// <summary> /// Custom BJS region documentation domain - we should generalize this /// </summary> public string BJSDocsDomain { get; set; } /// <summary> /// The root folder containing SDK code samples /// </summary> public string CodeSamplesRootFolder { get; set; } /// <summary> /// Returns the concatenation of the output folder and the content subfolder /// </summary> public string ComputedContentFolder { get { return Path.Combine(OutputFolder, ContentSubFolderName); } } /// <summary> /// Constructs default options for the generator, which are to process /// all services found for the .Net 4.5 platform, and emit the doc /// framework static content files. The default paths are relative to /// the executing generator assembly. /// </summary> public GeneratorOptions() { Verbose = false; WriteStaticContent = true; // we don't default the sdk assembly root, as it can // change between invoking from within Visual Studio // or via our build scripts Platform = "net45"; Services = new [] { "*" }; OutputFolder = @"..\..\..\..\Deployment\docs"; ContentSubFolderName = "items"; BJSDocsDomain = "docs.amazonaws.cn"; } } }
130
aws-sdk-net
aws
C#
using System; using System.CodeDom; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Xml.XPath; using System.Xml.Linq; using SDKDocGenerator.Writers; using System.Xml; using System.Diagnostics; using System.Text.RegularExpressions; using System.Web; namespace SDKDocGenerator { public static class NDocUtilities { public const string MSDN_TYPE_URL_PATTERN = "https://msdn.microsoft.com/en-us/library/{0}.aspx"; public const string DOC_SAMPLES_SUBFOLDER = "AWSSDKDocSamples"; public const string crossReferenceOpeningTagText = "<see"; // <see> and <seealso> tags public const string crossReferenceClosingTagText = "/>"; public const string crefAttributeName = "cref"; public const string hrefAttributeName = "href"; public const string nameAttributeName = "name"; public const string targetAttributeName = "target"; // inner attribute of a cross reference tag we're interested in public static readonly string innerCrefAttributeText = crefAttributeName + "=\""; public static readonly string innerHrefAttributeText = hrefAttributeName + "=\""; private static readonly Dictionary<string, string> NdocToHtmlElementMapping = new Dictionary<string, string>(StringComparer.Ordinal) { { "summary", "p" }, { "para", "p" }, { "see", "a" }, { "paramref", "code" } }; #region manage ndoc instances // The reason we cache the doc data on the side instead of directly referencing doc instances from // the type information is becasue we are loading the assemblies for reflection in a separate app domain. private static IDictionary<string, IDictionary<string, XElement>> _ndocCache = new Dictionary<string, IDictionary<string, XElement>>(); public static string GenerateDocId(string serviceName, string platform) { // platform can be null; in which case we just use an empty string to construct the id. return string.Format("{0}:{1}", serviceName, platform == null ? "" : platform); } public static void LoadDocumentation(string assemblyName, string serviceName, string platform, GeneratorOptions options) { var ndocFilename = assemblyName + ".xml"; var platformSpecificNdocFile = Path.Combine(options.SDKAssembliesRoot, platform, ndocFilename); if (File.Exists(platformSpecificNdocFile)) { var docId = GenerateDocId(serviceName, platform); _ndocCache.Add(docId, CreateNDocTable(platformSpecificNdocFile, serviceName, options)); } } public static void UnloadDocumentation(string serviceName, string platform) { var docId = GenerateDocId(serviceName, platform); _ndocCache.Remove(docId); } public static IDictionary<string, XElement> GetDocumentationInstance(string serviceName, string platform) { return GetDocumentationInstance(GenerateDocId(serviceName, platform)); } public static IDictionary<string, XElement> GetDocumentationInstance(string docId) { IDictionary<string, XElement> doc = null; if (_ndocCache.TryGetValue(docId, out doc)) { return doc; } return null; } private static IDictionary<string, XElement> CreateNDocTable(string filePath, string serviceName, GeneratorOptions options) { var dict = new Dictionary<string, XElement>(); var document = LoadAssemblyDocumentationWithSamples(filePath, options.CodeSamplesRootFolder, serviceName); PreprocessCodeBlocksToPreTags(options, document); foreach (var element in document.XPathSelectElements("//members/member")) { var xattribute = element.Attributes().FirstOrDefault(x => x.Name.LocalName == "name"); if (xattribute == null) continue; dict[xattribute.Value] = element; } return dict; } #endregion public static XElement FindDocumentation(AbstractWrapper wrapper) { var ndoc = GetDocumentationInstance(wrapper.DocId); return FindDocumentation(ndoc, wrapper); } public static XElement FindDocumentation(IDictionary<string, XElement> ndoc, AbstractWrapper wrapper) { if (ndoc == null) return null; if (wrapper is TypeWrapper) return FindDocumentation(ndoc, (TypeWrapper)wrapper); if (wrapper is PropertyInfoWrapper) return FindDocumentation(ndoc, (PropertyInfoWrapper)wrapper); if (wrapper is MethodInfoWrapper) return FindDocumentation(ndoc, (MethodInfoWrapper)wrapper); if (wrapper is ConstructorInfoWrapper) return FindDocumentation(ndoc, (ConstructorInfoWrapper)wrapper); if (wrapper is FieldInfoWrapper) return FindDocumentation(ndoc, (FieldInfoWrapper)wrapper); return null; } public static XElement FindDocumentation(IDictionary<string, XElement> ndoc, FieldInfoWrapper info) { var signature = string.Format("F:{0}.{1}", info.DeclaringType.FullName, info.Name); XElement element; if (!ndoc.TryGetValue(signature, out element)) return null; return element; } public static XElement FindFieldDocumentation(TypeWrapper type, string fieldName) { var ndoc = GetDocumentationInstance(type.DocId); return FindFieldDocumentation(ndoc, type, fieldName); } public static XElement FindFieldDocumentation(IDictionary<string, XElement> ndoc, TypeWrapper type, string fieldName) { var signature = string.Format("F:{0}.{1}", type.FullName, fieldName); XElement element; if (!ndoc.TryGetValue(signature, out element)) return null; return element; } public static XElement FindDocumentation(IDictionary<string, XElement> ndoc, TypeWrapper type) { var signature = "T:" + type.FullName; XElement element; if (!ndoc.TryGetValue(signature, out element)) return null; return element; } public static XElement FindDocumentation(IDictionary<string, XElement> ndoc, PropertyInfoWrapper info) { var type = info.DeclaringType; var signature = string.Format("P:{0}.{1}", type.FullName, info.Name); XElement element; if (!ndoc.TryGetValue(signature, out element)) return null; return element; } public static XElement FindDocumentation(IDictionary<string, XElement> ndoc, EventInfoWrapper info) { var type = info.DeclaringType; var signature = string.Format("E:{0}.{1}", type.FullName, info.Name); XElement element; if (!ndoc.TryGetValue(signature, out element)) return null; return element; } public static string DetermineNDocNameLookupSignature(MethodInfo info, string docId) { return DetermineNDocNameLookupSignature(new MethodInfoWrapper(info, docId)); } public static string DetermineNDocNameLookupSignature(MethodInfoWrapper info) { var type = info.DeclaringType; var fullName = type.FullName ?? type.Namespace + "." + type.Name; var typeGenericParameters = type.GetGenericArguments(); var parameters = new StringBuilder(); foreach (var param in info.GetParameters()) { if (parameters.Length > 0) parameters.Append(","); DetermineParameterName(param.ParameterType, parameters, typeGenericParameters); if (param.IsOut) { parameters.Append("@"); } } var genericTag = ""; if (info.IsGenericMethod) { genericTag = "``" + info.GetGenericArguments().Length; } var signature = parameters.Length > 0 ? string.Format("M:{0}.{1}{2}({3})", fullName, info.Name, genericTag, parameters) : string.Format("M:{0}.{1}{2}", fullName, info.Name, genericTag); return signature; } private static void DetermineParameterName(TypeWrapper parameterTypeInfo, StringBuilder parameters, IList<TypeWrapper> typeGenericParameters) { if (parameterTypeInfo.IsGenericParameter) { var typeGenericParameterIndex = typeGenericParameters.IndexOf(parameterTypeInfo); var isClassGenericParameter = typeGenericParameterIndex >= 0; if (isClassGenericParameter) parameters.AppendFormat("`{0}", typeGenericParameterIndex); else parameters.AppendFormat("``{0}", 0); } else if (parameterTypeInfo.IsGenericType) { parameters .Append(parameterTypeInfo.GenericTypeName) .Append("{"); IList<TypeWrapper> args = parameterTypeInfo.GenericTypeArguments(); for (var i = 0; i < args.Count; i++) { if (i != 0) { parameters.Append(","); } DetermineParameterName(args[i], parameters, typeGenericParameters); } parameters.Append("}"); } else { parameters.Append(parameterTypeInfo.FullName); } } public static XElement FindDocumentation(IDictionary<string, XElement> ndoc, MethodInfoWrapper info) { var signature = DetermineNDocNameLookupSignature(info); XElement element; if (!ndoc.TryGetValue(signature, out element)) return null; return element; } public static XElement FindDocumentation(IDictionary<string, XElement> ndoc, ConstructorInfoWrapper info) { var type = info.DeclaringType; var parameters = new StringBuilder(); var typeGenericParameters = type.GetGenericArguments(); foreach (var param in info.GetParameters()) { if (parameters.Length > 0) parameters.Append(","); DetermineParameterName(param.ParameterType, parameters, typeGenericParameters); if (param.IsOut) { parameters.Append("@"); } } var formattedParmaters = parameters.Length > 0 ? string.Format("({0})", parameters) : parameters.ToString(); var signature = string.Format("M:{0}.#ctor{1}", type.FullName, formattedParmaters); XElement element; if (!ndoc.TryGetValue(signature, out element)) return null; return element; } public static string FindParameterDocumentation(XElement ndoc, string name) { if (ndoc == null) return string.Empty; var node = ndoc.XPathSelectElement(string.Format("./param[@name = '{0}']", name)); if (node == null) return string.Empty; return node.Value; } public static string FindReturnDocumentation(XElement ndoc) { if (ndoc == null) return string.Empty; var node = ndoc.XPathSelectElement("returns"); if (node == null) return string.Empty; return node.Value; } /// <summary> /// Finds the Async version of the specified non async method info. /// </summary> /// <param name="ndoc"></param> /// <param name="info"></param> /// <returns></returns> public static XElement FindDocumentationAsync(IDictionary<string, XElement> ndoc, MethodInfoWrapper info) { if (ndoc == null) return null; var type = info.DeclaringType; if (type.FullName == null) return null; var parameters = new StringBuilder(); foreach (var param in info.GetParameters()) { if (parameters.Length > 0) parameters.Append(","); if (param.ParameterType.IsGenericType) { parameters .Append(param.ParameterType.GenericTypeName) .Append("{") .Append(string.Join(",", param.ParameterType.GenericTypeArguments().Select(a => a.FullName))) .Append("}"); } else { parameters.Append(param.ParameterType.FullName); if (param.IsOut) parameters.Append("@"); } } if (parameters.Length > 0) parameters.Append(","); // Async methods have this additional parameter parameters.Append("System.Threading.CancellationToken"); var signature = parameters.Length > 0 ? string.Format("M:{0}.{1}({2})", type.FullName, info.Name + "Async", parameters) : string.Format("M:{0}.{1}", type.FullName, info.Name + "Async"); XElement element; if (!ndoc.TryGetValue(signature, out element)) return null; return element; } public static string TransformDocumentationToHTML(XElement element, string rootNodeName, AbstractTypeProvider typeProvider, FrameworkVersion version) { if (element == null) return string.Empty; var rootNode = element.XPathSelectElement(rootNodeName); if (rootNode == null) return string.Empty; if (rootNodeName.Equals("seealso", StringComparison.OrdinalIgnoreCase)) return SeeAlsoElementToHTML(rootNode, typeProvider, version); else return DocBlobToHTML(rootNode, typeProvider, version); } private static string SeeAlsoElementToHTML(XElement rootNode, AbstractTypeProvider typeProvider, FrameworkVersion version) { var reader = rootNode.CreateReader(); reader.MoveToContent(); var innerXml = reader.ReadInnerXml(); string content = ""; var href = rootNode.Attribute("href"); if (href != null) { content += string.Format(@"<div><a href=""{0}"" target=""_parent"" rel=""noopener noreferrer"">{1}</a></div>", href.Value, innerXml); } var cref = rootNode.Attribute("cref"); if (cref != null) { content += BaseWriter.CreateCrossReferenceTagReplacement(typeProvider, cref.Value, version); } return content; } private static string DocBlobToHTML(XElement rootNode, AbstractTypeProvider typeProvider, FrameworkVersion version) { using (var textWriter = new StringWriter()) { var writerSettings = new XmlWriterSettings { OmitXmlDeclaration = true }; using (var writer = XmlWriter.Create(textWriter, writerSettings)) { var reader = rootNode.CreateReader(); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: // handle self-closing element, like <a /> // this must be read before any other reading is done var selfClosingElement = reader.IsEmptyElement; // element name substitution, if necessary string elementName; if (!NdocToHtmlElementMapping.TryGetValue(reader.LocalName, out elementName)) elementName = reader.LocalName; // some elements can't be empty, use this variable for that string emptyElementContents = null; // start element writer.WriteStartElement(elementName); // copy over attributes if (reader.HasAttributes) { var isAbsoluteLink = false; var hasTarget = false; for (int i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); var attributeName = reader.Name; var attributeValue = reader.Value; var isCref = string.Equals(attributeName, crefAttributeName, StringComparison.Ordinal); var isHref = string.Equals(attributeName, hrefAttributeName, StringComparison.Ordinal); var isName = string.Equals(attributeName, nameAttributeName, StringComparison.Ordinal); var isTarget = string.Equals(attributeName, targetAttributeName, StringComparison.Ordinal); var writeAttribute = true; if (isCref) { // replace cref with href attributeName = hrefAttributeName; // extract type name from cref value for emptyElementContents var crefParts = attributeValue.Split(':'); if (crefParts.Length != 2) throw new InvalidOperationException(); var typeName = crefParts[1]; var targetType = typeProvider.GetType(typeName); if (targetType == null) { emptyElementContents = typeName; //If the type cannot be found do not render out the href attribute. //This will make it so things such as properties which we do not have //specific doc pages for do not render as a broken link but we can still //use the crefs in the code correctly. writeAttribute = false; } else emptyElementContents = targetType.CreateReferenceHtml(fullTypeName: true); } else if (isHref) { // extract href value for emptyElementContents emptyElementContents = attributeValue; if(attributeValue.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || attributeValue.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) { isAbsoluteLink = true; } } else if (isName) { emptyElementContents = attributeValue; } else if (isTarget) { hasTarget = true; } if(writeAttribute) { writer.WriteAttributeString(attributeName, attributeValue); } } if(elementName == "a" && isAbsoluteLink && !hasTarget) { //Add a target=\"_blank\" to allow the absolute link to break out //of the frame. writer.WriteAttributeString(targetAttributeName, "_blank"); } } // if this is a self-closing element, close it if (selfClosingElement) { // write empty element contents, if any if (!string.IsNullOrEmpty(emptyElementContents)) { writer.WriteRaw(emptyElementContents); } // close element now writer.WriteEndElement(); } break; case XmlNodeType.EndElement: writer.WriteEndElement(); break; case XmlNodeType.Text: writer.WriteRaw(reader.Value); break; default: throw new InvalidOperationException(); } } } return textWriter.ToString(); } } public static void PreprocessCodeBlocksToPreTags(GeneratorOptions options, XDocument doc) { var nodesToRemove = new List<XElement>(); var codeNodes = doc.XPathSelectElements("//code"); foreach (var codeNode in codeNodes) { string processedCodeSample = null; var xattribute = codeNode.Attributes().FirstOrDefault(x => x.Name.LocalName == "source"); if (xattribute != null) { var sourceRelativePath = xattribute.Value; xattribute = codeNode.Attributes().FirstOrDefault(x => x.Name.LocalName == "region"); if (xattribute == null) continue; var regionName = xattribute.Value; var samplePath = FindSampleCodePath(options.CodeSamplesRootFolder, sourceRelativePath); if (samplePath == null) { Console.Error.WriteLine("Error finding sample path for {0}", sourceRelativePath); continue; } var content = File.ReadAllText(samplePath); var startPos = content.IndexOf("#region " + regionName); if (startPos == -1) { Console.Error.WriteLine("Error finding region for {0}", regionName); continue; } startPos = content.IndexOf('\n', startPos); var endPos = content.IndexOf("#endregion", startPos); var sampleCode = content.Substring(startPos, endPos - startPos); processedCodeSample = HttpUtility.HtmlEncode(sampleCode); } else { processedCodeSample = HttpUtility.HtmlEncode(codeNode.Value); } if (processedCodeSample != null && processedCodeSample.IndexOf('\n') > -1) { processedCodeSample = LeftJustifyCodeBlocks(processedCodeSample); var preElement = new XElement("pre", processedCodeSample); preElement.SetAttributeValue("class", "brush: csharp"); codeNode.AddAfterSelf(preElement); nodesToRemove.Add(codeNode); string title = null; xattribute = codeNode.Attributes().FirstOrDefault(x => x.Name.LocalName == "title"); if (xattribute != null) title = xattribute.Value; if (title != null) { var titleElement = new XElement("h4", title); titleElement.SetAttributeValue("class", "csharp-code-sample-title"); preElement.AddBeforeSelf(titleElement); } } } nodesToRemove.ForEach(x => x.Remove()); } private static string FindSampleCodePath(string codeSampleRootDirectory, string relativePath) { if (string.IsNullOrEmpty(codeSampleRootDirectory)) return null; var fullPath = Path.Combine(codeSampleRootDirectory, relativePath); return !File.Exists(fullPath) ? null : fullPath; } private static string LeftJustifyCodeBlocks(string codeBlock) { // Switch tabs to 4 spaces var block = new StringBuilder(codeBlock).Replace("\t", new string(' ', 4)).ToString(); // Find the nearest indent location var nearestIndent = int.MaxValue; using (var reader = new StringReader(block)) { string line; while ((line = reader.ReadLine()) != null) { int indent = FindFirstNoWhitePosition(line); if (indent != -1 && indent < nearestIndent) nearestIndent = indent; } } // Substring all lines with content to the indent location; var reformattedBuilder = new StringBuilder(); using (var reader = new StringReader(block)) { string line; while ((line = reader.ReadLine()) != null) { if (string.IsNullOrWhiteSpace(line)) reformattedBuilder.AppendLine(line); else { var trimedLine = line.Substring(nearestIndent); reformattedBuilder.AppendLine(trimedLine); } } } return reformattedBuilder.ToString(); } private static int FindFirstNoWhitePosition(string line) { if (string.IsNullOrWhiteSpace(line)) return -1; for (int space = 0; space < line.Length; space++) { if (!Char.IsWhiteSpace(line[space])) return space; } return -1; } public static XDocument LoadAssemblyDocumentationWithSamples(string filePath, string samplesDir, string serviceName) { if (!string.IsNullOrEmpty(samplesDir)) { var extraDocNodes = new List<XmlNode>(); foreach (var pattern in new[] { ".extra.xml", ".GeneratedSamples.extra.xml" }) { var extraFile = Path.Combine(samplesDir, DOC_SAMPLES_SUBFOLDER, serviceName + pattern); if (File.Exists(extraFile)) { var extraDoc = new XmlDocument(); extraDoc.Load(extraFile); foreach (XmlNode node in extraDoc.SelectNodes("docs/doc")) { extraDocNodes.Add(node); } } } if (extraDocNodes.Any()) { Trace.WriteLine(String.Format("Merging {0} code samples into {1}", serviceName, filePath)); var sdkDoc = new XmlDocument(); sdkDoc.Load(filePath); var examplesMap = BuildExamplesMap(extraDocNodes); ProcessExtraDoc(sdkDoc, examplesMap); return XDocument.Load(new XmlNodeReader(sdkDoc), LoadOptions.PreserveWhitespace); } } return XDocument.Load(filePath, LoadOptions.PreserveWhitespace); } private static IDictionary<string, string> BuildExamplesMap(List<XmlNode> docNodes) { Trace.WriteLine(String.Format("Found {0} extra doc nodes", docNodes.Count), "verbose"); var map = new Dictionary<string, string>(StringComparer.Ordinal); foreach (var docNode in docNodes) { var members = docNode.SelectNodes("members/member"); foreach (XmlNode memberNode in members) { var nameAttribute = memberNode.Attributes["name"]; if (null == nameAttribute) throw new InvalidDataException("unable to retrieve 'name' attribute for member node."); var memberSpec = nameAttribute.Value; var exampleNode = docNode.SelectSingleNode("value/example"); var content = exampleNode.InnerXml; if (map.ContainsKey(memberSpec)) map[memberSpec] += content; else map[memberSpec] = content; } } return map; } private static void ProcessExtraDoc(XmlDocument sdkDocument, IDictionary<string, string> examplesMap) { foreach (var memberSpec in examplesMap.Keys) { var docNode = sdkDocument.SelectSingleNode(string.Format("doc/members/member[@name='{0}']", memberSpec)); if (null == docNode) { Trace.WriteLine(String.Format("** member name not found, skipping: {0}", memberSpec), "verbose"); continue; } XmlNode sdkExampleNode = docNode.SelectSingleNode("example"); if (null != sdkExampleNode) { sdkExampleNode.InnerXml = examplesMap[memberSpec]; } else { string sdkXml = docNode.InnerXml; sdkXml += String.Format("<example>{0}</example>", examplesMap[memberSpec]); docNode.InnerXml = sdkXml; } Trace.WriteLine(string.Format("Successfully updated SDK XML for member {0}", memberSpec), "verbose"); } } } }
772
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Reflection; namespace SDKDocGenerator { public abstract class AbstractWrapper : MarshalByRefObject { public string DocId { private set; get; } protected AbstractWrapper(string docId) { DocId = docId; } public override object InitializeLifetimeService() { return null; } } public abstract class AbstractTypeProvider : AbstractWrapper { protected AbstractTypeProvider(string docId) : base(docId) { } public virtual TypeWrapper GetType(string name) { return null; } public virtual IEnumerable<TypeWrapper> GetTypes() { return null; } public virtual IEnumerable<string> GetNamespaces() { return null; } public virtual IEnumerable<TypeWrapper> GetTypesForNamespace(string namespaceName) { return null; } } public class AssemblyWrapper : AbstractTypeProvider { Assembly _assembly; IList<TypeWrapper> _allTypes; IDictionary<string, TypeWrapper> _typesByFullName; IDictionary<string, IList<TypeWrapper>> _typesByNamespace; AbstractTypeProvider _deferredTypesProvider; public AssemblyWrapper(string docId) : base(docId) { } public void LoadAssembly(string path) { _assembly = Assembly.LoadFrom(path); _allTypes = new List<TypeWrapper>(); _typesByNamespace = new Dictionary<string, IList<TypeWrapper>>(); _typesByFullName = new Dictionary<string, TypeWrapper>(); foreach (var type in this._assembly.GetTypes()) { if (type.Namespace == null || !type.Namespace.StartsWith("Amazon") || type.Namespace.Contains(".Internal")) { continue; } if (type.IsNested) { if (type.IsVisible) { // nested + visible = publicly-accessible } else if (type.IsNestedFamily) { // nested + nested family = protected class inside a public class } else { continue; } } else // not-nested { if (!type.IsPublic) continue; } var wrapper = new TypeWrapper(type, DocId); _typesByFullName[wrapper.FullName] = wrapper; _allTypes.Add(wrapper); IList<TypeWrapper> namespaceTypes; if (!this._typesByNamespace.TryGetValue(wrapper.Namespace, out namespaceTypes)) { namespaceTypes = new List<TypeWrapper>(); _typesByNamespace[wrapper.Namespace] = namespaceTypes; } namespaceTypes.Add(wrapper); } } public string AssemblyVersion { get { return this._assembly.GetName().Version.ToString(); } } public AbstractTypeProvider DeferredTypesProvider { get { return _deferredTypesProvider; } set { _deferredTypesProvider = value; } } public override TypeWrapper GetType(string name) { TypeWrapper wrapper; if (!this._typesByFullName.TryGetValue(name, out wrapper)) { if (_deferredTypesProvider != null) { return _deferredTypesProvider.GetType(name); } return null; } return wrapper; } public override IEnumerable<TypeWrapper> GetTypes() { var types = new HashSet<TypeWrapper>(this._allTypes); if (_deferredTypesProvider != null) { types.UnionWith(_deferredTypesProvider.GetTypes()); } return types; } public override IEnumerable<string> GetNamespaces() { var namespaces = new HashSet<string>(this._typesByNamespace.Keys); if (_deferredTypesProvider != null) { namespaces.UnionWith(_deferredTypesProvider.GetNamespaces()); } return namespaces; } public override IEnumerable<TypeWrapper> GetTypesForNamespace(string namespaceName) { HashSet<TypeWrapper> typeSet = new HashSet<TypeWrapper>(); IList<TypeWrapper> namespaceTypes; if (this._typesByNamespace.TryGetValue(namespaceName, out namespaceTypes)) { typeSet.UnionWith(namespaceTypes); } if(_deferredTypesProvider != null) { typeSet.UnionWith(_deferredTypesProvider.GetTypesForNamespace(namespaceName)); } return typeSet; } public override string ToString() { return this._assembly.FullName; } } public class DeferredTypesProvider : AbstractTypeProvider { private readonly IDictionary<string, TypeWrapper> _typeDictionary = new Dictionary<string, TypeWrapper>(); private readonly IDictionary<string, IList<TypeWrapper>> _namespaceToTypeNames = new Dictionary<string, IList<TypeWrapper>>(); // Types implemented in service assemblies (such as AmazonS3Config) that exist in the namespaces below are output when we // process the awssdk.core manifest (which is done last), so they appear under the Amazon tree root in the docs. We // therefore collate these types and the parent assembly as we run, and will process them once we start to // process core. public readonly HashSet<string> Namespaces = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Amazon", "Amazon.Util", "Amazon.Runtime", "Amazon.Runtime.SharedInterfaces" }; public DeferredTypesProvider(string docId) : base(docId) { } /// <summary> /// Registers a collection of types implemented in a service assembly to be processed /// when the doc set for awssdk.core.dll is generated. /// </summary> /// <param name="types"></param> public void AddTypes(IEnumerable<TypeWrapper> types) { foreach (var type in types) { IList<TypeWrapper> list; if (_namespaceToTypeNames.TryGetValue(type.Namespace, out list)) { list.Add(type); } else { _namespaceToTypeNames.Add(type.Namespace, new List<TypeWrapper> { type }); } _typeDictionary.Add(type.FullName, type); } } public override TypeWrapper GetType(string fullName) { TypeWrapper type; _typeDictionary.TryGetValue(fullName, out type); return type; } public override IEnumerable<TypeWrapper> GetTypes() { return _typeDictionary.Values; } public override IEnumerable<string> GetNamespaces() { return _namespaceToTypeNames.Keys; } public override IEnumerable<TypeWrapper> GetTypesForNamespace(string namespaceName) { IList<TypeWrapper> types; if (_namespaceToTypeNames.TryGetValue(namespaceName, out types)) { return types; } else { return new List<TypeWrapper>(); } } } public class AttributeWrapper : AbstractWrapper { private CustomAttributeData _data; public AttributeWrapper(CustomAttributeData data, string docId) : base(docId) { _data = data; } private string _name; public string Name { get { if (string.IsNullOrEmpty(_name)) { var attributeLastIndex = _data.AttributeType.Name.LastIndexOf("Attribute", StringComparison.Ordinal); if (attributeLastIndex != -1) { _name = _data.AttributeType.Name.Substring(0, attributeLastIndex); } else { _name = _data.AttributeType.Name; } } return _name; } } private IEnumerable<string> _arguments; public IEnumerable<string> Arguments { get { if (_arguments == null) { _arguments = _data.ConstructorArguments.Select(argument => { switch(argument.ArgumentType.FullName) { case "System.String": return $"\"{argument.Value}\""; case "System.Boolean": return argument.Value.ToString().ToLower(); default: throw new NotImplementedException($"{argument.ArgumentType.FullName} is not implemented"); } }).ToList(); } return _arguments; } } } public class TypeWrapper : AbstractWrapper { readonly Type _type; public TypeWrapper(Type type, string docId) : base(docId) { this._type = type; } public override bool Equals(object obj) { return Equals(obj as TypeWrapper); } public bool Equals(TypeWrapper other) { if (other == null) return false; if (!string.Equals(DocId, other.DocId)) return false; if (_type != other._type) return false; return true; } public override int GetHashCode() { return _type.GetHashCode() + DocId.GetHashCode(); } public string JustName { get { return this._type.Name; } } public string Name { get { string name = this._type.Name; if (name != null && this._type.IsNested) { name = $"{this._type.DeclaringType.Name}.{this._type.Name}"; } return name; } } public string Namespace { get { return this._type.Namespace; } } private string _fullName; public string FullName { get { if (string.IsNullOrEmpty(_fullName)) { // _type can be of generic type T in which case FullName is null if (this._type.FullName != null && this._type.IsNested) { _fullName = new StringBuilder(this._type.FullName).Replace("+", ".").ToString(); } else { _fullName = this._type.FullName; } } return _fullName; } } private IEnumerable<AttributeWrapper> _attributes; public IEnumerable<AttributeWrapper> Attributes { get { if (_attributes == null) { _attributes = _type.CustomAttributes.Where(attribute => attribute.AttributeType.FullName.Equals("System.ObsoleteAttribute")) .Select(customAttribute => new AttributeWrapper(customAttribute, DocId)) .ToList(); } return _attributes; } } public string ManifestModuleName { get { return this._type.Assembly.ManifestModule.Name; } } public string[] GetEnumNames() { if (!this._type.IsEnum) return new string[0]; return System.Enum.GetNames(this._type); } public string GetDisplayName(bool useFullName) { string name; if (this.IsGenericParameter) name = this.JustName; else if (this.IsGenericType) { var baseName = this.Name; var pos = baseName.IndexOf('`'); var paramCount = this.GenericTypeArguments().Count; baseName = baseName.Substring(0, pos); var pars = new StringBuilder(); if (this._type.IsGenericTypeDefinition) { if (paramCount == 1) pars.Append("T"); else { for (var i = 1; i <= paramCount; i++) { if (pars.Length > 0) pars.Append(", "); pars.AppendFormat("T{0}", i); } } } else { foreach (var t in this._type.GenericTypeArguments) { if (pars.Length > 0) pars.Append(", "); pars.AppendFormat(new TypeWrapper(t, DocId).GetDisplayName(useFullName)); } } name = $"{baseName}&lt;{pars}&gt;"; } else { // if it's an anonymous generic type, just return it as we can // dig no further if (this.Name.Equals("T[]", StringComparison.Ordinal)) name = this.Name; else name = useFullName ? this.FullName : this.Name; } if (name == null) throw new ApplicationException($"Failed to resolve display for type {this._type}"); return name; } IList<ConstructorInfoWrapper> _constructors; public IList<ConstructorInfoWrapper> GetConstructors() { if (this._constructors == null) { this._constructors = new List<ConstructorInfoWrapper>(); foreach (var info in this._type.GetConstructors()) { this._constructors.Add(new ConstructorInfoWrapper(info, DocId)); } } return this._constructors; } public TypeWrapper BaseType { get { if (this._type.BaseType == null) return null; return new TypeWrapper(this._type.BaseType, DocId); } } public TypeWrapper GetElementType() { var elementType = this._type.GetElementType(); return new TypeWrapper(elementType, DocId); } public IList<TypeWrapper> GetInterfaces() { var interfaces = new List<TypeWrapper>(); foreach(var real in this._type.GetInterfaces()) { interfaces.Add(new TypeWrapper(real, DocId)); } return interfaces; } public IList<PropertyInfoWrapper> GetProperties() { var wrappers = new List<PropertyInfoWrapper>(); foreach (var info in this._type.GetProperties()) { wrappers.Add(new PropertyInfoWrapper(info, DocId)); } return wrappers; } public IList<MethodInfoWrapper> GetMethodsToDocument() { var wrappers = new List<MethodInfoWrapper>(); foreach (var info in this._type.GetMethods().Where(x => x.IsPublic && !x.Name.StartsWith("get_") && !x.Name.StartsWith("set_") && !x.Name.StartsWith("add_") && !x.Name.StartsWith("op_") && !x.Name.StartsWith("remove_") && !x.Name.StartsWith("Equals") && !x.Name.StartsWith("GetHashCode") && !x.Name.StartsWith("ToString") && x.DeclaringType != typeof(object))) { if(info.DeclaringType.Namespace.StartsWith("Amazon")) wrappers.Add(new MethodInfoWrapper(info, DocId)); } return wrappers; } public IList<TypeWrapper> GetNestedTypesToDocument() { var wrappers = new List<TypeWrapper>(); wrappers.AddRange(this._type.GetMembers() .Where(x => x.MemberType.Equals(MemberTypes.NestedType) && x.DeclaringType.Namespace.StartsWith("Amazon")) .Select(member => new TypeWrapper(_type.GetNestedType(member.Name), DocId))); return wrappers; } public IList<EventInfoWrapper> GetEvents() { var wrappers = new List<EventInfoWrapper>(); foreach (var info in this._type.GetEvents().Where(x => x.AddMethod.IsPublic)) { wrappers.Add(new EventInfoWrapper(info, DocId)); } return wrappers; } IList<FieldInfoWrapper> _fields; public IList<FieldInfoWrapper> GetFields() { if (this._fields == null) { this._fields = new List<FieldInfoWrapper>(); foreach (var info in this._type.GetFields().Where(x => x.IsPublic)) { this._fields.Add(new FieldInfoWrapper(info, DocId)); } } return this._fields; } public string CreateReferenceHtml(bool fullTypeName) { string html; var nameOrFullName = fullTypeName ? (this.FullName ?? this.Name) : this.Name; if (this.IsGenericParameter) { html = this.JustName; } else if (this.IsGenericType) { var fixedName = nameOrFullName.Substring(0, nameOrFullName.IndexOf('`')); using(var writer = new StringWriter()) { writer.Write("<a"); string url; if (this.IsAmazonNamespace) { url = $"../{GenerationManifest.OutputSubFolderFromNamespace(this.Namespace)}/{FilenameGenerator.GenerateFilename(this)}"; } else if (this.IsSystemNamespace) { writer.Write(" target=_new"); var fixedMsdnName = this.Name.Replace('`', '-'); url = $"https://docs.microsoft.com/en-us/dotnet/api/{this.Namespace}.{fixedMsdnName}"; } else { throw new ApplicationException($"Type {this.FullName} is not a System or Amazon type, no idea how to handle its help URL"); } writer.Write(" href=\"{0}\"", url); writer.Write(">"); writer.Write(fixedName); writer.Write("</a>"); writer.Write("&lt;"); var typeArguments = this.GenericTypeArguments(); for (int i = 0; i < typeArguments.Count;i++ ) { if (i != 0) writer.Write(", "); var typeArgument = typeArguments[i]; var argumentHtml = typeArgument.CreateReferenceHtml(fullTypeName); writer.Write(argumentHtml); } writer.Write("&gt;"); html = writer.ToString(); } } else if (this.IsArray) { var elementType = this.GetElementType(); var elementTypeHtml = elementType.CreateReferenceHtml(fullTypeName); html = $"{elementTypeHtml}[]"; } else { string url, label, target; if (this.IsAmazonNamespace) { url = $"../{GenerationManifest.OutputSubFolderFromNamespace(this.Namespace)}/{FilenameGenerator.GenerateFilename(this)}"; label = nameOrFullName; target = string.Empty; } else if (this.IsSystemNamespace) { url = string.Format(NDocUtilities.MSDN_TYPE_URL_PATTERN, this.GetDisplayName(true).ToLower()); target = " target=_new"; label = nameOrFullName; } else { throw new ApplicationException($"Type {this.FullName} is not a System or Amazon type, no idea how to handle its help URL"); } html = $"<a{target} href=\"{url}\" rel=\"noopener noreferrer\">{label}</a>"; } return html; } public bool IsSystemNamespace { get { return this.Namespace.Equals("System", StringComparison.Ordinal) || this.Namespace.StartsWith("System.", StringComparison.Ordinal); } } public bool IsAmazonNamespace { get { return this.Namespace.Equals("Amazon", StringComparison.Ordinal) || this.Namespace.StartsWith("Amazon.", StringComparison.Ordinal); } } // strips the type argument count off of generic collections so // we get a cleaner display public string GenericTypeName { get { if (!this.IsGenericType) return this.FullName; // FullName in this case includes the assembly info, reconstruct // using the namespace + name var apos = this.Name.LastIndexOf('`'); return $"{this.Namespace}.{(apos != -1 ? this.Name.Substring(0, apos) : this.Name)}"; } } public bool IsEnum { get { return this._type.IsEnum; } } public bool ContainsGenericParameters { get { return this._type.ContainsGenericParameters; } } public bool IsGenericParameter { get { return this._type.IsGenericParameter; } } public bool IsGenericType { get { return this._type.IsGenericType; } } public bool IsGenericTypeDefinition { get { return this._type.IsGenericTypeDefinition; } } public bool IsNested { get { return this._type.IsNested; } } public bool IsPublic { get { return this._type.IsPublic || this._type.IsNestedPublic; } } public bool IsSealed { get { return this._type.IsSealed && !this._type.IsAbstract; } } public bool IsAbstract { get { return this._type.IsAbstract && !this._type.IsSealed && this._type.IsClass; } } public bool IsStatic { get { return this._type.IsAbstract && this._type.IsSealed && this._type.IsClass; } } public bool IsClass { get { return this._type.IsClass; } } public bool IsInterface { get { return this._type.IsInterface; } } public bool IsValueType { get { return this._type.IsValueType; } } public bool IsStructure { get { return this._type.IsValueType && !this._type.IsEnum; } } public bool IsArray { get { return this._type.IsArray; } } public override string ToString() { return this._type.FullName; } IList<TypeWrapper> _genericTypeArguments; public IList<TypeWrapper> GenericTypeArguments() { if (this._genericTypeArguments == null) { this._genericTypeArguments = new List<TypeWrapper>(); foreach (var type in this._type.GenericTypeArguments) { this._genericTypeArguments.Add(new TypeWrapper(type, DocId)); } } return this._genericTypeArguments; } public IList<TypeWrapper> GetGenericArguments() { return this._type .GetGenericArguments() .Select(a => new TypeWrapper(a, DocId)) .ToList(); } } public class MemberInfoWrapper : AbstractWrapper { readonly MemberInfo _info; public MemberInfoWrapper(MemberInfo info, string docId) : base(docId) { this._info = info; } public string Name { get { return this._info.Name; } } public TypeWrapper DeclaringType { get { return new TypeWrapper(this._info.DeclaringType, DocId); } } public override string ToString() { return $"{this._info.DeclaringType.FullName}.{this._info.Name}"; } } public class FieldInfoWrapper : MemberInfoWrapper { readonly FieldInfo _info; public FieldInfoWrapper(FieldInfo info, string docId) : base(info, docId) { this._info = info; } public bool IsPublic { get { return this._info.IsPublic; } } public bool IsStatic { get { return this._info.IsStatic; } } public bool IsInitOnly { get { return this._info.IsInitOnly; } } public bool IsLiteral { get { return this._info.IsLiteral; } } TypeWrapper _fieldType; public TypeWrapper FieldType { get { return this._fieldType ?? (this._fieldType = new TypeWrapper(this._info.FieldType, DocId)); } } } public class MethodBaseWrapper : MemberInfoWrapper { readonly MethodBase _info; public MethodBaseWrapper(MethodBase info, string docId) : base(info, docId) { this._info = info; } public IList<ParameterInfoWrapper> GetParameters() { var wrappers = new List<ParameterInfoWrapper>(); foreach (var info in this._info.GetParameters()) { wrappers.Add(new ParameterInfoWrapper(info, DocId)); } return wrappers; } public bool IsPublic { get { return this._info.IsPublic; } } } public class ConstructorInfoWrapper : MethodBaseWrapper { readonly ConstructorInfo _info; public ConstructorInfoWrapper(ConstructorInfo info, string docId) : base(info, docId) { this._info = info; } public bool IsStatic { get { return _info.IsStatic; } } } public class MethodInfoWrapper : MethodBaseWrapper { readonly MethodInfo _info; public MethodInfoWrapper(MethodInfo info, string docId) : base(info, docId) { this._info = info; } public bool IsStatic { get { return _info.IsStatic; } } public bool IsAbstract { get { return this._info.IsAbstract; } } public bool IsVirtual { get { return this._info.IsVirtual && !this._info.IsAbstract; } } public TypeWrapper ReturnType { get { return new TypeWrapper(this._info.ReturnType, DocId); } } public bool IsGenericMethod { get { return this._info.IsGenericMethod; } } public TypeWrapper[] GetGenericArguments() { if (!this.IsGenericMethod) return null; var types = this._info.GetGenericArguments(); var wrappers = new TypeWrapper[types.Length]; for(int i = 0; i < types.Length; i++) { wrappers[i] = new TypeWrapper(types[i], DocId); } return wrappers; } public string FullName { get { return this._info.ToString(); } } } public class PropertyInfoWrapper : MemberInfoWrapper { readonly PropertyInfo _info; public PropertyInfoWrapper(PropertyInfo info, string docId) : base(info, docId) { this._info = info; } public bool IsPublic { get { if (this._info.GetGetMethod() == null) return false; var underlyingType = Nullable.GetUnderlyingType(this._info.GetGetMethod().GetType()); if (underlyingType != null) return underlyingType.IsPublic; return this._info.GetGetMethod().IsPublic; } } public bool IsStatic { get { // need to watch out for properties with only a single accessor, CanRead/CanWrite // don't seem too reliable with public/protected/private modifiers if (_info.CanRead) { var mi = _info.GetGetMethod(); if (mi != null) return mi.IsStatic; } if (_info.CanWrite) { var mi = _info.GetSetMethod(); if (mi != null) return mi.IsStatic; } return false; } } public TypeWrapper PropertyType { get { return new TypeWrapper(this._info.PropertyType, DocId); } } public MethodInfoWrapper GetGetMethod() { var method = this._info.GetGetMethod(); if (method == null) return null; return new MethodInfoWrapper(method, DocId); } public MethodInfoWrapper GetSetMethod() { var method = this._info.GetSetMethod(); if (method == null) return null; return new MethodInfoWrapper(method, DocId); } } public class ParameterInfoWrapper : AbstractWrapper { readonly ParameterInfo _info; public ParameterInfoWrapper(ParameterInfo info, string docId) : base(docId) { this._info = info; } public string Name { get { return this._info.Name; } } public TypeWrapper ParameterType { get { if (this._info.ParameterType.IsByRef) return new TypeWrapper(this._info.ParameterType.GetElementType(), DocId); return new TypeWrapper(this._info.ParameterType, DocId); } } public bool IsOut { get { return this._info.IsOut; } } public override string ToString() { return $"Parameter {this._info.Name}"; } } public class EventInfoWrapper : MemberInfoWrapper { readonly EventInfo _info; public EventInfoWrapper(EventInfo info, string docId) : base(info, docId) { this._info = info; } public bool IsStatic { get { // need to watch out for properties with only a single accessor, CanRead/CanWrite // don't seem too reliable with public/protected/private modifiers if (_info.AddMethod != null) { return _info.AddMethod.IsStatic; } if (_info.RemoveMethod != null) { return _info.RemoveMethod.IsStatic; } return false; } } } }
1,132
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using SDKDocGenerator.Writers; using System.Diagnostics; namespace SDKDocGenerator { /// <summary> /// Documentation generator for the AWS SDK for .NET v3+ codebase. /// </summary> public class SdkDocGenerator { private long? _startTimeTicks; // These may be packaged in the assemblies folder for non-NuGet users, // but shouldn't appear in the SDK's API reference private static readonly IEnumerable<string> _assembliesToSkip = new HashSet<string> { "AWSSDK.Extensions.CrtIntegration.dll", "AWSSDK.Extensions.NETCore.Setup.dll" }; public GeneratorOptions Options { get; private set; } /// <summary> /// How long the documentation generation took. /// </summary> public TimeSpan Duration { get { if (!_startTimeTicks.HasValue) throw new InvalidOperationException("Execute(...) method has not been called, no run duration data available"); return new TimeSpan(DateTime.Now.Ticks - _startTimeTicks.Value); } } /// <summary> /// Manages the individual namespace tocs and consolidates them all into /// a single tree on the conclusion of processing. /// </summary> public TOCWriter TOCWriter { get; private set; } /// <summary> /// Runs the doc generator to produce or update a consistent documentation /// set for the SDK. /// </summary> /// <param name="options"></param> /// <returns>0 on successful completion</returns> public int Execute(GeneratorOptions options) { // this is just to record the run duration, so we can monitor and optimize // build-time perf _startTimeTicks = DateTime.Now.Ticks; Options = options; Trace.Listeners.Add(new ConditionalConsoleTraceListener(Options.Verbose)); if (Options.TestMode) SetOptionsForTestMode(); if (string.IsNullOrEmpty(Options.SDKAssembliesRoot)) { Info("ERROR: SDKAssembliesRoot option not set"); return -1; } if (Options.Verbose) { Info("Starting generation with options:"); Info("...TestMode: {0}", Options.TestMode); Info("...Clean: {0}", Options.Clean); Info("...WriteStaticContent: {0}", Options.WriteStaticContent); Info("...WaitOnExit: {0}", Options.WaitOnExit); Info(""); Info("...SDKAssembliesRoot: {0}", Options.SDKAssembliesRoot); Info("...OutputFolder: {0}", Options.OutputFolder); Info("...Platform: {0}", Options.Platform); Info("...Services: {0}", string.Join(",", Options.Services)); Info("...CodeSamplesRootFolder: {0}", Options.CodeSamplesRootFolder); Info(""); } if (options.Clean) FileUtilties.CleanFolder(options.OutputFolder, true); if (!Directory.Exists(options.OutputFolder)) Directory.CreateDirectory(options.OutputFolder); // use the sdk root and primary platform to determine the set of // service manifests to process var manifests = ConstructGenerationManifests(); TOCWriter = new TOCWriter(options); GenerationManifest coreManifest = null; DeferredTypesProvider deferredTypes = new DeferredTypesProvider(null); foreach (var m in manifests) { if (m.ServiceName.Equals("Core", StringComparison.InvariantCultureIgnoreCase)) { coreManifest = m; continue; } m.Generate(deferredTypes, TOCWriter); } // now all service assemblies are processed, handle core plus any types in those assemblies that // we elected to defer until we processed core. coreManifest.ManifestAssemblyContext.SdkAssembly.DeferredTypesProvider = deferredTypes; coreManifest.Generate(null, TOCWriter); Info("Generating table of contents entries..."); TOCWriter.Write(); CopyVersionInfoManifest(); if (options.WriteStaticContent) { Info("Generating/copying static content:"); Info("...creating landing page"); var lpWriter = new LandingPageWriter(options); lpWriter.Write(); Info("...copying static resources"); var sourceLocation = Directory.GetParent(typeof(SdkDocGenerator).Assembly.Location).FullName; FileUtilties.FolderCopy(Path.Combine(sourceLocation, "output-files"), options.OutputFolder, true); } // Write out all the redirect rules for doc cross-linking. using (Stream stream = File.Open(Path.Combine(options.OutputFolder, SDKDocRedirectWriter.RedirectFileName), FileMode.Create)) { SDKDocRedirectWriter.Write(stream); } return 0; } /// <summary> /// Sets the generation options so as to perform a limited generation pass on one /// platform and a handul of assemblies to allow verification of doc generator changes. /// </summary> private void SetOptionsForTestMode() { Info("Revising command line options to limited set for test mode:"); Options.WaitOnExit = true; Options.Verbose = true; if (string.IsNullOrEmpty(Options.SDKAssembliesRoot)) Options.SDKAssembliesRoot = @"..\..\..\..\deployment\assemblies"; Options.Services = new[] { "Core", "DynamoDBv2", "S3", "EC2" }; Info("...sdkassembliesroot set to '{0}'", Options.SDKAssembliesRoot); Info("...platform set to '{0}'", Options.Platform); Info("...services set to {0}", string.Join(",", Options.Services)); Info(""); } /// <summary> /// Copies the json file containing the version information for each SDK assembly /// (by service) into the output docs folder. /// </summary> private void CopyVersionInfoManifest() { Info("Copying version information manifest..."); if (File.Exists(Options.SDKVersionFilePath)) { var destPath = Path.Combine(Options.ComputedContentFolder, Path.GetFileName(Options.SDKVersionFilePath)); File.Copy(Options.SDKVersionFilePath, destPath, true); } else { throw new Exception($"Failed to find version file at {Options.SDKVersionFilePath}."); } } /// <summary> /// Enumerates the assembly, folder and platform settings in the options /// to construct a per-service manifest that we will then process. Our preferred /// documentation source is for the 'net45' platform but if a subfolder does /// not exist under the root for this platform, we'll generate using the /// assemblies in the first subfolder we find. /// </summary> /// <remarks> /// Currently we only construct manifests for the assemblies we find in the /// preferred or first platform subfolder. Distinct assemblies that exist /// outside this folder do not get included. /// </remarks> /// <returns>Collections of service manifests to process</returns> private IList<GenerationManifest> ConstructGenerationManifests() { var platformSubfolders = Directory.GetDirectories(Options.SDKAssembliesRoot, "*", SearchOption.TopDirectoryOnly); var availablePlatforms = platformSubfolders.Select(Path.GetFileName).ToList(); if (!availablePlatforms.Any(ap => ap.Equals(Options.Platform, StringComparison.OrdinalIgnoreCase))) { Info("Warning: selected platform '{0}' is not available, switching to '{1}' for assembly discovery.", Options.Platform, availablePlatforms[0]); Options.Platform = availablePlatforms[0]; } var manifests = new List<GenerationManifest>(); // discover the matching service/core assemblies in the selected platform folder and // construct a processing manifest for each var assemblySourcePath = Path.Combine(Options.SDKAssembliesRoot, Options.Platform); if (Options.Verbose) Info("Discovering assemblies in {0}", assemblySourcePath); foreach (var service in Options.Services) { var namePattern = $"{GenerationManifest.AWSAssemblyNamePrefix}.{service}.dll"; var assemblies = Directory.GetFiles(assemblySourcePath, namePattern); foreach (var assembly in assemblies) { if (_assembliesToSkip.Any(toSkip => assembly.Contains(toSkip))) { continue; } // keep items as the root for content, but a further subfolder of the root namespace // will be added for the artifacts var artifactManifest = new GenerationManifest(assembly, Options.ComputedContentFolder, availablePlatforms, Options, true); manifests.Add(artifactManifest); } } return manifests; } private void Info(string message) { Trace.WriteLine(message); Trace.Flush(); } private void Info(string format, params object[] args) { Trace.WriteLine(string.Format(format, args)); Trace.Flush(); } private void InfoVerbose(string message) { Trace.WriteLine(message, "Verbose"); Trace.Flush(); } private void InfoVerbose(string format, params object[] args) { Trace.WriteLine(String.Format(format, args), "Verbose"); Trace.Flush(); } } public class ConditionalConsoleTraceListener : TraceListener { private readonly bool _verboseOption; public ConditionalConsoleTraceListener(bool verbose) { this._verboseOption = verbose; } public override void Write(string message) { Console.Write(message); } public override void WriteLine(string message) { Console.WriteLine(message); } public override void WriteLine(string message, string category) { if (_verboseOption) { Console.WriteLine($"[{category}]: {message}"); } } } }
297
aws-sdk-net
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Generator")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Organization")] [assembly: AssemblyProduct("Generator")] [assembly: AssemblyCopyright("Copyright © Organization 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("961e6b61-370e-4492-a8e6-867f9354753d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SDKDocGenerator.Syntax { public class CSharpSyntaxGenerator { private static readonly string _objectTypeName = "System.Object"; FrameworkVersion _version; public CSharpSyntaxGenerator(FrameworkVersion version) { this._version = version; } public string GenerateSyntax(TypeWrapper type) { var syntax = new SyntaxWriter(this._version); syntax.WriteAttributes(type); if (type.IsPublic) syntax.WriteToken("public"); if (type.IsEnum) { syntax.WriteToken("enum"); syntax.WriteTypeName(type); } else { if (type.IsSealed) syntax.WriteToken("sealed"); if (type.IsAbstract) syntax.WriteToken("abstract"); if (type.IsStatic) syntax.WriteToken("static"); if (type.IsClass) syntax.WriteToken("class"); else if (type.IsInterface) syntax.WriteToken("interface"); else if (type.IsValueType) syntax.WriteToken("struct"); syntax.WriteTypeName(type); var baseType = type.BaseType; if (baseType != null && !string.Equals(baseType.FullName, _objectTypeName, StringComparison.OrdinalIgnoreCase)) { syntax.WriteRaw(" :"); syntax.WriteTypeName(baseType); } var interfaces = type.GetInterfaces(); if (interfaces.Count > 0) { syntax.WriteNewLineWithTab(); syntax.BeginCommaDelimitedList(); foreach (var face in interfaces.OrderBy(x => x.Name)) { syntax.WriteTypeName(face); } syntax.EndCommaDelimitedList(); } } return syntax.CurrentSyntax; } public string GenerateSyntax(PropertyInfoWrapper info) { var syntax = new SyntaxWriter(this._version); if (info.IsPublic) syntax.WriteToken("public"); syntax.WriteTypeName(info.PropertyType); string methods = null; var getMethod = info.GetGetMethod(); var setMethod = info.GetSetMethod(); if (getMethod != null && getMethod.IsPublic && setMethod != null && setMethod.IsPublic) methods = "get; set;"; else if (getMethod != null && getMethod.IsPublic) methods = "get;"; else if (setMethod != null && setMethod.IsPublic) methods = "set;"; syntax.WriteRaw(string.Format(" {0} {{", info.Name)); syntax.WriteToken(methods); syntax.WriteRaw(" }"); return syntax.CurrentSyntax; } public string GenerateSyntax(MethodInfoWrapper info) { var syntax = new SyntaxWriter(this._version); if (info.IsPublic) syntax.WriteToken("public"); if (info.IsAbstract) syntax.WriteToken("abstract"); if (info.IsVirtual) syntax.WriteToken("virtual"); syntax.WriteTypeName(info.ReturnType); syntax.WriteRaw(" " + info.Name); var parameters = info.GetParameters(); AddParameters(syntax, parameters); return syntax.CurrentSyntax; } public string GenerateSyntax(ConstructorInfoWrapper info) { var syntax = new SyntaxWriter(this._version); if (info.IsPublic) syntax.WriteToken("public"); syntax.WriteTypeName(info.DeclaringType); var parameters = info.GetParameters(); AddParameters(syntax, parameters); return syntax.CurrentSyntax; } public string GenerateSyntax(FieldInfoWrapper info) { var syntax = new SyntaxWriter(this._version); if (info.IsPublic) syntax.WriteToken("public"); if (info.IsStatic) syntax.WriteToken("static"); if (info.IsInitOnly) syntax.WriteToken("readonly"); if (info.IsLiteral) syntax.WriteToken("const"); syntax.WriteTypeName(info.FieldType); syntax.WriteRaw(" " + info.Name); return syntax.CurrentSyntax; } public string GenerateSyntax(EventInfoWrapper info) { var syntax = new SyntaxWriter(this._version); syntax.WriteToken("public"); syntax.WriteToken("event"); syntax.WriteRaw(string.Format(" {0}EventHandler {0}", info.Name)); return syntax.CurrentSyntax; } private void AddParameters(SyntaxWriter syntax, IList<ParameterInfoWrapper> parameters) { syntax.WriteRaw("("); if (parameters.Count != 0) { // Used to track if need a trailing comma bool isFirstParameter = true; foreach (var parameter in parameters) { if (!isFirstParameter) syntax.WriteRaw(","); syntax.WriteNewLineWithTab(); syntax.WriteTypeName(parameter.ParameterType); syntax.WriteRaw(" " + parameter.Name); isFirstParameter = false; } syntax.WriteRaw("\n"); } syntax.WriteRaw(")"); } } }
199
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SDKDocGenerator.Syntax { public class SyntaxWriter { static Func<string, string> wrapHighlight = (x) => string.Format("<span style=\"color:Blue;\">{0}</span>", x); FrameworkVersion _version; StringBuilder _builder = new StringBuilder(); bool _inCommaDelimitedList = false; public SyntaxWriter(FrameworkVersion version) { this._version = version; } public void WriteToken(string token) { if(_builder.Length > 0 && !_builder.ToString().EndsWith("<br/>")) { _builder.Append(" "); } WriteValue(wrapHighlight(token)); } internal void WriteAttributes(TypeWrapper type) { foreach (var attributes in type.Attributes) { var line = $"[{attributes.Name}({string.Join(", ", attributes.Arguments)})]<br/>"; WriteValue(line); } } public void WriteTypeName(TypeWrapper type) { if (this._builder.Length > 0) this._builder.Append(" "); string typeName = type.GetDisplayName(false); if (typeName == "Void") typeName = "void"; WriteValue(typeName); } public void WriteRaw(string value) { this._builder.Append(value); } private void WriteValue(string value) { this._builder.Append(value); if (this._inCommaDelimitedList) this._builder.Append(","); } public void WriteNewLineWithTab() { this._builder.Append("\n "); } public void Reset() { this._builder = new StringBuilder(); } public string CurrentSyntax { get{return this._builder.ToString();} } public override string ToString() { return this._builder.ToString(); } public void BeginCommaDelimitedList() { this._inCommaDelimitedList = true; } public void EndCommaDelimitedList() { this._inCommaDelimitedList = false; if (this._builder[this._builder.Length - 1] == ',') { this._builder.Remove(this._builder.Length - 1, 1); } } } }
102
aws-sdk-net
aws
C#
#pragma warning disable 1587 #region Header /// /// IJsonWrapper.cs /// Interface that represents a type capable of handling all kinds of JSON /// data. This is mainly used when mapping objects through JsonMapper, and /// it's implemented by JsonData. /// /// The authors disclaim copyright to this source code. For more details, see /// the COPYING file included with this distribution. /// #endregion using System.Collections; using System.Collections.Specialized; #if (WIN_RT || WINDOWS_PHONE) using Amazon.MissingTypes; #endif namespace Json.LitJson { public enum JsonType { None, Object, Array, String, Int, Long, Double, Boolean } public interface IJsonWrapper : IList, IOrderedDictionary { bool IsArray { get; } bool IsBoolean { get; } bool IsDouble { get; } bool IsInt { get; } bool IsLong { get; } bool IsObject { get; } bool IsString { get; } bool GetBoolean (); double GetDouble (); int GetInt (); JsonType GetJsonType (); long GetLong (); string GetString (); void SetBoolean (bool val); void SetDouble (double val); void SetInt (int val); void SetJsonType (JsonType type); void SetLong (long val); void SetString (string val); string ToJson (); void ToJson (JsonWriter writer); } }
65
aws-sdk-net
aws
C#
#pragma warning disable 1587 #region Header /// /// JsonData.cs /// Generic type to hold JSON data (objects, arrays, and so on). This is /// the default type returned by JsonMapper.ToObject(). /// /// The authors disclaim copyright to this source code. For more details, see /// the COPYING file included with this distribution. /// #endregion using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; #if (WIN_RT || WINDOWS_PHONE) using Amazon.MissingTypes; #endif namespace Json.LitJson { public class JsonData : IJsonWrapper, IEquatable<JsonData> { #region Fields private IList<JsonData> inst_array; private bool inst_boolean; private double inst_double; private int inst_int; private long inst_long; private IDictionary<string, JsonData> inst_object; private string inst_string; private string json; private JsonType type; // Used to implement the IOrderedDictionary interface private IList<KeyValuePair<string, JsonData>> object_list; #endregion #region Properties public int Count { get { return EnsureCollection ().Count; } } public bool IsArray { get { return type == JsonType.Array; } } public bool IsBoolean { get { return type == JsonType.Boolean; } } public bool IsDouble { get { return type == JsonType.Double; } } public bool IsInt { get { return type == JsonType.Int; } } public bool IsLong { get { return type == JsonType.Long; } } public bool IsObject { get { return type == JsonType.Object; } } public bool IsString { get { return type == JsonType.String; } } #endregion #region ICollection Properties int ICollection.Count { get { return Count; } } bool ICollection.IsSynchronized { get { return EnsureCollection ().IsSynchronized; } } object ICollection.SyncRoot { get { return EnsureCollection ().SyncRoot; } } #endregion #region IDictionary Properties bool IDictionary.IsFixedSize { get { return EnsureDictionary ().IsFixedSize; } } bool IDictionary.IsReadOnly { get { return EnsureDictionary ().IsReadOnly; } } ICollection IDictionary.Keys { get { EnsureDictionary (); IList<string> keys = new List<string> (); foreach (KeyValuePair<string, JsonData> entry in object_list) { keys.Add (entry.Key); } return (ICollection) keys; } } ICollection IDictionary.Values { get { EnsureDictionary (); IList<JsonData> values = new List<JsonData> (); foreach (KeyValuePair<string, JsonData> entry in object_list) { values.Add (entry.Value); } return (ICollection) values; } } #endregion #region IJsonWrapper Properties bool IJsonWrapper.IsArray { get { return IsArray; } } bool IJsonWrapper.IsBoolean { get { return IsBoolean; } } bool IJsonWrapper.IsDouble { get { return IsDouble; } } bool IJsonWrapper.IsInt { get { return IsInt; } } bool IJsonWrapper.IsLong { get { return IsLong; } } bool IJsonWrapper.IsObject { get { return IsObject; } } bool IJsonWrapper.IsString { get { return IsString; } } #endregion #region IList Properties bool IList.IsFixedSize { get { return EnsureList ().IsFixedSize; } } bool IList.IsReadOnly { get { return EnsureList ().IsReadOnly; } } #endregion #region IDictionary Indexer object IDictionary.this[object key] { get { return EnsureDictionary ()[key]; } set { if (! (key is String)) throw new ArgumentException ( "The key has to be a string"); JsonData data = ToJsonData (value); this[(string) key] = data; } } #endregion #region IOrderedDictionary Indexer object IOrderedDictionary.this[int idx] { get { EnsureDictionary (); return object_list[idx].Value; } set { EnsureDictionary (); JsonData data = ToJsonData (value); KeyValuePair<string, JsonData> old_entry = object_list[idx]; inst_object[old_entry.Key] = data; KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> (old_entry.Key, data); object_list[idx] = entry; } } #endregion #region IList Indexer object IList.this[int index] { get { return EnsureList ()[index]; } set { EnsureList (); JsonData data = ToJsonData (value); this[index] = data; } } #endregion #region Public Indexers public IEnumerable<string> PropertyNames { get { EnsureDictionary(); return inst_object.Keys; } } public JsonData this[string prop_name] { get { EnsureDictionary (); JsonData data = null; inst_object.TryGetValue(prop_name, out data); return data; } set { EnsureDictionary (); KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> (prop_name, value); if (inst_object.ContainsKey (prop_name)) { for (int i = 0; i < object_list.Count; i++) { if (object_list[i].Key == prop_name) { object_list[i] = entry; break; } } } else object_list.Add (entry); inst_object[prop_name] = value; json = null; } } public JsonData this[int index] { get { EnsureCollection (); if (type == JsonType.Array) return inst_array[index]; return object_list[index].Value; } set { EnsureCollection (); if (type == JsonType.Array) inst_array[index] = value; else { KeyValuePair<string, JsonData> entry = object_list[index]; KeyValuePair<string, JsonData> new_entry = new KeyValuePair<string, JsonData> (entry.Key, value); object_list[index] = new_entry; inst_object[entry.Key] = value; } json = null; } } #endregion #region Constructors public JsonData () { } public JsonData (bool boolean) { type = JsonType.Boolean; inst_boolean = boolean; } public JsonData (double number) { type = JsonType.Double; inst_double = number; } public JsonData (int number) { type = JsonType.Int; inst_int = number; } public JsonData (long number) { type = JsonType.Long; inst_long = number; } public JsonData (object obj) { if (obj is Boolean) { type = JsonType.Boolean; inst_boolean = (bool) obj; return; } if (obj is Double) { type = JsonType.Double; inst_double = (double) obj; return; } if (obj is Int32) { type = JsonType.Int; inst_int = (int) obj; return; } if (obj is Int64) { type = JsonType.Long; inst_long = (long) obj; return; } if (obj is String) { type = JsonType.String; inst_string = (string) obj; return; } throw new ArgumentException ( "Unable to wrap the given object with JsonData"); } public JsonData (string str) { type = JsonType.String; inst_string = str; } #endregion #region Implicit Conversions public static implicit operator JsonData (Boolean data) { return new JsonData (data); } public static implicit operator JsonData (Double data) { return new JsonData (data); } public static implicit operator JsonData (Int32 data) { return new JsonData (data); } public static implicit operator JsonData (Int64 data) { return new JsonData (data); } public static implicit operator JsonData (String data) { return new JsonData (data); } #endregion #region Explicit Conversions public static explicit operator Boolean (JsonData data) { if (data.type != JsonType.Boolean) throw new InvalidCastException ( "Instance of JsonData doesn't hold a double"); return data.inst_boolean; } public static explicit operator Double (JsonData data) { if (data.type != JsonType.Double) throw new InvalidCastException ( "Instance of JsonData doesn't hold a double"); return data.inst_double; } public static explicit operator Int32 (JsonData data) { if (data.type != JsonType.Int) throw new InvalidCastException ( "Instance of JsonData doesn't hold an int"); return data.inst_int; } public static explicit operator Int64 (JsonData data) { if (data.type != JsonType.Long) throw new InvalidCastException ( "Instance of JsonData doesn't hold an int"); return data.inst_long; } public static explicit operator String (JsonData data) { if (data.type != JsonType.String) throw new InvalidCastException ( "Instance of JsonData doesn't hold a string"); return data.inst_string; } #endregion #region ICollection Methods void ICollection.CopyTo (Array array, int index) { EnsureCollection ().CopyTo (array, index); } #endregion #region IDictionary Methods void IDictionary.Add (object key, object value) { JsonData data = ToJsonData (value); EnsureDictionary ().Add (key, data); KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> ((string) key, data); object_list.Add (entry); json = null; } void IDictionary.Clear () { EnsureDictionary ().Clear (); object_list.Clear (); json = null; } bool IDictionary.Contains (object key) { return EnsureDictionary ().Contains (key); } IDictionaryEnumerator IDictionary.GetEnumerator () { return ((IOrderedDictionary) this).GetEnumerator (); } void IDictionary.Remove (object key) { EnsureDictionary ().Remove (key); for (int i = 0; i < object_list.Count; i++) { if (object_list[i].Key == (string) key) { object_list.RemoveAt (i); break; } } json = null; } #endregion #region IEnumerable Methods IEnumerator IEnumerable.GetEnumerator () { return EnsureCollection ().GetEnumerator (); } #endregion #region IJsonWrapper Methods bool IJsonWrapper.GetBoolean () { if (type != JsonType.Boolean) throw new InvalidOperationException ( "JsonData instance doesn't hold a boolean"); return inst_boolean; } double IJsonWrapper.GetDouble () { if (type != JsonType.Double) throw new InvalidOperationException ( "JsonData instance doesn't hold a double"); return inst_double; } int IJsonWrapper.GetInt () { if (type != JsonType.Int) throw new InvalidOperationException ( "JsonData instance doesn't hold an int"); return inst_int; } long IJsonWrapper.GetLong () { if (type != JsonType.Long) throw new InvalidOperationException ( "JsonData instance doesn't hold a long"); return inst_long; } string IJsonWrapper.GetString () { if (type != JsonType.String) throw new InvalidOperationException ( "JsonData instance doesn't hold a string"); return inst_string; } void IJsonWrapper.SetBoolean (bool val) { type = JsonType.Boolean; inst_boolean = val; json = null; } void IJsonWrapper.SetDouble (double val) { type = JsonType.Double; inst_double = val; json = null; } void IJsonWrapper.SetInt (int val) { type = JsonType.Int; inst_int = val; json = null; } void IJsonWrapper.SetLong (long val) { type = JsonType.Long; inst_long = val; json = null; } void IJsonWrapper.SetString (string val) { type = JsonType.String; inst_string = val; json = null; } string IJsonWrapper.ToJson () { return ToJson (); } void IJsonWrapper.ToJson (JsonWriter writer) { ToJson (writer); } #endregion #region IList Methods int IList.Add (object value) { return Add (value); } void IList.Clear () { EnsureList ().Clear (); json = null; } bool IList.Contains (object value) { return EnsureList ().Contains (value); } int IList.IndexOf (object value) { return EnsureList ().IndexOf (value); } void IList.Insert (int index, object value) { EnsureList ().Insert (index, value); json = null; } void IList.Remove (object value) { EnsureList ().Remove (value); json = null; } void IList.RemoveAt (int index) { EnsureList ().RemoveAt (index); json = null; } #endregion #region IOrderedDictionary Methods IDictionaryEnumerator IOrderedDictionary.GetEnumerator () { EnsureDictionary (); return new OrderedDictionaryEnumerator ( object_list.GetEnumerator ()); } void IOrderedDictionary.Insert (int idx, object key, object value) { string property = (string) key; JsonData data = ToJsonData (value); this[property] = data; KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> (property, data); object_list.Insert (idx, entry); } void IOrderedDictionary.RemoveAt (int idx) { EnsureDictionary (); inst_object.Remove (object_list[idx].Key); object_list.RemoveAt (idx); } #endregion #region Private Methods private ICollection EnsureCollection () { if (type == JsonType.Array) return (ICollection) inst_array; if (type == JsonType.Object) return (ICollection) inst_object; throw new InvalidOperationException ( "The JsonData instance has to be initialized first"); } private IDictionary EnsureDictionary () { if (type == JsonType.Object) return (IDictionary) inst_object; if (type != JsonType.None) throw new InvalidOperationException ( "Instance of JsonData is not a dictionary"); type = JsonType.Object; inst_object = new Dictionary<string, JsonData> (); object_list = new List<KeyValuePair<string, JsonData>> (); return (IDictionary) inst_object; } private IList EnsureList () { if (type == JsonType.Array) return (IList) inst_array; if (type != JsonType.None) throw new InvalidOperationException ( "Instance of JsonData is not a list"); type = JsonType.Array; inst_array = new List<JsonData> (); return (IList) inst_array; } private JsonData ToJsonData (object obj) { if (obj == null) return null; if (obj is JsonData) return (JsonData) obj; return new JsonData (obj); } private static void WriteJson (IJsonWrapper obj, JsonWriter writer) { if (obj.IsString) { writer.Write (obj.GetString ()); return; } if (obj.IsBoolean) { writer.Write (obj.GetBoolean ()); return; } if (obj.IsDouble) { writer.Write (obj.GetDouble ()); return; } if (obj.IsInt) { writer.Write (obj.GetInt ()); return; } if (obj.IsLong) { writer.Write (obj.GetLong ()); return; } if (obj.IsArray) { writer.WriteArrayStart (); foreach (object elem in (IList) obj) WriteJson ((JsonData) elem, writer); writer.WriteArrayEnd (); return; } if (obj.IsObject) { writer.WriteObjectStart (); foreach (DictionaryEntry entry in ((IDictionary) obj)) { writer.WritePropertyName ((string) entry.Key); WriteJson ((JsonData) entry.Value, writer); } writer.WriteObjectEnd (); return; } } #endregion public int Add (object value) { JsonData data = ToJsonData (value); json = null; return EnsureList ().Add (data); } public void Clear () { if (IsObject) { ((IDictionary) this).Clear (); return; } if (IsArray) { ((IList) this).Clear (); return; } } public bool Equals (JsonData x) { if (x == null) return false; if (x.type != this.type) return false; switch (this.type) { case JsonType.None: return true; case JsonType.Object: return this.inst_object.Equals (x.inst_object); case JsonType.Array: return this.inst_array.Equals (x.inst_array); case JsonType.String: return this.inst_string.Equals (x.inst_string); case JsonType.Int: return this.inst_int.Equals (x.inst_int); case JsonType.Long: return this.inst_long.Equals (x.inst_long); case JsonType.Double: return this.inst_double.Equals (x.inst_double); case JsonType.Boolean: return this.inst_boolean.Equals (x.inst_boolean); } return false; } public JsonType GetJsonType () { return type; } public void SetJsonType (JsonType type) { if (this.type == type) return; switch (type) { case JsonType.None: break; case JsonType.Object: inst_object = new Dictionary<string, JsonData> (); object_list = new List<KeyValuePair<string, JsonData>> (); break; case JsonType.Array: inst_array = new List<JsonData> (); break; case JsonType.String: inst_string = default (String); break; case JsonType.Int: inst_int = default (Int32); break; case JsonType.Long: inst_long = default (Int64); break; case JsonType.Double: inst_double = default (Double); break; case JsonType.Boolean: inst_boolean = default (Boolean); break; } this.type = type; } public string ToJson () { if (json != null) return json; StringWriter sw = new StringWriter (); JsonWriter writer = new JsonWriter (sw); writer.Validate = false; WriteJson (this, writer); json = sw.ToString (); return json; } public void ToJson (JsonWriter writer) { bool old_validate = writer.Validate; writer.Validate = false; WriteJson (this, writer); writer.Validate = old_validate; } public override string ToString () { switch (type) { case JsonType.Array: return "JsonData array"; case JsonType.Boolean: return inst_boolean.ToString (); case JsonType.Double: return inst_double.ToString (); case JsonType.Int: return inst_int.ToString (); case JsonType.Long: return inst_long.ToString (); case JsonType.Object: return "JsonData object"; case JsonType.String: return inst_string; } return "Uninitialized JsonData"; } } internal class OrderedDictionaryEnumerator : IDictionaryEnumerator { IEnumerator<KeyValuePair<string, JsonData>> list_enumerator; public object Current { get { return Entry; } } public DictionaryEntry Entry { get { KeyValuePair<string, JsonData> curr = list_enumerator.Current; return new DictionaryEntry (curr.Key, curr.Value); } } public object Key { get { return list_enumerator.Current.Key; } } public object Value { get { return list_enumerator.Current.Value; } } public OrderedDictionaryEnumerator ( IEnumerator<KeyValuePair<string, JsonData>> enumerator) { list_enumerator = enumerator; } public bool MoveNext () { return list_enumerator.MoveNext (); } public void Reset () { list_enumerator.Reset (); } } }
1,010
aws-sdk-net
aws
C#
#pragma warning disable 1587 #region Header /// /// JsonException.cs /// Base class throwed by LitJSON when a parsing error occurs. /// /// The authors disclaim copyright to this source code. For more details, see /// the COPYING file included with this distribution. /// #endregion using System; namespace Json.LitJson { public class JsonException : Exception { public JsonException () : base () { } internal JsonException (ParserToken token) : base (String.Format ( "Invalid token '{0}' in input string", token)) { } internal JsonException (ParserToken token, Exception inner_exception) : base (String.Format ( "Invalid token '{0}' in input string", token), inner_exception) { } internal JsonException (int c) : base (String.Format ( "Invalid character '{0}' in input string", (char) c)) { } internal JsonException (int c, Exception inner_exception) : base (String.Format ( "Invalid character '{0}' in input string", (char) c), inner_exception) { } public JsonException (string message) : base (message) { } public JsonException (string message, Exception inner_exception) : base (message, inner_exception) { } } }
62
aws-sdk-net
aws
C#
#pragma warning disable 1587 #region Header /// /// JsonMapper.cs /// JSON to .Net object and object to JSON conversions. /// /// The authors disclaim copyright to this source code. For more details, see /// the COPYING file included with this distribution. /// #endregion using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; namespace Json.LitJson { internal struct PropertyMetadata { public MemberInfo Info; public bool IsField; public Type Type; } internal struct ArrayMetadata { private Type element_type; private bool is_array; private bool is_list; public Type ElementType { get { if (element_type == null) return typeof (JsonData); return element_type; } set { element_type = value; } } public bool IsArray { get { return is_array; } set { is_array = value; } } public bool IsList { get { return is_list; } set { is_list = value; } } } internal struct ObjectMetadata { private Type element_type; private bool is_dictionary; private IDictionary<string, PropertyMetadata> properties; public Type ElementType { get { if (element_type == null) return typeof (JsonData); return element_type; } set { element_type = value; } } public bool IsDictionary { get { return is_dictionary; } set { is_dictionary = value; } } public IDictionary<string, PropertyMetadata> Properties { get { return properties; } set { properties = value; } } } internal delegate void ExporterFunc (object obj, JsonWriter writer); public delegate void ExporterFunc<T> (T obj, JsonWriter writer); internal delegate object ImporterFunc (object input); public delegate TValue ImporterFunc<TJson, TValue> (TJson input); public delegate IJsonWrapper WrapperFactory (); public class JsonMapper { #region Fields private static int max_nesting_depth; private static IFormatProvider datetime_format; private static IDictionary<Type, ExporterFunc> base_exporters_table; private static IDictionary<Type, ExporterFunc> custom_exporters_table; private static IDictionary<Type, IDictionary<Type, ImporterFunc>> base_importers_table; private static IDictionary<Type, IDictionary<Type, ImporterFunc>> custom_importers_table; private static IDictionary<Type, ArrayMetadata> array_metadata; private static readonly object array_metadata_lock = new Object (); private static IDictionary<Type, IDictionary<Type, MethodInfo>> conv_ops; private static readonly object conv_ops_lock = new Object (); private static IDictionary<Type, ObjectMetadata> object_metadata; private static readonly object object_metadata_lock = new Object (); private static IDictionary<Type, IList<PropertyMetadata>> type_properties; private static readonly object type_properties_lock = new Object (); private static JsonWriter static_writer; private static readonly object static_writer_lock = new Object (); #endregion #region Constructors static JsonMapper () { max_nesting_depth = 100; array_metadata = new Dictionary<Type, ArrayMetadata> (); conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> (); object_metadata = new Dictionary<Type, ObjectMetadata> (); type_properties = new Dictionary<Type, IList<PropertyMetadata>> (); static_writer = new JsonWriter (); datetime_format = DateTimeFormatInfo.InvariantInfo; base_exporters_table = new Dictionary<Type, ExporterFunc> (); custom_exporters_table = new Dictionary<Type, ExporterFunc> (); base_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>> (); custom_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>> (); RegisterBaseExporters (); RegisterBaseImporters (); } #endregion #region Private Methods private static void AddArrayMetadata (Type type) { if (array_metadata.ContainsKey (type)) return; ArrayMetadata data = new ArrayMetadata (); data.IsArray = type.IsArray; if (type.GetInterface("System.Collections.IList") != null) data.IsList = true; foreach (PropertyInfo p_info in type.GetProperties()) { if (p_info.Name != "Item") continue; ParameterInfo[] parameters = p_info.GetIndexParameters (); if (parameters.Length != 1) continue; if (parameters[0].ParameterType == typeof (int)) data.ElementType = p_info.PropertyType; } lock (array_metadata_lock) { try { array_metadata.Add (type, data); } catch (ArgumentException) { return; } } } private static void AddObjectMetadata (Type type) { if (object_metadata.ContainsKey (type)) return; ObjectMetadata data = new ObjectMetadata (); if (type.GetInterface("System.Collections.IDictionary") != null) data.IsDictionary = true; data.Properties = new Dictionary<string, PropertyMetadata> (); foreach (PropertyInfo p_info in type.GetProperties()) { if (p_info.Name == "Item") { ParameterInfo[] parameters = p_info.GetIndexParameters (); if (parameters.Length != 1) continue; if (parameters[0].ParameterType == typeof (string)) data.ElementType = p_info.PropertyType; continue; } PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = p_info; p_data.Type = p_info.PropertyType; data.Properties.Add (p_info.Name, p_data); } foreach (FieldInfo f_info in type.GetFields()) { PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = f_info; p_data.IsField = true; p_data.Type = f_info.FieldType; data.Properties.Add (f_info.Name, p_data); } lock (object_metadata_lock) { try { object_metadata.Add (type, data); } catch (ArgumentException) { return; } } } private static void AddTypeProperties (Type type) { if (type_properties.ContainsKey (type)) return; IList<PropertyMetadata> props = new List<PropertyMetadata> (); foreach (PropertyInfo p_info in type.GetProperties()) { if (p_info.Name == "Item") continue; PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = p_info; p_data.IsField = false; props.Add (p_data); } foreach (FieldInfo f_info in type.GetFields()) { PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = f_info; p_data.IsField = true; props.Add (p_data); } lock (type_properties_lock) { try { type_properties.Add (type, props); } catch (ArgumentException) { return; } } } private static MethodInfo GetConvOp (Type t1, Type t2) { lock (conv_ops_lock) { if (! conv_ops.ContainsKey (t1)) conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ()); } if (conv_ops[t1].ContainsKey (t2)) return conv_ops[t1][t2]; MethodInfo op = t1.GetMethod( "op_Implicit", new Type[] { t2 }); lock (conv_ops_lock) { try { conv_ops[t1].Add (t2, op); } catch (ArgumentException) { return conv_ops[t1][t2]; } } return op; } private static object ReadValue (Type inst_type, JsonReader reader) { reader.Read (); if (reader.Token == JsonToken.ArrayEnd) return null; if (reader.Token == JsonToken.Null) { if (!inst_type.IsClass) throw new JsonException (String.Format ( "Can't assign null to an instance of type {0}", inst_type)); return null; } if (reader.Token == JsonToken.Double || reader.Token == JsonToken.Int || reader.Token == JsonToken.Long || reader.Token == JsonToken.String || reader.Token == JsonToken.Boolean) { Type json_type = reader.Value.GetType (); if (inst_type.IsAssignableFrom(json_type)) return reader.Value; // If there's a custom importer that fits, use it if (custom_importers_table.ContainsKey (json_type) && custom_importers_table[json_type].ContainsKey ( inst_type)) { ImporterFunc importer = custom_importers_table[json_type][inst_type]; return importer (reader.Value); } // Maybe there's a base importer that works if (base_importers_table.ContainsKey (json_type) && base_importers_table[json_type].ContainsKey ( inst_type)) { ImporterFunc importer = base_importers_table[json_type][inst_type]; return importer (reader.Value); } // Maybe it's an enum if (inst_type.IsEnum) return Enum.ToObject (inst_type, reader.Value); // Try using an implicit conversion operator MethodInfo conv_op = GetConvOp (inst_type, json_type); if (conv_op != null) return conv_op.Invoke (null, new object[] { reader.Value }); // No luck throw new JsonException (String.Format ( "Can't assign value '{0}' (type {1}) to type {2}", reader.Value, json_type, inst_type)); } object instance = null; if (reader.Token == JsonToken.ArrayStart) { AddArrayMetadata (inst_type); ArrayMetadata t_data = array_metadata[inst_type]; if (! t_data.IsArray && ! t_data.IsList) throw new JsonException (String.Format ( "Type {0} can't act as an array", inst_type)); IList list; Type elem_type; if (! t_data.IsArray) { list = (IList) Activator.CreateInstance (inst_type); elem_type = t_data.ElementType; } else { list = new List<object> (); elem_type = inst_type.GetElementType (); } while (true) { object item = ReadValue (elem_type, reader); if (reader.Token == JsonToken.ArrayEnd) break; list.Add (item); } if (t_data.IsArray) { int n = list.Count; instance = Array.CreateInstance (elem_type, n); for (int i = 0; i < n; i++) ((Array) instance).SetValue (list[i], i); } else instance = list; } else if (reader.Token == JsonToken.ObjectStart) { AddObjectMetadata (inst_type); ObjectMetadata t_data = object_metadata[inst_type]; instance = Activator.CreateInstance (inst_type); while (true) { reader.Read (); if (reader.Token == JsonToken.ObjectEnd) break; string property = (string) reader.Value; if (t_data.Properties.ContainsKey (property)) { PropertyMetadata prop_data = t_data.Properties[property]; if (prop_data.IsField) { ((FieldInfo) prop_data.Info).SetValue ( instance, ReadValue (prop_data.Type, reader)); } else { PropertyInfo p_info = (PropertyInfo) prop_data.Info; if (p_info.CanWrite) p_info.SetValue ( instance, ReadValue (prop_data.Type, reader), null); else ReadValue (prop_data.Type, reader); } } else { if (! t_data.IsDictionary) throw new JsonException (String.Format ( "The type {0} doesn't have the " + "property '{1}'", inst_type, property)); ((IDictionary) instance).Add ( property, ReadValue ( t_data.ElementType, reader)); } } } return instance; } private static IJsonWrapper ReadValue (WrapperFactory factory, JsonReader reader) { reader.Read (); if (reader.Token == JsonToken.ArrayEnd || reader.Token == JsonToken.Null) return null; IJsonWrapper instance = factory (); if (reader.Token == JsonToken.String) { instance.SetString ((string) reader.Value); return instance; } if (reader.Token == JsonToken.Double) { instance.SetDouble ((double) reader.Value); return instance; } if (reader.Token == JsonToken.Int) { instance.SetInt ((int) reader.Value); return instance; } if (reader.Token == JsonToken.Long) { instance.SetLong ((long) reader.Value); return instance; } if (reader.Token == JsonToken.Boolean) { instance.SetBoolean ((bool) reader.Value); return instance; } if (reader.Token == JsonToken.ArrayStart) { instance.SetJsonType (JsonType.Array); while (true) { IJsonWrapper item = ReadValue (factory, reader); // nij - added check to see if the item is not null. This is to handle arrays within arrays. // In those cases when the outer array read the inner array an item was returned back the current // reader.Token is at the ArrayEnd for the inner array. if (item == null && reader.Token == JsonToken.ArrayEnd) break; ((IList) instance).Add (item); } } else if (reader.Token == JsonToken.ObjectStart) { instance.SetJsonType (JsonType.Object); while (true) { reader.Read (); if (reader.Token == JsonToken.ObjectEnd) break; string property = (string) reader.Value; ((IDictionary) instance)[property] = ReadValue ( factory, reader); } } return instance; } private static void RegisterBaseExporters () { base_exporters_table[typeof (byte)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((byte) obj)); }; base_exporters_table[typeof (char)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToString ((char) obj)); }; base_exporters_table[typeof (DateTime)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToString ((DateTime) obj, datetime_format)); }; base_exporters_table[typeof (decimal)] = delegate (object obj, JsonWriter writer) { writer.Write ((decimal) obj); }; base_exporters_table[typeof (sbyte)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((sbyte) obj)); }; base_exporters_table[typeof (short)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((short) obj)); }; base_exporters_table[typeof (ushort)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((ushort) obj)); }; base_exporters_table[typeof (uint)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToUInt64 ((uint) obj)); }; base_exporters_table[typeof (ulong)] = delegate (object obj, JsonWriter writer) { writer.Write ((ulong) obj); }; } private static void RegisterBaseImporters () { ImporterFunc importer; importer = delegate (object input) { return Convert.ToByte ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (byte), importer); importer = delegate (object input) { return Convert.ToUInt64 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (ulong), importer); importer = delegate (object input) { return Convert.ToSByte ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (sbyte), importer); importer = delegate (object input) { return Convert.ToInt16 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (short), importer); importer = delegate (object input) { return Convert.ToUInt16 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (ushort), importer); importer = delegate (object input) { return Convert.ToUInt32 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (uint), importer); importer = delegate (object input) { return Convert.ToSingle ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (float), importer); importer = delegate (object input) { return Convert.ToDouble ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (double), importer); importer = delegate (object input) { return Convert.ToDecimal ((double) input); }; RegisterImporter (base_importers_table, typeof (double), typeof (decimal), importer); importer = delegate (object input) { return Convert.ToUInt32 ((long) input); }; RegisterImporter (base_importers_table, typeof (long), typeof (uint), importer); importer = delegate (object input) { return Convert.ToChar ((string) input); }; RegisterImporter (base_importers_table, typeof (string), typeof (char), importer); importer = delegate (object input) { return Convert.ToDateTime ((string) input, datetime_format); }; RegisterImporter (base_importers_table, typeof (string), typeof (DateTime), importer); } private static void RegisterImporter ( IDictionary<Type, IDictionary<Type, ImporterFunc>> table, Type json_type, Type value_type, ImporterFunc importer) { if (! table.ContainsKey (json_type)) table.Add (json_type, new Dictionary<Type, ImporterFunc> ()); table[json_type][value_type] = importer; } private static void WriteValue (object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) throw new JsonException ( String.Format ("Max allowed object depth reached while " + "trying to export from type {0}", obj.GetType ())); if (obj == null) { writer.Write (null); return; } if (obj is IJsonWrapper) { if (writer_is_private) writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ()); else ((IJsonWrapper) obj).ToJson (writer); return; } if (obj is String) { writer.Write ((string) obj); return; } if (obj is Double) { writer.Write ((double) obj); return; } if (obj is Int32) { writer.Write ((int) obj); return; } if (obj is Boolean) { writer.Write ((bool) obj); return; } if (obj is Int64) { writer.Write ((long) obj); return; } if (obj is Array) { writer.WriteArrayStart (); foreach (object elem in (Array) obj) WriteValue (elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd (); return; } if (obj is IList) { writer.WriteArrayStart (); foreach (object elem in (IList) obj) WriteValue (elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd (); return; } if (obj is IDictionary) { writer.WriteObjectStart (); foreach (DictionaryEntry entry in (IDictionary) obj) { writer.WritePropertyName ((string) entry.Key); WriteValue (entry.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd (); return; } Type obj_type = obj.GetType (); // See if there's a custom exporter for the object if (custom_exporters_table.ContainsKey (obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type]; exporter (obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey (obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type]; exporter (obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type e_type = Enum.GetUnderlyingType (obj_type); if (e_type == typeof (long) || e_type == typeof (uint) || e_type == typeof (ulong)) writer.Write ((ulong) obj); else writer.Write ((int) obj); return; } // Okay, so it looks like the input should be exported as an // object AddTypeProperties (obj_type); IList<PropertyMetadata> props = type_properties[obj_type]; writer.WriteObjectStart (); foreach (PropertyMetadata p_data in props) { if (p_data.IsField) { writer.WritePropertyName (p_data.Info.Name); WriteValue (((FieldInfo) p_data.Info).GetValue (obj), writer, writer_is_private, depth + 1); } else { PropertyInfo p_info = (PropertyInfo) p_data.Info; if (p_info.CanRead) { writer.WritePropertyName (p_data.Info.Name); WriteValue (p_info.GetValue (obj, null), writer, writer_is_private, depth + 1); } } } writer.WriteObjectEnd (); } #endregion public static string ToJson (object obj) { lock (static_writer_lock) { static_writer.Reset (); WriteValue (obj, static_writer, true, 0); return static_writer.ToString (); } } public static void ToJson (object obj, JsonWriter writer) { WriteValue (obj, writer, false, 0); } public static JsonData ToObject (JsonReader reader) { return (JsonData) ToWrapper ( delegate { return new JsonData (); }, reader); } public static JsonData ToObject (TextReader reader) { JsonReader json_reader = new JsonReader (reader); return (JsonData) ToWrapper ( delegate { return new JsonData (); }, json_reader); } public static JsonData ToObject (string json) { return (JsonData) ToWrapper ( delegate { return new JsonData (); }, json); } public static T ToObject<T> (JsonReader reader) { return (T) ReadValue (typeof (T), reader); } public static T ToObject<T> (TextReader reader) { JsonReader json_reader = new JsonReader (reader); return (T) ReadValue (typeof (T), json_reader); } public static T ToObject<T> (string json) { JsonReader reader = new JsonReader (json); return (T) ReadValue (typeof (T), reader); } public static IJsonWrapper ToWrapper (WrapperFactory factory, JsonReader reader) { return ReadValue (factory, reader); } public static IJsonWrapper ToWrapper (WrapperFactory factory, string json) { JsonReader reader = new JsonReader (json); return ReadValue (factory, reader); } public static void RegisterExporter<T> (ExporterFunc<T> exporter) { ExporterFunc exporter_wrapper = delegate (object obj, JsonWriter writer) { exporter ((T) obj, writer); }; custom_exporters_table[typeof (T)] = exporter_wrapper; } public static void RegisterImporter<TJson, TValue> ( ImporterFunc<TJson, TValue> importer) { ImporterFunc importer_wrapper = delegate (object input) { return importer ((TJson) input); }; RegisterImporter (custom_importers_table, typeof (TJson), typeof (TValue), importer_wrapper); } public static void UnregisterExporters () { custom_exporters_table.Clear (); } public static void UnregisterImporters () { custom_importers_table.Clear (); } } }
919
aws-sdk-net
aws
C#
#pragma warning disable 1587 #region Header /// /// JsonReader.cs /// Stream-like access to JSON text. /// /// The authors disclaim copyright to this source code. For more details, see /// the COPYING file included with this distribution. /// #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace Json.LitJson { public enum JsonToken { None, ObjectStart, PropertyName, ObjectEnd, ArrayStart, ArrayEnd, Int, Long, Double, String, Boolean, Null } public class JsonReader { #region Fields private Stack<JsonToken> depth = new Stack<JsonToken>(); private int current_input; private int current_symbol; private bool end_of_json; private bool end_of_input; private Lexer lexer; private bool parser_in_string; private bool parser_return; private bool read_started; private TextReader reader; private bool reader_is_owned; private object token_value; private JsonToken token; #endregion #region Public Properties public bool AllowComments { get { return lexer.AllowComments; } set { lexer.AllowComments = value; } } public bool AllowSingleQuotedStrings { get { return lexer.AllowSingleQuotedStrings; } set { lexer.AllowSingleQuotedStrings = value; } } public bool EndOfInput { get { return end_of_input; } } public bool EndOfJson { get { return end_of_json; } } public JsonToken Token { get { return token; } } public object Value { get { return token_value; } } #endregion #region Constructors public JsonReader (string json_text) : this (new StringReader (json_text), true) { } public JsonReader (TextReader reader) : this (reader, false) { } private JsonReader (TextReader reader, bool owned) { if (reader == null) throw new ArgumentNullException ("reader"); parser_in_string = false; parser_return = false; read_started = false; lexer = new Lexer (reader); end_of_input = false; end_of_json = false; this.reader = reader; reader_is_owned = owned; } #endregion #region Private Methods private void ProcessNumber (string number) { if (number.IndexOf ('.') != -1 || number.IndexOf ('e') != -1 || number.IndexOf ('E') != -1) { double n_double; if (Double.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out n_double)) { token = JsonToken.Double; token_value = n_double; return; } } int n_int32; if (Int32.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out n_int32)) { token = JsonToken.Int; token_value = n_int32; return; } long n_int64; if (Int64.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out n_int64)) { token = JsonToken.Long; token_value = n_int64; return; } // Shouldn't happen, but just in case, return something token = JsonToken.Int; token_value = 0; } private void ProcessSymbol () { if (current_symbol == '[') { token = JsonToken.ArrayStart; parser_return = true; } else if (current_symbol == ']') { token = JsonToken.ArrayEnd; parser_return = true; } else if (current_symbol == '{') { token = JsonToken.ObjectStart; parser_return = true; } else if (current_symbol == '}') { token = JsonToken.ObjectEnd; parser_return = true; } else if (current_symbol == '"') { if (parser_in_string) { parser_in_string = false; parser_return = true; } else { if (token == JsonToken.None) token = JsonToken.String; parser_in_string = true; } } else if (current_symbol == (int) ParserToken.CharSeq) { token_value = lexer.StringValue; } else if (current_symbol == (int) ParserToken.False) { token = JsonToken.Boolean; token_value = false; parser_return = true; } else if (current_symbol == (int) ParserToken.Null) { token = JsonToken.Null; parser_return = true; } else if (current_symbol == (int) ParserToken.Number) { ProcessNumber (lexer.StringValue); parser_return = true; } else if (current_symbol == (int) ParserToken.Pair) { token = JsonToken.PropertyName; } else if (current_symbol == (int) ParserToken.True) { token = JsonToken.Boolean; token_value = true; parser_return = true; } } private bool ReadToken () { if (end_of_input) return false; lexer.NextToken (); if (lexer.EndOfInput) { Close (); return false; } current_input = lexer.Token; return true; } #endregion public void Close () { if (end_of_input) return; end_of_input = true; end_of_json = true; reader = null; } public bool Read() { if (end_of_input) return false; if (end_of_json) { end_of_json = false; } token = JsonToken.None; parser_in_string = false; parser_return = false; // Check if the first read call. If so then do an extra ReadToken because Read assumes that the previous // call to Read has already called ReadToken. if (!read_started) { read_started = true; if (!ReadToken()) return false; } do { current_symbol = current_input; ProcessSymbol(); if (parser_return) { if (this.token == JsonToken.ObjectStart || this.token == JsonToken.ArrayStart) { depth.Push(this.token); } else if (this.token == JsonToken.ObjectEnd || this.token == JsonToken.ArrayEnd) { // Clear out property name if is on top. This could happen if the value for the property was null. if (depth.Peek() == JsonToken.PropertyName) depth.Pop(); // Pop the opening token for this closing token. Make sure it is of the right type otherwise // the document is invalid. var opening = depth.Pop(); if (this.token == JsonToken.ObjectEnd && opening != JsonToken.ObjectStart) throw new JsonException("Error: Current token is ObjectEnd which does not match the opening " + opening.ToString()); if (this.token == JsonToken.ArrayEnd && opening != JsonToken.ArrayStart) throw new JsonException("Error: Current token is ArrayEnd which does not match the opening " + opening.ToString()); // If that last element is popped then we reached the end of the JSON object. if (depth.Count == 0) { end_of_json = true; } } // If the top of the stack is an object start and the next read is a string then it must be a property name // to add to the stack. else if (depth.Count > 0 && depth.Peek() != JsonToken.PropertyName && this.token == JsonToken.String && depth.Peek() == JsonToken.ObjectStart) { this.token = JsonToken.PropertyName; depth.Push(this.token); } if ( (this.token == JsonToken.ObjectEnd || this.token == JsonToken.ArrayEnd || this.token == JsonToken.String || this.token == JsonToken.Boolean || this.token == JsonToken.Double || this.token == JsonToken.Int || this.token == JsonToken.Long || this.token == JsonToken.Null || this.token == JsonToken.String )) { // If we found a value but we are not in an array or object then the document is an invalid json document. if (depth.Count == 0) { if (this.token != JsonToken.ArrayEnd && this.token != JsonToken.ObjectEnd) { throw new JsonException("Value without enclosing object or array"); } } // The valud of the property has been processed so pop the property name from the stack. else if (depth.Peek() == JsonToken.PropertyName) { depth.Pop(); } } // Read the next token that will be processed the next time the Read method is called. // This is done ahead of the next read so we can detect if we are at the end of the json document. // Otherwise EndOfInput would not return true until an attempt to read was made. if (!ReadToken() && depth.Count != 0) throw new JsonException("Incomplete JSON Document"); return true; } } while (ReadToken()); // If we reached the end of the document but there is still elements left in the depth stack then // the document is invalid JSON. if (depth.Count != 0) throw new JsonException("Incomplete JSON Document"); end_of_input = true; return false; } } }
367
aws-sdk-net
aws
C#
#pragma warning disable 1587 #region Header /// /// JsonWriter.cs /// Stream-like facility to output JSON text. /// /// The authors disclaim copyright to this source code. For more details, see /// the COPYING file included with this distribution. /// #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace Json.LitJson { internal enum Condition { InArray, InObject, NotAProperty, Property, Value } internal class WriterContext { public int Count; public bool InArray; public bool InObject; public bool ExpectingValue; public int Padding; } public class JsonWriter { #region Fields private static NumberFormatInfo number_format; private WriterContext context; private Stack<WriterContext> ctx_stack; private bool has_reached_end; private char[] hex_seq; private int indentation; private int indent_value; private StringBuilder inst_string_builder; private bool pretty_print; private bool validate; private TextWriter writer; #endregion #region Properties public int IndentValue { get { return indent_value; } set { indentation = (indentation / indent_value) * value; indent_value = value; } } public bool PrettyPrint { get { return pretty_print; } set { pretty_print = value; } } public TextWriter TextWriter { get { return writer; } } public bool Validate { get { return validate; } set { validate = value; } } #endregion #region Constructors static JsonWriter () { number_format = NumberFormatInfo.InvariantInfo; } public JsonWriter () { inst_string_builder = new StringBuilder (); writer = new StringWriter (inst_string_builder); Init (); } public JsonWriter (StringBuilder sb) : this (new StringWriter (sb)) { } public JsonWriter (TextWriter writer) { if (writer == null) throw new ArgumentNullException ("writer"); this.writer = writer; Init (); } #endregion #region Private Methods private void DoValidation (Condition cond) { if (! context.ExpectingValue) context.Count++; if (! validate) return; if (has_reached_end) throw new JsonException ( "A complete JSON symbol has already been written"); switch (cond) { case Condition.InArray: if (! context.InArray) throw new JsonException ( "Can't close an array here"); break; case Condition.InObject: if (! context.InObject || context.ExpectingValue) throw new JsonException ( "Can't close an object here"); break; case Condition.NotAProperty: if (context.InObject && ! context.ExpectingValue) throw new JsonException ( "Expected a property"); break; case Condition.Property: if (! context.InObject || context.ExpectingValue) throw new JsonException ( "Can't add a property here"); break; case Condition.Value: if (! context.InArray && (! context.InObject || ! context.ExpectingValue)) throw new JsonException ( "Can't add a value here"); break; } } private void Init () { has_reached_end = false; hex_seq = new char[4]; indentation = 0; indent_value = 4; pretty_print = false; validate = true; ctx_stack = new Stack<WriterContext> (); context = new WriterContext (); ctx_stack.Push (context); } private static void IntToHex (int n, char[] hex) { int num; for (int i = 0; i < 4; i++) { num = n % 16; if (num < 10) hex[3 - i] = (char) ('0' + num); else hex[3 - i] = (char) ('A' + (num - 10)); n >>= 4; } } private void Indent () { if (pretty_print) indentation += indent_value; } private void Put (string str) { if (pretty_print && ! context.ExpectingValue) for (int i = 0; i < indentation; i++) writer.Write (' '); writer.Write (str); } private void PutNewline () { PutNewline (true); } private void PutNewline (bool add_comma) { if (add_comma && ! context.ExpectingValue && context.Count > 1) writer.Write (','); if (pretty_print && ! context.ExpectingValue) writer.Write ("\r\n"); } private void PutString (string str) { Put (String.Empty); writer.Write ('"'); int n = str.Length; for (int i = 0; i < n; i++) { char c = str[i]; switch (c) { case '\n': writer.Write ("\\n"); continue; case '\r': writer.Write ("\\r"); continue; case '\t': writer.Write ("\\t"); continue; case '"': case '\\': writer.Write ('\\'); writer.Write (c); continue; case '\f': writer.Write ("\\f"); continue; case '\b': writer.Write ("\\b"); continue; } if ((int) c >= 32 && (int) c <= 126) { writer.Write (c); continue; } if (c < ' ' || (c >= '\u0080' && c < '\u00a0')) { // Turn into a \uXXXX sequence IntToHex((int)c, hex_seq); writer.Write("\\u"); writer.Write(hex_seq); } else { writer.Write(c); } } writer.Write ('"'); } private void Unindent () { if (pretty_print) indentation -= indent_value; } #endregion public override string ToString () { if (inst_string_builder == null) return String.Empty; return inst_string_builder.ToString (); } public void Reset () { has_reached_end = false; ctx_stack.Clear (); context = new WriterContext (); ctx_stack.Push (context); if (inst_string_builder != null) inst_string_builder.Remove (0, inst_string_builder.Length); } public void Write (bool boolean) { DoValidation (Condition.Value); PutNewline (); Put (boolean ? "true" : "false"); context.ExpectingValue = false; } public void Write (decimal number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write (double number) { DoValidation (Condition.Value); PutNewline (); string str = Convert.ToString (number, number_format); Put (str); if (str.IndexOf ('.') == -1 && str.IndexOf ('E') == -1) writer.Write (".0"); context.ExpectingValue = false; } public void Write (int number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write (long number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number)); context.ExpectingValue = false; } public void Write (string str) { DoValidation (Condition.Value); PutNewline (); if (str == null) Put ("null"); else PutString (str); context.ExpectingValue = false; } public void Write (ulong number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write(DateTime date) { DoValidation(Condition.Value); PutNewline(); Put(ConvertToUnixEpochMilliSeconds(date).ToString(CultureInfo.InvariantCulture)); context.ExpectingValue = false; } private static readonly DateTime EPOCH_START = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public static int ConvertToUnixEpochSeconds(DateTime dateTime) { return (int)ConvertToUnixEpochMilliSeconds(dateTime); } public static double ConvertToUnixEpochMilliSeconds(DateTime dateTime) { var ts = new TimeSpan(dateTime.ToUniversalTime().Ticks - EPOCH_START.Ticks); double milli = Math.Round(ts.TotalMilliseconds, 0) / 1000.0; return milli; } public void WriteArrayEnd () { DoValidation (Condition.InArray); PutNewline (false); ctx_stack.Pop (); if (ctx_stack.Count == 1) has_reached_end = true; else { context = ctx_stack.Peek (); context.ExpectingValue = false; } Unindent (); Put ("]"); } public void WriteArrayStart () { DoValidation (Condition.NotAProperty); PutNewline (); Put ("["); context = new WriterContext (); context.InArray = true; ctx_stack.Push (context); Indent (); } public void WriteObjectEnd () { DoValidation (Condition.InObject); PutNewline (false); ctx_stack.Pop (); if (ctx_stack.Count == 1) has_reached_end = true; else { context = ctx_stack.Peek (); context.ExpectingValue = false; } Unindent (); Put ("}"); } public void WriteObjectStart () { DoValidation (Condition.NotAProperty); PutNewline (); Put ("{"); context = new WriterContext (); context.InObject = true; ctx_stack.Push (context); Indent (); } public void WritePropertyName (string property_name) { DoValidation (Condition.Property); PutNewline (); PutString (property_name); if (pretty_print) { if (property_name.Length > context.Padding) context.Padding = property_name.Length; for (int i = context.Padding - property_name.Length; i >= 0; i--) writer.Write (' '); writer.Write (": "); } else writer.Write (':'); context.ExpectingValue = true; } } }
495
aws-sdk-net
aws
C#
#pragma warning disable 1587 #region Header /// /// Lexer.cs /// JSON lexer implementation based on a finite state machine. /// /// The authors disclaim copyright to this source code. For more details, see /// the COPYING file included with this distribution. /// #endregion using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Json.LitJson { internal class FsmContext { public bool Return; public int NextState; public Lexer L; public int StateStack; } internal class Lexer { #region Fields private delegate bool StateHandler (FsmContext ctx); private static int[] fsm_return_table; private static StateHandler[] fsm_handler_table; private bool allow_comments; private bool allow_single_quoted_strings; private bool end_of_input; private FsmContext fsm_context; private int input_buffer; private int input_char; private TextReader reader; private int state; private StringBuilder string_buffer; private string string_value; private int token; private int unichar; #endregion #region Properties public bool AllowComments { get { return allow_comments; } set { allow_comments = value; } } public bool AllowSingleQuotedStrings { get { return allow_single_quoted_strings; } set { allow_single_quoted_strings = value; } } public bool EndOfInput { get { return end_of_input; } } public int Token { get { return token; } } public string StringValue { get { return string_value; } } #endregion #region Constructors static Lexer () { PopulateFsmTables (); } public Lexer (TextReader reader) { allow_comments = true; allow_single_quoted_strings = true; input_buffer = 0; string_buffer = new StringBuilder (128); state = 1; end_of_input = false; this.reader = reader; fsm_context = new FsmContext (); fsm_context.L = this; } #endregion #region Static Methods private static int HexValue (int digit) { switch (digit) { case 'a': case 'A': return 10; case 'b': case 'B': return 11; case 'c': case 'C': return 12; case 'd': case 'D': return 13; case 'e': case 'E': return 14; case 'f': case 'F': return 15; default: return digit - '0'; } } private static void PopulateFsmTables () { fsm_handler_table = new StateHandler[28] { State1, State2, State3, State4, State5, State6, State7, State8, State9, State10, State11, State12, State13, State14, State15, State16, State17, State18, State19, State20, State21, State22, State23, State24, State25, State26, State27, State28 }; fsm_return_table = new int[28] { (int) ParserToken.Char, 0, (int) ParserToken.Number, (int) ParserToken.Number, 0, (int) ParserToken.Number, 0, (int) ParserToken.Number, 0, 0, (int) ParserToken.True, 0, 0, 0, (int) ParserToken.False, 0, 0, (int) ParserToken.Null, (int) ParserToken.CharSeq, (int) ParserToken.Char, 0, 0, (int) ParserToken.CharSeq, (int) ParserToken.Char, 0, 0, 0, 0 }; } private static char ProcessEscChar (int esc_char) { switch (esc_char) { case '"': case '\'': case '\\': case '/': return Convert.ToChar (esc_char); case 'n': return '\n'; case 't': return '\t'; case 'r': return '\r'; case 'b': return '\b'; case 'f': return '\f'; default: // Unreachable return '?'; } } private static bool State1 (FsmContext ctx) { while (ctx.L.GetChar ()) { if (ctx.L.input_char == ' ' || ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') continue; if (ctx.L.input_char >= '1' && ctx.L.input_char <= '9') { ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 3; return true; } switch (ctx.L.input_char) { case '"': ctx.NextState = 19; ctx.Return = true; return true; case ',': case ':': case '[': case ']': case '{': case '}': ctx.NextState = 1; ctx.Return = true; return true; case '-': ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 2; return true; case '0': ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 4; return true; case 'f': ctx.NextState = 12; return true; case 'n': ctx.NextState = 16; return true; case 't': ctx.NextState = 9; return true; case '\'': if (! ctx.L.allow_single_quoted_strings) return false; ctx.L.input_char = '"'; ctx.NextState = 23; ctx.Return = true; return true; case '/': if (! ctx.L.allow_comments) return false; ctx.NextState = 25; return true; default: return false; } } return true; } private static bool State2 (FsmContext ctx) { ctx.L.GetChar (); if (ctx.L.input_char >= '1' && ctx.L.input_char<= '9') { ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 3; return true; } switch (ctx.L.input_char) { case '0': ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 4; return true; default: return false; } } private static bool State3 (FsmContext ctx) { while (ctx.L.GetChar ()) { if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') { ctx.L.string_buffer.Append ((char) ctx.L.input_char); continue; } if (ctx.L.input_char == ' ' || ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') { ctx.Return = true; ctx.NextState = 1; return true; } switch (ctx.L.input_char) { case ',': case ']': case '}': ctx.L.UngetChar (); ctx.Return = true; ctx.NextState = 1; return true; case '.': ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 5; return true; case 'e': case 'E': ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 7; return true; default: return false; } } return true; } private static bool State4 (FsmContext ctx) { ctx.L.GetChar (); if (ctx.L.input_char == ' ' || ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') { ctx.Return = true; ctx.NextState = 1; return true; } switch (ctx.L.input_char) { case ',': case ']': case '}': ctx.L.UngetChar (); ctx.Return = true; ctx.NextState = 1; return true; case '.': ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 5; return true; case 'e': case 'E': ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 7; return true; default: return false; } } private static bool State5 (FsmContext ctx) { ctx.L.GetChar (); if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') { ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 6; return true; } return false; } private static bool State6 (FsmContext ctx) { while (ctx.L.GetChar ()) { if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') { ctx.L.string_buffer.Append ((char) ctx.L.input_char); continue; } if (ctx.L.input_char == ' ' || ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') { ctx.Return = true; ctx.NextState = 1; return true; } switch (ctx.L.input_char) { case ',': case ']': case '}': ctx.L.UngetChar (); ctx.Return = true; ctx.NextState = 1; return true; case 'e': case 'E': ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 7; return true; default: return false; } } return true; } private static bool State7 (FsmContext ctx) { ctx.L.GetChar (); if (ctx.L.input_char >= '0' && ctx.L.input_char<= '9') { ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 8; return true; } switch (ctx.L.input_char) { case '+': case '-': ctx.L.string_buffer.Append ((char) ctx.L.input_char); ctx.NextState = 8; return true; default: return false; } } private static bool State8 (FsmContext ctx) { while (ctx.L.GetChar ()) { if (ctx.L.input_char >= '0' && ctx.L.input_char<= '9') { ctx.L.string_buffer.Append ((char) ctx.L.input_char); continue; } if (ctx.L.input_char == ' ' || ctx.L.input_char >= '\t' && ctx.L.input_char<= '\r') { ctx.Return = true; ctx.NextState = 1; return true; } switch (ctx.L.input_char) { case ',': case ']': case '}': ctx.L.UngetChar (); ctx.Return = true; ctx.NextState = 1; return true; default: return false; } } return true; } private static bool State9 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'r': ctx.NextState = 10; return true; default: return false; } } private static bool State10 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'u': ctx.NextState = 11; return true; default: return false; } } private static bool State11 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'e': ctx.Return = true; ctx.NextState = 1; return true; default: return false; } } private static bool State12 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'a': ctx.NextState = 13; return true; default: return false; } } private static bool State13 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'l': ctx.NextState = 14; return true; default: return false; } } private static bool State14 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 's': ctx.NextState = 15; return true; default: return false; } } private static bool State15 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'e': ctx.Return = true; ctx.NextState = 1; return true; default: return false; } } private static bool State16 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'u': ctx.NextState = 17; return true; default: return false; } } private static bool State17 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'l': ctx.NextState = 18; return true; default: return false; } } private static bool State18 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'l': ctx.Return = true; ctx.NextState = 1; return true; default: return false; } } private static bool State19 (FsmContext ctx) { while (ctx.L.GetChar ()) { switch (ctx.L.input_char) { case '"': ctx.L.UngetChar (); ctx.Return = true; ctx.NextState = 20; return true; case '\\': ctx.StateStack = 19; ctx.NextState = 21; return true; default: ctx.L.string_buffer.Append ((char) ctx.L.input_char); continue; } } return true; } private static bool State20 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case '"': ctx.Return = true; ctx.NextState = 1; return true; default: return false; } } private static bool State21 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case 'u': ctx.NextState = 22; return true; case '"': case '\'': case '/': case '\\': case 'b': case 'f': case 'n': case 'r': case 't': ctx.L.string_buffer.Append ( ProcessEscChar (ctx.L.input_char)); ctx.NextState = ctx.StateStack; return true; default: return false; } } private static bool State22 (FsmContext ctx) { int counter = 0; int mult = 4096; ctx.L.unichar = 0; while (ctx.L.GetChar ()) { if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9' || ctx.L.input_char >= 'A' && ctx.L.input_char <= 'F' || ctx.L.input_char >= 'a' && ctx.L.input_char <= 'f') { ctx.L.unichar += HexValue (ctx.L.input_char) * mult; counter++; mult /= 16; if (counter == 4) { ctx.L.string_buffer.Append ( Convert.ToChar (ctx.L.unichar)); ctx.NextState = ctx.StateStack; return true; } continue; } return false; } return true; } private static bool State23 (FsmContext ctx) { while (ctx.L.GetChar ()) { switch (ctx.L.input_char) { case '\'': ctx.L.UngetChar (); ctx.Return = true; ctx.NextState = 24; return true; case '\\': ctx.StateStack = 23; ctx.NextState = 21; return true; default: ctx.L.string_buffer.Append ((char) ctx.L.input_char); continue; } } return true; } private static bool State24 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case '\'': ctx.L.input_char = '"'; ctx.Return = true; ctx.NextState = 1; return true; default: return false; } } private static bool State25 (FsmContext ctx) { ctx.L.GetChar (); switch (ctx.L.input_char) { case '*': ctx.NextState = 27; return true; case '/': ctx.NextState = 26; return true; default: return false; } } private static bool State26 (FsmContext ctx) { while (ctx.L.GetChar ()) { if (ctx.L.input_char == '\n') { ctx.NextState = 1; return true; } } return true; } private static bool State27 (FsmContext ctx) { while (ctx.L.GetChar ()) { if (ctx.L.input_char == '*') { ctx.NextState = 28; return true; } } return true; } private static bool State28 (FsmContext ctx) { while (ctx.L.GetChar ()) { if (ctx.L.input_char == '*') continue; if (ctx.L.input_char == '/') { ctx.NextState = 1; return true; } ctx.NextState = 27; return true; } return true; } #endregion private bool GetChar () { if ((input_char = NextChar ()) != -1) return true; end_of_input = true; return false; } private int NextChar () { if (input_buffer != 0) { int tmp = input_buffer; input_buffer = 0; return tmp; } return reader.Read (); } public bool NextToken () { StateHandler handler; fsm_context.Return = false; while (true) { handler = fsm_handler_table[state - 1]; if (! handler (fsm_context)) throw new JsonException (input_char); if (end_of_input) return false; if (fsm_context.Return) { string_value = string_buffer.ToString (); string_buffer.Length = 0; token = fsm_return_table[state - 1]; if (token == (int) ParserToken.Char) token = input_char; state = fsm_context.NextState; return true; } state = fsm_context.NextState; } } private void UngetChar () { input_buffer = input_char; } } }
912
aws-sdk-net
aws
C#
#pragma warning disable 1587 #region Header /// /// ParserToken.cs /// Internal representation of the tokens used by the lexer and the parser. /// /// The authors disclaim copyright to this source code. For more details, see /// the COPYING file included with this distribution. /// #endregion namespace Json.LitJson { internal enum ParserToken { // Lexer tokens None = System.Char.MaxValue + 1, Number, True, False, Null, CharSeq, // Single char Char, // Parser Rules Text, Object, ObjectPrime, Pair, PairRest, Array, ArrayPrime, Value, ValueRest, String, // End of input End, // The empty rule Epsilon } }
46
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; namespace SDKDocGenerator.Writers { public abstract class BaseTemplateWriter { public GeneratorOptions Options { get; private set; } protected BaseTemplateWriter(GeneratorOptions options) { this.Options = options; } protected abstract string GetTemplateName(); protected abstract String ReplaceTokens(String templateBody); protected virtual string TemplateOutputPath { get { return Path.Combine(Options.OutputFolder, GetTemplateName()); } } public void Write() { var templateName = GetTemplateName(); using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("SDKDocGenerator.Templates." + templateName)) using (var reader = new StreamReader(stream)) { var templateBody = reader.ReadToEnd(); var finalBody = ReplaceTokens(templateBody); var templateOutput = TemplateOutputPath; var outputPath = Path.GetDirectoryName(templateOutput); if (!Directory.Exists(outputPath)) Directory.CreateDirectory(outputPath); using (var writer = new StreamWriter(templateOutput)) { writer.Write(finalBody); } } } } }
54
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using System.Reflection; namespace SDKDocGenerator.Writers { public abstract class BaseWriter { protected FrameworkVersion _version; public static readonly List<TableColumnHeader> FieldTableColumnHeaders = new List<TableColumnHeader> { new TableColumnHeader { CssClass = "iconColumn" }, new TableColumnHeader {Title = "Name", CssClass = "nameColumn"}, new TableColumnHeader {Title = "Type", CssClass = "typeColumn"}, new TableColumnHeader {Title = "Description", CssClass = "descriptionColumn"} }; public static readonly List<TableColumnHeader> PropertiesTableColumnHeaders = new List<TableColumnHeader> { new TableColumnHeader { CssClass = "iconColumn" }, new TableColumnHeader {Title = "Name", CssClass = "nameColumn"}, new TableColumnHeader {Title = "Type", CssClass = "typeColumn"}, new TableColumnHeader {Title = "Description", CssClass = "descriptionColumn"} }; public static readonly List<TableColumnHeader> IconisedNameDescriptionTableColumnHeaders = new List<TableColumnHeader> { new TableColumnHeader {CssClass = "iconColumn"}, new TableColumnHeader {Title = "Name", CssClass = "nameColumn"}, new TableColumnHeader {Title = "Description", CssClass = "descriptionColumn"} }; public static readonly List<TableColumnHeader> NameDescriptionTableColumnHeaders = new List<TableColumnHeader> { new TableColumnHeader {Title = "Name", CssClass = "nameColumn"}, new TableColumnHeader {Title = "Description", CssClass = "descriptionColumn"} }; private const string FeedbackSection = "<!-- BEGIN-FEEDBACK-SECTION --><span class=\"feedback\">{0}</span><!-- END-FEEDBACK-SECTION -->"; public static string BJSDisclaimerTemplate = "AWS services or capabilities described in AWS Documentation may vary by region/location. " + "Click <a href=\"https://{0}/en_us/aws/latest/userguide/services.html\">Getting Started with Amazon AWS</a> to see specific differences applicable to the China (Beijing) Region."; public GenerationManifest Artifacts { get; private set; } public AbstractTypeProvider TypeProvider { get; private set; } protected BaseWriter(GenerationManifest artifacts, AbstractTypeProvider typeProvider, FrameworkVersion version) { Artifacts = artifacts; TypeProvider = typeProvider; _version = version; } protected BaseWriter(GenerationManifest artifacts, FrameworkVersion version) : this(artifacts, artifacts.ManifestAssemblyContext.SdkAssembly, version) { } public string BJSRegionDisclaimer { get { return string.Format(BJSDisclaimerTemplate, Artifacts.Options.BJSDocsDomain); } } protected abstract string GetTitle(); protected abstract string GetMemberName(); protected abstract string GetMemberType(); protected abstract string GenerateFilename(); protected abstract string GenerateFilepath(); protected abstract XElement GetSummaryDocumentation(); protected virtual void AddSummaryNotes(TextWriter writer) { } protected abstract void WriteContent(TextWriter writer); // the computed relative path(s) to the root of the doc set // (ie to the folder containing ./items) protected string RootRelativePath { get; private set; } public void Write() { var filename = Path.Combine(Artifacts.OutputFolder, GenerateFilepath(), GenerateFilename()); try { RootRelativePath = ComputeRelativePathToRoot(filename); } catch (PathTooLongException) { Console.WriteLine("Path is too long for file : {0}", filename); throw; } var directory = new FileInfo(filename).Directory.FullName; if (!Directory.Exists(directory)) { Console.WriteLine("\t\tcreating directory: {0}", directory); Directory.CreateDirectory(directory); } using (var writer = new StringWriter()) { writer.WriteLine("<html>"); writer.WriteLine("<head>"); writer.WriteLine("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"/>"); writer.WriteLine("<meta name=\"guide-name\" content=\"API Reference\"/>"); writer.WriteLine("<meta name=\"service-name\" content=\"AWS SDK for .NET Version 3\"/>"); writer.WriteLine("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}/resources/style.css\"/>", RootRelativePath); writer.WriteLine("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}/resources/syntaxhighlighter/shCore.css\">", RootRelativePath); writer.WriteLine("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}/resources/syntaxhighlighter/shThemeDefault.css\">", RootRelativePath); writer.WriteLine("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}/resources/sdkstyle.css\"/>", RootRelativePath); // every page needs a title, meta description and canonical url to satisfy indexing. The summary/synopsis // text for an element has proven unreliable as a useful source for info the search results so stay with // the page title for now writer.WriteLine("<meta name=\"description\" content=\"{0}\">", GetTitle()); writer.WriteLine("<title>{0} | AWS SDK for .NET V3</title>", GetTitle()); writer.WriteLine("<script type=\"text/javascript\" src=\"/assets/js/awsdocs-boot.js\"></script>"); writer.WriteLine("<link rel=\"canonical\" href=\"https://docs.aws.amazon.com/sdkfornet/v3/apidocs/index.html?page={0}&tocid={1}\"/>", FilenameGenerator.Escape(this.GenerateFilename()), FilenameGenerator.Escape(this.GetTOCID())); writer.WriteLine("</head>"); writer.WriteLine("<body>"); // every page needs two hidden divs giving the search indexer the product title and guide name writer.WriteLine("<div id=\"product_name\">AWS SDK Version 3 for .NET</div>"); writer.WriteLine("<div id=\"guide_name\">API Reference</div>"); WriteRegionDisclaimer(writer); this.WriteHeader(writer); this.WriteToolbar(writer); writer.WriteLine("<div id=\"pageContent\">"); this.WriteContent(writer); writer.WriteLine("</div>"); this.WriteFooter(writer); writer.WriteLine("</body>"); writer.WriteLine("</html>"); // normalize all line endings so any docs committed into Git present a consistent // set of line terminators for core.autocrlf to work with var content = new StringBuilder(writer.ToString()); content.Replace("\r\n", "\n").Replace("\n", "\r\n"); using (var fileWriter = new StreamWriter(filename)) { fileWriter.Write(content); } } } protected virtual void WriteRegionDisclaimer(TextWriter writer) { // comment disclaimer is used by DCA pipeline only at present writer.WriteLine("<!--REGION_DISCLAIMER_DO_NOT_REMOVE-->"); // the BJS disclaimer uses its own div with js/css control of // visibility instead of its own pipeline (currently) and that // div needs to be suppressed from the dca-deployed docs writer.WriteLine("<!-- BEGIN-SECTION -->"); writer.WriteLine("<div id=\"regionDisclaimer\">"); writer.WriteLine("<p>{0}</p>", BJSRegionDisclaimer); writer.WriteLine("</div>"); writer.WriteLine("<!-- END-SECTION -->"); } protected virtual void WriteHeader(TextWriter writer) { writer.WriteLine("<div id=\"pageHeader\">"); writer.WriteLine("<div id=\"titles\">"); writer.WriteLine("<h1>{0}</h1>", this.GetMemberName()); if (this.GetMemberType() != null) writer.WriteLine("<h2 class=\"subtitle\">{0}</h2>", this.GetMemberType()); writer.WriteLine("</div>"); writer.WriteLine("</div>"); } protected virtual void WriteToolbar(TextWriter writer) { writer.WriteLine("<div id=\"pageToolbar\">"); writer.WriteLine("<!-- BEGIN-SECTION -->"); writer.WriteLine("<div id=\"search\">"); writer.WriteLine("<form action=\"/search/doc-search.html\" target=\"_blank\" onsubmit=\"return AWSHelpObj.searchFormSubmit(this);\" method=\"get\">"); writer.WriteLine("<div id=\"sfrm\">"); writer.WriteLine("<span id=\"lbl\">"); writer.WriteLine("<label for=\"sel\">Search: </label>"); writer.WriteLine("</span>"); writer.WriteLine("<select aria-label=\"Search From\" name=\"searchPath\" id=\"sel\">"); writer.WriteLine("<option value=\"all\">Entire Site</option>"); writer.WriteLine("<option value=\"articles\">Articles &amp; Tutorials</option>"); writer.WriteLine("<option value=\"documentation\">Documentation</option>"); writer.WriteLine("<option value=\"documentation-product\">Documentation - This Product</option>"); writer.WriteLine("<option selected=\"\" value=\"documentation-guide\">Documentation - This Guide</option>"); writer.WriteLine("<option value=\"releasenotes\">Release Notes</option>"); writer.WriteLine("<option value=\"code\">Sample Code &amp; Libraries</option>"); writer.WriteLine("</select>"); writer.WriteLine("<div id=\"searchInputContainer\">"); writer.WriteLine("<input aria-label=\"Search\" type=\"text\" name=\"searchQuery\" id=\"sq\">"); writer.WriteLine("<input type=\"image\" alt=\"Go\" src=\"{0}/resources/search-button.png\" id=\"sb\">", RootRelativePath); writer.WriteLine("</div>"); writer.WriteLine("</div>"); writer.WriteLine("<input id=\"this_doc_product\" type=\"hidden\" value=\"AWS SDK for .NET Version 3\" name=\"this_doc_product\">"); writer.WriteLine("<input id=\"this_doc_guide\" type=\"hidden\" value=\"API Reference\" name=\"this_doc_guide\">"); writer.WriteLine("<input type=\"hidden\" value=\"en_us\" name=\"doc_locale\">"); writer.WriteLine("</form>"); writer.WriteLine("</div>"); writer.WriteLine("<!-- END-SECTION -->"); writer.WriteLine("</div>"); } protected virtual void WriteFooter(TextWriter writer) { writer.WriteLine("<div id=\"pageFooter\">"); writer.WriteLine("<span class=\"newline linkto\"><a href=\"javascript:void(0)\" onclick=\"AWSHelpObj.displayLink('{0}/{1}', '{2}')\">Link to this page</a></span>", this.GenerateFilepath(), FilenameGenerator.Escape(this.GenerateFilename()), FilenameGenerator.Escape(this.GetTOCID())); writer.WriteLine("<span class=\"divider\">&nbsp;</span>"); writer.WriteLine(FeedbackSection, GenerateFeedbackHTML()); writer.WriteLine("<div id=\"awsdocs-legal-zone-copyright\"></div>"); writer.WriteLine("</div>"); WriteScriptFiles(writer); } protected abstract string GetTOCID(); private string ComputeRelativePathToRoot(string filePath) { var docsRootFolder = Path.GetDirectoryName(Artifacts.OutputFolder); // trim ./items var pathFromDocsRoot = Path.GetDirectoryName(filePath).Substring(docsRootFolder.Length + 1); var pathComponents = pathFromDocsRoot.Split('\\'); var rel = new StringBuilder(); for (var i = 0; i < pathComponents.Length; i++) { if (i > 0) rel.Append("/"); rel.Append(".."); } return rel.ToString(); } private string GenerateFeedbackHTML() { var filename = FilenameGenerator.Escape(Path.GetFileNameWithoutExtension(GenerateFilename())); const string baseUrl = "https://docs.aws.amazon.com/forms/aws-doc-feedback"; var queryString = string.Format("?service_name={0}&amp;file_name={1}", "NET-Ref-V3", // service_name filename // guide_name ); var fullUrl = baseUrl + queryString; const string feedbackContentFormat = "<span id=\"feedback\">" + "<!-- BEGIN-FEEDBACK-SECTION -->" + "Did this page help you?&nbsp;&nbsp;" + "<a href=\"https://docs.aws.amazon.com/sdkfornet/latest/apidocs/feedbackyes.html?topic_id={0}\" target=\"_blank\">Yes</a>&nbsp;&nbsp;" + "<a href=\"https://docs.aws.amazon.com/sdkfornet/latest/apidocs/feedbackno.html?topic_id={0}\" target=\"_blank\">No</a>&nbsp;&nbsp;&nbsp;" + "<a href=\"{1}\" target=\"_blank\">Tell us about it...</a>" + "</span>" + "<!-- END-FEEDBACK-SECTION -->"; string feedbackContent = string.Format(feedbackContentFormat, filename, fullUrl); return feedbackContent; } protected virtual void WriteScriptFiles(TextWriter writer) { var isCore = Artifacts.ServiceName.Equals("Core", StringComparison.OrdinalIgnoreCase); writer.WriteLine("<script type=\"text/javascript\" src=\"{0}/resources/jquery.min.js\"></script>", RootRelativePath); writer.WriteLine("<script type=\"text/javascript\">jQuery.noConflict();</script>"); writer.WriteLine("<script type=\"text/javascript\" src=\"{0}/resources/parseuri.js\"></script>", RootRelativePath); writer.WriteLine("<script type=\"text/javascript\" src=\"{0}/resources/pagescript.js\"></script>", RootRelativePath); writer.WriteLine("<script type=\"text/javascript\" src=\"{0}/resources/parentloader.js\"></script>", RootRelativePath); writer.WriteLine("<!-- BEGIN-SECTION -->"); writer.WriteLine("<script type=\"text/javascript\">"); writer.WriteLine("jQuery(function ($) {"); writer.WriteLine("var host = parseUri($(window.parent.location).attr('href')).host;"); writer.WriteLine("if (AWSHelpObj.showRegionalDisclaimer(host)) {"); writer.WriteLine("$(\"div#regionDisclaimer\").css(\"display\", \"block\");"); writer.WriteLine("} else {"); writer.WriteLine("$(\"div#regionDisclaimer\").remove();"); writer.WriteLine("}"); var versionInfoFile = RootRelativePath + "/items/_sdk-versions.json"; if (isCore) writer.WriteLine("AWSHelpObj.setAssemblyVersion(\"{0}\");", versionInfoFile); else writer.WriteLine("AWSHelpObj.setAssemblyVersion(\"{0}\", \"{1}\");", versionInfoFile, Artifacts.ServiceName); writer.WriteLine("});"); writer.WriteLine("</script>"); writer.WriteLine("<!-- END-SECTION -->"); writer.WriteLine("<script type=\"text/javascript\" src=\"{0}/resources/syntaxhighlighter/shCore.js\"></script>", RootRelativePath); writer.WriteLine("<script type=\"text/javascript\" src=\"{0}/resources/syntaxhighlighter/shBrushCSharp.js\"></script>", RootRelativePath); writer.WriteLine("<script type=\"text/javascript\" src=\"{0}/resources/syntaxhighlighter/shBrushPlain.js\"></script>", RootRelativePath); writer.WriteLine("<script type=\"text/javascript\" src=\"{0}/resources/syntaxhighlighter/shBrushXml.js\"></script>", RootRelativePath); writer.WriteLine("<script type=\"text/javascript\">SyntaxHighlighter.all()</script>"); } protected string FormatParameters(IList<ParameterInfoWrapper> infos) { var sb = new StringBuilder(); foreach (var info in infos) { if (sb.Length > 0) sb.Append(", "); string parameterTypeName; switch (info.ParameterType.FullName) { case "System.String": parameterTypeName = "string"; break; case "System.Int32": parameterTypeName = "int"; break; case "System.Double": parameterTypeName = "double"; break; case "System.Float": parameterTypeName = "float"; break; case "System.Boolean": parameterTypeName = "bool"; break; case "System.Object": parameterTypeName = "object"; break; default: parameterTypeName = info.ParameterType.GetDisplayName(false); break; } sb.AppendFormat("{0}{1}", info.IsOut ? "out " : "", parameterTypeName); } return sb.ToString(); } protected void AddMemberTableSectionHeader(TextWriter writer, string name, bool showIconColumn = true) { AddMemberTableSectionHeader(writer, name, showIconColumn ? IconisedNameDescriptionTableColumnHeaders : NameDescriptionTableColumnHeaders); } /// <summary> /// Adds a standard member-name/description table with optional type column /// </summary> /// <param name="writer"></param> /// <param name="title"></param> /// <param name="columnHeaders"></param> protected void AddMemberTableSectionHeader(TextWriter writer, string title, List<TableColumnHeader> columnHeaders) { writer.WriteLine("<div>"); writer.WriteLine("<div>"); writer.WriteLine("<div class=\"collapsibleSection\">"); writer.WriteLine("<h2 id=\"{1}\" class=\"title\">{0}</h2>", title, title.Replace(" ", "").ToLower()); writer.WriteLine("</div>"); writer.WriteLine("</div>"); writer.WriteLine("<div class=\"sectionbody\">"); writer.WriteLine("<table class=\"members\">"); writer.WriteLine("<tbody>"); writer.WriteLine("<tr>"); foreach (var ch in columnHeaders) { writer.Write("<th"); if (!string.IsNullOrEmpty(ch.Id)) writer.Write(" id=\"{0}\"", ch.Id); if (!string.IsNullOrEmpty(ch.CssClass)) writer.Write(" class=\"{0}\"", ch.CssClass); writer.Write(">"); if (!string.IsNullOrEmpty(ch.Title)) writer.Write(ch.Title); writer.Write("</th>"); } writer.WriteLine("</tr>"); } protected void AddMemberTableSectionClosing(TextWriter writer) { writer.WriteLine("</tbody>"); writer.WriteLine("</table>"); writer.WriteLine("</div>"); writer.WriteLine("</div>"); } protected void AddSectionHeader(TextWriter writer, string name) { writer.WriteLine("<div>"); writer.WriteLine("<div>"); writer.WriteLine("<div class=\"collapsibleSection\">"); writer.WriteLine("<h2 id=\"{1}\" class=\"title\">{0}</h2>", name, name.Replace(" ", "").ToLower()); writer.WriteLine("</div>"); writer.WriteLine("</div>"); writer.WriteLine("<div class=\"sectionbody\">"); } protected void AddSectionClosing(TextWriter writer) { writer.WriteLine("</div>"); writer.WriteLine("</div>"); } protected void AddSummaryDocumentation(TextWriter writer) { writer.WriteLine("<div id=\"summaryblock\">"); var element = GetSummaryDocumentation(); if (element != null) { var htmlDocs = NDocUtilities.TransformDocumentationToHTML(element, "summary", TypeProvider, this._version); writer.WriteLine(htmlDocs); AddSummaryNotes(writer); } writer.WriteLine("</div>"); } protected void AddRemarksDocumentation(TextWriter writer) { var element = GetSummaryDocumentation(); if (element != null) { var htmlDocs = NDocUtilities.TransformDocumentationToHTML(element, "remarks", TypeProvider, this._version); if (string.IsNullOrEmpty(htmlDocs)) return; AddSectionHeader(writer, "Remarks"); writer.WriteLine(htmlDocs); AddSectionClosing(writer); } } protected void AddExamples(TextWriter writer) { var element = GetSummaryDocumentation(); if (element != null) { var htmlDocs = NDocUtilities.TransformDocumentationToHTML(element, "example", TypeProvider, this._version); if (string.IsNullOrEmpty(htmlDocs)) return; AddSectionHeader(writer, "Examples"); writer.WriteLine(htmlDocs); AddSectionClosing(writer); } } protected void AddSeeAlso(TextWriter writer) { var element = GetSummaryDocumentation(); if (element != null) { var htmlDocs = NDocUtilities.TransformDocumentationToHTML(element, "seealso", TypeProvider, this._version); if (string.IsNullOrEmpty(htmlDocs)) return; AddSectionHeader(writer, "See Also"); writer.WriteLine(htmlDocs); AddSectionClosing(writer); } } protected void AddNamespace(TextWriter writer, string ns, string moduleName) { writer.WriteLine("<div id=\"namespaceblock\">"); writer.Write("<p>"); writer.Write("<strong>Namespace: </strong>{0}<br/>", ns); writer.Write("<strong>Assembly: </strong>{0}", moduleName); writer.Write("<span id=\"versionData\">"); writer.Write("<br/><strong>Version: </strong><span id=\"assemblyVersion\">3.x.y.z</span>"); writer.Write("</span>"); writer.Write("</p>"); writer.WriteLine("</div>"); } protected void AddVersionInformation(TextWriter writer, AbstractWrapper wrapper) { AddSectionHeader(writer, "Version Information"); var docs35 = NDocUtilities.FindDocumentation(Artifacts.NDocForPlatform("net35"), wrapper); var docs45 = NDocUtilities.FindDocumentation(Artifacts.NDocForPlatform("net45"), wrapper); var docsCore20 = NDocUtilities.FindDocumentation(Artifacts.NDocForPlatform("netstandard2.0"), wrapper); var docsNetCoreApp31 = NDocUtilities.FindDocumentation(Artifacts.NDocForPlatform("netcoreapp3.1"), wrapper); // If there is no documentation then assume it is available for all platforms. var boolNoDocs = docs35 == null && docs45 == null && docsCore20 == null && docsNetCoreApp31 == null; // .NET Core App var netCoreAppVersions = new List<string>(); if (boolNoDocs || (wrapper != null && docsNetCoreApp31 != null)) netCoreAppVersions.Add("3.1"); if(netCoreAppVersions.Count > 0) { writer.WriteLine("<p><strong>.NET Core App: </strong><br/>Supported in: {0}<br/>", string.Join(", ", netCoreAppVersions)); } // .NET Standard var netstandardVersions = new List<string>(); if (boolNoDocs || (wrapper != null && docsCore20 != null)) netstandardVersions.Add("2.0"); if(netstandardVersions.Count > 0) { writer.WriteLine("<p><strong>.NET Standard: </strong><br/>Supported in: {0}<br/>", string.Join(", ", netstandardVersions)); } // .NET Framework var netframeworkVersions = new List<string>(); if (boolNoDocs || (wrapper != null && docs45 != null)) netframeworkVersions.Add("4.5"); if (boolNoDocs || (wrapper != null && docs35 != null)) { netframeworkVersions.Add("4.0"); netframeworkVersions.Add("3.5"); } if (netframeworkVersions.Count > 0) { writer.WriteLine("<p><strong>.NET Framework: </strong><br/>Supported in: {0}<br/>", string.Join(", ", netframeworkVersions)); } AddSectionClosing(writer); } protected void AddSyntax(TextWriter writer, string csharpSyntax) { if (string.IsNullOrEmpty(csharpSyntax)) return; AddSectionHeader(writer, "Syntax"); writer.WriteLine("<div class=\"codeSnippetContainer\">"); writer.WriteLine("<div class=\"codeSnippetContainerTabs\">"); writer.WriteLine("<div class=\"codeSnippetContainerTabActive\">"); writer.WriteLine("<a class=\"languageTabLabel\">C#</a>"); writer.WriteLine("</div>"); writer.WriteLine("</div>"); writer.WriteLine("<div class=\"codeSnippetContainerCodeContainer\">"); writer.WriteLine("<div style=\"color:Black;\">"); writer.WriteLine("<pre class=\"syntax\">{0}</pre>", csharpSyntax); writer.WriteLine("</div>"); writer.WriteLine("</div>"); writer.WriteLine("</div>"); AddSectionClosing(writer); } public static string GetCrossReferenceTypeName(XElement element) { var node = element.Attribute("cref"); if (node == null) return null; var typeName = node.Value; return typeName; } public void WriteCrossReferenceTagReplacement(TextWriter writer, string typeName) { var replacement = CreateCrossReferenceTagReplacement(TypeProvider, typeName, this._version); writer.Write(replacement); } public static string CreateCrossReferenceTagReplacement(AbstractTypeProvider typeProvider, string crefTypeName, FrameworkVersion version) { const string amazonNamespaceRoot = "Amazon."; var target = string.Empty; string url = null; string typeName; if (crefTypeName.Length > 2 && crefTypeName[1] == ':') // cref M:, T:, P:, F: indicators typeName = crefTypeName.Substring(2); else typeName = crefTypeName; var typeWrapper = typeProvider.GetType(typeName); if (typeWrapper != null) url = string.Format("./{0}", FilenameGenerator.GenerateFilename(typeWrapper)); else if (typeName.StartsWith("system.", StringComparison.OrdinalIgnoreCase)) { url = string.Format(NDocUtilities.MSDN_TYPE_URL_PATTERN, typeName.ToLower()); target = "target=_new"; } // If we couldn't generate a url to use with an anchor tag, make the typename italic+bold so // that it at least stands out. if (url == null) return string.Format("<i><b>{0}</b></i>", typeName); // If the type is one of ours, strip the namespace from the display text to condense things // a little if (typeName.StartsWith(amazonNamespaceRoot, StringComparison.Ordinal)) { var lastPeriodIndex = typeName.LastIndexOf('.'); typeName = typeName.Substring(lastPeriodIndex + 1); } return string.Format("<a href=\"{0}\" {2} rel=\"noopener noreferrer\">{1}</a>", url, typeName, target); } } /// <summary> /// Used to build ordered collections of table headers used in the various /// sections of a page. Custom css (as id or class) can optionally be applied. /// </summary> public class TableColumnHeader { /// <summary> /// The colum header displayed to the user. If not specified the column /// will have a blank title. /// </summary> public string Title { get; set; } /// <summary> /// if set, applied as an 'id' attribute on the resulting td element /// </summary> public string Id { get; set; } /// <summary> /// If set, applied as a 'class' attribute on the resulting td element /// </summary> public string CssClass { get; set; } } }
666
aws-sdk-net
aws
C#
using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml.Linq; using SDKDocGenerator.Syntax; namespace SDKDocGenerator.Writers { public class ClassWriter : BaseWriter { readonly TypeWrapper _versionType; public ClassWriter(GenerationManifest artifacts, FrameworkVersion version, TypeWrapper versionType) : base(artifacts, version) { _versionType = versionType; _version = version; } protected override string GenerateFilename() { return FilenameGenerator.GenerateFilename(this._versionType); } protected override string GenerateFilepath() { return GenerationManifest.OutputSubFolderFromNamespace(_versionType.Namespace); } protected override string GetTitle() { return string.Format("{0} {1}", GetMemberName(), GetMemberType()); } protected override string GetMemberName() { return this._versionType.GetDisplayName(false); } protected override string GetMemberType() { if (this._versionType.IsInterface) return "Interface"; if (this._versionType.IsStructure) return "Structure"; if (this._versionType.IsEnum) return "Enumeration"; return "Class"; } protected override void WriteContent(TextWriter writer) { AddSummaryDocumentation(writer); AddInheritanceHierarchy(writer); AddNamespace(writer, this._versionType.Namespace, this._versionType.ManifestModuleName); AddSyntax(writer); writer.WriteLine("<p>The {0} type exposes the following members</p>", this._versionType.GetDisplayName(false)); if (this._versionType.IsEnum) { AddEnumMembers(writer); } else { AddConstructors(writer); AddProperties(writer); AddMethods(writer); AddEvents(writer); AddFields(writer); AddExamples(writer); } AddRemarksDocumentation(writer); AddVersionInformation(writer, this._versionType); } protected override XElement GetSummaryDocumentation() { var element = NDocUtilities.FindDocumentation(this._versionType); return element; } private void AddInheritanceHierarchy(TextWriter writer) { IList<TypeWrapper> types = new List<TypeWrapper>(); var current = this._versionType; while (current != null) { types.Add(current); current = current.BaseType; } AddSectionHeader(writer, "Inheritance Hierarchy"); int level = 0; foreach (var type in types.Reverse()) { for (int i = 0; i < level * 2; i++) { writer.Write("&nbsp;"); } if (type.FullName == this._versionType.FullName) writer.WriteLine("{0}.{1}", type.Namespace, type.GetDisplayName(false)); else { writer.WriteLine(type.CreateReferenceHtml(fullTypeName: true)); } writer.WriteLine("<br />"); ++level; } AddSectionClosing(writer); } void AddConstructors(TextWriter writer) { var constructors = this._versionType.GetConstructors().Where(x => x.IsPublic); if (!constructors.Any()) return; AddMemberTableSectionHeader(writer, "Constructors"); foreach (var info in constructors.OrderBy(x => x.Name)) { AddConstructor(writer, info); } AddMemberTableSectionClosing(writer); } void AddConstructor(TextWriter writer, ConstructorInfoWrapper info) { writer.WriteLine("<tr>"); writer.WriteLine("<td>"); writer.WriteLine("<img class=\"publicMethod\" src=\"{0}/resources/blank.gif\" title=\"Public Method\" alt=\"Public Method\"/>", RootRelativePath); if (info.IsStatic) writer.WriteLine("<img class=\"static\" src=\"{0}/resources/blank.gif\" title=\"Static Method\" alt=\"Static Method\"/>", RootRelativePath); writer.WriteLine("</td>"); writer.WriteLine("<td>"); var filename = FilenameGenerator.GenerateFilename(info); var parameters = FormatParameters(info.GetParameters()); var hrefLink = string.Format("<a href=\"./{0}\">{1}({2})</a>", filename, info.DeclaringType.Name, parameters); writer.WriteLine(hrefLink); writer.WriteLine("</td>"); writer.WriteLine("<td>"); var docs = NDocUtilities.FindDocumentation(info); var html = NDocUtilities.TransformDocumentationToHTML(docs, "summary", this.Artifacts.ManifestAssemblyContext.SdkAssembly, this._version); writer.WriteLine(html); writer.WriteLine("</td>"); writer.WriteLine("</tr>"); } void AddProperties(TextWriter writer) { var properties = this._versionType.GetProperties(); if (!properties.Any()) return; AddMemberTableSectionHeader(writer, "Properties", PropertiesTableColumnHeaders); foreach (var info in properties.OrderBy(x => x.Name)) { AddProperty(writer, info); } AddMemberTableSectionClosing(writer); } void AddProperty(TextWriter writer, PropertyInfoWrapper propertyInfo) { writer.WriteLine("<tr>"); writer.WriteLine("<td>"); writer.WriteLine("<img class=\"publicProperty\" src=\"{0}/resources/blank.gif\" title=\"Public Property\" alt=\"Public Property\"/>", RootRelativePath); if (propertyInfo.IsStatic) writer.WriteLine("<img class=\"static\" src=\"{0}/resources/blank.gif\" title=\"Static Property\" alt=\"Static Property\"/>", RootRelativePath); writer.WriteLine("</td>"); writer.WriteLine("<td>"); writer.WriteLine(propertyInfo.Name); writer.WriteLine("</td>"); writer.WriteLine("<td>"); writer.Write(ConstructTypeInfoLinkContent(propertyInfo.PropertyType)); writer.WriteLine("</td>"); writer.WriteLine("<td>"); string html = string.Empty; var isInherited = !propertyInfo.DeclaringType.Equals(_versionType); if (isInherited) { html = string.Format("Inherited from {0}.{1}.", propertyInfo.DeclaringType.Namespace, propertyInfo.DeclaringType.Name); } else { var docs = NDocUtilities.FindDocumentation(propertyInfo); html = NDocUtilities.TransformDocumentationToHTML(docs, "summary", Artifacts.ManifestAssemblyContext.SdkAssembly, this._version); } writer.WriteLine(html); writer.WriteLine("</td>"); writer.WriteLine("</tr>"); } void AddMethods(TextWriter writer) { var methods = this._versionType.GetMethodsToDocument(); if (!methods.Any()) return; AddMemberTableSectionHeader(writer, "Methods"); const string net35PatternNote = "<div class=\"noteblock\"><div class=\"noteheader\">Note:</div>" + "<p>Asynchronous operations (methods ending with <i>Async</i>) in the table below are for .NET 4.5 or higher. " + "For .NET 3.5 the SDK follows the standard naming convention of <b>Begin</b><i>MethodName</i> and <b>End</b><i>MethodName</i> to " + "indicate asynchronous operations - these method pairs are not shown in the table below.</p></div>"; writer.WriteLine(net35PatternNote); foreach (var info in methods.OrderBy(x => x.Name)) { AddMethod(writer, info); } AddMemberTableSectionClosing(writer); } void AddMethod(TextWriter writer, MethodInfoWrapper info) { writer.WriteLine("<tr>"); writer.WriteLine("<td>"); writer.WriteLine("<img class=\"publicMethod\" src=\"{0}/resources/blank.gif\" title=\"Public Method\" alt=\"Public Method\"/>", RootRelativePath); if (info.IsStatic) writer.WriteLine("<img class=\"static\" src=\"{0}/resources/blank.gif\" title=\"Static Method\" alt=\"Static Method\"/>", RootRelativePath); writer.WriteLine("</td>"); writer.WriteLine("<td>"); writer.WriteLine("<a href=\"{0}/items/{1}/{2}\">{3}({4})</a>", RootRelativePath, GenerationManifest.OutputSubFolderFromNamespace(info.DeclaringType.Namespace), FilenameGenerator.GenerateFilename(info), info.Name, FormatParameters(info.GetParameters())); writer.WriteLine("</td>"); writer.WriteLine("<td>"); string html = string.Empty; var isInherited = !info.DeclaringType.Equals(_versionType); if (isInherited) { html = string.Format("Inherited from {0}.{1}.", info.DeclaringType.Namespace, info.DeclaringType.Name); } else { var docs = NDocUtilities.FindDocumentation(info); html = NDocUtilities.TransformDocumentationToHTML(docs, "summary", Artifacts.ManifestAssemblyContext.SdkAssembly, this._version); } writer.WriteLine(html); writer.WriteLine("</td>"); writer.WriteLine("</tr>"); } void AddFields(TextWriter writer) { var fields = this._versionType.GetFields(); if (!fields.Any()) return; AddMemberTableSectionHeader(writer, "Fields", FieldTableColumnHeaders); foreach (var info in fields.OrderBy(x => x.Name)) { AddField(writer, info); } AddMemberTableSectionClosing(writer); } void AddField(TextWriter writer, FieldInfoWrapper info) { writer.WriteLine("<tr>"); writer.WriteLine("<td>"); writer.WriteLine("<img class=\"field\" src=\"{0}/resources/blank.gif\" title=\"Field\" alt=\"Field\"/>", RootRelativePath); if (info.IsStatic) writer.WriteLine("<img class=\"static\" src=\"{0}/resources/blank.gif\" title=\"Static Field\" alt=\"Static Field\"/>", RootRelativePath); writer.WriteLine("</td>"); writer.WriteLine("<td>{0}</td>", info.Name); writer.WriteLine("<td>"); writer.Write(ConstructTypeInfoLinkContent(info.FieldType)); writer.WriteLine("</td>"); writer.WriteLine("<td>"); string html = string.Empty; var isInherited = !info.DeclaringType.Equals(_versionType); if (isInherited) { html = string.Format("Inherited from {0}.{1}.", info.DeclaringType.Namespace, info.DeclaringType.Name); } else { var docs = NDocUtilities.FindDocumentation(info); html = NDocUtilities.TransformDocumentationToHTML(docs, "summary", Artifacts.ManifestAssemblyContext.SdkAssembly, this._version); } writer.WriteLine(html); writer.WriteLine("</td>"); writer.WriteLine("</tr>"); } void AddEvents(TextWriter writer) { var fields = this._versionType.GetEvents(); if (!fields.Any()) return; AddMemberTableSectionHeader(writer, "Events"); foreach (var info in fields.OrderBy(x => x.Name)) { AddEvent(writer, info); } AddMemberTableSectionClosing(writer); } void AddEvent(TextWriter writer, EventInfoWrapper info) { writer.WriteLine("<tr>"); writer.WriteLine("<td>"); writer.WriteLine("<img class=\"event\" src=\"{0}/resources/blank.gif\" title=\"Event\" alt=\"Event\"/>", RootRelativePath); if (info.IsStatic) writer.WriteLine("<img class=\"static\" src=\"{0}/resources/blank.gif\" title=\"Static Event\" alt=\"Static Event\"/>", RootRelativePath); writer.WriteLine("</td>"); writer.WriteLine("<td>"); writer.WriteLine("<a href=\"{0}/items/{1}/{2}\">{3}</a>", RootRelativePath, GenerationManifest.OutputSubFolderFromNamespace(info.DeclaringType.Namespace), FilenameGenerator.GenerateFilename(info), info.Name); writer.WriteLine("</td>"); writer.WriteLine("<td>"); string html = string.Empty; var isInherited = !info.DeclaringType.Equals(_versionType); if (isInherited) { html = string.Format("Inherited from {0}.{1}.", info.DeclaringType.Namespace, info.DeclaringType.Name); } else { var docs = NDocUtilities.FindDocumentation(info); html = NDocUtilities.TransformDocumentationToHTML(docs, "summary", Artifacts.ManifestAssemblyContext.SdkAssembly, this._version); } writer.WriteLine(html); writer.WriteLine("</td>"); writer.WriteLine("</tr>"); } public void AddEnumMembers(TextWriter writer) { var enumNames = this._versionType.GetEnumNames(); if (!enumNames.Any()) return; AddMemberTableSectionHeader(writer, "Members"); foreach (var name in enumNames.OrderBy(x => x)) { AddEnumMember(writer, name); } AddMemberTableSectionClosing(writer); } void AddEnumMember(TextWriter writer, string enumName) { writer.WriteLine("<tr>"); writer.WriteLine("<td>"); writer.WriteLine("<img class=\"field\" src=\"{0}/resources/blank.gif\" title=\"Enum\" alt=\"Enum\"/>", RootRelativePath); writer.WriteLine("</td>"); writer.WriteLine("<td>"); writer.WriteLine(enumName); writer.WriteLine("</td>"); writer.WriteLine("<td>"); var docs = NDocUtilities.FindFieldDocumentation(this._versionType, enumName); var html = NDocUtilities.TransformDocumentationToHTML(docs, "summary", Artifacts.ManifestAssemblyContext.SdkAssembly, this._version); writer.WriteLine(html); writer.WriteLine("</td>"); writer.WriteLine("</tr>"); } /// <summary> /// Constructs href markup, enclosed in a span, to the page containing the details of the /// specified type (this can be external to AWS documentation) as well as in another service. /// </summary> /// <param name="typeWrapper"></param> string ConstructTypeInfoLinkContent(TypeWrapper typeWrapper) { var sb = new StringBuilder("<span>"); sb.Append(typeWrapper.CreateReferenceHtml(fullTypeName: true)); sb.Append("</span>"); return sb.ToString(); } protected void AddSyntax(TextWriter writer) { var csharpSyntax = new CSharpSyntaxGenerator(this._version).GenerateSyntax(this._versionType); base.AddSyntax(writer, csharpSyntax); } protected override string GetTOCID() { return this._versionType.FullName.Replace('.', '_'); } } }
439
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using System.Xml.XPath; using System.Xml.Linq; using SDKDocGenerator.Syntax; namespace SDKDocGenerator.Writers { public class ConstructorWriter : MethodBaseWriter { readonly ConstructorInfoWrapper _constructorInfo; public ConstructorWriter(GenerationManifest artifacts, FrameworkVersion version, ConstructorInfoWrapper constructorInfo) : base(artifacts, version, constructorInfo) { this._constructorInfo = constructorInfo; } protected override string GenerateFilename() { return FilenameGenerator.GenerateFilename(this._constructorInfo); } protected override string GenerateFilepath() { return GenerationManifest.OutputSubFolderFromNamespace(_constructorInfo.DeclaringType.Namespace); } protected override string GetTitle() { var par = FormatParameters(this._constructorInfo.GetParameters()); if (string.IsNullOrEmpty(par)) return string.Format("{0} {1}", this._constructorInfo.DeclaringType.Name, GetMemberType()); return string.Format("{0} {1} ({2})", this._constructorInfo.DeclaringType.GetDisplayName(false), GetMemberType(), FormatParameters(this._constructorInfo.GetParameters())); } protected override string GetMemberName() { var par = FormatParameters(this._constructorInfo.GetParameters()); if (string.IsNullOrEmpty(par)) return string.Format("{0}", this._constructorInfo.DeclaringType.Name); return string.Format("{0} ({1})", this._constructorInfo.DeclaringType.GetDisplayName(false), FormatParameters(this._constructorInfo.GetParameters())); } protected override string GetMemberType() { return "Constructor"; } protected override XElement GetSummaryDocumentation() { var element = NDocUtilities.FindDocumentation(this._constructorInfo); return element; } protected override string GetSyntax() { return new CSharpSyntaxGenerator(this._version).GenerateSyntax(this._constructorInfo); } } }
72
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SDKDocGenerator.Writers { class EnumWriter { } }
13
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using System.Xml.XPath; using System.Xml.Linq; using SDKDocGenerator.Syntax; namespace SDKDocGenerator.Writers { public class EventWriter : MemberWriter { readonly EventInfoWrapper _eventInfo; public EventWriter(GenerationManifest artifacts, FrameworkVersion version, EventInfoWrapper eventInfo) : base(artifacts, version, eventInfo) { this._eventInfo = eventInfo; } protected override string GenerateFilename() { return FilenameGenerator.GenerateFilename(this._eventInfo); } protected override string GenerateFilepath() { return GenerationManifest.OutputSubFolderFromNamespace(_eventInfo.DeclaringType.Namespace); } protected override string GetTitle() { return string.Format("{0} {1}", GetMemberName(), GetMemberType()); } protected override string GetMemberName() { return string.Format("{0}.{1}", this._eventInfo.DeclaringType.GetDisplayName(false), this._eventInfo.Name); } protected override string GetMemberType() { return "Property"; } protected override XElement GetSummaryDocumentation() { var element = NDocUtilities.FindDocumentation(this._eventInfo); return element; } protected override string GetSyntax() { return new CSharpSyntaxGenerator(this._version).GenerateSyntax(this._eventInfo); } } }
62
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using System.Xml.XPath; using System.Xml.Linq; using SDKDocGenerator.Syntax; namespace SDKDocGenerator.Writers { public class FieldWriter : MemberWriter { readonly FieldInfoWrapper _fieldInfo; public FieldWriter(GenerationManifest artifacts, FrameworkVersion version, FieldInfoWrapper FieldInfo) : base(artifacts, version, FieldInfo) { this._fieldInfo = FieldInfo; } protected override string GenerateFilename() { return FilenameGenerator.GenerateFilename(this._fieldInfo); } protected override string GenerateFilepath() { return GenerationManifest.OutputSubFolderFromNamespace(_fieldInfo.DeclaringType.Namespace); } protected override string GetTitle() { return string.Format("{0} {1}", GetMemberName(), GetMemberType()); } protected override string GetMemberName() { return string.Format("{0}.{1}", this._fieldInfo.DeclaringType.GetDisplayName(false), this._fieldInfo.Name); } protected override string GetMemberType() { return "Field"; } protected override XElement GetSummaryDocumentation() { var element = NDocUtilities.FindDocumentation(this._fieldInfo); return element; } protected override string GetSyntax() { return new CSharpSyntaxGenerator(this._version).GenerateSyntax(this._fieldInfo); } } }
62
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SDKDocGenerator.Writers { public class LandingPageWriter : BaseTemplateWriter { public LandingPageWriter(GeneratorOptions options) : base(options) { } protected override string GetTemplateName() { return "sdk-api-home.html"; } protected override string TemplateOutputPath { get { return Path.Combine(Options.ComputedContentFolder, GetTemplateName()); } } protected override string ReplaceTokens(string templateBody) { var disclaimer = string.Format("<p>{0}</p>", string.Format(BaseWriter.BJSDisclaimerTemplate, Options.BJSDocsDomain)); var finalBody = templateBody.Replace("{regionDisclaimer}", disclaimer); return finalBody; } } }
38
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.ComTypes; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading.Tasks; using System.Xml.XPath; using System.Xml.Linq; namespace SDKDocGenerator.Writers { public abstract class MemberWriter : BaseWriter { readonly MemberInfoWrapper _info; protected MemberWriter(GenerationManifest artifacts, FrameworkVersion version, MemberInfoWrapper info) : base(artifacts, version) { this._info = info; } protected abstract string GetSyntax(); protected override void WriteContent(TextWriter writer) { AddSummaryDocumentation(writer); AddNamespace(writer, this._info.DeclaringType.Namespace, this._info.DeclaringType.ManifestModuleName); base.AddSyntax(writer, GetSyntax()); AddParameters(writer); AddReturn(writer); AddExceptions(writer); AddRemarksDocumentation(writer); AddExamples(writer); AddVersionInformation(writer, this._info); AddSeeAlso(writer); } protected virtual void AddParameters(TextWriter writer) { } protected virtual void AddReturn(TextWriter writer) { } protected virtual void AddExceptions(TextWriter writer) { var ndoc = GetSummaryDocumentation(); if (ndoc == null) return; var elements = ndoc.XPathSelectElements("exception"); if (!elements.Any()) return; var headers = new List<TableColumnHeader> { new TableColumnHeader {Title = "Exception", CssClass = "nameColumn"}, new TableColumnHeader {Title = "Condition", CssClass = "descriptionColumn"} }; AddMemberTableSectionHeader(writer, "Exceptions", headers); foreach (var element in elements) { var crossReferencedType = GetCrossReferenceTypeName(element); if (string.IsNullOrEmpty(crossReferencedType)) continue; string condition = element.Value; AddException(writer, crossReferencedType, condition); } AddMemberTableSectionClosing(writer); } void AddException(TextWriter writer, string typeName, string condition) { writer.WriteLine("<tr>"); writer.WriteLine("<td>"); WriteCrossReferenceTagReplacement(writer, typeName); writer.WriteLine("</td>"); writer.WriteLine("<td>"); writer.WriteLine(condition); writer.WriteLine("</td>"); writer.WriteLine("</tr>"); } protected override string GetTOCID() { // Have to probe to form up namespace qualified name, as some generic // definitions do not have 'FullName' available. This will likely need // extending over time. var name = this._info.DeclaringType.FullName ?? this._info.DeclaringType.GenericTypeName; return name.Replace('.', '_'); } } }
112
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SDKDocGenerator.Writers { public abstract class MethodBaseWriter : MemberWriter { readonly MethodBaseWrapper _info; protected MethodBaseWriter(GenerationManifest artifacts, FrameworkVersion version, MethodBaseWrapper info) : base(artifacts, version, info) { this._info = info; } protected override void AddParameters(System.IO.TextWriter writer) { var parameters = this._info.GetParameters(); if (parameters.Count == 0) return; var ndoc = GetSummaryDocumentation(); writer.WriteLine("<div class=\"sectionbody\">"); writer.WriteLine("<div id=\"parameters\">"); writer.WriteLine("<h3><strong class=\"subHeading\">Parameters</strong></h3>"); writer.WriteLine("</div>"); foreach (var parameter in parameters) { writer.WriteLine("<dl>"); writer.WriteLine("<dt>"); writer.WriteLine("<span class=\"parameter\">{0}</span>", parameter.Name); writer.WriteLine("</dt>"); writer.WriteLine("<dd>"); var paramType = parameter.ParameterType; writer.WriteLine("Type: {0}<br />", paramType.CreateReferenceHtml(fullTypeName: true)); var doc = NDocUtilities.FindParameterDocumentation(ndoc, parameter.Name); writer.WriteLine("<p>{0}</p>", doc); writer.WriteLine("</dd>"); writer.WriteLine("</dl>"); } writer.WriteLine("</div>"); } } }
58
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using System.Xml.XPath; using System.Xml.Linq; using System.Text.RegularExpressions; using SDKDocGenerator.Syntax; namespace SDKDocGenerator.Writers { public class MethodWriter : MethodBaseWriter { readonly MethodInfoWrapper _methodInfo; readonly bool _isFakeAsync; readonly bool _hasAsyncVersion; public MethodWriter(GenerationManifest artifacts, FrameworkVersion version, MethodInfoWrapper methodInfo) : base(artifacts, version, methodInfo) { this._methodInfo = methodInfo; this._isFakeAsync = this._methodInfo.FullName == "Amazon.Lambda.Model.InvokeAsyncResponse InvokeAsync(Amazon.Lambda.Model.InvokeAsyncRequest)"; if (_isFakeAsync || !this._methodInfo.Name.EndsWith("Async", StringComparison.Ordinal)) { //This is not an Async method. Lookup if an Async version exists for .NET Core. this._hasAsyncVersion = NDocUtilities.FindDocumentationAsync(Artifacts.NDocForPlatform("netcoreapp3.1"), methodInfo) != null; } } protected override string GenerateFilename() { return FilenameGenerator.GenerateFilename(this._methodInfo); } protected override string GenerateFilepath() { return GenerationManifest.OutputSubFolderFromNamespace(_methodInfo.DeclaringType.Namespace); } protected override string GetTitle() { var par = FormatParameters(this._methodInfo.GetParameters()); if (string.IsNullOrEmpty(par)) return string.Format("{0}.{1} {2}", this._methodInfo.DeclaringType.GetDisplayName(false), this._methodInfo.Name, GetMemberType()); return string.Format("{0}.{1} {2} ({3})", this._methodInfo.DeclaringType.GetDisplayName(false), this._methodInfo.Name, GetMemberType(), par); } protected override string GetMemberName() { var par = FormatParameters(this._methodInfo.GetParameters()); if (string.IsNullOrEmpty(par)) return string.Format("{0}.{1}", this._methodInfo.DeclaringType.GetDisplayName(false), this._methodInfo.Name); return string.Format("{0}.{1} ({2})", this._methodInfo.DeclaringType.GetDisplayName(false), this._methodInfo.Name, par); } protected override string GetMemberType() { return "Method"; } protected override XElement GetSummaryDocumentation() { var element = NDocUtilities.FindDocumentation(this._methodInfo); return element; } protected override string GetSyntax() { return new CSharpSyntaxGenerator(this._version).GenerateSyntax(this._methodInfo); } protected override void AddReturn(System.IO.TextWriter writer) { var returnType = this._methodInfo.ReturnType; if (returnType == null || returnType.FullName == "System.Void") return; writer.WriteLine("<div class=\"sectionbody\">"); writer.WriteLine("<div class=\"returnType\">"); writer.WriteLine("<h3><strong class=\"subHeading\">Return Value</strong></h3><br />"); writer.WriteLine("</div>"); writer.WriteLine("<div class=\"returnTypeName\">Type: {0}</div>", returnType.CreateReferenceHtml(fullTypeName: false)); var ndoc = GetSummaryDocumentation(); if (ndoc != null) { var returnDoc = NDocUtilities.FindReturnDocumentation(ndoc); if (returnDoc != null) { writer.WriteLine("<div class=\"returnTypeDoc\">{0}</div>", returnDoc); } } writer.WriteLine("</div>"); } protected override void AddSummaryNotes(TextWriter writer) { if (!this._isFakeAsync && this._methodInfo.Name.EndsWith("Async", StringComparison.Ordinal)) { const string net35PatternNote = " For .NET 3.5 the operation is implemented as a pair of methods using the standard naming convention of " + "<b>Begin</b><i>{0}</i> and <b>End</b><i>{0}</i>."; const string patternNote = "<div class=\"noteblock\"><div class=\"noteheader\">Note:</div>" + "<p>This is an asynchronous operation using the standard naming convention for .NET 4.5 or higher." + "{0}</p></div>"; var name = this._methodInfo.Name.Substring(0, this._methodInfo.Name.Length - 5); writer.WriteLine(patternNote, string.Format(net35PatternNote, name)); } else if (this._hasAsyncVersion) { const string platforms = ".NET Core"; const string syncPatternNote = "<div class=\"noteblock\"><div class=\"noteheader\">Note:</div>" + "<p> For {0} this operation is only available in asynchronous form. Please refer to <i>{1}</i><b>Async</b>.</p></div>"; writer.WriteLine(syncPatternNote, platforms, _methodInfo.Name); } } private bool ShouldEmitRewriteRule { get { // This check is mostly to keep the generator from emitting multiple rewrite rules for the same shape. // i.e. we don't want a rewrite rule for bcl35, bcl45, and netstandard. We only emit rules for bcl45 // we don't want to emit rules for both Async and Sync. We only emit rules for Async. return (this._version == FrameworkVersion.DotNet45 && !this._methodInfo.Name.EndsWith("Async", StringComparison.Ordinal) && this._methodInfo.DeclaringType.IsClass && !this._methodInfo.DeclaringType.IsAbstract); } } private IEnumerable<string> GetSeeAlsoLinks() { var element = GetSummaryDocumentation(); if (element != null) { var seeAlsoList = element.XPathSelectElements("seealso"); if (seeAlsoList != null) { return seeAlsoList.Select(e => e.Attribute("href") != null ? e.Attribute("href").Value.ToString() : null) .Where(s => s != null) .ToList(); } } return null; } protected override void WriteContent(TextWriter writer) { base.WriteContent(writer); if (ShouldEmitRewriteRule) { var links = GetSeeAlsoLinks(); if (links != null) { foreach(var link in links) { string serviceId; string shape; if (SDKDocRedirectWriter.ExtractServiceIDAndShapeFromUrl(link, out serviceId, out shape)) { string docPath = string.Format("{0}{1}/{2}", SDKDocRedirectWriter.DocPathPrefix, GenerateFilepath(), GenerateFilename().Replace('\\', '/')); SDKDocRedirectWriter.AddRule(serviceId, shape, docPath); break; } } } } } } }
193
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SDKDocGenerator.Writers { public class NamespaceWriter : BaseWriter { readonly string _namespaceName; readonly AssemblyWrapper _assemblyWrapper; public NamespaceWriter(GenerationManifest artifacts, FrameworkVersion version, string namespaceName) : base(artifacts, version) { this._namespaceName = namespaceName; this._assemblyWrapper = artifacts.ManifestAssemblyContext.SdkAssembly; } protected override string GenerateFilename() { return FilenameGenerator.GenerateNamespaceFilename(this._namespaceName); } protected override string GenerateFilepath() { return GenerationManifest.OutputSubFolderFromNamespace(_namespaceName); } protected override string GetTitle() { return string.Format("{0} {1}", GetMemberName(), GetMemberType()); } protected override string GetMemberName() { return this._namespaceName; } protected override string GetMemberType() { return "Namespace"; } protected override void WriteContent(System.IO.TextWriter writer) { AddClasses(writer); AddStructures(writer); AddInterfaces(writer); AddEnums(writer); } protected override System.Xml.Linq.XElement GetSummaryDocumentation() { return null; } void AddClasses(TextWriter writer) { var constructors = this._assemblyWrapper.GetTypesForNamespace(this._namespaceName).Where(x => x.IsPublic && x.IsClass); if (!constructors.Any()) return; AddMemberTableSectionHeader(writer, "Classes"); foreach (var info in constructors.OrderBy(x => x.Name)) { AddRow(writer, info, "class"); } AddMemberTableSectionClosing(writer); } void AddStructures(TextWriter writer) { var constructors = this._assemblyWrapper.GetTypesForNamespace(this._namespaceName).Where(x => x.IsPublic && x.IsStructure); if (!constructors.Any()) return; AddMemberTableSectionHeader(writer, "Structures"); foreach (var info in constructors.OrderBy(x => x.Name)) { AddRow(writer, info, "struct"); } AddMemberTableSectionClosing(writer); } void AddInterfaces(TextWriter writer) { var constructors = this._assemblyWrapper.GetTypesForNamespace(this._namespaceName).Where(x => x.IsPublic && x.IsInterface); if (!constructors.Any()) return; AddMemberTableSectionHeader(writer, "Interfaces"); foreach (var info in constructors.OrderBy(x => x.Name)) { AddRow(writer, info, "interface"); } AddMemberTableSectionClosing(writer); } void AddEnums(TextWriter writer) { var constructors = this._assemblyWrapper.GetTypesForNamespace(this._namespaceName).Where(x => x.IsPublic && x.IsEnum); if (!constructors.Any()) return; AddMemberTableSectionHeader(writer, "Enums"); foreach (var info in constructors.OrderBy(x => x.Name)) { AddRow(writer, info, "enum"); } AddMemberTableSectionClosing(writer); } void AddRow(TextWriter writer, TypeWrapper info, string cssImageClass) { writer.WriteLine("<tr>"); // funky but works var imageClassDisplayName = string.Format("{0}{1}", cssImageClass.Substring(0, 1).ToUpper(), cssImageClass.Substring(1)); writer.WriteLine("<td>"); writer.WriteLine("<img class=\"{0}\" src=\"{2}/resources/blank.gif\" title=\"{1}\" alt=\"{1}\"/>", cssImageClass, imageClassDisplayName, RootRelativePath); writer.WriteLine("</td>"); writer.WriteLine("<td>"); writer.WriteLine("<a href=\"./{0}\">{1}</a>", FilenameGenerator.GenerateFilename(info), info.GetDisplayName(false)); writer.WriteLine("</td>"); writer.WriteLine("<td>"); var docs = NDocUtilities.FindDocumentation(NDocUtilities.GetDocumentationInstance(info.DocId), info); var html = NDocUtilities.TransformDocumentationToHTML(docs, "summary", Artifacts.ManifestAssemblyContext.SdkAssembly, this._version); writer.WriteLine(html); writer.WriteLine("</td>"); writer.WriteLine("</tr>"); } protected override string GetTOCID() { return this._namespaceName.Replace('.', '_'); } } }
148
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using System.Xml.XPath; using System.Xml.Linq; using SDKDocGenerator.Syntax; namespace SDKDocGenerator.Writers { public class PropertyWriter : MemberWriter { readonly PropertyInfoWrapper _propertyInfo; public PropertyWriter(GenerationManifest artifacts, FrameworkVersion version, PropertyInfoWrapper propertyInfo) : base(artifacts, version, propertyInfo) { this._propertyInfo = propertyInfo; } protected override string GenerateFilename() { return FilenameGenerator.GenerateFilename(this._propertyInfo); } protected override string GenerateFilepath() { return GenerationManifest.OutputSubFolderFromNamespace(_propertyInfo.DeclaringType.Namespace); } protected override string GetTitle() { return string.Format("{0} {1}", GetMemberName(), GetMemberType()); } protected override string GetMemberName() { return string.Format("{0}.{1}", this._propertyInfo.DeclaringType.GetDisplayName(false), this._propertyInfo.Name); } protected override string GetMemberType() { return "Property"; } protected override XElement GetSummaryDocumentation() { var element = NDocUtilities.FindDocumentation(this._propertyInfo); return element; } protected override string GetSyntax() { return new CSharpSyntaxGenerator(this._version).GenerateSyntax(this._propertyInfo); } protected override void AddReturn(System.IO.TextWriter writer) { var returnType = this._propertyInfo.PropertyType; if (returnType == null) return; writer.WriteLine("<div class=\"sectionbody\">"); writer.WriteLine("<div id=\"returnType\">"); writer.WriteLine("<strong class=\"subHeading\">Property Value</strong><br />"); writer.WriteLine("</div>"); var sb = new StringBuilder("Type: <span>"); var nsFolder = GenerationManifest.OutputSubFolderFromNamespace(_propertyInfo.DeclaringType.Namespace); sb.Append(EmitTypeLinkMarkup(returnType, this._version)); if (returnType.IsGenericType) { sb.Append(ProcessGenericParameterTypes(returnType.GenericTypeArguments(), _version)); } writer.WriteLine("{0}</span>", sb); writer.WriteLine("</div>"); } internal static string ProcessGenericParameterTypes(IList<TypeWrapper> typedArgs, FrameworkVersion version) { var sb = new StringBuilder(); sb.Append("&lt;"); for (var i = 0; i < typedArgs.Count; i++) { if (i > 0) sb.Append(", "); var a = typedArgs[i]; sb.Append(EmitTypeLinkMarkup(a, version)); if (a.IsGenericType) sb.Append(ProcessGenericParameterTypes(a.GenericTypeArguments(), version)); } sb.Append("&gt;"); return sb.ToString(); } internal static string EmitTypeLinkMarkup(TypeWrapper t, FrameworkVersion version) { return t.CreateReferenceHtml(fullTypeName: false); } } }
112
aws-sdk-net
aws
C#
using System; using System.IO; using System.Text.RegularExpressions; using System.Collections.Generic; namespace SDKDocGenerator { #region rules public abstract class RewriteRuleBase { public string Pattern; public string Substitution; public string Flags; public static string RuleName = "RewriteRule"; public override string ToString() { return string.Format(@"{0} {1} ""{2}"" {3}", RuleName, Pattern, Substitution, Flags); } public int CompareTo(object obj) { return this.ToString().CompareTo(obj.ToString()); } } public class RewriteRule : RewriteRuleBase, IComparable { public RewriteRule(string pattern, string substitution) { Pattern = pattern; Substitution = substitution; Flags = "[L,R,NE]"; } } #endregion public static class SDKDocRedirectWriter { public const string RedirectFileName = @"package.redirects.conf"; public const string DocPathPrefix = @"/sdkfornet/v3/apidocs/index.html?page="; public const string ToolId = @"DotNetSDKV3"; private static Regex UrlPattern = new Regex(".*/WebAPI/(.*)/(.*)"); private static IDictionary<string, ISet<RewriteRule>> _rulesForServices = new SortedDictionary<string, ISet<RewriteRule>>(); public static void Write(Stream stream) { using (StreamWriter writer = new StreamWriter(stream)) { int totalRuleCount = 0; foreach (var service in _rulesForServices) { totalRuleCount += service.Value.Count; } // skip rule for all rules writer.WriteLine(@"RewriteCond ""%{REQUEST_URI}"" ""!^/goto/DotNetSDKV3/"""); writer.WriteLine(string.Format(@"RewriteRule "".?"" ""-"" [S={0}]", totalRuleCount)); foreach (var service in _rulesForServices) { foreach (var rule in service.Value) { writer.WriteLine(rule.ToString()); } } } } public static bool ExtractServiceIDAndShapeFromUrl(string link, out string serviceId, out string shape) { Match match = UrlPattern.Match(link); if (match.Success && match.Groups.Count == 3) { serviceId = match.Groups[1].ToString(); shape = match.Groups[2].ToString(); return true; } else { serviceId = ""; shape = ""; System.Console.WriteLine("** Failed to match : " + link); } return false; } public static void AddRule(string serviceId, string shape, string docPath) { string requestedPath = string.Format("^/goto/{0}/{1}/{2}", ToolId, serviceId, shape); ISet<RewriteRule> set; if (!_rulesForServices.TryGetValue(serviceId, out set)) { set = new SortedSet<RewriteRule>(); _rulesForServices.Add(serviceId, set); } set.Add(new RewriteRule(requestedPath, docPath)); } } }
107
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Json; using Json.LitJson; namespace SDKDocGenerator.Writers { public class TOCWriter : BaseTemplateWriter { private readonly Dictionary<string, string> _namespaceTocs = new Dictionary<string, string>(); private const string TocFilesFolderName = "_tocfiles"; private const string TocFilenameSuffix = ".toc.json"; private const string TocIdFieldName = "id"; private const string TocHrefFieldName = "href"; private const string TocNodesFieldName = "nodes"; public TOCWriter(GeneratorOptions options) : base(options) { } /// <summary> /// Creates or updates a per-namespace json file during generation of docs for types in that /// namespace. These will be added to the _namespaceTocs collection to be collated into /// one single master toc at the end of processing of all namespaces. /// </summary> /// <example> /// An partial and annotated example of what one data file looks like for the /// 'Amazon' namespace: /// { /// "Amazon" : // this is used as the display name of the root for the entries /// { /// "id" : "Amazon", // the unique id assigned to the li element /// "href" : "./items/Amazon/N_.html", // the target of the link /// "nodes": { // collection of child nodes for the namespace /// "AWSConfigs" : { // display name for child node /// "id" : "Amazon_AWSConfigs", // the unique li id /// "href" : "./items/Amazon/TAWSConfigs.html" // the target of the link /// }, /// "LoggingOptions" : { /// "id" : "Amazon_LoggingOptions", /// "href" : "./items/Amazon\TLoggingOptions.html" /// }, /// ... /// } /// } /// } /// </example> public void BuildNamespaceToc(string nameSpace, AssemblyWrapper sdkAssemblyWrapper) { var sb = new StringBuilder(); var jsonWriter = new JsonWriter(sb); jsonWriter.WriteObjectStart(); WriteNamespaceToc(jsonWriter, nameSpace, sdkAssemblyWrapper); jsonWriter.WriteObjectEnd(); var nsTocContents = sb.ToString(); if (_namespaceTocs.ContainsKey(nameSpace)) _namespaceTocs[nameSpace] = nsTocContents; else _namespaceTocs.Add(nameSpace, nsTocContents); PersistNamespaceToc(nameSpace); } protected override string GetTemplateName() { return "TOC.html"; } protected override string ReplaceTokens(string templateBody) { var tocContent = TransformNamespaceTocsToHtml(); var finalBody = templateBody.Replace("{TOC}", tocContent); return finalBody; } /// <summary> /// Loads the toc snippet file for the specified namespace, adding it to the managed /// collection for later collation into the overall toc file. /// </summary> //void LoadNamespaceToc(string nameSpace) //{ // var filePath = Path.Combine(Options.ComputedContentFolder, tocFilesFolderName); // if (!Directory.Exists(filePath)) // return; // var tocFile = Path.Combine(filePath, nameSpace + extensionPattern); // if (File.Exists(tocFile)) // { // using (var reader = File.OpenText(tocFile)) // { // var tocContent = reader.ReadToEnd(); // _namespaceTocs.Add(nameSpace, tocContent); // } // } //} void WriteNamespaceToc(JsonWriter writer, string ns, AssemblyWrapper sdkAssemblyWrapper) { var tocId = ns.Replace(".", "_"); var nsFilePath = Path.Combine("./" + Options.ContentSubFolderName, GenerationManifest.OutputSubFolderFromNamespace(ns), FilenameGenerator.GenerateNamespaceFilename(ns)).Replace('\\', '/'); writer.WritePropertyName(ns); writer.WriteObjectStart(); writer.WritePropertyName(TocIdFieldName); writer.Write(tocId); writer.WritePropertyName(TocHrefFieldName); writer.Write(nsFilePath); writer.WritePropertyName(TocNodesFieldName); writer.WriteObjectStart(); foreach (var type in sdkAssemblyWrapper.GetTypesForNamespace(ns).OrderBy(x => x.Name)) { var filePath = Path.Combine("./" + Options.ContentSubFolderName, GenerationManifest.OutputSubFolderFromNamespace(type.Namespace), FilenameGenerator.GenerateFilename(type)).Replace('\\', '/'); writer.WritePropertyName(type.GetDisplayName(false)); writer.WriteObjectStart(); writer.WritePropertyName(TocIdFieldName); writer.Write(type.GetDisplayName(true).Replace(".", "_")); writer.WritePropertyName(TocHrefFieldName); writer.Write(filePath); writer.WriteObjectEnd(); } writer.WriteObjectEnd(); writer.WriteObjectEnd(); } /// <summary> /// Persists a toc snippet file, in json format, from the managed collection. /// </summary> void PersistNamespaceToc(string nameSpace) { var tocFilesSubfolder = Path.Combine(Options.ComputedContentFolder, TocFilesFolderName); if (!Directory.Exists(tocFilesSubfolder)) Directory.CreateDirectory(tocFilesSubfolder); var filePath = Path.Combine(tocFilesSubfolder, nameSpace + TocFilenameSuffix); using (var writer = File.CreateText(filePath)) { writer.Write(_namespaceTocs[nameSpace]); } } /// <summary> /// Emit the set of namespace files encapsulated in json to a TOC based around /// unordered lists, returning the html for inclusion on the page. /// </summary> /// <returns></returns> string TransformNamespaceTocsToHtml() { var writer = new StringWriter(); writer.Write("<ul class=\"awstoc\">"); foreach (var ns in _namespaceTocs.Keys.OrderBy(x => x)) { var nsJson = JsonMapper.ToObject(new JsonReader(_namespaceTocs[ns])); var nsName = nsJson.PropertyNames.First(); var nsData = nsJson[0]; var nsId = (string) nsData["id"]; var nsFilePath = (string)nsData["href"]; writer.Write(@"<li class=""nav"" id=""{0}""> <button type = ""button"" aria-label=""{2} child nodes"" aria-expanded=""false""></button> <a class=""nav"" href=""{1}"" target=""contentpane"" id=""{2}-parentnode"">{2}</a>", nsId, nsFilePath, nsName); writer.Write("<ul role=\"region\" aria-labelledby=\"{0}\"/>",nsName); var nsNodes = nsData["nodes"]; foreach (var p in nsNodes.PropertyNames) { var nodeObj = nsNodes[p]; writer.Write("<li class=\"nav leaf\" id=\"{0}\"><a class=\"nav leaf\" href=\"{1}\" target=\"contentpane\">{2}</a></li>", nodeObj["id"], nodeObj["href"], p); } writer.Write("</ul></li>"); } writer.Write("</ul>"); return writer.ToString(); } } }
207
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Util; using Amazon.Runtime.SharedInterfaces; using Amazon.Util; using Aws.Crt.Auth; using Aws.Crt.Http; using AWSSDK.Extensions.CrtIntegration; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; namespace Amazon.Extensions.CrtIntegration { /// <summary> /// Asymmetric Sigv4 (SigV4a) protocol signer using the implementation provided by Aws.Crt.Auth /// </summary> public class CrtAWS4aSigner : IAWSSigV4aProvider { public CrtAWS4aSigner() : this(true) { } public CrtAWS4aSigner(bool signPayload) { SignPayload = signPayload; } public bool SignPayload { get; private set; } /// <summary> /// Protocol for the requests being signed /// </summary> public ClientProtocol Protocol { get { return ClientProtocol.RestProtocol; } } /// <summary> /// Calculates and signs the specified request using the Asymmetric SigV4 signing protocol /// by using theAWS account credentials given in the method parameters. The resulting signature /// is added to the request headers as 'Authorization'. /// </summary> /// <param name="request"> /// The request to compute the signature for. Additional headers mandated by the /// SigV4a protocol will be added to the request before signing. /// </param> /// <param name="clientConfig"> /// Client configuration data encompassing the service call (notably authentication /// region, endpoint and service name). /// </param> /// <param name="metrics">Metrics for the request</param> /// <param name="credentials">The AWS credentials for the account making the service call</param> public void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, ImmutableCredentials credentials) { SignRequest(request, clientConfig, metrics, credentials); } /// <summary> /// Calculates the signature for the specified request using the Asymmetric SigV4 signing protocol /// </summary> /// <param name="request"> /// The request to compute the signature for. Additional headers mandated by the /// SigV4a protocol will be added to the request before signing. /// </param> /// <param name="clientConfig"> /// Client configuration data encompassing the service call (notably authentication /// region, endpoint and service name). /// </param> /// <param name="metrics">Metrics for the request</param> /// <param name="credentials">The AWS credentials for the account making the service call</param> /// <returns>AWS4aSigningResult for the given request</returns> public AWS4aSigningResult SignRequest(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, ImmutableCredentials credentials) { var signedAt = AWS4Signer.InitializeHeaders(request.Headers, request.Endpoint); var serviceSigningName = !string.IsNullOrEmpty(request.OverrideSigningServiceName) ? request.OverrideSigningServiceName : AWS4Signer.DetermineService(clientConfig); if (serviceSigningName == "s3") { // Older versions of the S3 package can be used with newer versions of Core, this guarantees no double encoding will be used. // The new behavior uses endpoint resolution rules, which are not present prior to 3.7.100 request.UseDoubleEncoding = false; } var regionSet = AWS4Signer.DetermineSigningRegion(clientConfig, clientConfig.RegionEndpointServiceName, request.AlternateEndpoint, request); request.DeterminedSigningRegion = regionSet; AWS4Signer.SetXAmzTrailerHeader(request.Headers, request.TrailingHeaders); var signingConfig = PrepareCRTSigningConfig( AwsSignatureType.HTTP_REQUEST_VIA_HEADERS, regionSet, serviceSigningName, signedAt, credentials, request.UseDoubleEncoding); // If the request should use a fixed x-amz-content-sha256 header value, determine the appropriate one var fixedBodyHash = request.TrailingHeaders?.Count > 0 ? AWS4Signer.V4aStreamingBodySha256WithTrailer : AWS4Signer.V4aStreamingBodySha256; signingConfig.SignedBodyValue = AWS4Signer.SetRequestBodyHash(request, SignPayload, fixedBodyHash, ChunkedUploadWrapperStream.V4A_SIGNATURE_LENGTH); var crtRequest = CrtHttpRequestConverter.ConvertToCrtRequest(request); var signingResult = AwsSigner.SignHttpRequest(crtRequest, signingConfig); var authorizationValue = Encoding.Default.GetString(signingResult.Get().Signature); var signedCrtRequest = signingResult.Get().SignedRequest; CrtHttpRequestConverter.CopyHeadersFromCrtRequest(request, signedCrtRequest); var dateStamp = AWS4Signer.FormatDateTime(signedAt, AWSSDKUtils.ISO8601BasicDateFormat); var scope = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}", dateStamp, serviceSigningName, AWS4Signer.Terminator); AWS4aSigningResult result = new AWS4aSigningResult( credentials.AccessKey, signedAt, CrtHttpRequestConverter.ExtractSignedHeaders(signedCrtRequest), scope, regionSet, authorizationValue, serviceSigningName, "", credentials); return result; } /// /// <summary> /// Calculates the signature for the specified request using the Asymmetric SigV4 /// signing protocol in preparation for generating a presigned URL. /// </summary> /// <param name="request"> /// The request to compute the signature for. Additional headers mandated by the /// SigV4a protocol will be added to the request before signing. /// </param> /// <param name="clientConfig"> /// Client configuration data encompassing the service call (notably authentication /// region, endpoint and service name). /// </param> /// <param name="metrics">Metrics for the request</param> /// <param name="credentials">The AWS credentials for the account making the service call</param> /// <param name="serviceSigningName">Service to sign the request for</param> /// <param name="overrideSigningRegion">Region to sign the request for</param> /// <returns>AWS4aSigningResult for the given request</returns> public AWS4aSigningResult Presign4a(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, ImmutableCredentials credentials, string serviceSigningName, string overrideSigningRegion) { if (serviceSigningName == "s3") { // Older versions of the S3 package can be used with newer versions of Core, this guarantees no double encoding will be used. // The new behavior uses endpoint resolution rules, which are not present prior to 3.7.100 request.UseDoubleEncoding = false; } var signedAt = AWS4Signer.InitializeHeaders(request.Headers, request.Endpoint); var regionSet = overrideSigningRegion ?? AWS4Signer.DetermineSigningRegion(clientConfig, clientConfig.RegionEndpointServiceName, request.AlternateEndpoint, request); var signingConfig = PrepareCRTSigningConfig( AwsSignatureType.HTTP_REQUEST_VIA_QUERY_PARAMS, regionSet, serviceSigningName, signedAt, credentials, request.UseDoubleEncoding); if (AWS4PreSignedUrlSigner.ServicesUsingUnsignedPayload.Contains(serviceSigningName)) { signingConfig.SignedBodyValue = AWS4Signer.UnsignedPayload; } else { signingConfig.SignedBodyValue = AWS4Signer.EmptyBodySha256; } // The expiration may have already be set in a header when marshalling the GetPreSignedUrlRequest -> IRequest if (request.Parameters != null && request.Parameters.ContainsKey(HeaderKeys.XAmzExpires)) { signingConfig.ExpirationInSeconds = Convert.ToUInt64(request.Parameters[HeaderKeys.XAmzExpires]); } var crtRequest = CrtHttpRequestConverter.ConvertToCrtRequest(request); var signingResult = AwsSigner.SignHttpRequest(crtRequest, signingConfig); string authorizationValue = Encoding.Default.GetString(signingResult.Get().Signature); var dateStamp = AWS4Signer.FormatDateTime(signedAt, AWSSDKUtils.ISO8601BasicDateFormat); var scope = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}", dateStamp, serviceSigningName, AWS4Signer.Terminator); AWS4aSigningResult result = new AWS4aSigningResult( credentials.AccessKey, signedAt, CrtHttpRequestConverter.ExtractSignedHeaders(signingResult.Get().SignedRequest), scope, regionSet, authorizationValue, serviceSigningName, signingResult.Get().SignedRequest.Uri, credentials); return result; } /// <summary> /// Signs one chunk of a request when transferring a payload using multiple chunks /// </summary> /// <param name="chunkBody">Content of the current chunk to sign</param> /// <param name="previousSignature">Signature of the previously signed chunk</param> /// <param name="headerSigningResult">Signing result for the "seed" signature consisting of headers</param> /// <returns>Signature of the current chunk</returns> public string SignChunk(Stream chunkBody, string previousSignature, AWS4aSigningResult headerSigningResult) { var signingConfig = PrepareCRTSigningConfig(AwsSignatureType.HTTP_REQUEST_CHUNK, headerSigningResult); signingConfig.SignedBodyHeader = AwsSignedBodyHeaderType.NONE; // The previous signature may be padded with '*' up to 144 characters, which is used // when actually sending a chunk but not when calculating the next chunk's signature. previousSignature = previousSignature.TrimEnd('*'); var signingResult = AwsSigner.SignChunk(chunkBody, Encoding.UTF8.GetBytes(previousSignature), signingConfig); return Encoding.UTF8.GetString(signingResult.Get().Signature); } /// <summary> /// Signs the final chunk containing trailing headers /// </summary> /// <param name="trailingHeaders">Trailing header keys and values</param> /// <param name="previousSignature">Signature of the previously signed chunk</param> /// <param name="headerSigningResult">Signing result for the "seed" signature consisting of headers</param> /// <returns>Signature of the trailing header chunk</returns> public string SignTrailingHeaderChunk(IDictionary<string, string> trailingHeaders, string previousSignature, AWS4aSigningResult headerSigningResult) { var signingConfig = PrepareCRTSigningConfig(AwsSignatureType.HTTP_REQUEST_TRAILING_HEADERS, headerSigningResult); signingConfig.SignedBodyHeader = AwsSignedBodyHeaderType.NONE; var headerArray = trailingHeaders.Select(kvp => new HttpHeader(kvp.Key, kvp.Value)).ToArray(); // The previous signature may be padded with '*' up to 144 characters, which is used // when actually sending a chunk but not when calculating the next chunk's signature. previousSignature = previousSignature.TrimEnd('*'); var signingResult = AwsSigner.SignTrailingHeaders(headerArray, Encoding.UTF8.GetBytes(previousSignature), signingConfig); return Encoding.UTF8.GetString(signingResult.Get().Signature); } /// <summary> /// Helper function to set up an Aws.Crt.Auth.SigningConfig /// </summary> /// <param name="signatureType">Signature type</param> /// <param name="headerSigningResult">Signing result for the request's headers</param> /// <returns>Prepared CRT signing configuration</returns> public AwsSigningConfig PrepareCRTSigningConfig(AwsSignatureType signatureType, AWS4aSigningResult headerSigningResult) { return PrepareCRTSigningConfig(signatureType, headerSigningResult.RegionSet, headerSigningResult.Service, headerSigningResult.DateTime, headerSigningResult.Credentials, useDoubleEncoding: true); } /// <summary> /// Helper function to set up an Aws.Crt.Auth.SigningConfig /// </summary> /// <param name="signatureType">Signature type</param> /// <param name="region">Signing region</param> /// <param name="service">Service to sign the request for</param> /// <param name="signedAt">Timestamp to sign at</param> /// <param name="credentials">The AWS credentials for the account making the service call</param> /// <param name="useDoubleEncoding">Use double uri encoding when required</param> /// <returns>Prepared CRT signing configuration</returns> public AwsSigningConfig PrepareCRTSigningConfig(AwsSignatureType signatureType, string region, string service, DateTime signedAt, ImmutableCredentials credentials, bool useDoubleEncoding) { var signingConfig = new AwsSigningConfig { Algorithm = AwsSigningAlgorithm.SIGV4A, SignedBodyHeader = AwsSignedBodyHeaderType.X_AMZ_CONTENT_SHA256, SignatureType = signatureType, Region = region, Service = service, Timestamp = new DateTimeOffset(signedAt), Credentials = new Credentials(credentials.AccessKey, credentials.SecretKey, credentials.Token) }; signingConfig.UseDoubleUriEncode = useDoubleEncoding; signingConfig.ShouldNormalizeUriPath = useDoubleEncoding; return signingConfig; } } }
324
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.Runtime.SharedInterfaces.Internal; using Aws.Crt.Checksums; using System; namespace AWSSDK.Extensions.CrtIntegration { /// <summary> /// Wrapper for checksum algorithms provided by Aws.Crt.Checksums /// </summary> public class CrtChecksums : IChecksumProvider { /// <summary> /// Computes a CRC32 hash /// </summary> /// <param name="source">Data to hash</param> /// <returns>CRC32 hash as a base64-encoded string</returns> public string Crc32(byte[] source) => ConvertUintChecksumToBase64(Crc.crc32(source)); /// <summary> /// Computes a CRC32 hash /// </summary> /// <param name="source">Data to hash</param> /// <param name="previous">Previous value of a rolling checksum</param> /// <returns>Updated CRC32 hash as 32-bit integer</returns> public uint Crc32(byte[] source, uint previous) => Crc.crc32(source, previous); /// <summary> /// Computes a CRC32C hash /// </summary> /// <param name="source">Data to hash</param> /// <returns>CRC32C hash as a base64-encoded string</returns> public string Crc32C(byte[] source) => ConvertUintChecksumToBase64(Crc.crc32c(source)); /// <summary> /// Computes a CRC32C hash /// </summary> /// <param name="source">Data to hash</param> /// <param name="previous">Previous value of a rolling checksum</param> /// <returns>Updated CRC32C hash as 32-bit integer</returns> public uint Crc32C(byte[] source, uint previous) => Crc.crc32c(source, previous); /// <summary> /// Converts the 32-bit checksum from CRT into a base-64 string /// </summary> /// <param name="checksum">32-bit checksum</param> /// <returns>Checksum as a base64-encoded string</returns> private string ConvertUintChecksumToBase64(uint checksum) { var bytes = BitConverter.GetBytes(checksum); if (BitConverter.IsLittleEndian) { Array.Reverse(bytes); } return Convert.ToBase64String(bytes); } } }
75
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Util; using Amazon.Util; using Aws.Crt.Http; using System; using System.Collections.Generic; using System.IO; namespace AWSSDK.Extensions.CrtIntegration { /// <summary> /// Utility functions for converting between the SDK and CRT HTTP Request objects /// </summary> public class CrtHttpRequestConverter { // CRT calculates and sets these headers when signing, the SDK must not pass them in // See s_forbidden_headers in aws_signing.c private static readonly HashSet<string> CrtForbiddenHeaders = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { HeaderKeys.XAmzContentSha256Header, HeaderKeys.XAmzDateHeader, HeaderKeys.AuthorizationHeader, HeaderKeys.XAmzRegionSetHeader, HeaderKeys.XAmzSecurityTokenHeader }; // CRT calculates and sets these query params when signing, the SDK must not pass them in // See s_forbidden_params in aws_signing.c private static readonly HashSet<string> CrtForbiddenQueryParams = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { HeaderKeys.XAmzSignature, HeaderKeys.XAmzDateHeader, HeaderKeys.XAmzCredential, HeaderKeys.XAmzAlgorithm, HeaderKeys.XAmzSignedHeadersHeader, HeaderKeys.XAmzSecurityTokenHeader, HeaderKeys.XAmzExpires }; /// <summary> /// Converts the SDK's IRequest to the CRT's HttpRequest Object /// </summary> /// <param name="request">SDK request</param> /// <returns>CRT request</returns> public static Aws.Crt.Http.HttpRequest ConvertToCrtRequest(IRequest request) { // Remove any query params that CRT will set if (request.ParameterCollection != null && request.ParameterCollection.Count > 0) { foreach (var queryParam in request.ParameterCollection.GetSortedParametersList()) { if (CrtForbiddenQueryParams.Contains(queryParam.Key)) { request.ParameterCollection.Remove(queryParam.Key); } } } var crtRequest = new Aws.Crt.Http.HttpRequest { // Using OriginalString here because ComposeUrl -> ResolveResourcePath -> // JoinResourcePathSegments -> UrlEncode will escape some sequeneces (e.g. Ä -> %C3%84) // but initializing that as a Uri will convert it back to Ä Uri = AmazonServiceClient.ComposeUrl(request, false).OriginalString, Method = request.HttpMethod }; if (request.ContentStream != null) { if (request.ContentStream.CanSeek) { crtRequest.BodyStream = request.ContentStream; } else if (request.ContentStream is WrapperStream wrappedStream) { crtRequest.BodyStream = wrappedStream.GetSeekableBaseStream(); } else { throw new AWSCommonRuntimeException("Unable to pass an HTTP request with a non-seekable content stream to CRT."); } } else if (request.Content != null) { crtRequest.BodyStream = new MemoryStream(request.Content); } var headerList = new List<HttpHeader>(request.Headers.Count); foreach (var header in request.Headers) { // Skip CRT-calculated headers if (!CrtForbiddenHeaders.Contains(header.Key)) { headerList.Add(new HttpHeader(header.Key, header.Value)); } } crtRequest.Headers = headerList.ToArray(); return crtRequest; } /// <summary> /// Copies the headers from a CRT requst back to an existing SDK request /// </summary> /// <param name="request">SDK request</param> /// <param name="crtRequest">CRT request</param> public static void CopyHeadersFromCrtRequest(IRequest request, Aws.Crt.Http.HttpRequest crtRequest) { // Replace all of the SDK request's headers with the CRT headers (i.e. may now include signing-related headers) request.Headers.Clear(); foreach (var header in crtRequest.Headers) { request.Headers.Add(header.Name, header.Value); } } /// <summary> /// Extracts the list of signed headers from the 'Authorization' header set by CRT /// </summary> /// <param name="crtRequest">Signed CRT HTTPRequest</param> /// <returns>semicolon-delimited list of signed headers</returns> public static string ExtractSignedHeaders(Aws.Crt.Http.HttpRequest crtRequest) { const string startOfSignedHeadersPiece = "SignedHeaders="; foreach (var header in crtRequest.Headers) { if (header.Name == HeaderKeys.AuthorizationHeader) { foreach (var piece in header.Value.Split(' ')) { if (piece.StartsWith(startOfSignedHeadersPiece)) { var signedHeaders = piece.Substring(startOfSignedHeadersPiece.Length); signedHeaders = signedHeaders.TrimEnd(','); // Remove trailing , separating SignedHeaders from Signature return signedHeaders; } } } } return ""; } } }
160
aws-sdk-net
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("AWSSDK.Extensions.CrtIntegration")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyProduct("Amazon Web Services Common Runtime integration with the AWS .NET SDK")] [assembly: AssemblyDescription("Amazon Web Services Common Runtime integration with the AWS .NET SDK")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.7.0.0")]
21
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon; using Amazon.Runtime; using Amazon.Extensions.NETCore.Setup; namespace Amazon.Extensions.NETCore.Setup { /// <summary> /// The options used to construct AWS service clients like the Amazon.S3.AmazonS3Client. /// </summary> public class AWSOptions { /// <summary> /// The profile used to fetch AWS credentials for from the profile manager. /// </summary> public string Profile { get; set; } /// <summary> /// The location of the registered profiles. Set if using the non standard locations for profile stores. /// This is mostly used when running the application outside of an EC2 instance where the preferred /// IAM credentials are used and also not running under a logged on user. /// </summary> public string ProfilesLocation { get; set; } /// <summary> /// The AWS region the service client should use when making service operations. /// </summary> public RegionEndpoint Region { get; set; } /// <summary> /// If set this role will be assumed using the resolved AWS credentials. /// </summary> public string SessionRoleArn { get; set; } /// <summary> /// The session name for the assumed session using the SessionRoleArn. /// </summary> public string SessionName { get; set; } = "DefaultSessionName"; /// <summary> /// AWS Credentials used for creating service clients. If this is set it overrides the Profile property. /// </summary> public AWSCredentials Credentials { get; set; } /// <summary> /// The default configuration mode set for created service clients. /// </summary> public DefaultConfigurationMode? DefaultConfigurationMode { get; set; } private ClientConfig _defaultClientConfig; /// <summary> /// A default ClientConfig object. When service client is created any values set on the default ClientConfig /// are copied to the service specific client config. /// </summary> public ClientConfig DefaultClientConfig { get { if (this._defaultClientConfig == null) this._defaultClientConfig = new DefaultClientConfig(); return this._defaultClientConfig; } internal set { this._defaultClientConfig = value; } } /// <summary> /// Logging settings that should be applied to SDK global configuration. This setting is applied while creating /// the service client through this package. /// </summary> public LoggingSetting Logging { get; set; } /// <summary> /// Create a service client for the specified service interface using the options set in this instance. /// For example if T is set to IAmazonS3 then the AmazonS3ServiceClient which implements IAmazonS3 is created /// and returned. /// </summary> /// <typeparam name="T">The service interface that a service client will be created for.</typeparam> /// <returns>The service client that implements the service interface.</returns> public T CreateServiceClient<T>() where T : IAmazonService { return (T)ClientFactory.CreateServiceClient(null, typeof(T), this); } /// <summary> /// Container for logging settings of the SDK /// </summary> public class LoggingSetting { /// <summary> /// Logging destination. /// </summary> public LoggingOptions? LogTo { get; set; } /// <summary> /// When to log responses. /// </summary> public ResponseLoggingOption? LogResponses { get; set; } /// <summary> /// Gets or sets the size limit in bytes for logged responses. If logging for response /// body is enabled, logged response body is limited to this size. The SDK defaults to 1KB if this property is net set. /// </summary> public int? LogResponsesSizeLimit { get; set; } /// <summary> /// Whether or not to log SDK metrics. /// </summary> public bool? LogMetrics { get; set; } } } }
137
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Reflection; using Amazon.Runtime; using Amazon.Runtime.CredentialManagement; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Amazon.Extensions.NETCore.Setup { /// <summary> /// The factory class for creating AWS service clients from the AWS SDK for .NET. /// </summary> internal class ClientFactory { private static readonly Type[] EMPTY_TYPES = Array.Empty<Type>(); private static readonly object[] EMPTY_PARAMETERS = Array.Empty<object>(); private Type _serviceInterfaceType; private AWSOptions _awsOptions; /// <summary> /// Constructs an instance of the ClientFactory /// </summary> /// <param name="type">The type object for the Amazon service client interface, for example IAmazonS3.</param> internal ClientFactory(Type type, AWSOptions awsOptions) { _serviceInterfaceType = type; _awsOptions = awsOptions; } /// <summary> /// Creates the AWS service client that implements the service client interface. The AWSOptions object /// will be searched for in the IServiceProvider. /// </summary> /// <param name="provider">The dependency injection provider.</param> /// <returns>The AWS service client</returns> internal object CreateServiceClient(IServiceProvider provider) { var loggerFactory = provider.GetService<Microsoft.Extensions.Logging.ILoggerFactory>(); var logger = loggerFactory?.CreateLogger("AWSSDK"); var options = _awsOptions ?? provider.GetService<AWSOptions>(); if(options == null) { var configuration = provider.GetService<IConfiguration>(); if(configuration != null) { options = configuration.GetAWSOptions(); if (options != null) logger?.LogInformation("Found AWS options in IConfiguration"); } } return CreateServiceClient(logger, _serviceInterfaceType, options); } /// <summary> /// Creates the AWS service client that implements the service client interface. The AWSOptions object /// will be searched for in the IServiceProvider. /// </summary> /// <param name="provider">The dependency injection provider.</param> /// <returns>The AWS service client</returns> internal static IAmazonService CreateServiceClient(ILogger logger, Type serviceInterfaceType, AWSOptions options) { PerformGlobalConfig(logger, options); var credentials = CreateCredentials(logger, options); if (!string.IsNullOrEmpty(options?.SessionRoleArn)) { credentials = new AssumeRoleAWSCredentials(credentials, options.SessionRoleArn, options.SessionName); } var config = CreateConfig(serviceInterfaceType, options); var client = CreateClient(serviceInterfaceType, credentials, config); return client as IAmazonService; } /// <summary> /// Performs all of the global settings that have been specified in AWSOptions. /// </summary> /// <param name="logger"></param> /// <param name="options"></param> private static void PerformGlobalConfig(ILogger logger, AWSOptions options) { if(options?.Logging != null) { if(options.Logging.LogTo.HasValue && AWSConfigs.LoggingConfig.LogTo != options.Logging.LogTo.Value) { AWSConfigs.LoggingConfig.LogTo = options.Logging.LogTo.Value; logger?.LogDebug($"Configuring SDK LogTo: {AWSConfigs.LoggingConfig.LogTo}"); } if (options.Logging.LogResponses.HasValue && AWSConfigs.LoggingConfig.LogResponses != options.Logging.LogResponses.Value) { AWSConfigs.LoggingConfig.LogResponses = options.Logging.LogResponses.Value; logger?.LogDebug($"Configuring SDK LogResponses: {AWSConfigs.LoggingConfig.LogResponses}"); } if (options.Logging.LogMetrics.HasValue && AWSConfigs.LoggingConfig.LogMetrics != options.Logging.LogMetrics.Value) { AWSConfigs.LoggingConfig.LogMetrics = options.Logging.LogMetrics.Value; logger?.LogDebug($"Configuring SDK LogMetrics: {AWSConfigs.LoggingConfig.LogMetrics}"); } if (options.Logging.LogResponsesSizeLimit.HasValue && AWSConfigs.LoggingConfig.LogResponsesSizeLimit != options.Logging.LogResponsesSizeLimit.Value) { AWSConfigs.LoggingConfig.LogResponsesSizeLimit = options.Logging.LogResponsesSizeLimit.Value; logger?.LogDebug($"Configuring SDK LogResponsesSizeLimit: {AWSConfigs.LoggingConfig.LogResponsesSizeLimit}"); } } } /// <summary> /// Creates the service client using the credentials and client config. /// </summary> /// <param name="credentials"></param> /// <param name="config"></param> /// <returns></returns> private static AmazonServiceClient CreateClient(Type serviceInterfaceType, AWSCredentials credentials, ClientConfig config) { var clientTypeName = serviceInterfaceType.Namespace + "." + serviceInterfaceType.Name.Substring(1) + "Client"; var clientType = serviceInterfaceType.GetTypeInfo().Assembly.GetType(clientTypeName); if (clientType == null) { throw new AmazonClientException($"Failed to find service client {clientTypeName} which implements {serviceInterfaceType.FullName}."); } var constructor = clientType.GetConstructor(new Type[] { typeof(AWSCredentials), config.GetType() }); if (constructor == null) { throw new AmazonClientException($"Service client {clientTypeName} missing a constructor with parameters AWSCredentials and {config.GetType().FullName}."); } return constructor.Invoke(new object[] { credentials, config }) as AmazonServiceClient; } /// <summary> /// Creates the AWSCredentials using either the profile indicated from the AWSOptions object /// of the SDK fallback credentials search. /// </summary> /// <param name="options"></param> /// <returns></returns> private static AWSCredentials CreateCredentials(ILogger logger, AWSOptions options) { if (options != null) { if (options.Credentials != null) { logger?.LogInformation("Using AWS credentials specified with the AWSOptions.Credentials property"); return options.Credentials; } if (!string.IsNullOrEmpty(options.Profile)) { var chain = new CredentialProfileStoreChain(options.ProfilesLocation); AWSCredentials result; if (chain.TryGetAWSCredentials(options.Profile, out result)) { logger?.LogInformation($"Found AWS credentials for the profile {options.Profile}"); return result; } else { logger?.LogInformation($"Failed to find AWS credentials for the profile {options.Profile}"); } } } var credentials = FallbackCredentialsFactory.GetCredentials(); if (credentials == null) { logger?.LogError("Last effort to find AWS Credentials with AWS SDK's default credential search failed"); throw new AmazonClientException("Failed to find AWS Credentials for constructing AWS service client"); } else { logger?.LogInformation("Found credentials using the AWS SDK's default credential search"); } return credentials; } /// <summary> /// Creates the ClientConfig object for the service client. /// </summary> /// <param name="options"></param> /// <returns></returns> private static ClientConfig CreateConfig(Type serviceInterfaceType, AWSOptions options) { var configTypeName = serviceInterfaceType.Namespace + "." + serviceInterfaceType.Name.Substring(1) + "Config"; var configType = serviceInterfaceType.GetTypeInfo().Assembly.GetType(configTypeName); var constructor = configType.GetConstructor(EMPTY_TYPES); ClientConfig config = constructor.Invoke(EMPTY_PARAMETERS) as ClientConfig; if(options == null) { options = new AWSOptions(); } if (options.DefaultConfigurationMode.HasValue) { config.DefaultConfigurationMode = options.DefaultConfigurationMode.Value; } var defaultConfig = options.DefaultClientConfig; var emptyArray = new object[0]; var singleArray = new object[1]; var clientConfigTypeInfo = options.DefaultClientConfig.GetType(); var properties = clientConfigTypeInfo.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in properties) { if (property.GetMethod != null && property.SetMethod != null) { // Skip RegionEndpoint because it is set below and calling the get method on the // property triggers the default region fallback mechanism. if (string.Equals(property.Name, "RegionEndpoint", StringComparison.Ordinal)) continue; // DefaultConfigurationMode is skipped from the DefaultClientConfig because it is expected to be set // at the top level of AWSOptions which is done before this loop. if (string.Equals(property.Name, "DefaultConfigurationMode", StringComparison.Ordinal)) continue; // Skip setting RetryMode if it is set to legacy but the DefaultConfigurationMode is not legacy. // This will allow the retry mode to be configured from the DefaultConfiguration. // This is a workaround to handle the inability to tell if RetryMode was explicitly set. if (string.Equals(property.Name, "RetryMode", StringComparison.Ordinal) && defaultConfig.RetryMode == RequestRetryMode.Legacy && config.DefaultConfigurationMode != DefaultConfigurationMode.Legacy) continue; singleArray[0] = property.GetMethod.Invoke(defaultConfig, emptyArray); if (singleArray[0] != null) { property.SetMethod.Invoke(config, singleArray); } } } // Setting RegionEndpoint only if ServiceURL was not set, because ServiceURL value will be lost otherwise if (options.Region != null && string.IsNullOrEmpty(defaultConfig.ServiceURL)) { config.RegionEndpoint = options.Region; } return config; } } }
267
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Amazon.Extensions.NETCore.Setup { /// <summary> /// Exception for errors loading AWS options from IConfiguration object. /// </summary> public class ConfigurationException : Exception { /// <summary> /// Construct instance of ConfigurationException /// </summary> /// <param name="message">The error message.</param> public ConfigurationException(string message) : base(message) { } /// <summary> /// Construct instance of ConfigurationException /// </summary> /// <param name="message">The error message.</param> /// <param name="exception">Original exception.</param> public ConfigurationException(string message, Exception exception) : base(message, exception) { } /// <summary> /// The property that has an invalid value. /// </summary> public string PropertyName { get; set; } /// <summary> /// The value that was configured for the PropertyName. /// </summary> public string PropertyValue { get; set; } } }
51
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Reflection; using Amazon; using Amazon.Runtime; using Amazon.Util; using Amazon.Extensions.NETCore.Setup; using System.Linq; namespace Microsoft.Extensions.Configuration { /// <summary> /// This class adds extension methods to IConfiguration making it easier to pull out /// AWS configuration options. /// </summary> public static class ConfigurationExtensions { /// <summary> /// The default section where settings are read from the IConfiguration object. This is set to "AWS". /// </summary> public const string DEFAULT_CONFIG_SECTION = "AWS"; /// <summary> /// Constructs an AWSOptions class with the options specified in the "AWS" section in the IConfiguration object. /// </summary> /// <param name="config"></param> /// <returns>The AWSOptions containing the values set in configuration system.</returns> public static AWSOptions GetAWSOptions(this IConfiguration config) { return GetAWSOptions(config, DEFAULT_CONFIG_SECTION); } /// <summary> /// Constructs an AWSOptions class with the options specified in the "AWS" section in the IConfiguration object. /// </summary> /// <param name="config"></param> /// <param name="configSection">The config section to extract AWS options from.</param> /// <returns>The AWSOptions containing the values set in configuration system.</returns> public static AWSOptions GetAWSOptions(this IConfiguration config, string configSection) { return GetAWSOptions<DefaultClientConfig>(config, configSection); } /// <summary> /// Constructs an AWSOptions class with the options specified in the "AWS" section in the IConfiguration object. /// </summary> /// <typeparam name="TConfig">The AWS client config to be used in creating clients, like AmazonS3Config.</typeparam> /// <param name="config"></param> /// <returns>The AWSOptions containing the values set in configuration system.</returns> public static AWSOptions GetAWSOptions<TConfig>(this IConfiguration config) where TConfig : ClientConfig, new() { return GetAWSOptions<TConfig>(config, DEFAULT_CONFIG_SECTION); } /// <summary> /// Constructs an AWSOptions class with the options specified in the "AWS" section in the IConfiguration object. /// </summary> /// <typeparam name="TConfig">The AWS client config to be used in creating clients, like AmazonS3Config.</typeparam> /// <param name="config"></param> /// <param name="configSection">The config section to extract AWS options from.</param> /// <returns>The AWSOptions containing the values set in configuration system.</returns> public static AWSOptions GetAWSOptions<TConfig>(this IConfiguration config, string configSection) where TConfig : ClientConfig, new() { var options = new AWSOptions { DefaultClientConfig = new TConfig(), }; IConfiguration section; if (string.IsNullOrEmpty(configSection)) section = config; else section = config.GetSection(configSection); if (section == null) return options; var clientConfigType = typeof(TConfig); var properties = clientConfigType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var element in section.GetChildren()) { try { var property = properties.SingleOrDefault(p => p.Name.Equals(element.Key, StringComparison.OrdinalIgnoreCase)); if (property == null || property.SetMethod == null) continue; if (property.PropertyType == typeof(string) || property.PropertyType.GetTypeInfo().IsPrimitive) { var value = Convert.ChangeType(element.Value, property.PropertyType); property.SetMethod.Invoke(options.DefaultClientConfig, new object[] { value }); } else if (property.PropertyType == typeof(TimeSpan) || property.PropertyType == typeof(Nullable<TimeSpan>)) { var milliSeconds = Convert.ToInt64(element.Value); var timespan = TimeSpan.FromMilliseconds(milliSeconds); property.SetMethod.Invoke(options.DefaultClientConfig, new object[] { timespan }); } else if (property.PropertyType.IsEnum) { var value = Enum.Parse(property.PropertyType, element.Value); if ( value != null ) { property.SetMethod.Invoke(options.DefaultClientConfig, new object[] { value }); } } } catch(Exception e) { throw new ConfigurationException($"Error reading value for property {element.Key}.", e) { PropertyName = element.Key, PropertyValue = element.Value }; } } if (!string.IsNullOrEmpty(section["Profile"])) { options.Profile = section["Profile"]; } // Check legacy name if the new name isn't set else if (!string.IsNullOrEmpty(section["AWSProfileName"])) { options.Profile = section["AWSProfileName"]; } if (!string.IsNullOrEmpty(section["ProfilesLocation"])) { options.ProfilesLocation = section["ProfilesLocation"]; } // Check legacy name if the new name isn't set else if (!string.IsNullOrEmpty(section["AWSProfilesLocation"])) { options.ProfilesLocation = section["AWSProfilesLocation"]; } if (!string.IsNullOrEmpty(section["Region"])) { options.Region = RegionEndpoint.GetBySystemName(section["Region"]); } // Check legacy name if the new name isn't set else if (!string.IsNullOrEmpty(section["AWSRegion"])) { options.Region = RegionEndpoint.GetBySystemName(section["AWSRegion"]); } if (!string.IsNullOrEmpty(section["DefaultsMode"])) { if(!Enum.TryParse<DefaultConfigurationMode>(section["DefaultsMode"], out var mode)) { throw new ArgumentException($"Invalid value for DefaultConfiguration. Valid values are: {string.Join(", ", Enum.GetNames(typeof(DefaultConfigurationMode)))} "); } options.DefaultConfigurationMode = mode; } if (!string.IsNullOrEmpty(section["SessionRoleArn"])) { options.SessionRoleArn = section["SessionRoleArn"]; } if (!string.IsNullOrEmpty(section["SessionName"])) { options.SessionName = section["SessionName"]; } var loggingSection = section.GetSection("Logging"); if(loggingSection != null) { options.Logging = new AWSOptions.LoggingSetting(); if (!string.IsNullOrEmpty(loggingSection[nameof(AWSOptions.LoggingSetting.LogTo)])) { if (!Enum.TryParse<LoggingOptions>(loggingSection[nameof(AWSOptions.LoggingSetting.LogTo)], out var logTo)) { throw new ArgumentException($"Invalid value for {nameof(AWSOptions.LoggingSetting.LogTo)}. Valid values are: {string.Join(", ", Enum.GetNames(typeof(LoggingOptions)))} "); } options.Logging.LogTo = logTo; } if (!string.IsNullOrEmpty(loggingSection[nameof(AWSOptions.LoggingSetting.LogResponses)])) { if (!Enum.TryParse<ResponseLoggingOption>(loggingSection[nameof(AWSOptions.LoggingSetting.LogResponses)], out var logResponses)) { throw new ArgumentException($"Invalid value for {nameof(AWSOptions.LoggingSetting.LogResponses)}. Valid values are: {string.Join(", ", Enum.GetNames(typeof(ResponseLoggingOption)))} "); } options.Logging.LogResponses = logResponses; } if (!string.IsNullOrEmpty(loggingSection[nameof(AWSOptions.LoggingSetting.LogResponsesSizeLimit)])) { if (!int.TryParse(loggingSection[nameof(AWSOptions.LoggingSetting.LogResponsesSizeLimit)], out var logResponsesSizeLimit)) { throw new ArgumentException($"Invalid integer value for {nameof(AWSOptions.LoggingSetting.LogResponsesSizeLimit)}."); } options.Logging.LogResponsesSizeLimit = logResponsesSizeLimit; } if (!string.IsNullOrEmpty(loggingSection[nameof(AWSOptions.LoggingSetting.LogMetrics)])) { if (!bool.TryParse(loggingSection[nameof(AWSOptions.LoggingSetting.LogMetrics)], out var logMetrics)) { throw new ArgumentException($"Invalid boolean value for {nameof(AWSOptions.LoggingSetting.LogMetrics)}."); } options.Logging.LogMetrics = logMetrics; } } return options; } } }
229
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Runtime; namespace Amazon.Extensions.NETCore.Setup { /// <summary> /// Default ClientConfig used as a holder for settings specified in configuration system. /// </summary> internal class DefaultClientConfig : ClientConfig { public DefaultClientConfig() { } public override string RegionEndpointServiceName { get { return null; } } public override string ServiceVersion { get { return null; } } public override string UserAgent { get { return null; } } } }
59
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Amazon.Runtime; using Amazon.Extensions.NETCore.Setup; using Microsoft.Extensions.DependencyInjection.Extensions; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// This class adds extension methods to IServiceCollection making it easier to add Amazon service clients /// to the NET Core dependency injection framework. /// </summary> public static class ServiceCollectionExtensions { /// <summary> /// Adds the AWSOptions object to the dependency injection framework providing information /// that will be used to construct Amazon service clients. /// </summary> /// <param name="collection"></param> /// <param name="options">The default AWS options used to construct AWS service clients with.</param> /// <returns>Returns back the IServiceCollection to continue the fluent system of IServiceCollection.</returns> public static IServiceCollection AddDefaultAWSOptions(this IServiceCollection collection, AWSOptions options) { collection.Add(new ServiceDescriptor(typeof(AWSOptions), options)); return collection; } /// <summary> /// Adds the AWSOptions object to the dependency injection framework providing information /// that will be used to construct Amazon service clients. /// </summary> /// <param name="collection"></param> /// <param name="implementationFactory">The factory that creates the default AWS options. /// The AWS options will be used to construct AWS service clients /// </param> /// <param name="lifetime">The lifetime of the AWSOptions. The default is Singleton.</param> /// <returns>Returns back the IServiceCollection to continue the fluent system of IServiceCollection.</returns> public static IServiceCollection AddDefaultAWSOptions( this IServiceCollection collection, Func<IServiceProvider, AWSOptions> implementationFactory, ServiceLifetime lifetime = ServiceLifetime.Singleton) { collection.Add(new ServiceDescriptor(typeof(AWSOptions), implementationFactory, lifetime)); return collection; } /// <summary> /// Adds the Amazon service client to the dependency injection framework. The Amazon service client is not /// created until it is requested. If the ServiceLifetime property is set to Singleton, the default, then the same /// instance will be reused for the lifetime of the process and the object should not be disposed. /// </summary> /// <typeparam name="T">The AWS service interface, like IAmazonS3.</typeparam> /// <param name="collection"></param> /// <param name="lifetime">The lifetime of the service client created. The default is Singleton.</param> /// <returns>Returns back the IServiceCollection to continue the fluent system of IServiceCollection.</returns> public static IServiceCollection AddAWSService<T>(this IServiceCollection collection, ServiceLifetime lifetime = ServiceLifetime.Singleton) where T : IAmazonService { return AddAWSService<T>(collection, null, lifetime); } /// <summary> /// Adds the Amazon service client to the dependency injection framework. The Amazon service client is not /// created until it is requested. If the ServiceLifetime property is set to Singleton, the default, then the same /// instance will be reused for the lifetime of the process and the object should not be disposed. /// </summary> /// <typeparam name="T">The AWS service interface, like IAmazonS3.</typeparam> /// <param name="collection"></param> /// <param name="options">The AWS options used to create the service client overriding the default AWS options added using AddDefaultAWSOptions.</param> /// <param name="lifetime">The lifetime of the service client created. The default is Singleton.</param> /// <returns>Returns back the IServiceCollection to continue the fluent system of IServiceCollection.</returns> public static IServiceCollection AddAWSService<T>(this IServiceCollection collection, AWSOptions options, ServiceLifetime lifetime = ServiceLifetime.Singleton) where T : IAmazonService { Func<IServiceProvider, object> factory = new ClientFactory(typeof(T), options).CreateServiceClient; var descriptor = new ServiceDescriptor(typeof(T), factory, lifetime); collection.Add(descriptor); return collection; } /// <summary> /// Adds the Amazon service client to the dependency injection framework if the service type hasn't already been registered. /// The Amazon service client is not created until it is requested. If the ServiceLifetime property is set to Singleton, /// the default, then the same instance will be reused for the lifetime of the process and the object should not be disposed. /// </summary> /// <typeparam name="T">The AWS service interface, like IAmazonS3.</typeparam> /// <param name="collection"></param> /// <param name="lifetime">The lifetime of the service client created. The default is Singleton.</param> /// <returns>Returns back the IServiceCollection to continue the fluent system of IServiceCollection.</returns> public static IServiceCollection TryAddAWSService<T>(this IServiceCollection collection, ServiceLifetime lifetime = ServiceLifetime.Singleton) where T : IAmazonService { return TryAddAWSService<T>(collection, null, lifetime); } /// <summary> /// Adds the Amazon service client to the dependency injection framework if the service type hasn't already been registered. /// The Amazon service client is not created until it is requested. If the ServiceLifetime property is set to Singleton, /// the default, then the same instance will be reused for the lifetime of the process and the object should not be disposed. /// </summary> /// <typeparam name="T">The AWS service interface, like IAmazonS3.</typeparam> /// <param name="collection"></param> /// <param name="options">The AWS options used to create the service client overriding the default AWS options added using AddDefaultAWSOptions.</param> /// <param name="lifetime">The lifetime of the service client created. The default is Singleton.</param> /// <returns>Returns back the IServiceCollection to continue the fluent system of IServiceCollection.</returns> public static IServiceCollection TryAddAWSService<T>(this IServiceCollection collection, AWSOptions options, ServiceLifetime lifetime = ServiceLifetime.Singleton) where T : IAmazonService { Func<IServiceProvider, object> factory = new ClientFactory(typeof(T), options).CreateServiceClient; var descriptor = new ServiceDescriptor(typeof(T), factory, lifetime); collection.TryAdd(descriptor); return collection; } } }
135
aws-sdk-net
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("AWSSDK.Extensions.NETCore.Setup")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET extensions for .NET Core setup")] [assembly: AssemblyDescription("Amazon Web Services SDK for .NET extensions for .NET Core setup")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.7.7")]
21
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using AWSSDK.Extensions.CrtIntegration; using System; using System.Collections.Generic; using System.Text; using Xunit; namespace CrtIntegrationTests { /// <summary> /// Tests for the CRT checksum wrapper /// </summary> public class ChecksumTests { public static IEnumerable<object[]> Crc32TestCases => new List<object[]> { new object[] { "", "AAAAAA=="}, new object[] {"abc", "NSRBwg=="}, new object[] {"Hello world", "i9aeUg=="} }; public static IEnumerable<object[]> Crc32CTestCases => new List<object[]> { new object[] { "", "AAAAAA=="}, new object[] {"abc", "Nks/tw=="}, new object[] {"Hello world", "crUfeA=="} }; [Theory] [MemberData(nameof(Crc32TestCases))] public void Crc32Test(string content, string expectedHash) { Assert.Equal(expectedHash, new CrtChecksums().Crc32(Encoding.Default.GetBytes(content))); } [Theory] [MemberData(nameof(Crc32TestCases))] public void RollingCrc32Test(string content, string expectedHash) { uint rollingChecksum = 0; var crtChecksum = new CrtChecksums(); foreach (var c in content) { rollingChecksum = crtChecksum.Crc32(Encoding.Default.GetBytes(new char[] { c }), rollingChecksum); } var bytes = BitConverter.GetBytes(rollingChecksum); if (BitConverter.IsLittleEndian) { Array.Reverse(bytes); } Assert.Equal(expectedHash, Convert.ToBase64String(bytes)); } [Theory] [MemberData(nameof(Crc32CTestCases))] public void Crc32CTest(string content, string expectedHash) { Assert.Equal(expectedHash, new CrtChecksums().Crc32C(Encoding.Default.GetBytes(content))); } [Theory] [MemberData(nameof(Crc32CTestCases))] public void RollingCrc32CTest(string content, string expectedHash) { uint rollingChecksum = 0; var crtChecksum = new CrtChecksums(); foreach (var c in content) { rollingChecksum = crtChecksum.Crc32C(Encoding.Default.GetBytes(new char[] { c }), rollingChecksum); } var bytes = BitConverter.GetBytes(rollingChecksum); if (BitConverter.IsLittleEndian) { Array.Reverse(bytes); } Assert.Equal(expectedHash, Convert.ToBase64String(bytes)); } } }
102
aws-sdk-net
aws
C#
using Amazon.Runtime; using System; using Amazon; using Amazon.Runtime.Internal; namespace CrtIntegrationTests { /// <summary> /// Generic service client configuration /// </summary> public class TestClientConfig : ClientConfig { public override string ServiceVersion => throw new NotImplementedException(); public override string UserAgent => throw new NotImplementedException(); public override string RegionEndpointServiceName => ""; public TestClientConfig() : base(new DummyDefaultConfigurationProvider()) { } private class DummyDefaultConfigurationProvider : IDefaultConfigurationProvider { public IDefaultConfiguration GetDefaultConfiguration( RegionEndpoint clientRegion, DefaultConfigurationMode? requestedConfigurationMode = null) { return new DefaultConfiguration(); } } } }
35