How to count the POST request in bytes in c#? - c#

I am using POST method to send the SMS using PLIVO but the problem is I need to know the Request bytes before sending from another tool which is Arduino . I could see in the Response debugger that Request.ContentLenght is 156 but this is not correct when we are supplying the bytes in Arduino
Please check the below code for Reference I need to know the Request with Payload size in bytes
using Plivo;
using Plivo.API;
using RestSharp;
using System;
using System.Collections.Generic;
namespace PlivoSMSApp
{
class Program
{
static void Main(string[] args)
{
Program obj = new Program();
bool isSMSSent = obj.SendSms("+91852762678", "+420603797597", "Send SMS using Plivo");
}
public bool SendSms(string from, string to, string text)
{
string authId = "TestAuthID";
string autoToken = "TestAuthToken";
RestAPI plivo = new RestAPI(authId, autoToken);
IRestResponse resp = plivo.send_message(new Dictionary<string, string>()
{
{ "src", ""+from+"" }, // Sender's phone number with country code
{ "dst", ""+to+"" }, // Receiver's phone number with country code
{ "text", ""+text+"" }, // Your SMS text message
// To send Unicode text
// {"text", "こんにちは、元気ですか?"} // Your SMS text message - Japanese
// {"text", "Ce est texte généré aléatoirement"} // Your SMS text message - French
{ "url", "http://google.com/delivery_report"}, // The URL to which with the status of the message is sent
{ "method", "POST"} // Method to invoke the url
});
if (!String.IsNullOrEmpty(resp.ErrorMessage))
return false;
return true;
}
}
}

Related

How to remove characters from a received request body

I was trying to develop an API to receive GPS data from an IOT device. Below which is the data coming from the device.
O||GPS[ {"GPSTime": "01/09/2021 02:34:03", "Coordinates": "0.000000", "RegisterNo": "144"} ]
I have created an API as mentioned below. When I post data to this API its giving bad request because of invalid json format. Need to know how to remove characters from a received request body and how to take the data only from inside curly bracket.
public class GPSController : ApiController
{
[HttpPost]
[Route("GPSData")]
// public HttpResponseMessage Post([FromBody]GPSModel gPSData)
public HttpResponseMessage Post([FromBody]GPSData gPSData)
{
using (DBEntities entities = new DBEntities())
{
var ins = new GPSData();
ins.Coordinates= gPSData.Coordinates;
ins.GPSTime = gPSData.GPSTime;
ins.UpdatedTime = DateTime.Now;
entities.GPSDatas.Add(ins);
entities.SaveChanges();
var message = Request.CreateResponse(HttpStatusCode.Created, gPSData);
message.Headers.Location = new Uri(Request.RequestUri + gPSData.RegisterNo.ToString());
return message;
}
}
}

FCM notification sent by FirebaseAdmin in C# cannot be received

I am trying to send FCM notification to a particular device after some data is saved to database. However, the notification cannot be received by my mobile app running in Android emulator and built with Flutter.
I tested the same registration token from FCM console and the notification can be received.
Here is my implementation in my C#
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace MyNeighbours.Server.Infrastructure.Services
{
public class FirebaseService : IFirebaseService
{
public FirebaseService()
{
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "firebase-private-key.json")),
});
}
public async Task<string> SendNotification(IEnumerable<string> fcmRegistrationTokens, string title, string body)
{
Message message = new Message()
{
Token = "some valid token",
Data = new Dictionary<string, string>()
{
{"title", title},
{"body", body},
},
};
var response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
return response;
}
}
}
Every time when I send a notification, response always shows succeeded with a message id. I can also confirm the private key json file is loaded.
Can anyone please help? Thank you
try to add Notification in Message{} and set sound and priority:
Notification = new Notification()
{
Title = Title,
Body = Body
},
Android = new AndroidConfig()
{
Notification = new AndroidNotification()
{
Sound = "default",
Priority = NotificationPriority.MAX
}
},
Apns = new ApnsConfig()
{
Aps = new Aps()
{
Sound = "default"
}
}

How to send a json object instead of a string with Azure Client SDK

I'm struggling with creating a message from a device to the IotHub in the correct format.
I'm using the Azure Client SDK (Microsoft.Azure.Devices.Client)
For better understanding lets start with a small example, we have the following string:
var TableName = "table01";
var PartitionKey = "key01";
string messagePayload = $"{{\"tablename\":\"{TableName}\",\"partitionkey\":\"{PartitionKey}\"}}";
( Taken from the example Send device to cloud telemetry) we create an eventMessage
using var eventMessage = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(messagePayload))
{
ContentEncoding = Encoding.UTF8.ToString(),
ContentType = "application/json"
};
And then send it to the Cloud:
Console.WriteLine(messagePayload);
await deviceClient.SendEventAsync(eventMessage);
Output from the writeline, which is what I wanted in the first place:
{"tablename":"table01","partitionkey":"key01"}
What I can see in the shell after following the answer about watching incoming IotHub Messages:
{
"event": {
"origin": "WinSensorTest",
"module": "",
"interface": "",
"component": "",
"payload": "{\"tablename\":\"table01\",\"partitionkey\":\"key01\"}"
}
}
The Problem is, that I want it to either look like the code below or completely without the "event" etc, just the string above.
{
"event":{
"origin":"WinSensorTest",
"module":"",
"interface":"",
"component":"",
"payload":{
"tablename":"table01",
"partitionkey":"key01"
}
}
}
Where did I go wrong, how can the payload be correct json format?
Edit:
I just tried the same in Java, with the same result. Why does this not work, or is the data seen in the shell not correctly parsed?
If you create a proper Json object first it works and also shows up correct in the shell - interestingly only for this c# project, I tried doing the same in Java on Android and the same wierd formatting stuff still happens even after making an object with gson.
For the solution:
class JsonMessage
{
public string tablename { get; set; }
public string partitionkey { get; set; }
}
And then Used JsonMessage and JsonConvert to get the desired payload.
JsonMessage newMsg = new JsonMessage()
{
tablename = "table01",
partitionkey = "key01",
};
string payload = JsonConvert.SerializeObject(newMsg);
using var eventMessage = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(payload))
{
ContentEncoding = Encoding.UTF8.ToString(),
ContentType = "application/json"
};

Send recording by mail to recipients in twilio voice call

I want to send recording by mail to recipients in twilio voice call when call completed. Can anyone please suggest how to achieve it?
I have got the solution, we can achieve this by setting RecordingStatusCallback while receiving or making call and then handle RecordingStatusCallback, send the recording to recipient according to requirement as:
public CallResource MakeOutboundPhoneCallsAsync(OutgoingCallRequest request, string accountSid, string authToken, Guid userId)
{
try
{
TwilioClient.Init(accountSid, authToken);
List<string> statusCallbackEvent = new List<string> { "answered", "completed" };
CallResource response =
CallResource.Create(
url: new Uri("http://demo.twilio.com/docs/voice.xml"),
to: new PhoneNumber(request.ToPhoneNumber),
from: new PhoneNumber(request.FromPhoneNumber),
method: Twilio.Http.HttpMethod.Get,
record: request.Record,
recordingStatusCallback: baseUrl + "/api/Twilio/OutboundCalls/RecordingStatusCallback",
recordingStatusCallbackMethod: Twilio.Http.HttpMethod.Post
);
return response;
}
catch (Exception e)
{
throw e;
}
}
and then handle call back as in your controller:
[HttpPost("RecordingStatusCallback")]
public IActionResult RecordingStatusCallback()
{
//Get callback values here and write code To send email
}

Twilio is sending multiple messages to the same number

I am trying to learn how to use Twilio to send SMS, and I am using the sample code from the tutorials. When I run the code, it is sending the message to my phone at least twice. Am I missing something?
Here is the C# code:
using System;
using System.Collections.Generic;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace Quickstart
{
class SmsSender
{
static void Main(string[] args)
{
// Find your Account Sid and Auth Token at twilio.com/user/account
const string accountSid = "xxxxxxxxxxxxxxxxxxxxxxx";
const string authToken = "xxxxxxxxxxxxxxxxxxxxxx";
// Initialize the Twilio client
TwilioClient.Init(accountSid, authToken);
// Send a new outgoing SMS by POSTing to the Messages resource
MessageResource.Create(
from: new PhoneNumber("XXXXXXXXX"), // From number, must be an SMS-enabled Twilio number
to: new PhoneNumber("XXXXXXXXX"), // To number, if using Sandbox see note above
// Message content
body: $"This is a test.");
Console.WriteLine($"Sent message to Andrew");
}
}
}

Categories

Resources