i am using fcm to send push notifications from api to the clients the code which i was using it below:
if (notificationModel.IsDeviceAndroid){
FcmSettings settings = new FcmSettings(){
SenderId = _notificationSettings.SenderId,
ServerKey = _notificationSettings.ServerKey
};
string authorizationKey = string.Format("keyy={0}", settings.ServerKey);
string deviceToken = notificationModel.DeviceId;
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", authorizationKey);
httpClient.DefaultRequestHeaders.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
DataPayload dataPayload = new DataPayload();
dataPayload.Title = notificationModel.Title;
dataPayload.Body = notificationModel.Body;
GoogleNotification notification = new GoogleNotification();
notification.Data = dataPayload;
notification.Notification = dataPayload;
var fcm = new FcmSender(settings,httpClient);
try {
var fcmSendResponse = await fcm.SendAsync(deviceToken, notification);
if (fcmSendResponse.IsSuccess()) {
var resposne = new GetNotificationResponseDto(){
Title = notificationModel.Title,
Message = notificationModel.Body
};
return new ServiceResponse<GetNotificationResponseDto>(resposne);
} else {
var resposne = new GetNotificationResponseDto(){
Title = "Error",
Message = "Notification dose not sent"
};
return new ServiceResponse<GetNotificationResponseDto>(resposne);
}
}catch(ArgumentException ex){
return new ServiceResponse<GetNotificationResponseDto>(default) {
Error = new ResponseError(ex.Message)
};
}
The code is working on the local machine and send notification to the client successfully.
but i got the internal server error 500 on the remote server so please can anyone give me the solution for this error
thank you
Related
I have an Alexa skill and a winform on a windows 10 device. I'm sending a message from the winform to Alexa using the Skill Messaging API. I've got the access token, sent the message and received a 202 status code to say the 'message has been successfully accepted, and will be sent to the skill' so I believe everything on the winform side is okay.
The code for it;
var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (requestMessage, certificate, chain, policyErrors) => true;
using (var httpClient = new HttpClient(handler))
{
// Obtain skill messaging token
using (var requestToken = new HttpRequestMessage(new HttpMethod("POST"), "https://api.amazon.com/auth/O2/token"))
{
requestToken.Content = new StringContent("grant_type=client_credentials&scope=alexa:skill_messaging&client_id=amzn1.application-oa2-client.************&client_secret=************");
requestToken.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var responseToken = httpClient.SendAsync(requestToken);
Response r = JsonConvert.DeserializeObject<Response>(responseToken.Result.Content.ReadAsStringAsync().Result);
// Send message
using (var requestMessage = new HttpRequestMessage(new HttpMethod("POST"), "https://api.eu.amazonalexa.com/v1/skillmessages/users/" + strUserId))
{
requestMessage.Headers.TryAddWithoutValidation("Authorization", "Bearer " + r.access_token);
requestMessage.Content = new StringContent("{ \"data\" : { \"message\" : \"Hi pickle\" }}");
requestMessage.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var responseMessage = httpClient.SendAsync(requestMessage);
MessageBox.Show(responseMessage.Result.ToString());
}
}
}
How do I capture the incoming message event on the skill though?
Looking at the docs I need to handle an incoming request of type Messaging.MessageReceived? Is that correct?
I tried something like that in the skills FunctionHandler but didn't have any luck.
public SkillResponse FunctionHandler(SkillRequest input, ILambdaContext context)
{
// Initialise response
skillResponse = new SkillResponse
{
Version = "1.0",
Response = new ResponseBody()
};
ssmlResponse = new SsmlOutputSpeech();
if (input.GetRequestType() == typeof(LaunchRequest))
{
LaunchRequestHandler(input, context);
}
else if (input.GetRequestType() == typeof(IntentRequest))
{
IntentRequestHandler(input, context);
}
else if (input.GetRequestType() == typeof(SessionEndedRequest))
{
SessionEndedRequestHandler(input, context);
}
else if(input.GetRequestType().Equals("Messaging.MessageReceived"))
{
ssmlResponse.Ssml = "<speak>" + input.Request.Type + "</speak>";
}
skillResponse.Response.OutputSpeech = ssmlResponse;
return skillResponse;
}
How do I react to the message? Is it permissions I need to set up? Does the incoming message not trigger the functionhandler the same way the echo device does?
Thanks.
I'm getting Status Code 405, Method not allowed error when sending email that has an attachment. I'm using HttpClient to post my request to the API rather Microsoft Graph Client. Don't want to have dependency of Microsoft Graph library. My send email without attachment works fine but not with the attachment.
try
{
const string url = "https://graph.microsoft.com/v1.0/users/myemail#outlook.com/sendMail";
var path = "C:\\Attachments\\image1.jpg";
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
byte[] bytes = File.ReadAllBytes(path);
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
var email = new Email
{
Message = new Message
{
Subject = "Test subject",
Body = new Body
{
ContentType = "Text",
Content = "message"
},
ToRecipients = new List<Recipients>
{
new Recipients
{
EmailAddress = new EmailAddress
{
Address = "testemail#outlook.com"
}
}
},
Attachments = new List<Attachment>
{
new Attachment
{
Name = "image1.jpg",
ContentBytes = base64String,
ContentType = "image/jpeg"
}
}
}
};
var jsonMessage = JsonConvert.SerializeObject(email);
var content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(url, content).Result;
response.EnsureSuccessStatusCode();
}
}
catch (HttpRequestException e)
{
Console.WriteLine(e.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Following is the answer if someone else get stuck with same issue
For "Attachment" object, Microsoft Graph need '#odata.type' property with the value of '#microsoft.graph.fileAttachment'
Attachments = new List<Attachment>
{
new Attachment
{
//GraphDataType property name will be changed to #odata.type
GraphDataType = "#microsoft.graph.fileAttachment",
Name = "image1.jpg",
ContentBytes = base64String,
ContentType = "image/jpeg"
}
}
Replace 'GraphDataType' inside Serialized Object with '#odata.type'
var jsonMessage = JsonConvert.SerializeObject(email);
jsonMessage = jsonMessage.Replace("GraphDataType", "#odata.type");
I am implementing c # with FireBase, it sends me error 401 'INVALID_KEY_TYPE'
private static Uri FireBasePushNotificationsURL = new Uri("https://fcm.googleapis.com/fcm/send");
private static string ServerKey = "AIzaSyA9fL8lPyxcrngIDDsDeUbq9sPTkavXXXX";
public static async Task<bool> SendPushNotification(string deviceTokens, string title, string body, object data)
{
bool sent = false;
if (deviceTokens.Count() > 0)
{
//Object creation
var messageInformation = new
{
to = "fZ0EyxU-tsk:APA91bE3-qo4DwL9phteDJC8pG6iLdr-YSSl-N_2SJne3U6eyUhmEuZNQhJi0YM-XXXXXX",
priority = "high",
content_available = true,
notification = new
{
body = "Test",
title = "Test miguel",
badge = 1
},
};
//Object to JSON STRUCTURE => using Newtonsoft.Json;
string jsonMessage = JsonConvert.SerializeObject(messageInformation);
//Create request to Firebase API
var request = new HttpRequestMessage(HttpMethod.Post, FireBasePushNotificationsURL);
request.Headers.TryAddWithoutValidation("Authorization", "key=" + ServerKey);
request.Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");
HttpResponseMessage result;
using (var client = new HttpClient())
{
result = await client.SendAsync(request);
sent = sent && result.IsSuccessStatusCode;
}
}
return sent;
}
I have the same problem. The problem is that you take the wrong server key.
The right firebase server key is Project > Settings > Cloud Messaging > Server Key
I'm trying to call Send on the GmailService from a C# .NET MVC app. and I keep getting a 403 error when I call send.
I've checked my scopes, the Gmail setup definitely has the Gmail API enabled, and my ClientID and ClientSecret are fresh.
var httpClient = new HttpClient{
BaseAddress = new Uri("https://www.googleapis.com")
};
var requestUrl = $"oauth2/v4/token?code={code}&client_id={ClientId}&client_secret={SecretKey}&redirect_uri={RedirectUrl}&grant_type=authorization_code";
var dict = new Dictionary<string, string>{
{ "Content-Type", "application/x-www-form-urlencoded" }
};
var req = new HttpRequestMessage(HttpMethod.Post, requestUrl){Content = new FormUrlEncodedContent(dict)};
var response = await httpClient.SendAsync(req);
var token = JsonConvert.DeserializeObject<GmailToken>(await response.Content.ReadAsStringAsync());
Session["user"] = token.AccessToken;
//var obj = await GetuserProfile(token.AccessToken);
var obj = await DoSendEmail(token);
public void DoSendEmail(GmailToken inToken) {
const string fromAcct = "XXXXXXXX#gmail.com";
TokenResponse token = new TokenResponse();
token.AccessToken = inToken.AccessToken;
token.ExpiresInSeconds = inToken.ExpiresIn;
token.IdToken = inToken.IdToken;
token.TokenType = inToken.TokenType;
token.IssuedUtc = DateTime.UtcNow;
IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer {
ClientSecrets = secrets,
Scopes = SCOPES,
ProjectId = "Xcent CP"
});
UserCredential credential = new UserCredential(flow, fromAcct, token);
if (credential.Token.IsExpired(credential.Flow.Clock)) {
bool success = credential.RefreshTokenAsync(CancellationToken.None).Result;
if (!success) {
throw new Exception("Could not refresh token");
}
}
GmailService gs = null;
try {
gs = new GmailService(new Google.Apis.Services.BaseClientService.Initializer() {
ApplicationName = APP_NAME,
HttpClientInitializer = credential
});
var mailMessage = new System.Net.Mail.MailMessage();
mailMessage.From = new System.Net.Mail.MailAddress(fromAcct);
mailMessage.To.Add("XXXXXXXX#comcast.net");
mailMessage.ReplyToList.Add(fromAcct);
mailMessage.Subject = "Test email";
mailMessage.Body = "<html><body>Hi <b>Lee</b>, this is <b>yet another</b> test message.</body></html>";
mailMessage.IsBodyHtml = true;
var mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mailMessage);
var gmailMessage = new Google.Apis.Gmail.v1.Data.Message {
Raw = Encode(mimeMessage.ToString())
};
gs.Users.Messages.Send(gmailMessage, fromAcct).Execute();
}
catch (Exception ex) {
throw ex;
}
finally {
if (gs != null) {
gs.Dispose();
}
gs = null;
}
}
I'm not sure where to look...I've been through many many many online articles and tutorials, tried seemingly everything, and I'm still stuck with the 403 error. Help!
Thanks,
Lee
So after many hours spent looking at this I figured out the problem. My link to the Google login was this:
Response.Redirect($"https://accounts.google.com/o/oauth2/v2/auth?client_id={ClientId}&response_type=code&scope=openid%20email%20profile&redirect_uri={RedirectUrl}&state=abcdef");
"openid%20email%20profile" was the only scope I was specifying for the login, hence the 403 error about the scope I was using for the flow variable.
phew!
I am trying to implement Mail Chimp's new API with my ASP.NET C# website so when a user enters their email address into an input box it will be added to my mailchimp list automatically. I have tried various other methods however none of these have worked.
I have tried a Web Client which threw a 405 Cannot use that Method response and a HttpClient which threw an error on the starred GetStringAsync method call because its not a task.
My code so far is detailed below:
public bool BatchSubscribe(IEnumerable<MailChimpSubscriberModel> newSubscribers)
{
if (string.IsNullOrEmpty(_defaultListId)) throw new ArgumentNullException(Res.Resource.MailChimpIntegrationNoListId);
if (string.IsNullOrEmpty(_apiKey)) throw new ArgumentNullException(Res.Resource.MailChimpIntegrationNoApiKey);
foreach (MailChimpSubscriberModel subscriber in newSubscribers)
{
string url = "https://" + _dataPoint + ".api.mailchimp.com/3.0/lists/" + _defaultListId + "/";
Subscriber member = new Subscriber();
member.email = subscriber.Email;
member.subscribed = "subscribed";
string jsonString = new JavaScriptSerializer().Serialize(member);
//using (WebClient client = new WebClient())
//{
// client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
// client.Headers[HttpRequestHeader.Authorization] = new AuthenticationHeaderValue("Basic", _apiKey).ToString();
// string HtmlResult = client.(url, jsonString);
// return true;
//}
using (var http = new HttpClient())
{
http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", _apiKey);
string content = await http.**GetStringAsync**(#"https://us11.api.mailchimp.com/3.0/lists");
Console.WriteLine(content);
}
}
return false;
}
I'm a bit late to this question, but as it took me half a day to figure it out, here there is my answer, so it can help others. I'm using MailChimp 3.0:
private void subscribeAddress()
{
string apiKey = "APIKEY-usX"; //your API KEY created by you.
string dataCenter = "usX";
string listID = "listID"; //The ListID of the list you want to use.
SubscribeClassCreatedByMe subscribeRequest = new SubscribeClassCreatedByMe
{
email_address = "somebodys#email.com",
status = "subscribed"
};
subscribeRequest.merge_fields = new MergeFieldClassCreatedByMe();
subscribeRequest.merge_fields.FNAME = "YourName";
subscribeRequest.merge_fields.LNAME = "YourSurname";
using (HttpClient client = new HttpClient())
{
var uri = "https://" + dataCenter + ".api.mailchimp.com/";
var endpoint = "3.0/lists/" + listID + "/members";
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", apiKey);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri(uri);
//NOTE: To avoid the method being 'async' we access to '.Result'
HttpResponseMessage response = client.PostAsJsonAsync(endpoint, subscribeRequest).Result;//PostAsJsonAsync method serializes an object to
//JSON and then sends the JSON payload in a POST request
//StatusCode == 200
// -> Status == "subscribed" -> Is on the list now
// -> Status == "unsubscribed" -> this address used to be on the list, but is not anymore
// -> Status == "pending" -> This address requested to be added with double-opt-in but hasn't confirmed yet
// -> Status == "cleaned" -> This address bounced and has been removed from the list
//StatusCode == 404
if ((response.IsSuccessStatusCode))
{
//Your code here
}
}
}
Here there are the classes SubscribeClassCreatedByMe and MergeFieldClassCreatedByMe
namespace Subscriber
{
public class SubscribeClassCreatedByMe
{
public string email_address { get; set; }
public string status { get; set; }
public MergeFieldClassCreatedByMe merge_fields { get; set; }
}
}
namespace Subscriber
{
public class MergeFieldClassCreatedByMe
{
public string FNAME { get; set; }
public string LNAME { get; set; }
}
}
Well, I hope this help!!
401 isn't "cannot use that method" it's "Unauthorized". You've got an authentication error. From the looks of things, you're not quite doing basic auth the right way. Check out this example for the details you're missing.
PS: the response that comes back from APIv3 is usually pretty helpful, so you should always make sure to look at that whole response, not just the status code.
It works if you change auth to these lines:
String username = "abc"; //anything
String password = apiKey; //your apikey
String encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", encoded);
Below code snippet is should work on .NET Core 2.1 using Mailchimp API V3.0:
string url = #"https://" + mailchimpInstance + ".api.mailchimp.com/3.0/lists/" + ListId + "/members";
var info = new Info() { email_address = "example#gmail.com", status = "subscribed" };
var infoJson = JsonConvert.SerializeObject(info);
using (var client = new HttpClient())
{
var uri = "https://" + mailchimpInstance + ".api.mailchimp.com/";
var endpoint = "3.0/lists/" + ListId + "/members";
try
{
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic",ApiKey);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri(uri);
var content = new StringContent(infoJson.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(endpoint, content);
var responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine("Response from server -> " + responseString);
return Ok();
Add into References MailChimp.Net.dll
than you can define an interface like
IMailChimpManager manager = new MailChimpManager(ConfigurationManager.AppSettings["MailChimpApiKey"].ToString());
than you can add or update your client in your MailChimp list
Member m = await manager.Members.AddOrUpdateAsync(ConfigurationManager.AppSettings["MailChimpListId"].ToString(), new Member { EmailAddress = _email, EmailType = "html", Status = Status.Pending});
m = await manager.Members.AddOrUpdateAsync(ConfigurationManager.AppSettings["MailChimpListId"].ToString(), new Member { EmailAddress = _email, EmailType = "html", Status = Status.Subscribed });
It is very simple.. I think...