I know this question have been ask a lot of time in android but not ios. So I already test out push notification with FCM it work fine. Mine problem is wether it's a way to create custom notification rather than letting the system to handle the notification with the notification payload?
-Users can send data messages with FCM.What you have to send is,
Sample PostMan Json data:
{ "data": {
"any key": "any value",
"any key 2": "any value 2"
},
"to" : "token received to mobile from FCM"
}
Payload inside "data" can change according to the requirement.
Mobile end:
application(_:didReceiveRemoteNotification:) override method will get fire.So it is unto developer to extract data from the userInfo property in iOS and use it.
For ios using c# working code:-
public bool NotificationToiosDevice()
{
bool str;
try
{
//Create the web request with fire base API
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
//serverKey - Key from Firebase cloud messaging server
tRequest.Headers.Add(string.Format("Authorization: key={0}", "AAAALNl-P7o:APA91bE38khU73UTdIj7L6LvVS3uI6f47REmxl.................................."));
//Sender Id - From firebase project setting
tRequest.Headers.Add(string.Format("Sender: id={0}", "12345"));
tRequest.ContentType = "application/json";
var payload = new
{
to = "dDDbFltwE5o:APA91bFmZZ-c1pNp................",
priority = "high",
content_available = true,
notification = new
{
title = "Title Of Notification",
},
data = new
{
body = new { Parameter1 = "FirstParameterValue", Parameter2 = "SecondParameterValue" },
},
};
string jsonNotificationFormat = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
Byte[] byteArray = Encoding.UTF8.GetBytes(jsonNotificationFormat);
tRequest.ContentLength = byteArray.Length;
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
if (dataStreamResponse != null) using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
// str = sResponseFromServer;
}
}
}
}
str = true;
}
catch (Exception ex)
{
str = false;
}
return str;
}
Related
I am using GraphAPI SDK to create a new Team in Microsoft Teams:
var newTeam = new Team()
{
DisplayName = teamName,
Description = teamName,
AdditionalData = new Dictionary<string, object>()
{
{"template#odata.bind", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"}
},
Members = new TeamMembersCollectionPage()
{
new AadUserConversationMember
{
Roles = new List<String>()
{
"owner"
},
AdditionalData = new Dictionary<string, object>()
{
{"user#odata.bind", $"https://graph.microsoft.com/v1.0/users/{userId}"}
}
}
}
};
var team = await this.graphStableClient.Teams
.Request()
.AddAsync(newTeam);
The problem is that I get always null. According documentation this method returns a 202 response (teamsAsyncOperation), but the AddAsync method from SDK returns a Team object. Is there any way to get the tracking url to check if the team creation has been finished with the SDK?
Documentation and working SDK works different... As they wrote in microsoft-graph-docs/issues/10840, we can only get the teamsAsyncOperation header values if we use HttpRequestMessage as in contoso-airlines-teams-sample. They wrote to the people who asks this problem, look to the joined teams :)) :)
var newTeam = new Team()
{
DisplayName = model.DisplayName,
Description = model.Description,
AdditionalData = new Dictionary<string, object>
{
["template#odata.bind"] = $"{graph.BaseUrl}/teamsTemplates('standard')",
["members"] = owners.ToArray()
}
};
// we cannot use 'await client.Teams.Request().AddAsync(newTeam)'
// as we do NOT get the team ID back (object is always null) :(
BaseRequest request = (BaseRequest)graph.Teams.Request();
request.ContentType = "application/json";
request.Method = "POST";
string location;
using (HttpResponseMessage response = await request.SendRequestAsync(newTeam, CancellationToken.None))
location = response.Headers.Location.ToString();
// looks like: /teams('7070b1fd-1f14-4a06-8617-254724d63cde')/operations('c7c34e52-7ebf-4038-b306-f5af2d9891ac')
// but is documented as: /teams/7070b1fd-1f14-4a06-8617-254724d63cde/operations/c7c34e52-7ebf-4038-b306-f5af2d9891ac
// -> this split supports both of them
string[] locationParts = location.Split(new[] { '\'', '/', '(', ')' }, StringSplitOptions.RemoveEmptyEntries);
string teamId = locationParts[1];
string operationId = locationParts[3];
// before querying the first time we must wait some secs, else we get a 404
int delayInMilliseconds = 5_000;
while (true)
{
await Task.Delay(delayInMilliseconds);
// lets see how far the teams creation process is
TeamsAsyncOperation operation = await graph.Teams[teamId].Operations[operationId].Request().GetAsync();
if (operation.Status == TeamsAsyncOperationStatus.Succeeded)
break;
if (operation.Status == TeamsAsyncOperationStatus.Failed)
throw new Exception($"Failed to create team '{newTeam.DisplayName}': {operation.Error.Message} ({operation.Error.Code})");
// according to the docs, we should wait > 30 secs between calls
// https://learn.microsoft.com/en-us/graph/api/resources/teamsasyncoperation?view=graph-rest-1.0
delayInMilliseconds = 30_000;
}
// finally, do something with your team...
I found a solution from another question... Tried and saw that it's working...
Here I have written code for Gmail API to fetch mail with date filter
I am able to fetch MessageId and ThreadId using the First API. On the basis of MessageId, I put that messageId parameter in a List object and I have sent this parameter in foreach loop from List to the next API to fetch email body on basis of messageID. But the process is very slow for fetching messages from Gmail
public async Task<ActionResult> DisplayEmailWithFilter (string fromDate, string toDate) {
Message messageObj = new Message ();
Example exampleObj = new Example ();
List<GmailMessage> gmailMessagesList = new List<GmailMessage> ();
GmailMessage gmailMessage = new GmailMessage ();
var responseData = "";
//dateFilter string parameter Created with Date Values
string dateFilter = "in:Inbox after:" + fromDate + " before:" + toDate;
try {
// calling Gmail API to get MessageID Details by Date Filter
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue (scheme: "Bearer",
parameter : Session["Token"].ToString ());
HttpResponseMessage responseMessage = await client.GetAsync ("https://www.googleapis.com/gmail/v1/users/me/messages?q=" + dateFilter);
if (responseMessage.IsSuccessStatusCode) {
var data = responseMessage.Content;
}
try {
responseData = responseMessage.Content.ReadAsStringAsync ().Result;
//This Json Data Converted into List Object
var msgList = JsonConvert.DeserializeObject<Root1> (responseData);
//loop for Fetching EmailMessageData by MessageID
if (msgList.resultSizeEstimate != 0) {
foreach (var msgItem in msgList.messages) {
messageObj.id = msgItem.id;
//Calling API with MessageID Parameter to fetch Respective Message Data
HttpResponseMessage responseMessageList = await client.GetAsync ("https://www.googleapis.com/gmail/v1/users/userId/messages/id?id=" + messageObj.id.ToString () + "&userId=me&format=full");
if (responseMessageList.IsSuccessStatusCode) {
var dataNew = responseMessageList.Content;
var responseDataNew = responseMessageList.Content.ReadAsStringAsync ().Result;
//Converting json string in Object
exampleObj = JsonConvert.DeserializeObject<Example> (responseDataNew);
gmailMessage.Body = exampleObj.snippet;
//fetching Header Values comparing with string to get Data
for (int i = 1; i < exampleObj.payload.headers.Count; i++) {
if (exampleObj.payload.headers[i].name.ToString () == "Date") {
gmailMessage.RecievedDate = exampleObj.payload.headers[i].value;
}
if (exampleObj.payload.headers[i].name.ToString () == "Subject") {
gmailMessage.Subject = exampleObj.payload.headers[i].value;
}
if (exampleObj.payload.headers[i].name.ToString () == "Message-ID") {
gmailMessage.SenderEmailID = exampleObj.payload.headers[i].value;
}
if (exampleObj.payload.headers[i].name.ToString () == "From") {
gmailMessage.SenderName = exampleObj.payload.headers[i].value;
}
}
//Adding This Object Values in GmailMessgage List Object
gmailMessagesList.Add (
new GmailMessage {
Body = exampleObj.snippet,
SenderEmailID = gmailMessage.SenderEmailID,
RecievedDate = gmailMessage.RecievedDate,
SenderName = gmailMessage.SenderName,
Subject = gmailMessage.Subject,
});
}
}
}
} catch (Exception e) {
string errorMgs = e.Message.ToString ();
throw;
}
} catch (Exception e) {
string errorMgs = e.Message.ToString ();
throw;
}
return View (gmailMessagesList);
}
I can fetch Gmail email datewise but it took so much time to fetch. how can I improve my code and performance faster?
The query seems like the most you can do. If you know more information about those emails, like a specific subjects or there always come from the same sender you can try to filter that too, like you would in the Gmail interface.
Other way you would be kind of out of luck. You are limited by the files retrieved from User.messages.list.
If you need to escape from the API limitations maybe trying to retrieve the message other way would be the correct way to go. Considerate creating a small code to retrieve message by the IMAP protocol. Several questions in this topic may help you:
Reading Gmail messages using Python IMAP
Reading Gmail Email in Python
How can I get an email message's text content using Python?
Airwatch documentation is gawdawful. So bear with me.
From Airwatch SDK, how to I get the currently logged in username/user certificate?
It's in the API
//setup authorization profile
var client = new RestClient("https://enterprise.telstra.com/api/mdm");
client.Authenticator=new HttpBasicAuthenticator("#####", "#######");
var request = new RestRequest("devices/search", DataFormat.Json);
request.AddHeader("aw-tenant-code", "##########");
//get the data as json
var response = client.Get(request);
if (response.IsSuccessful)
{
//serialize the data into the Devices[] array RootObject
RootObject ro = new RootObject();
ro = JsonConvert.DeserializeObject<RootObject>(response.Content);
//create a new DataTable with columns specifically required
DataTable dt = new DataTable("tblDevices");
dt.Columns.Add("AssetNumber");
dt.Columns.Add("DeviceFriendlyName");
dt.Columns.Add("IMEI");
dt.Columns.Add("MacAddress");
dt.Columns.Add("Model");
dt.Columns.Add("DeviceType");
dt.Columns.Add("OEMinfo");
dt.Columns.Add("Platform");
dt.Columns.Add("SerialNumber");
dt.Columns.Add("UserEmailAddress");
dt.Columns.Add("UserName");
//iterate through each device data and add it into a DataRow
foreach(Device d in ro.Devices)
{
DataRow dr = dt.NewRow();
dr["UserName"] = d.UserName.ToUpper(); //uppercase the userid
//add the row to the table
dt.Rows.Add(dr);
}
With godly help from the client
AWController.clientInstance().retrieveStoredPublicCertificates { payload, error in
if let _ = error {
return
}
guard let payload = payload as? [String : [PKCS12Certificate]] else {
return
}
processCertificates(payload)
NotificationCenter.default.post(name: .awSDKCeritificatesReceived,
object: payload)
}
I am implementing the DocuSign functionality in my application to sign the PDF.
I am following the below link:
https://www.docusign.com/developer-center/api-overview
We are able to add signature in the PDF while using the steps mentioned in the above link but while calling the same method for second time to signed a new PDF we are getting error message at the line of CreateEnvelope()
Error Response: { "errorCode": "UNSPECIFIED_ERROR", "message":
"Input string was not in a correct format." }
it generate an error while Creating envelop. at this line
EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef);
Below is the code which i use
static string userName = Utility.GetConfigValue("docSignUserName");
static string password = Utility.GetConfigValue("docSignPassword");
static string integratorKey = Utility.GetConfigValue("docSignIntegratorKey");
static string baseURL = "";
public static SignedPDF SignDocument(UserViewModel user, StateViewModel state, string signFilePath, string newFilePath, string controlSign)
{
PdfReader pdfReader = new PdfReader(signFilePath);
PdfReader newpdfReader = new PdfReader(newFilePath);
PdfStamper pdfStamper = new PdfStamper(newpdfReader, new FileStream(HttpContext.Current.Server.MapPath(Utility.GetConfigValue("StateTaxForms")) + "Test.pdf", FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
IList<AcroFields.FieldPosition> fieldPositions = pdfFormFields.GetFieldPositions(controlSign);
try
{
AcroFields.FieldPosition fieldPosition = fieldPositions[0];
// Enter recipient (signer) name and email address
string recipientName = user.FirstName + " " + user.LastName;
string recipientEmail = user.Email;
// instantiate api client with appropriate environment (for production change to www.docusign.net/restapi)
string basePath = Utility.GetConfigValue("docSignInstantiateClient");
// instantiate a new api client
ApiClient apiClient = new ApiClient(basePath);
// set client in global config so we don't need to pass it to each API object
Configuration.Default.ApiClient = apiClient;
string authHeader = "{\"Username\":\"" + userName + "\", \"Password\":\"" + password + "\", \"IntegratorKey\":\"" + integratorKey + "\"}";
Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader);
// we will retrieve this from the login() results
string accountId = null;
// the authentication api uses the apiClient (and X-DocuSign-Authentication header) that are set in Configuration object
AuthenticationApi authApi = new AuthenticationApi();
LoginInformation loginInfo = authApi.Login();
// user might be a member of multiple accounts
accountId = loginInfo.LoginAccounts[0].AccountId;
// Read a file from disk to use as a document
byte[] fileBytes = File.ReadAllBytes(signFilePath);
EnvelopeDefinition envDef = new EnvelopeDefinition();
envDef.EmailSubject = "Please sign this document";
// Add a document to the envelope
Document doc = new Document();
doc.DocumentBase64 = System.Convert.ToBase64String(fileBytes);
doc.Name = "SignedFile.pdf";
doc.DocumentId = "1";
envDef.Documents = new List<Document>();
envDef.Documents.Add(doc);
// Add a recipient to sign the documeent
Signer signer = new Signer();
signer.Name = recipientName;
signer.Email = recipientEmail;
signer.RecipientId = "1";
// must set |clientUserId| to embed the recipient
signer.ClientUserId = "1234";
// Create a |SignHere| tab somewhere on the document for the recipient to sign
signer.Tabs = new Tabs();
signer.Tabs.SignHereTabs = new List<SignHere>();
SignHere signHere = new SignHere();
var height = pdfReader.GetPageSize(1).Height;
signHere.DocumentId = "1";
signHere.RecipientId = "1";
signHere.PageNumber = Convert.ToInt32(fieldPosition.page).ToString();
signHere.XPosition = Convert.ToInt32(fieldPosition.position.Left).ToString();
if (state.Abbreviation == "DC" && controlSign != "Signature of Employee")
{
signHere.YPosition = (height - Convert.ToInt32(fieldPosition.position.Top - 5)).ToString();
}
else
{
signHere.YPosition = (height - Convert.ToInt32(fieldPosition.position.Top + 35)).ToString();
}
if (state.Abbreviation == "NC" && controlSign != "Signature of Employee")
{
signHere.YPosition = (height - Convert.ToInt32(fieldPosition.position.Top + 25)).ToString();
}
signer.Tabs.SignHereTabs.Add(signHere);
envDef.Recipients = new Recipients();
envDef.Recipients.Signers = new List<Signer>();
envDef.Recipients.Signers.Add(signer);
// set envelope status to "sent" to immediately send the signature request
envDef.Status = "sent";
// Use the EnvelopesApi to create and send the signature request
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef);
RecipientViewRequest viewOptions = new RecipientViewRequest()
{
ReturnUrl = Utility.GetConfigValue("docSignReturnURL"),
ClientUserId = "1234", // must match clientUserId set in step #2!
AuthenticationMethod = "email",
UserName = recipientName,
Email = recipientEmail
};
// create the recipient view (aka signing URL)
ViewUrl recipientView = envelopesApi.CreateRecipientView(accountId, envelopeSummary.EnvelopeId, viewOptions);
// Start the embedded signing session!
//var value = System.Diagnostics.Process.Start(recipientView.Url);
SignedPDF signedPDF = new SignedPDF();
signedPDF.URL = recipientView.Url;
signedPDF.EnvelopeID = envelopeSummary.EnvelopeId;
return signedPDF;
}
catch (Exception ex)
{
throw new PDFSignException(ErrorConstants.THERE_WAS_AN_ERROR_WHILE_SIGNING_PDF);
}
finally
{
pdfStamper.Close();
pdfReader.Close();
}
}
Hi CodingDawg this is the JSON
{
"documents": [
{
"documentBase64": "",
"documentId": "1",
"name": "SignedFile.pdf"
}
],
"emailSubject": "Please sign this document",
"recipients": {
"signers": [
{
"clientUserId": "1234",
"email": "sagar.mali#tudip.com",
"name": "Sagar Mali",
"recipientId": "1",
"tabs": {
"signHereTabs": [
{
"documentId": "1",
"pageNumber": "1",
"recipientId": "1",
"xPosition": "192",
"yPosition": "679.968"
}
]
}
}
]
},
"status": "sent"
}
We have removed the base 64 string as the length was not supporting.
Make sure the signHere.XPosition & signHere.YPosition values are passed correctly.
The following statement could evaluate to a decimal value. Make sure it is an integer.
signHere.YPosition = (height - Convert.ToInt32(fieldPosition.position.Top + 25)).ToString();
Troubleshooting Step
Please run envelopeDefinition.ToJson() (Sdk documentation) and make sure the final Json posted to the DocuSign api is correct.
If I send notification to iOS device from FCM console I am getting the message alert on notification center (swipe down from the Top of the screen to view Notification Centre).
didRecievedRemoteNotification Output is :
{
aps = {
alert = "From console";
};
"gcm.message_id" = "0:1470206236110595%b2c76869b2c76869";
"gcm.n.e" = 1;
"google.c.a.c_id" = 2979094970349938289;
"google.c.a.e" = 1;
"google.c.a.ts" = 1470206236;
"google.c.a.udt" = 0;
}
But if send notification to iOS device I am sending using api from my server I am not receiving message alert on notification center (swipe down from the Top of the screen to view Notification Centre).
didRecievedRemoteNotification Output is :
{
"collapse_key" = "do_not_collapse";
from = 67981113117;
message = "alert from api";
time = "03-08-2016 12:44:53";
}
My API code is which is in C#:
string RegIDs = "some id";
var appID = "some id";
var SenderID = "some id";
var value = Text1.Text;
WebRequest tRequest;
tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "POST";
tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
tRequest.Headers.Add(string.Format("Authorization: key={0}", appID));
tRequest.Headers.Add(string.Format("Sender: id={0}", SenderID));
//Data_Post Format
// string postData = "{'collapse_key' : 'demo', 'registration_id': [ '" + regId + "' ],
//'data': {'message': '" + Label1.Text + "'},'time_to_live' : '3' }";
//json for android
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
+ value + "&data.time=" + System.DateTime.Now.ToString() + "®istration_id=" + RegIDs + "";
Console.WriteLine(postData);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = (WebResponse)tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
Label3.Text = sResponseFromServer; //printing response from GCM server.
tReader.Close();
dataStream.Close();
tResponse.Close();
Another alternative in order to test push notifications without using Firebase console is using Postman. Attached two images with configuration details.
Image 1: Set notification payload
Image 2: Set request headers ( Content-Type and Authorization )
Firebase push notification endpoint: https://fcm.googleapis.com/fcm/send