Urban Airship API V3 Push request - 400 Bad request - urbanairship.com

I am getting 400 - Bad request.
This is my request:
{
"audience" : {
"tags": ["994c4298-89ba-4715-879d-10540fcf0059","a82e8789-3239-4899-b6dc-1e6a71dc06d4"]
},
"notification": {
"alert": "19 Aug Test",
"extra": {"NewsID":"127"}
},
"device_types": "all"
}
This is my code:
using (var client = new WebClient())
string PostData = "I am assigining above json string here";
UTF8Encoding encoding = new UTF8Encoding();
var dataToPost = encoding.GetBytes(PostData);
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Headers.Add(HttpRequestHeader.Accept,"application/vnd.urbanairship+json; version=3;");
//client.Headers[HttpRequestHeader.Accept] = "application/vnd.urbanairship+json; version=3";
client.Credentials = new NetworkCredential("App key", "Master key");
var result = client.UploadData("https://go.urbanairship.com/api/push/", "POST", dataToPost);
Stream stream = new MemoryStream(result);
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();

Worked when I changed "tags" to "tag" and put "extra" in "ios": {"extra": "blah blah blah"}
I think they have made these changes in V3.
Thanks.

Related

How do I post multiline message using Teams Webhooks?

I have a webhook setup to post a message to one of our Teams Team channels. I'm using one of the teams webhook examples given here: https://learn.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference#hero-card .
The problem I have is that I am unable to display multiple lines. In the example below, I'd like to separate out 'Test1' and 'Test2' on separate lines. However, using \n or \n in the JSON didn't translate to multi line format in Teams. Screenshot outcome attached below.
"type": "message",
"attachments": [
{
"contentType": "application/vnd.microsoft.card.hero",
"content": {
"title": "Alerts",
"text": "*Test1 \n *Test\n",
"buttons": [
{
"type": "openUrl",
"title": "Open in SumoLogic",
"value": ""
}
]
}
}
]
}
What is the way to send a multi-line message to Teams using webhook? Any guidance here is appreciated.
Please try using \n\n and check.
I know this is an old post, but if anyone still needs this you can use AdaptiveCards
$ using AdaptiveCards;
AdaptiveCard card = new AdaptiveCard("1.5");
card.AdditionalProperties.Add("$schema", "http://adaptivecards.io/schemas/adaptive-card.json");
var msTeamsWidthOption = new { width = "Full" };
card.AdditionalProperties.Add("msteams", msTeamsWidthOption);
AdaptiveTextBlock titleBlock = new AdaptiveTextBlock
{
Size = AdaptiveTextSize.Large,
Weight = AdaptiveTextWeight.Bolder,
Wrap = true,
Text = title
};
AdaptiveTextBlock messageBlock = new AdaptiveTextBlock
{
Wrap = true,
Text = message
};
card.Body.Add(titleBlock);
card.Body.Add(messageBlock);
AdaptiveCardWrapper adaptiveCardWrapper = new AdaptiveCardWrapper
{
attachments = new List<Attachments> { new Attachments { content = card} }
};
var address = Environment.GetEnvironmentVariable("WebhookUrl");
var content = new StringContent(JsonConvert.SerializeObject(adaptiveCardWrapper), Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(address, content);
You can use line breaks within a string with "Wrap = true", or you can add multiple cards to a single message. Or both.
https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using?tabs=cURL#send-adaptive-cards-using-an-incoming-webhook

Update TFS Web with a Python script

How can I update a certain field in tfs web with Python?
I have connected to tfs and have received an HTML response.
I have a json with the data that I would like to insert to tfs testCases field.
JSON:
data = json.loads(url.read().decode()) (Json external data)
HTML:
tfsResponse = requests.get(tfsApi, auth=HttpNtlmAuth(username, password))
if tfsResponse.ok:
print(tfsResponse)
soup = BeautifulSoup(tfsResponse.text, 'lxml')
How can I do it?
It's not able to directly use Jenkins automation tests results to update TFS test case.
You need use Rest API to handle this. You need to extract the test results fist then update them to TFS server.
With using below Rest API:
PATCH https://dev.azure.com/{organization}/{project}/_apis/test/Runs/{runId}/results?api-version=5.1
Sample body
[
{
"state": "Completed",
"testPoint": {
"id": 10
},
"outcome": "Passed",
"testCase": {
"id": 4567
}
}
]
If you want to use code, a code snippet for your reference, should similar to Python:
try
{
var u = new Uri("https://{My Account}.visualstudio.com");
VssCredentials c = new VssCredentials(new Microsoft.VisualStudio.Services.Common.VssBasicCredential(string.Empty, "PAT"));
var connection = new VssConnection(u, c);
var testClient = connection.GetClient<TestManagementHttpClient>();
int testpointid = 1;
string teamProject = "MyProjectName";
RunCreateModel run = new RunCreateModel(name: "TestCase Name", plan: new Microsoft.TeamFoundation.TestManagement.WebApi.ShallowReference("TestPlan Id"), pointIds: new int[] { testpointid });
TestRun testrun = testClient.CreateTestRunAsync(run, teamProject).Result;
TestCaseResult caseResult = new TestCaseResult() { State = "Completed", Outcome = "passed", Id = 100000 };
var testResults = testClient.UpdateTestResultsAsync(new TestCaseResult[] { caseResult }, teamProject, testrun.Id).Result;
RunUpdateModel runmodel = new RunUpdateModel(state: "Completed");
TestRun testRunResult = testClient.UpdateTestRunAsync(runmodel, teamProject, testrun.Id, runmodel).Result;
}
catch (AggregateException e)
{
Console.WriteLine(e.InnerException.Message);
}

Unable to get json node values

This is the json response format that I have and need to read the first node value "html". I have tried to few ways to get the value but unable to get it
[
{
"html": "<!DOCTYPE html>\n <html>\n <head>\n <\/html>\n \n",
<\/html>\n \n",
"headers": {},
"subject": "Register new account",
"messageId": "475603953.247.1565607800153#dfrsbdd201.abc.com.au",
"priority": "normal",
"from": [],
"to": [],
"date": "2019-08-12T11:03:20.000Z",
"receivedDate": "2019-08-12T11:09:42.000Z",
"receivedAt": "2019-08-12T11:09:44.900Z"
},
{+},
{+}
]
I tried couple of things
RequestSpecification emailReq = given().with().pathParam("email",emailName);
Response emailResp = emailReq.contentType("application/json").get("https://restmail.net/mail/{email}");
JSONObject value = new JSONObject(emailResp.asString());
I got this error
org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:505)
and then I removed this last line to use But this does not gives me error. pls refer screenshot for this
JSONArray responseJson = new JSONArray(emailResp.asString());
Tried this as well
List<HashMap<String, Object>> jsonObjectsInArray = emailResp.jsonPath().getList("$");
for (HashMap<String, Object> singleLeg : jsonObjectsInArray) {
String value = (String) singleLeg.get("html");
}
But again array size is 0
Need some suggestion of how to get the value of node - "html". Pls suggest. what mistake am I doing here?
Thanks in advance
RequestSpecification emailReq = given().with().pathParam("email",emailName);
int retries = 5;
List<HashMap<String, Object>> emails = Arrays.asList();
. . .
emailResp = emailReq.get("restmail.net/mail{email}");
if (emailResp.getStatusCode() == 200) { emails = emailResp.jsonPath().getList("$");
String email = emails.get(0).get("html").toString();

How to send 'JSON' in post request using deluge?

I have a JSON data, which i need to pass it in POST method. I have no idea how to convert JSON data as query paramters. Kindly help me how to send this type of a JSON data in POST method using deluge.
jsonData = {
"author": "urn:li:person:12345",
"lifecycleState": "PUBLISHED",
"specificContent": {
"com.linkedin.ugc.ShareContent": {
"shareCommentary": {
"text": "Hello World! This is my first Share on LinkedIn!"
},
"shareMediaCategory": "NONE"
}
},
"visibility": {
"com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
}
}
This is what i actually tried:
headerData = Map();
headerData.put("Content-Type","application/json charset=utf-8");
headerData.put("X-Restli-Protocol-Version","2.0.0");
headerData.put("x-li-format","json");
//json data
fields = "{\"author\":\"urn:li:person:368964147\",\"lifecycleState\":\"PUBLISHED\",\"specificContent\": {\"com.linkedin.ugc.ShareContent\":{\"shareCommentary\":{\"text\": \"Hello World! This is my first Share on LinkedIn!\"},\"shareMediaCategory\": \"NONE\"}},\"visibility\":{\"com.linkedin.ugc.MemberNetworkVisibility\":\"PUBLIC\"}}";
//info fields;
response = invokeurl
[
url :"https://api.linkedin.com/v2/ugcPosts"
type :POST
parameters:fields
headers:headerData
connection:"li"
];
info response;
I expect:
params = Map();
params.put("author","urn:li:person:12345");
params.put("lifecycleState","PUBLISHED");
...so on
Thanks.
I found the deluge code to convert JSON data to query parameters.
param = Map();
param.put("author","urn:li:person:YoTjU8Fmfk");
param.put("lifecycleState","PUBLISHED");
specificContent = Map();
ShareContent = Map();
shareCommentary = Map();
shareCommentary.put("text","Hello World! This is my first Share on LinkedIn!");
ShareContent.put("shareCommentary",shareCommentary);
specificContent.put("com.linkedin.ugc.ShareContent",ShareContent);
specificContent.put("shareMediaCategory","NONE");
param.put("specificContent",specificContent);
visibility = Map();
visibility.put("com.linkedin.ugc.MemberNetworkVisibility","PUBLIC");
param.put("visibility",visibility);

How do I send API push message with .Net / Parse.com? (C#)

This is my application code for sending push message using PARSE
public static string ParseAuthenticate(string strUserName, string
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.parse.com/1/push");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("X-Parse-Application-Id", "my app id");
httpWebRequest.Headers.Add("X-Parse-REST-API-KEY", "my rest api key");
httpWebRequest.Method = "POST";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
return responseText;
}
}
Request body
{
"channels": [
"test"
],
"data": {
"alert": "12345"
}
}
Above code where is pass my request parameter(body)? how to frame my request as JSON format?
Thanks in advance.Please help me to solve this issue.
Bellow code is running for push notification using parse in .net.
private bool PushNotification(string pushMessage)
{
bool isPushMessageSend = false;
string postString = "";
string urlpath = "https://api.parse.com/1/push";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(urlpath);
postString = "{ \"channels\": [ \"Trials\" ], " +
"\"data\" : {\"alert\":\"" + pushMessage + "\"}" +
"}";
httpWebRequest.ContentType = "application/json";
httpWebRequest.ContentLength = postString.Length;
httpWebRequest.Headers.Add("X-Parse-Application-Id", "My Parse App Id");
httpWebRequest.Headers.Add("X-Parse-REST-API-KEY", "My Rest API Key");
httpWebRequest.Method = "POST";
StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
requestWriter.Write(postString);
requestWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
JObject jObjRes = JObject.Parse(responseText);
if (Convert.ToString(jObjRes).IndexOf("true") != -1)
{
isPushMessageSend = true;
}
}
return isPushMessageSend;
}
To send Notification to all app user you have to set the
Data field like so:
postString = "{\"data\": { \"alert\": \"Test Notification 2 From Parse Via Chinwag Admin\" },\"where\": { \"deviceType\": \"ios\" }}";