push notification on website using service worker and fcm - c#

Hi I am new in push notification. I want to implement push notification on my website using service worker and fcm. I have follow this url 'https://developers.google.com/web/fundamentals/codelabs/push-notifications/' and create my client application its show notification popup when I allow notification its create entpoint , p256dh and auth key. I have also created a service using entpoint , p256dh , auth and private, public key and send notification . this notification is receipt by client.
c# code for send notification are given below.
var pushEndpoint = #"https://fcm.googleapis.com/fcm/send/fOetqkkxzlM:APA91bHASHHThdRC4dDCnZJxAy6ZngUHhxsT9mjF5xuBDpM5kzy-dq2jcbQtsiDcXZ9WcOTE4GWzUZkvGbt3xBH0y61mqbkRVkjvBfvgnUqAGf1hsIrUXpsrl9nfqmrlXx2UFWaTJerC";
var p256dh = #"BHmoaUoqJ6rUitaXj-YvXbuORO_x6lFigO-NV1ceDygb4GhywOw7WIKWOtWqMsVswl8pUCVJrPiNtyVQFirD1oI";
var auth = #"-aFkO3hZKP6u0BZwKRNDiw";
var subject = #"mailto:xyz#gmail.com";
var publicKey = #"BNizeduk-kgre_pz7aj0_t89t-5nvQttzyL17rQfsc7GlOFIfn0qVKyLF81ahCGdsMdhWz-5n_PQavZHywBt9Rs";
var privateKey = #"W21b4Jh9qSoGI7GpKHAq6ikMBjTStiBvQP_wWVvVRqE";
var subscription = new PushSubscription(pushEndpoint, p256dh, auth);
var vapidDetails = new VapidDetails(subject, publicKey, privateKey);
//var gcmAPIKey = #"[your key here]";
string payload = #"{""user"":{""name"":""mohan"",""teamname"":""b"",""email"":""c"",""players"":[""1"",""2""]}}";
var webPushClient = new WebPushClient();
try
{
webPushClient.SendNotification(subscription, payload, vapidDetails);
//webPushClient.SendNotification(subscription, "payload", gcmAPIKey);
}
catch (WebPushException exception)
{
Console.WriteLine("Http STATUS code" + exception.StatusCode);
}
my problem is for every client i have to pass I have to pass entpoint , p256dh , auth key.Can I automate it . like can i get this keys (entpoint , p256dh , auth ) for all the users who has subscribed users and send message at one time.
please help

Related

Firebase: server response does not contain a JSON object

I am trying to run a ASP.NET Core API to send FCM push notifications.
The API works with Firebase SDK. The code is basically the one in the documentation:
Initialize the default app, configPath being the JSON project configuration
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile(configPath), //JSON con API Key credentials
});
Example of the payload I am sending
//Send a message to the device corresponding to the provided
//registration token.
//var message = new Message()
//{
// Data = new Dictionary<string, string>()
// {
// { "score", "850" },
// { "time", "2:45" },
// },
// Token = registrationToken,
// Notification = new Notification
// {
// Body = "Test"
// }
//};
The async task I am sending
string response = await FirebaseMessaging.DefaultInstance.SendAsync(payload).ConfigureAwait(false);
Everything works OK on local (push notifications are being send), configuration seems to be alright but the deployed API running on my server returns the following error:
Server runs on Windows 10, has internet connectivity and already has other APIs (not FCM related) working fine.
As a ServiceUnavailable error I have already checked if its a Firebase problem but then again if it is Firebase problem it wouldn't work on local, right?

Add subscriber to Mailchimp through API 3.0

I'm attempting to integrate version 3 of Mailchimp's API to add a subscriber to one of my mailing lists. The code below is what I have thus far, and my intention is to call it in my contact form method when the user fills out their email to subscribe. In theory it should get this email stored in emailAddress and POST it to MailChimp, but theorys are not practical. Below is my current method of POST data:
private string InsertIntoMailChimpGeneralList(string emailAddress)
{
var apiKey = ConfigurationManager.AppSettings["MailChimpAPIKeyGeneral"];
var dataCenter = ConfigurationManager.AppSettings["MailChimpDataCenterIDGeneral"];
var listId = ConfigurationManager.AppSettings["mailChimpListIDGeneral"];
var email_address = emailAddress;
var status = "subscribed";
using (var wc = new System.Net.WebClient())
{
// Data to be posted to add email address to list
var data = new { email_address, status };
// Serialize to JSON using Json.Net
var json = JsonConvert.SerializeObject(data);
// Base URL to MailChimp API
string apiUrl = "https://" + dataCenter + ".api.mailchimp.com/3.0/";
// Construct URL to API endpoint being used
var url = string.Concat(apiUrl, "lists/", listId, "/members?");
// Set content type
wc.Headers.Add("Content-Type", "application/json");
// Generate authorization header
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(":" + apiKey));
// Set authorization header
wc.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
// Post and get JSON response
string sendUrl = wc.UploadString(url, json);
return sendUrl;
}
}
In my contact form I have a check where I want the email address added in the contact form (emailAddress is the variable used here) to post that data to the list, when the form is submitted:
if (ConfigurationManager.AppSettings["UseMailChimpIntegration"].ToString().ToLower().Trim() == "true")
{
InsertIntoMailChimpGeneralList(emailAddress);
}
I feel I've implemented this wrong. I was able to get it working on v2 but upgrading to v3 has left me clueless at this point. My contact form runs fine and stored my values in my local database, but does not POST that data through to mailchimp.
I've triple checked my API/datacenter values, and would appreciate some assistance.

I am working on Sending push notification to android devices from C# Web app

I am Creating Application to send push notifications to Android devices using firebase and azure notification hub.
How to store RegistrationID using Push.RegisterAsync In my Code ...
Here RegistrationId is generated from firebaseinstanceID Refresh Token which is every time new So how Can I handle thatid` for sending notifications to registered devices?
var refreshedToken = FirebaseInstanceId.Instance.Token;
var templates = new JObject();
templates["genericMessage"] = new JObject
{
{ "body", templateBodyFCM }
};
var client = new MobileServiceClient(HalalApps.App.MobileServiceUrl);
var push = client.GetPush();
await push.RegisterAsync(refreshedToken, templates);

C# TweetSharp not sending Tweets

I am using TweetSharp to send tweets to users (currently testing it) however it keeps coming back with Bad Authentication Data
{"errors":[{"code":215,"message":"Bad Authentication data."}]}
I have checked my app settings and it has full read and write access. I have also tried to regenerate my consumer keys but still not luck.
here is my code
public ActionResult AccessToken()
{
string oauth_consumer_key = "<consumer key>";
string oauth_consumer_secret = "<consumer secret>";
var service = new TwitterService(oauth_consumer_key, oauth_consumer_secret);
// Now we need the Token and TokenSecret
OAuthRequestToken requestToken = service.GetRequestToken("http://localhost:37808/");
string authURL = service.GetAuthorizationUri(requestToken).ToString();
Process.Start(authURL);
SendTweetOptions options = new SendTweetOptions();
options.Status = "Hello there Twitter";
service.SendTweet(options);
var re = service.Response.Response;
return View();
}
Am I doing anything wrong?
Finally solved the issue and it works well. Based upon comments from Yort.
public ActionResult AccessToken()
{
// Step 1 - Retrieve an OAuth Request Token
TwitterService service = new TwitterService(ConfigurationManager.AppSettings["TwitterConsumerKey"], ConfigurationManager.AppSettings["TwitterConsumerSecret"]);
// This is the registered callback URL
OAuthRequestToken requestToken = service.GetRequestToken("http://localhost:37808/Twitter/OToken");
// Step 2 - Redirect to the OAuth Authorization URL
Uri uri = service.GetAuthorizationUri(requestToken);
return new RedirectResult(uri.ToString(), false /*permanent*/);
//return View();
}
public ActionResult OToken()
{
return View();
}
public ActionResult UserInfo(string oauth_token, string oauth_verifier)
{
var requestToken = new OAuthRequestToken { Token = oauth_token };
// Step 3 - Exchange the Request Token for an Access Token
TwitterService service = new TwitterService(ConfigurationManager.AppSettings["TwitterConsumerKey"],
ConfigurationManager.AppSettings["TwitterConsumerSecret"]);
OAuthAccessToken accessToken = service.GetAccessToken(requestToken, oauth_verifier);
// Step 4 - User authenticates using the Access Token
service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
TwitterUser user = service.VerifyCredentials(new VerifyCredentialsOptions());
ViewBag.Message = string.Format("{0}", user.ScreenName);
// Step 5 - Send Tweet to User TimeLine
SendTweetOptions options = new SendTweetOptions();
string URL = "file:\\C:\\Users\\<User>\\Desktop\\test.jpg";
string path = new Uri(URL).LocalPath;
// Sending with Media
using (var stream = new FileStream(path, FileMode.Open))
{
service.SendTweetWithMedia(new SendTweetWithMediaOptions
{
Status = "<status>",
Images = new Dictionary<string, Stream> { { path, stream } }
});
}
var responseText = service.Response.StatusCode;
if (responseText.ToString() == "OK")
{
ViewBag.Message = "Tweet Successful";
}
else
{
ViewBag.Message = "Tweet Unsuccessful";
}
return View();
}
}
I don't believe you can send Tweets as just a consumer, the Tweets have to be "owned" by a user account. You need to register a Twitter account, then do the full oauth authentication process to get an access token (in addition to the consumer token), then reauthorise the TweetSharp service using both tokens.
Your code above nearly gets there (I think). After the Process.start call there needs to be logic to use the verifier returned in the browser (a number displayed after the user logs in) to complete the auth process and act as that user. At the moment, your code gets half way through that process but does not complete it, so when you try to tweet your TweetSharp service is only authed as the app and not the user.
The originalTweetSharp readme.md does include the missing bits of code. Step 3 needs the actual verifier returned in the browser after login:
// Step 3 - Exchange the Request Token for an Access Token
string verifier = "123456"; // <-- This is input into your application by your user
OAuthAccessToken access = service.GetAccessToken(requestToken, verifier);
// Step 4 - User authenticates using the Access Token
service.AuthenticateWith(access.Token, access.TokenSecret);
//Now your tweet call should work here.
It also looks like you're doing this in a web app on the server? In which case you're using entirely the wrong oauth flow (I believe). This one is designed for desktop apps, hence the call that starts a new browser process for the user to login with. I'm not entirely sure how the web flow works as I've never used it, but I believe you need to redirect the user to the authorisation url you receive, and the callback registered with Twitter should point back to your site. I think there is some kind of state parameter that can be passed back through the oauth flow so you can implement your own logic to pickup where you left off based on a session id or similar.
I worked on this subject before. You have to developer account before the send tweet because you need tokens and keys. It's my windows service project.
I wrote my tokens and key codes in App.config
<appSettings>
<add key="twitterAccessToken" value="*****"/>
<add key="twitterAccessTokenSecret" value="*****"/>
<add key="twitterConsumerKey" value="*****"/>
<add key="twitterConsumerSecret" value="*****"/>
public static void SendTweet()
{
try
{
GetPixelImageFile();
string key = ConfigurationSettings.AppSettings.Get("twitterConsumerKey");
string secret = ConfigurationSettings.AppSettings.Get("twitterConsumerSecret");
string token = ConfigurationSettings.AppSettings.Get("twitterAccessToken");
string tokenSecret = ConfigurationSettings.AppSettings.Get("twitterAccessTokenSecret");
string message = "Color, Colorful, Pixel, Art, PixelColouring, Follow";
var service = new TweetSharp.TwitterService(key, secret);
service.AuthenticateWith(token, tokenSecret);
using (var stream = new FileStream(#"C:\Images\Pixel.png", FileMode.Open))
{
var result = service.SendTweetWithMedia(new SendTweetWithMediaOptions
{
Status = message,
Images = new Dictionary<string, Stream> { { "john", stream } }
});
SendMail("SendTweet", (result == null ? "" : result.Text));
}
}
catch (Exception ex)
{
SendMail("SendTweet", ex.Message);
}
}

chat using UCWA

I am trying to implement a 2-way chat using UCWA(Lync web app) , I am able to send the data to a client , but how do i receive it back from that client ? to implement a proper 2-way chat ?
I have attached the code to send some ping to a specific user , how do i receive data back from the user to implement the chat ?
private void StarConversation(string startConversationLink, string hostName, string accessToken, string tokenType)
{
var myObject = new JObject();
myObject.Add("operationId", Guid.NewGuid().ToString().Replace("-", ""));
myObject.Add("to", "sip:xyz#abcd.com");
myObject.Add("subject", "TestConv");
List<string> outgoing = new List<string>();
List<string> incoming = new List<string>();
List<string> timeout = new List<string>();
JObject href = new JObject();
string sending = "Hey there ! how are you doing ?";
href.Add("href", "data:text/plain;base64," + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sending)));
JObject message = new JObject();
message.Add("message", href);
myObject.Add("_links", message);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", tokenType + " " + accessToken);
client.PostAsync(new Uri(hostName + startConversationLink), new StringContent(JsonConvert.SerializeObject(myObject), Encoding.UTF8, "application/json")).Result;
if (response.IsSuccessStatusCode)
{
Uri temp = new Uri(hostName + m_eventsLink);
HttpResponseMessage response2 = Get(client, temp.ToString());
string nextLink = string.Empty;
string timeo ;
string ss = string.Empty;
int i =0;
if (response2.IsSuccessStatusCode)
{
string retData2 = response2.Content.ReadAsStringAsync().Result;
var o = JObject.Parse(retData2);
nextLink = o["_links"]["next"]["href"].Value<string>();
response = client.PostAsync(new Uri(hostName + startConversationLink), new StringContent(JsonConvert.SerializeObject(myObject), Encoding.UTF8, "application/json")).Result;
temp = new Uri(hostName + m_eventsLink);
response2 = Get(client, temp.ToString());
retData2 = response2.Content.ReadAsStringAsync().Result;
o = JObject.Parse(retData2);
}
}
}
What you are doing at this point is starting a Conversation with the user and providing an initial message to go with the messagingInvitation. What I do not know from this code slice is:
Are you listening to Events? (This is really important as this is how you will know that the 2nd party accepted/declined the messagingInvitation among other things like who is typing and messages). I would suggest looking into GettingStarted-Events and setting up a mechanism to request events.
Are you making frequent (~3-5min) POST request on reportMyActivity to ensure the application is not recycled. Check out Resources-reportMyActivity if not.
If the code is listening to events and reporting activity. The next step will be listening for the messagingInvitation and check conversation/messaging events. Conversation will transition from Connecting (state) (messageInvitation is being processed) to Connected (messagingInvitation was accepted) or Disconnected (messagingInvitation was declined, conversation ended, other errors). Assuming the other user accepts the next event to check is messaging state for Connected (this means the messaging modality is active in the conversation and useful methods like sendMessage, addParticipant, and setIsTyping will be available) or Disconnected (this means messaging modality is not active and addMessaging can be used to enable this modality.
If you can reach this point message events will appear when any participant sends a message to the conversation. The direction property can be used to determine when the current UCWA user has sent a message (outgoing) and for all other users there should be a participant property that can identify the user.

Categories