AWS Cloudfront files' invalidation via REST API and Powershell - powershell

I'm trying to write a PowerShell script to invalidate an object of AWS Cloudfront distribution (just a specific file), and not sure how to produce the "signed URL" they're asking for.
My code so far is:
$authPref = "AWS4-HMAC-SHA256"
$AWSAccessKey = "xxx"
$AWSSecretKey = "xxx"
$awsDateOnly = (Get-Date).AddHours(-3).ToString("yyyyMMdd")
$awsRegion = "us-east-1"
$awsServiceName = "cloudfront"
$awsRequestType = "aws4_request"
$stringToSign = $authPref + " " + $awsCallerReference + " " + $awsDateOnly + "/" + $awsRegion + "/" + $awsServiceName + "/" + $awsRequestType + " SOME_STRING_NOT_SURE_WHAT"
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Text.Encoding]::ASCII.GetBytes($stringToSign)
$awsHMAC = $hmacsha.ComputeHash([Text.Encoding]::ASCII.GetBytes($AWSSecretKey))
$awsHMAC = [Convert]::ToBase64String($awsHMAC)
$awsSignedToken = $authPref + " Credential=" + $AWSAccessKey + "/" + $awsDateOnly + "/" + $awsRegion + "/" + $awsServiceName + "/" + $awsRequestType + ", SignedHeaders=content-type;host;x-amz-date, Signature=" + $awsHMAC
#POST /2017-03-25/distribution/$awsDistributionID/invalidation HTTP/1.1
$awsDistributionID = "xxx"
$awsCallerReference = (Get-Date).AddHours(-3).ToString("yyyyMMdd'T'HHmmss'Z'")
$invalidateObjectXML = #"
<?xml version="1.0" encoding="UTF-8"?>
<InvalidationBatch xmlns="http://cloudfront.amazonaws.com/doc/2017-03-25/">
<CallerReference>$awsCallerReference</CallerReference>
<Paths>
<Items>
<Path>/</Path>
</Items>
<Quantity>1</Quantity>
</Paths>
</InvalidationBatch>
"#
[xml]$invalidateObjectXML = $invalidateObjectXML
$awsCFuri = "https://cloudfront.amazonaws.com/2017-03-25/distribution/$awsDistributionID/invalidation"
Invoke-WebRequest -Method POST `
-Uri $awsCFuri `
-Headers #{"content-type"="text/xml";
"x-amz-date"="$awsCallerReference";
"authorization"="$awsSignedToken";
"host"="cloudfront.amazonaws.com"} `
-Body $invalidateObjectXML
The response is:
<ErrorResponse xmlns="http://cloudfront.amazonaws.com/doc/2017-03-25/"><Error><Type>Sender</Type><Code>SignatureDoesNotMatch</Code><Message>The request
signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation
for details.
The Canonical String for this request should have been
'POST
/2017-03-25/distribution/blabla/invalidation
content-type:text/xml
host:cloudfront.amazonaws.com
x-amz-date:20170503T203650Z
content-type;host;x-amz-date
blabla'
The String-to-Sign should have been
'AWS4-HMAC-SHA256
20170503T203650Z
20170503/us-east-1/cloudfront/aws4_request
blabla'
</Message></Error><RequestId>123-123</RequestId></ErrorResponse>
At line:1 char:1
So obviously I'm doing something wrong with the signed URL string that I do, but what it is?
Couldn't find any examples on the internet (not AWS docs nor any other blog) that demonstrates it in Powershell.
Thanks

AWS has developed a PowerShell module to interact with the AWS API called the AWS Tools for PowerShell. This module specifically handles request building and signing for you, so this method of calling to the raw API becomes unnecessary.
You can use this specifically to invalidate objects in a CloudFront distribution with the New-CFInvalidation cmdlet. Write the paths you want to invalidate to the Paths_Item parameter.
Signature:
New-CFInvalidation
-DistributionId <String>
-InvalidationBatch_CallerReference <String>
-Paths_Item <String[]>
-Paths_Quantity <Int32>
-Force <SwitchParameter>
Further Reading
AWS Documentation - Invalidating Objects and Displaying Information about Invalidations
AWS Documentation - New-CFInvalidation Cmdlet

Related

authorization for API gateway

I used this tutorial and created "put" endpoint successfully.
https://sanderknape.com/2017/10/creating-a-serverless-api-using-aws-api-gateway-and-dynamodb/
When I follow this advice, I get authroization required error..
Using your favorite REST client, try to PUT an item into DynamoDB
using your API Gateway URL.
python is my favorite client:
import requests
api_url = "https://0pg2858koj.execute-api.us-east-1.amazonaws.com/tds"
PARAMS = {"name": "test", "favorite_movie":"asdsf"}
r = requests.put(url=api_url, params=PARAMS)
the response is 403
My test from console is successful, but not able to put a record from python.
The first step you can take to resolve the problem is to investigate the information returned by AWS in the 403 response. It will provide a header, x-amzn-ErrorType and error message with information about the concrete error. You can test it with curl in verbose mode (-v) or with your Python code. Please, review the relevant documentation to obtain a detailed enumeration of all the possible error reasons.
In any case, looking at your code, it is very likely that you did not provide the necessary authentication or authorization information to AWS.
The kind of information that you must provide depends on which mechanism you configured to access your REST API in API Gateway.
If, for instance, you configured IAM based authentication, you need to set up your Python code to generate an Authorization header with an AWS Signature derived from your user access key ID and associated secret key. The AWS documentation provides an example of use with Postman.
The AWS documentation also provides several examples of how to use python and requests to perform this kind of authorization.
Consider, for instance, this example for posting information to DynamoDB:
# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# This file is 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/
#
# 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.
# AWS Version 4 signing example
# DynamoDB API (CreateTable)
# See: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html
# This version makes a POST request and passes request parameters
# in the body (payload) of the request. Auth information is passed in
# an Authorization header.
import sys, os, base64, datetime, hashlib, hmac
import requests # pip install requests
# ************* REQUEST VALUES *************
method = 'POST'
service = 'dynamodb'
host = 'dynamodb.us-west-2.amazonaws.com'
region = 'us-west-2'
endpoint = 'https://dynamodb.us-west-2.amazonaws.com/'
# POST requests use a content type header. For DynamoDB,
# the content is JSON.
content_type = 'application/x-amz-json-1.0'
# DynamoDB requires an x-amz-target header that has this format:
# DynamoDB_<API version>.<operationName>
amz_target = 'DynamoDB_20120810.CreateTable'
# Request parameters for CreateTable--passed in a JSON block.
request_parameters = '{'
request_parameters += '"KeySchema": [{"KeyType": "HASH","AttributeName": "Id"}],'
request_parameters += '"TableName": "TestTable","AttributeDefinitions": [{"AttributeName": "Id","AttributeType": "S"}],'
request_parameters += '"ProvisionedThroughput": {"WriteCapacityUnits": 5,"ReadCapacityUnits": 5}'
request_parameters += '}'
# Key derivation functions. See:
# http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
def sign(key, msg):
return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
def getSignatureKey(key, date_stamp, regionName, serviceName):
kDate = sign(('AWS4' + key).encode('utf-8'), date_stamp)
kRegion = sign(kDate, regionName)
kService = sign(kRegion, serviceName)
kSigning = sign(kService, 'aws4_request')
return kSigning
# Read AWS access key from env. variables or configuration file. Best practice is NOT
# to embed credentials in code.
access_key = os.environ.get('AWS_ACCESS_KEY_ID')
secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
if access_key is None or secret_key is None:
print('No access key is available.')
sys.exit()
# Create a date for headers and the credential string
t = datetime.datetime.utcnow()
amz_date = t.strftime('%Y%m%dT%H%M%SZ')
date_stamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope
# ************* TASK 1: CREATE A CANONICAL REQUEST *************
# http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
# Step 1 is to define the verb (GET, POST, etc.)--already done.
# Step 2: Create canonical URI--the part of the URI from domain to query
# string (use '/' if no path)
canonical_uri = '/'
## Step 3: Create the canonical query string. In this example, request
# parameters are passed in the body of the request and the query string
# is blank.
canonical_querystring = ''
# Step 4: Create the canonical headers. Header names must be trimmed
# and lowercase, and sorted in code point order from low to high.
# Note that there is a trailing \n.
canonical_headers = 'content-type:' + content_type + '\n' + 'host:' + host + '\n' + 'x-amz-date:' + amz_date + '\n' + 'x-amz-target:' + amz_target + '\n'
# Step 5: Create the list of signed headers. This lists the headers
# in the canonical_headers list, delimited with ";" and in alpha order.
# Note: The request can include any headers; canonical_headers and
# signed_headers include those that you want to be included in the
# hash of the request. "Host" and "x-amz-date" are always required.
# For DynamoDB, content-type and x-amz-target are also required.
signed_headers = 'content-type;host;x-amz-date;x-amz-target'
# Step 6: Create payload hash. In this example, the payload (body of
# the request) contains the request parameters.
payload_hash = hashlib.sha256(request_parameters.encode('utf-8')).hexdigest()
# Step 7: Combine elements to create canonical request
canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash
# ************* TASK 2: CREATE THE STRING TO SIGN*************
# Match the algorithm to the hashing algorithm you use, either SHA-1 or
# SHA-256 (recommended)
algorithm = 'AWS4-HMAC-SHA256'
credential_scope = date_stamp + '/' + region + '/' + service + '/' + 'aws4_request'
string_to_sign = algorithm + '\n' + amz_date + '\n' + credential_scope + '\n' + hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()
# ************* TASK 3: CALCULATE THE SIGNATURE *************
# Create the signing key using the function defined above.
signing_key = getSignatureKey(secret_key, date_stamp, region, service)
# Sign the string_to_sign using the signing_key
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
# ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************
# Put the signature information in a header named Authorization.
authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature
# For DynamoDB, the request can include any headers, but MUST include "host", "x-amz-date",
# "x-amz-target", "content-type", and "Authorization". Except for the authorization
# header, the headers must be included in the canonical_headers and signed_headers values, as
# noted earlier. Order here is not significant.
# # Python note: The 'host' header is added automatically by the Python 'requests' library.
headers = {'Content-Type':content_type,
'X-Amz-Date':amz_date,
'X-Amz-Target':amz_target,
'Authorization':authorization_header}
# ************* SEND THE REQUEST *************
print('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')
print('Request URL = ' + endpoint)
r = requests.post(endpoint, data=request_parameters, headers=headers)
print('\nRESPONSE++++++++++++++++++++++++++++++++++++')
print('Response code: %d\n' % r.status_code)
print(r.text)
I think it could be easily adapted to your needs.
In the console, everything works fine because when you invoke your REST endpoints in API Gateway, you are connected to a user who is already authenticated and authorized to access these REST endpoints.

DSC for initialising and formatting disks

I need to format a disk for servers using DSC. I tried using the below from
https://blogs.msdn.microsoft.com/timomta/2016/04/23/how-to-use-powershell-dsc-to-prepare-a-data-drive-on-an-azure-vm/#comment-1865
But it doesnt work as it doesn't seem to be complete, I get errors
"+ xWaitforDisk Disk2 + ~~~~~~~~~~~~ Resource 'xWaitForDisk' requires
that a value of type 'String' be provided for property 'DiskId'.
At line:18 char:1 + DiskNumber = 2 + ~~~~~~~~~~ The member
'DiskNumber' is not valid. Valid members are 'DependsOn', 'DiskId',
'DiskIdType', 'PsDscRunAsCredential', 'RetryCount',
'RetryIntervalSec'. "
Configuration DataDisk
{
Import-DSCResource -ModuleName xStorage
Node localhost
{
xWaitforDisk Disk2
{
DiskNumber = 2
RetryIntervalSec = 60
Count = 60
}
xDisk FVolume
{
DiskNumber = 2
DriveLetter = 'F'
FSLabel = 'Data'
}
}
You need to replace DiskNumber with DiskID.
Take a look at the examples on GitHub https://github.com/PowerShell/StorageDsc/tree/dev/Modules/StorageDsc/Examples/Resources
You can find the DiskId with powershell use the command: Get-Disk

Importing a git repo from one vsts team project to another team project using vsts rest api

Want to initiate a VSTS git repo import from project A to Project B. Following script is written to createthe import request via REST API. It is giving bad request 400 as described below. Any clues?
param(
<parameter(mandatory=$true)>
[string] $token,
<parameter(mandatory=$true)>
[string] $collectionUri,
<parameter(mandatory=$true)>
[string] $TargetTeamProject,
<parameter(mandatory=$true)>
[string] $TargetGitRepoName,
<parameter(mandatory=$true)>
[string] $SourceGitRepoUrl
)
$User=""
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $User,$token)));
$header = #{Authorization=("Basic {0}" -f $base64AuthInfo)};
$Uri = $collectionUri + $TargetTeamProject + '/_apis/git/repositories/' + $TargetGitRepoName + '/importRequests?api-version=4.1-preview.1'
$ImportRequestData = '{"parameters": {"gitSource": {"url": "' + $SourceGitRepoUrl + '"}}}'
write-host 'calling:' $Uri
write-host 'with data:' $ImportRequestData
$ImportResponse = Invoke-RestMethod -Method Post -ContentType application/json -Uri $Uri -Body $ImportRequestData -Headers $header
$ImportResponse
Called it with
.\CreateImportRequest.ps1 -token '*************************************' -collectionUri 'https://myvsts.visualstudio.com/DefaultCollection/' -TargetTeamProject 'HasiTempJava' -TargetGitRepoName 'impfromhasiJava' -SourceGitRepoUrl 'https://myvsts.visualstudio.com/DefaultCollection/_git/HasiJava'
When passed existing empty repo it throws bad request exception
Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
At C:\Users\chamindac\Desktop\CreateImportRequest.ps1:33 char:19
+ ... tResponse = Invoke-RestMethod -Method Post -ContentType application/j ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand</parameter(mandatory=$true)></parameter(mandatory=$true)></parameter(mandatory=$true)></parameter(mandatory=$true)></parameter(mandatory=$true)>
When a new repo name used it is giving below error which is correct I believe since url refers to a non existing repo
<parameter(mandatory=$true)><parameter(mandatory=$true)><parameter(mandatory=$true)><parameter(mandatory=$true)><parameter(mandatory=$true) class="">Invoke-RestMethod : {"$id":"1","innerException":null,"message":"TF401019: The Git repository with name or identifier impfromhasiJavaNew does not exist or you do not have permissions for the operation you are
attempting.","typeName":"Microsoft.TeamFoundation.Git.Server.GitRepositoryNotFoundException, Microsoft.TeamFoundation.Git.Server","typeKey":"GitRepositoryNotFoundException","errorCode":0,"eventId":3000}
At C:\Users\chamindac\Desktop\CreateImportRequest.ps1:33 char:19
+ ... tResponse = Invoke-RestMethod -Method Post -ContentType application/j ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand </parameter(mandatory=$true)></parameter(mandatory=$true)></parameter(mandatory=$true)></parameter(mandatory=$true)></parameter(mandatory=$true)>
As per documentation (https://learn.microsoft.com/en-us/rest/api/vsts/git/import%20requests/create) only required parameter is the source git repo url. Is there any additional parameter requirements?
Post url used
https://myvsts.visualstudio.com/DefaultCollection/HasiTempJava/_apis/git/repositories/impfromhasiJava/importRequests?api-version=4.1-preview.1
Request Body
{"parameters": {"gitSource": {"url": "https://myvsts.visualstudio.com/DefaultCollection/_git/HasiJava"}}}
You need to add the source repo (from project A) as an External Git Endpoint for the target project (project B), and then provide the argument serviceEndpointId for create import requests REST API.
Detail steps ad below:
Create External Git Endpoint in target project
In project B -> Services Hub (https://account.visualstudio.com/projectB/_admin/_services) -> New Service Endpoint -> External Git -> add source repo from project A as the server URL (https://account.visualstudio.com/projectA/_git/sourcerepo) -> OK.
Get the endpoint id
Use the REST API as below:
GET https://marinaliu.visualstudio.com/GitTest/_apis/serviceendpoint/endpoints/?api-version=4.1-preview.1
Then get the endpoint id from the response (assume it's c534772b-bf52-442f-abd0-544d6bf76ed9).
import git repo to the target porject
Then import the source repo from project A to project B:
POST https://account.visualstudio.com/projectB/_apis/git/repositories/targetrepo/importRequests?api-version=4.1-preview.1
application/json:
{
"parameters": {
"gitSource": {
"url": "https://marinaliu.visualstudio.com/projectA/_git/sourcerepo"
},
"serviceEndpointId": "c534772b-bf52-442f-abd0-544d6bf76ed9"
}
}
More details, you can refer the blog Import a Git Project with REST API between VSTS Team Projects.

Azure API Management Report API using Powershell

I'm trying to execute APIM Report API using Powershell but it doesn't works.
Here's powershell code.
$gen_sas_code = #"
using System;
using System.Text;
using System.Globalization;
using System.Security.Cryptography;
public class Sas
{
public static void GenSas()
{
var id = "integration";
var key = "myprimarykey";
var expiry = DateTime.UtcNow.AddDays(10);
using (var encoder = new HMACSHA512(Encoding.UTF8.GetBytes(key)))
{
var dataToSign = id + "\n" + expiry.ToString("O", CultureInfo.InvariantCulture);
var hash = encoder.ComputeHash(Encoding.UTF8.GetBytes(dataToSign));
var signature = Convert.ToBase64String(hash);
var encodedToken = string.Format("SharedAccessSignature uid={0}&ex={1:o}&sn={2}", id, expiry, signature);
Console.WriteLine(encodedToken);
}
}
}
"#
Add-Type -TypeDefinition $gen_sas_code -Language CSharp
$sas = [Sas]::GenSas()
$interval = "PT15M"
$start_time = "'2017-10-16T04:02:00'"
$end_time = "'2017-10-16T04:15:00'"
$report_url = "https://myapim.management.azure-api.net/reports/byTime?api-version=2017-03-01&interval=$interval&`$filter=timestamp+ge+datetime$start_time+and++timestamp+le+datetime$end_time"
$report_headers = #{ "Authorization" = "$sas" };
Invoke-RestMethod -Method Get -Uri $report_url -Headers $report_headers
I referred this document about report API (https://learn.microsoft.com/en-us/rest/api/apimanagement/apimanagementrest/azure-api-management-rest-api-report-entity#ReportByTime).
Here's error response.
*The remote server returned error: (401) Unzuthorized
Invoke-RestMethod : リモート サーバーがエラーを返しました: (401) 許可されていません*
発生場所 C:\sas.ps1:56 文字:1
+ Invoke-RestMethod -Method Get -Uri $report_url -Headers $report_headers
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod]、WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
So, I consider that the powershell code has some problems because I have already confirmed that the SAS which is generated by above code works correctly by executing Report API using curl command.
Do you have any ideas?
It's a slightly annoying issue, but it comes down to newline handling in Powershell, the \n in the .net sample is referring to a newline, so you have to use the native way PowerShell declares a newline with a backtick instead, so do this:
var dataToSign = id + "`n" + expiry.ToString("O", CultureInfo.InvariantCulture);
... instead of:
var dataToSign = id + "\n" + expiry.ToString("O", CultureInfo.InvariantCulture);
Try using this script to generate the token https://github.com/Azure/api-management-samples/blob/master/scripts/Get_AzureRmApiManagementManagementToken.ps1

Windows Azure REST API Update Role Doesn't Take Effect

I'm doing some proof of concept work on azure, trying to get a role using the Get Role URL:
https://management.core.windows.net/<subscription-id>/services/hostedservices/<cloudservice-name>/deployments/<deployment-name>/roles/<role-name>
And then update the role using the Update Role URL:
https://management.core.windows.net/<subscription-id>/services/hostedservices/<cloudservice-name>/deployments/<deployment-name>/roleinstances/<role-name>
Both of those URLs are straight from the msdn pages. The GET request works and I get XML that matches what I see in the management console.
When I then add an element to the xml and send that back with a PUT on the update URL, I get a 200 response, but I never see the change in the management console. I also don't see any error message when I send gibberish. I'm connecting from C#, and a coworker suggested I could get the response with this:
var response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(response.ToString());
But that gets me a 404 error.
Is there an extra step to commit the update? And how can I see the response that msdn mentions?
2 suggestions:
When I am just doing quick SMAPI work I use AzureTools (http://blogs.msdn.com/b/kwill/archive/2013/08/26/azuretools-the-diagnostic-utility-used-by-the-windows-azure-developer-support-team.aspx). Specifically, look in the Misc Tools section under "Service Management REST API". This will show you the full response.
To answer your question about how to get the response (txtSMAPIResponse is where AzureTools puts the response info):
System.IO.Stream receiveStream;
System.IO.StreamReader readStream;
Encoding encode;
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
txtSMAPIRequest.Text = request.Headers.ToString();
txtSMAPIResponse.Text = ex.Message + Environment.NewLine + Environment.NewLine + ex.Response.Headers.ToString();
try
{
receiveStream = ex.Response.GetResponseStream();
encode = System.Text.Encoding.GetEncoding("utf-8");
// Pipes the stream to a higher level stream reader with the required encoding format.
readStream = new System.IO.StreamReader(receiveStream, encode);
txtSMAPIResponse.Text += readStream.ReadToEnd();
// Releases the resources of the response.
response.Close();
// Releases the resources of the Stream.
readStream.Close();
}
catch
{
}
return;
}
txtSMAPIRequest.Text = request.Method + " " + request.RequestUri + " " + request.ProtocolVersion + Environment.NewLine + Environment.NewLine;
txtSMAPIRequest.Text += request.Headers.ToString();
txtSMAPIResponse.Text = (int)response.StatusCode + " - " + response.StatusDescription + Environment.NewLine + Environment.NewLine;
txtSMAPIResponse.Text += response.Headers + Environment.NewLine + Environment.NewLine;
receiveStream = response.GetResponseStream();
encode = System.Text.Encoding.GetEncoding("utf-8");
// Pipes the stream to a higher level stream reader with the required encoding format.
readStream = new System.IO.StreamReader(receiveStream, encode);
txtSMAPIResponse.Text += readStream.ReadToEnd();
// Releases the resources of the response.
response.Close();
// Releases the resources of the Stream.
readStream.Close();
}
I've got the same problem. In my case EndPointACL is not getting updated. Very painful thing is for every update , we have to send the entire ConfigurationSet; There is no way to update the ACL for particular end point.
A typical update looks like this:
<?xml version="1.0"?>
<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>
<InputEndpoint>
<LocalPort>100</LocalPort>
<Name>TCP-100</Name>
<Port>100</Port>
<Protocol>tcp</Protocol>
<EndpointACL>
<Rules>
<Rule>
<Order>1</Order>
<Action>deny</Action>
<RemoteSubnet>108.239.229.0/24</RemoteSubnet>
<Description>test-rule</Description>
</Rule>
</Rules>
</EndpointACL>
</InputEndpoint>
</InputEndpoints>
<SubnetNames>
<SubnetName>Subnet-1</SubnetName>
</SubnetNames>
</ConfigurationSet>
</ConfigurationSets>
</PersistentVMRole>