How to add contact in the list using sendgrid? - c#

I'm trying to add contact in the list so i'm using this link below to Add a Single Recipient to a List :
click here
I have Advanced 100k plan and using full access api key but still getting forbidden error.
Please help me out in this.
My code
string data = #"[
{
'age': 25,
'email': 'example#example.com',
'first_name': '',
'last_name': 'User'
},
{
'age': 25,
'email': 'example2#example.com',
'first_name': 'Example',
'last_name': 'User'
}
]";
var client = new SendGridClient("#################");
var json = JsonConvert.DeserializeObject<Object>(data);
data = json.ToString();
var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "contactdb/recipients", requestBody: data);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
return response;

You can resolve this by editing your API Keys settings in Send Grid and enabling the permissions for the features you need access to for that API Key.
API Keys settings

Related

Loop through a json response received from facebook graph api in c# and get the latest value. (then, store it in database in dot net core)

I'm using the graph API of facebook to get the permalink of facebook posts. But it seems the endpoint always returns an array of all the posted posts.
So, I need to take the response and loop through it and get only the latest value that is always the first pair in the response.
Here is the response I get using the graph explorer. I only need the first pair from data array i.e the permalink_url and the id so that I can store them separately in a database to embed posts in my website using the permalink.
{
"data": [
{
"permalink_url": "https://www.facebook.com/347775946439542/photos/a.348021906414946/358023508748119/?type=3",
"id": "347775946439542_358023508748119"
},
{
"permalink_url": "https://www.facebook.com/347775946439542/photos/a.348021906414946/350654269485043/?type=3",
"id": "347775946439542_350654269485043"
},
{
"permalink_url": "https://www.facebook.com/347775946439542/photos/a.348021906414946/350651839485286/?type=3",
"id": "347775946439542_350651839485286"
}
],
"paging": {
"cursors": {
"before": "QVFIUlRGODNTaFZAueEUxQ2VvcHlrMUw1MGE0U0FCblhZAY1hVbFBGUHhHdXlrSkgzSm0tb05pSGpFOXBYVG9EcnN5T21sQTgtYy1jSjhrZAW9WYmg5YmpVMXpQWTRLUkQ3ZA05PcEZAjUTNyV2VuV05hRG8yVlBaa3pia3dFTVRLU05nU0pU",
"after": "QVFIUlBHMG44ZAkxHdUsxb012bVlOQ0ZAfaDhHLUZA6VEt6MHd0QjJYZADlfZAVk2aExSdlJESUU2SlVDaVJsYzI4dnlmUllZASzhKd3Nkb09aa2ZAMRHZAFTGhMVHFoQ1hjNE5zNDJ2aV96UGtVQUpBeHE1b2xUTzk2SHZALLTZA1Y3pZAZAmJOMENS"
}
}
}
I did go through some questions on this that used newtonsoft but couldn't get it to work.
So any help on how to loop through this in C# (razor page) and then return them from a method. Thenafter I need to store both the permalink as well as the id in database.
Here is my method: Here _getPermalink has the endpoint I have to hit.
Also 'str' has the response which is shown below. I have to fetch the permalink and id from that.
public string GetPermalink()
{
WebClient client = new WebClient();
Stream data = client.OpenRead(_getPermalink);
StreamReader reader = new StreamReader(data);
string str = "";
str = reader.ReadLine();
data.Close();
return str;
}
When I call this endpoint from the method:string res = facebook.GetPermalink(); (Here facebook is just a constructor with values required for making the call to endpoint such as page id, access token,etc.)
The same response looks something like this.
{"data":[{"permalink_url":"https:\/\/www.facebook.com\/347775946439542\/photos\/a.348021906414946\/358023508748119\/?type=3","id":"347775946439542_358023508748119"},{"permalink_url":"https:\/\/www.facebook.com\/347775946439542\/photos\/a.348021906414946\/350654269485043\/?type=3","id":"347775946439542_350654269485043"},{"permalink_url":"https:\/\/www.facebook.com\/347775946439542\/photos\/a.348021906414946\/350651839485286\/?type=3","id":"347775946439542_350651839485286"}],"paging":{"cursors":{"before":"QVFIUlRGODNTaFZAueEUxQ2VvcHlrMUw1MGE0U0FCblhZAY1hVbFBGUHhHdXlrSkgzSm0tb05pSGpFOXBYVG9EcnN5T21sQTgtYy1jSjhrZAW9WYmg5YmpVMXpQWTRLUkQ3ZA05PcEZAjUTNyV2VuV05hRG8yVlBaa3pia3dFTVRLU05nU0pU
I'm relatively new with the concept of json object/arrays in C# and using newtonsoft. Any help and explanations are appreciated.
(PS: Is there a way to get the permalink and id of the Latest Posts ONLY, using the facebook graph api?)
Given the JSON data you posted, you can get the first permalink URL from it using the following one-liner:
string permalinkUrl = (string)JObject.Parse(json).SelectToken("data[0].permalink_url");
Demo: https://dotnetfiddle.net/SUgz51

SNS - JSON message body failed to parse

I am trying to send to mobile devices a remote notification through Amazon SNS. I got a database which i store the JSON (payload) which needs to be given to PublishRequest of the SNS. I serialise the json in code and pass it to the request.
The issue is that SNS fails with an error: "MESSAGE STRUCTURE - JSON MESSAGE BODY FAILED TO PARSE"
As a requirement, the service (which is responsible to communicate with SNS and send the notification) has to retrieve from DB (MySQL) the json.
What I am missing?
The database is MySQL and the service is written in .Net Core
string messageFromDb = JsonConvert.SerializeObject(input.Payload);
var request = new PublishRequest
{
TargetArn = endpoint.EndpointArn,
MessageStructure = "json",
Message = messageFromDb
};
PublishResponse publishResponse = await _client.PublishAsync(request);
JSON from DB:
{"APNS": {"aps": {"alert": "Check out the new!", "sound": "default"}, "category": {"type": "sports"}}}
I tried also this without any luck:
{"default": "something", "APNS": {"aps": {"alert": "Check out the new games!", "sound": "default"}, "game": {"type": "Xbox"}}}
Finally I figured it out, maybe this answer will help someone. The JSON in the DB should be
{"aps": {"alert": "Check out the new!", "sound": "default"}, "category": {"type": "sports"}}
The .Net code should be:
AWSRoot obj = new AWSRoot(input.Payload);
var request = new PublishRequest
{
TargetArn = endpoint.EndpointArn,
MessageStructure = "json",
Message = JsonConvert.SerializeObject(obj)
};
PublishResponse publishResponse = await _client.PublishAsync(request);
AWSRoot is the root object that we create for SNS
public class AWSRoot
{
public string APNS { get; set; }
public AWSRoot(string payload)
{
APNS = payload;
}
}

post an email to a survey using the surveymonkey api

we have a survey in surveymonkey and using c# to try and add the email addresses to the survey using the surveymonkey api. the api works fine for GETS but we have yet to get a POST to work. all we get back is
"docs": "https://developer.surveymonkey.com/api/v3/#error-codes",
"message": "There was an error retrieving the requested resource.",
"id": "1020",
"name": "Resource Not Found",
"http_status_code": 404
all of the id's are correct as we can GET information about the survey but cannot POST to it. we have granted all the scopes so there shouldn't be a limitation or restriction on that side. SurveyMonkey api support might as well not exist as they are a complete waste of time and cannot answer a single question about their api.
the code below is our latest attempt at calling out to the api with a POST. we put the actual ids in the uri instead of {id} I did not include our id's here for the obvious reasons.
using (var client = new HttpClient())
{
var uri = new Uri("https://api.surveymonkey.net/v3/surveys/{id}/collectors/{id}/messages/{id}/recipients-d");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",ConfigurationManager.AppSettings["SurveyMonkeyAccessToken"]);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent("{ \"email\": + " + emailAddress + " }", Encoding.UTF8, "application/json");
var response = client.PostAsync(uri,content);
ParseSurveyPostResponses(response)
}
anyone successfully post to a surveymonkey survey using their V3 api?
What exactly are you trying to do? Are you trying to create an email collector? Are you trying to create a new message on that email collector?
Are you trying to add recipients to that email? are you trying to send out the email?
Creating an email collector:
POST /v3/<survey_id>/collectors
{
"type": "email"
}
Adding a message to an email collector:
POST /v3/collectors/<collector_id>/messages
{
"type": "invite"
}
Add recipients to a message:
POST /collectors/<collector_id>/messages/<message_id>/recipients
{
"email": "test#example.com",
"first_name": "Test",
"last_name": "Example",
"custom_fields": {
"1": "First Value",
"2": "Second Value",
"3": "Third Value"
},
"extra_fields": {
"field_name1": "field_value1",
"field_name2": "field_value2"
}
}
NOTE: You can also add recipients in bulk
NOTE2: Custom fields are stored on the associated contact in your contact list, Extra Fields are only stored on the recipient for that message and only accessible through the API.
Sending out the email:
POST /v3/collectors/<collector_id>/messages/<message_id>/send
{
"scheduled_date": "2017-07-18T16:52:22"
}
NOTE: you can exclude the scheduled_date and just send in {} to send the message right away.

Updating trigger frequency of Azure Logic App using API

I am trying to update the recurrence frequency and interval of a Logic App using Azure Logic SDK and it is failing with this error message
Microsoft.Rest.Azure.CloudException: The request to patch workflow 'kk-test-logic-app' is not supported.
None of the fields inside the properties object can be patched.
Here is a code snippet showing what I am trying to do.
var workflow = await _client.Value.Workflows.GetAsync(resourceGroupName, workflowName);
dynamic workflowDefinition = workflow.Definition;
workflowDefinition.triggers[triggerName]["recurrence"] = JToken.FromObject(new { frequency = triggerFrequency, interval = triggerInterval });
await _client.Value.Workflows.UpdateAsync(resourceGroupName, workflowName, workflow);
where _client is Lazy<LogicManagementClient>.
Here is the definition of the trigger I am trying to update (got using Fiddler):
"triggers": {
"When_a_new_email_arrives": {
"recurrence": {
"frequency": "Hour",
"interval": 2
},
"splitOn": "#triggerBody()?.value",
"type": "ApiConnection",
"inputs": {
"host": {
"api": {
"runtimeUrl": "https://logic-apis-southindia.azure-apim.net/apim/office365"
},
"connection": {
"name": "#parameters('$connections')['office365']['connectionId']"
}
},
"method": "get",
"path": "/Mail/OnNewEmail",
"queries": {
"folderPath": "Inbox",
"importance": "Any"
}
}
}
}
Note that I am able to successfully retrieve the workflows, workflowRuns, workflowTriggers etc. Only the update operation is failing. Any ideas on how to update properties of workflows using the SDK?
UPDATE:
As pointed out by Amor-MSFT in the comments below, this is a defect and as a workaround, I am currently using CreateOrUpdateAsync instead of UpdateAsync. A new defect has been created in GitHub to get this to the attention of the SDK development team.
The trigger currently executes every 30s checking if a new mail was received from a certain email address and is working well as expected. I'm trying to change the recurrence frequency from 30s to 2hours using the code I provided.
I created a mail trigger and I can reproduce the issue if I use invoke UpdateAsync method. According to the source code of Azure Logic C# SDK, it send a PATCH request which is not supported according the response message. After changed the HTTP method to PUT, I can update the workflow. Here is the sample code which I used to send the PUT request.
string triggerName = "When_a_new_email_arrives";
string resourceGroupName = "my resourcegroup name";
string workflowName = "my-LogicApp";
string subscriptionID = "my-subscriptionID";
var workflow = await _client.Workflows.GetAsync(resourceGroupName, workflowName);
string url = string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Logic/workflows/{2}?api-version=2016-06-01",
subscriptionID, resourceGroupName, workflowName);
HttpClient client = new HttpClient();
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Put, url);
message.Headers.Add("Authorization", "Bearer put your token here");
message.Headers.Add("Accept", "application/json");
message.Headers.Add("Expect", "100-continue");
dynamic workflowDefinition = workflow.Definition;
workflowDefinition.triggers[triggerName]["recurrence"] = JToken.FromObject(new { frequency = "Minute", interval = 20 });
string s = workflow.ToString();
string workflowString = JsonConvert.SerializeObject(workflow, _client.SerializationSettings);
message.Content = new StringContent(workflowString, Encoding.UTF8, "application/json");
await client.SendAsync(message);

ElasticSearch Index/Insert with NEST fail

I'm trying to insert some JSON data into elastic search for testing.
here is the code:
var node = new Uri("http://localhost:9200");
var settings = new ConnectionSettings(node);
settings.DefaultIndex("FormId");
var client = new ElasticClient(settings);
var myJson = #"{ ""hello"" : ""world"" }";
var response = client.Index(myJson, i => i.Index("FormId")
.Type("resp")
.Id((int)r.id)
.Refresh()
);
Nothing is inserted, and I get the following error from ES:
{Invalid NEST response built from a unsuccesful low level call on PUT: /FormId/resp/1?refresh=true}
I've tried to find some example on that but all use a predefined structure of data, instead I want to use JSON data, with unstructured data.
The above error messsage is from NEST.
Elastic replies (and write in the log) the following message:
MapperParsingException[failed to parse]; nested- NotXContentException[Compressor detection can only be called on some xcontent bytes or compressed xcontent bytes];
Failed to parse { ""hello"" : ""world"" } ????
A few observations:
the index name needs to be lowercase
the index will be automatically created when you index a document into it, although this feature can be turned off in configuration. If you'd like to also control the mapping for the document, it's best to create the index first.
use an anonymous type to represent the json you wish to send (you can send a json string with the low level client i.e. client.LowLevel if you want to, but using an anonymous type is probably easier).
The .DebugInformation on the response should have all of the details for why the request failed
Here's an example to demonstrate how to get started
void Main()
{
var node = new Uri("http://localhost:9200");
var settings = new ConnectionSettings(node)
// lower case index name
.DefaultIndex("formid");
var client = new ElasticClient(settings);
// use an anonymous type
var myJson = new { hello = "world" };
// create the index if it doesn't exist
if (!client.IndexExists("formid").Exists)
{
client.CreateIndex("formid");
}
var indexResponse = client.Index(myJson, i => i
.Index("formid")
.Type("resp")
.Id(1)
.Refresh()
);
}
Now if we make a GET request to http://localhost:9200/formid/resp/1 we get back the document
{
"_index": "formid",
"_type": "resp",
"_id": "1",
"_version": 1,
"found": true,
"_source": {
"hello": "world"
}
}

Categories