I am getting this following error:
exception calling "UploadString" with "2" argument(s): "The remote server returned an error: (500)
Internal Server Error." At C:\Cinegy_Type\Helpers-Type.ps1:146 char:5 + $web.UploadString($url,
$xmlDoc.OuterXml) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [],
MethodInvocationException + FullyQualifiedErrorId : WebException
The method is this:
function Type-UpdateVariable([string]$name, [string]$value, [string]$type = "Text", [string]$server="localhost", [int]$instance=0)
{
#make a Type PostRequest XML document using .Net XML document object
$xmlDoc = New-Object System.Xml.XmlDocument;
#add root element for request - which is a 'PostRequest' element
$xmlRootElem = $xmlDoc.AppendChild($xmlDoc.CreateElement('PostRequest'));
#create SetValue element and define variable Name, Type and Value
$xmlSetValueElem = $xmlRootElem.AppendChild($xmlDoc.CreateElement('SetValue'));
$xmlSetValueElem.SetAttribute("Name", $name);
$xmlSetValueElem.SetAttribute("Type",$type);
$xmlSetValueElem.SetAttribute("Value", $value);
#create a .Net webclient which will be used to perform the HTTP POST
$web = new-object net.webclient
#Air requires that the data is in XML format and declared properly - so add the HTTP Header to state this
$web.Headers.add("Content-Type", "text/xml; charset=utf-8")
#perform the actual HTTP post to the IP and port (which is 5521 + instance number) of the XML data
$url = "http://" + $server + ":" + (5521 + $instance) + "/postbox"
$web.UploadString($url, $xmlDoc.OuterXml)
}
Line 146 is:
$web.UploadString($url, $xmlDoc.OuterXml)
what I do not understand is that this was working yesterday.
The full code can be found here: (Do not use line number here for reference, this has 3 scripts.)
https://pastebin.com/RtisgmiB
The web server you're posting to is having a problem; see meaning of a HTTP status code 500. Unless the data passed to your function are problematic, your code looks fine. There is nothing you're missing in that Powershell error message, which would give you a clue as to the issue.
Check the error log on the web server (best option)
Output the parameters to the console with the purpose of submitting the request manually through Postman, cURL, etc.
Good luck!
Related
I'm trying to use the Azure Cognitive Services API with Powershell to 'read' the contents of a .jpg in a blob store. Everything I am trying to do works perfectly using the Azure API demo/test page, so I am fairly sure that this, to a degree, proves that some elements I'm using in my code are valid. Well, at least they are when using the API testing tool.
Here is my Powershell:
Clear-Host
$myUri = "<ENDPOINT value from "keys and endpoint blade">/vision/v3.0/read/analyze?language=en"
$imagePath = "<path to image in blob. accessible online and anonymously>"
$subKey = "<KEY #1 from "keys and endpoint" blade>"
$headersHash = #{}
$headersHash.Add( "Host", "westeurope.api.cognitive.microsoft.com" )
$headersHash.Add( "Ocp-Apim-Subscription-Key", $subKey )
$headersHash.Add( "Content-Type","application/json" )
$bodyHash = #{ "url" = $imagePath }
out-host -InputObject "Sending request:"
$response = Invoke-WebRequest -uri $myUri `
-Method Post `
-Headers $headersHash `
-Body $bodyHash `
-verbose
"Response: $response"
When I send that, all I ever get is a:
Invoke-WebRequest : The remote server returned an error: (400) Bad Request.
At C:\scratch\testy.ps1:15 char:13
+ $response = Invoke-WebRequest -uri $myUri `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-W
ebRequest], WebException
+ FullyQualifiedErrorId :
WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
I must be missing something basic but I cannot see what. There are no published examples of using Powershell to access the CS APIs that I can find but there is an example with Python (requests) and I'm pretty sure I'm emulating and representing what goes into the Python example correctly. But then again, its not working so something isn't right.
Strangely, when I try to recreate this in Postman, I get a 202 but no response body, so its not possible for me to view or extract the apim-request-id in order to manufacture the next request to retrieve the results.
Found the issue. The problem was made clear when I wrapped the call in a try/catch block and put this in the catch block:
$streamReader =
[System.IO.StreamReader]::new($_.Exception.Response.GetResponseStream())
$ErrResp = $streamReader.ReadToEnd() | ConvertFrom-Json
$streamReader.Close()
I was then able to look at the contents of the $ErrResp variable and there was a fragment of a string which said "unable to download target image.." or something to that effect. Odd because I could use the URL I was supplying to instantly connect to and get the image.. so it had to be the way the URL was being injecting into the body.
It was.
When using a hashtable as the body, where your Content-Type is 'application/json' all you need to do, it seems, is use convertto-json with your hash first. This worked and I instantly got my 202 and the pointer to where to collect my results.
Hopefully this will help someone, somewhere, sometime.
I'm trying to make a GET request to Azure Table REST API with Postman.
I can make a working request with a C# program I found, but when I try to copy the same information into the Postman request it return the followign error:
Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
With the C# program I generate my UTC time and my Authorization code.
The program will give me the following output:
x-ms-date: Fri, 01 Nov 2019 10:13:26 GMT
Authorization: SharedKeyLite username:e4IREMOVEDSOMELETTERST4Ag=
Request URI: https://username.table.core.windows.net/MainTable(PartitionKey='akey',RowKey='130')
The generated output works in the C# program, because when I use:
result = await Client.GetAsync(requestUri);
The result will give me the information of (akey, 130).
When I pass them into postman it will still give me an error.
I do update the date in postman whenever I make a new authorized string.
My postman setup is as follows:
I eventually want to make this request with the ESP32, so it might be a bit unrelated, but the ESP is giving me the same error. Any tips on setting the headers correct either for Postman or the ESP are appreciated.
to make this work first create two variables in your environment :
{{utcDate}}
{{authToken}}
Then create a new Get request and setup your headers like this :
x-ms-version 2015-12-11
x-ms-date {{utcDate}}
Authorization SharedKey resourceName:{{authToken}}
DataServiceVersion 3.0;NetFx
MaxDataServiceVersion 3.0;NetFx
Accept application/json;odata=nometadata
Finally, define a Pre-request Script :
var now = new Date().toUTCString();
pm.environment.set("utcDate", now);
var hcar = "/resourceName/TableName";
var verb = request.method;
var cntMd5 = "";
var cntType = "";
var mKey="<Your service key goes here>";
var text = verb + "\n" + (cntMd5 || "") + "\n" + (cntType || "") + "\n" + now + "\n" + hcar;
var key = CryptoJS.enc.Base64.parse(mKey);
var signature = CryptoJS.HmacSHA256(text, key);
var base64Bits = CryptoJS.enc.Base64.stringify(signature);
pm.environment.set("authToken", base64Bits);
The reason for the variables is, authToken because you need a place holder to store the calculated token, utcDate because the same date in your header must be used to calculate your token.
I found that the problem was within Postman itself.
There has been an ongoing issue with the automatic URL encoding.
When I went directly to the MainTable the code of Mauricio worked.
I'm deeply confused trying to integrate AWS API Gateway with AWS Lambda, because i'm trying to execute a lambda function through the GET method and always my function is returning invalid parameter.
{"errorMessage":"Error - Invalid Group ID - undefined - alexa id:
undefined"}|
It happens because the parameters was not arriving to the function and idgrupo variable is <=0.
I'm trying to execute a lambda function with URL at this form:
domain.execute-api.us-east-1.amazonaws.com/prod/chkneopairtoken?idgrupo=3823&clientId={321356-6666-4745}&keypair=90809276
And in my Lambda function i'm doing it:
var idgrupo = event.idgrupo;
var alexaClientId = event.clientId;
var keypair = event.keypair;
if (idgrupo > 0){
} else{
console.log("Error - Invalid Group ID - " + idgrupo + " - alexa id: " + alexaClientId + " - ");
//callback(null, "Error - Invalid Group ID - " + idgrupo + " - alexa id: " + alexaClientId);
context.fail("Error - Invalid Group ID - " + idgrupo + " - alexa id: " + alexaClientId);
}
Are there the possibility to do what i'm trying to do?
I think it is not an integration error between API Gateway and AWS Lambda, because the function returns my custom error message, and I believe it is a transfer parameters error.
Go back to the "Integration Request" of your resource GET, under "Body Mapping Templates"
Select for the recommended option for "Request body passthrough"
Add a mapping template (clicking on the action "Add mapping template")
Write "application/json" for the content type
Add this template
{
"idgrupo" : "$input.params('idgrupo')",
"clientId" : "$input.params('clientId')",
"keypair" : "$input.params('keypair')"
}
In your API Gateway console, under "Integration Request", in the "Mapping Template" section, create a template for the content-type that you are submitting, and then just select "Method Request passthrough". This will pass everything through to the Lambda function.
Then in your Lambda function code you will need to reference those URL parameter values via event.params.idgrupo, event.params.clientId etc.
I have gone past 2 stages in the Embedded Signing API which I use in my WCF web service using C#.
The login credentials & the request envelope API calls work & the envelopeID is generated.
The 3rd step is the "get URL for the Embedded Console Sign View"
string reqBody = "<recipientViewRequest xmlns=\"http://www.docusign.com/restapi\">" +
"<authenticationMethod>" + "email" + "</authenticationMethod>" +
"<email>" + "jay.krishnamoorthy#gmail.com" + "</email>" + // NOTE: Use different email address if username provided in non-email format!
"<returnUrl>" + "http://www.docusign.com" + "</returnUrl>" + // username can be in email format or an actual ID string
"<clientUserId>" + "1001" + "</clientUserId>" +
"<userName>" + "Jay Krishnamoorthy" + "</userName>" +
"</recipientViewRequest>";
// append uri + "/views/recipient" to baseUrl and use in the request
request = (HttpWebRequest)WebRequest.Create(baseURL + uri + "/views/recipient");
request.Headers.Add("X-DocuSign-Authentication", authenticateStr);
request.ContentType = "application/xml";
request.Accept = "application/xml";
request.ContentLength = reqBody.Length;
request.Method = "POST";
// write the body of the request
byte[] body2 = System.Text.Encoding.UTF8.GetBytes(reqBody);
Stream dataStream2 = request.GetRequestStream();
dataStream2.Write(body2, 0, reqBody.Length);
dataStream2.Close();
// read the response
webResponse = (HttpWebResponse)request.GetResponse();-----> comes back with Bad request
Can some one help with the missing info in my request body which causes the BAD request response.
I'm having trouble making sense of the reqBody value in your question, so instead of commenting on that, I'll just provide a simple example of what a proper POST Recipient View request looks like (in XML format):
POST https://{{env}}.docusign.net/restapi/{{version}}/accounts/{{acctId}}/envelopes/{{envelopeId}}/views/recipient
<recipientViewRequest xmlns="http://www.docusign.com/restapi">
<authenticationMethod>Email</authenticationMethod>
<email>RECIPIENT_EMAIL_ADDRESS</email>
<returnUrl>http://www.google.com</returnUrl>
<clientUserId>CLIENT_USER_ID_VALUE_SPECIFIED_IN_THE_REQUEST</clientUserId>
<userName>RECIPIENT_NAME</userName>
</recipientViewRequest>
I'd suggest that you compare the request URI and request body I've included here with what you're sending, and adjust yours as needed to match.
Additionally, I'd recommend that you use a tool like "Fiddler" or something similar to examine the XML Request and Response as they're being sent over the wire -- i.e., identify problems by examining the raw XML using Fiddler, then update your code to fix the problems (i.e., to generate/send a properly formatted request). Being able to produce a trace of the raw XML Request / Response is a requirement of the DocuSign API Certification process, so you might as well figure that out sooner rather than later, as it's a valuable troubleshooting asset during development as well (when you get a "Bad Request" response like you're getting).
Your request body has all the proper elements and looks to be correct on first glance, however I see what you are doing wrong now. In your request body when you set the authentication method I see that you are setting it to:
"<authenticationMethod>" + "email" + "</authenticationMethod>"
This is incorrect. The value here actually needs to be the string email or Email, you don't enter the recipient's actual email address. The point of the authenticationMethod property is to tell the system what level of authentication you are expecting. If set to email then you are telling the system simply that the email address is the only form of authentication you want for that recipient. So what you want instead is:
"<authenticationMethod>email</authenticationMethod>"
I want to throw exception from server to client over the network like this.... this is server cod sending exception
InvalidOperationException ex = new InvalidOperationException("Duplicate Key Found");
streamWriter.WriteLine(ex);
and in client side :
object serverResponse = streamReader.ReadLine();
i read object like this from server but whenever i display its type it say serverResponse is of Type System.String rather than InvalidOperationException please help me in this.
Console.WriteLine("Type Is:" + serverResponse.GetType());