Using twilio c# client to pass twilio response back - c#

I am using the twilio c# wrapper and am able to receive communication from twilio. I am having trouble responding back to twilio with a response and having twilio recognize it. Currently I am trying to respond with a TwilioResponse. Anyone have a good example? This is a WebApi self hosted windows service.
ex. TwilioResponse().Message("ok");

I have used Same web API you can use the below menioned code but First you have to configure your APP in Twilio UserAccount.
public class WelcomeController : ApiController
{
public HttpResponseMessage Post(VoiceRequest request)
{
var response = new TwilioResponse();
response.Say("Welcome to Dhaval demo app. Please enter your 5 digit ID.");
response.Gather(new { numDigits = 5, action = string.Format("/api/Authenticate") });
return this.Request.CreateResponse(HttpStatusCode.OK, response.Element, new XmlMediaTypeFormatter());
}
}
When I press the 5 digit no then it will lend to Authetication Controller it' look like
public HttpResponseMessage Post(VoiceRequest request)
{
var response = new TwilioResponse();
var validIds = new List<string> { "12345", "23456", "34567" };
var userId = request.Digits;
var authenticated = validIds.Contains(userId);
if (!authenticated)
{
response.Say("You entered an invalid ID.");
response.Hangup();
}
else
{
response.Say("ID is valid.");
response.Redirect(string.Format("/api/Name?userId={0}", userId));
}
return this.Request.CreateResponse(HttpStatusCode.OK, response.Element, new XmlMediaTypeFormatter());
}
and it's work fine in my side, once again check it properly you have given the correct AuthToken
Cheers

After tinkering for a while, this seems to do the trick.
var twiml = new TwilioResponse().Message("test");
return TwilioResponse(twiml);
private HttpResponseMessage TwilioResponse(TwilioResponse twilioResponse)
{
return new HttpResponseMessage()
{
Content = new StringContent(twilioResponse.ToString(), Encoding.UTF8, "text/xml"),
StatusCode = System.Net.HttpStatusCode.OK
};
}

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;
}
}
}

Calling Microsoft Graph API to create an event, What am I doing wrong?

I've been trying to call Microsoft Graph API for creating events, however I've not been able to do it.
Context: I have a Web MVC application (C#) already in production, with the "common" authentication method, reading a database of users. Recently the customer asked me the possibility to create Microsoft Teams Meetings from the application and also those created meetings have to be scheduled in the Microsoft Teams Calendar with the "Join" button to enter the meeting.
I already configured the API permissions, client secret and used the other properties like tenant, user id, etc from the Azure Portal, I'm sharing a screenshot of my configuration. I'm doing the "Get access on behalf of a user" process.
API Permissions:
Permissions image
Taking the example of the authorize endpoint from the docs, of course I'm replacing the values with my own info
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
client_id=11111111-1111-1111-1111-111111111111
&response_type=code
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&response_mode=query
&scope=offline_access%20user.read%20mail.read
&state=12345
Here is my code to Receive the code once the user authorizes the permissions, I'm just storing the value in a static class for testing
public ActionResult ReceiveCode(string code)
{
AuthenticationConfig.Code = code;
//this.Code = code;
return RedirectToAction("Index");
}
Once I got the Auth code, I'm using it to create the event with the generated token, also I already verified that the token contains the permissions given in the Azure Portal.
This is the input for the /events endpoint
var json = JsonConvert.SerializeObject(new
{
subject = "Let's go for lunch",
body = new
{
contentType = "HTML",
content = "Does noon work for you?"
},
start = new
{
dateTime = "2017-04-15T12:00:00",
timeZone = "Pacific Standard Time",
},
end = new
{
dateTime = "2017-04-15T14:00:00",
timeZone = "Pacific Standard Time"
},
location = new
{
displayName = "Harry's Bar",
},
attendees = new List<Attendee>()
{
new Attendee
{
EmailAddress = new EmailAddress
{
Address = "mymail#whatever.com",
Name = "Foo Bar"
},
Type = AttendeeType.Required
}
},
allowNewTimeProposals = true,
isOnlineMeeting = true,
onlineMeetingProvider = "teamsForBusiness",
});
This is the complete method, for the json value, please see the json above. I also tried with the "me" url but it does not work either.
public async Task<ActionResult> OnlineMeeting()
{
try
{
var httpClient = new HttpClient();
var paramsDictionary = new Dictionary<string, string>();
paramsDictionary.Add("client_id",AuthenticationConfig.ClientId);
paramsDictionary.Add("scope", "Calendars.ReadWrite");
paramsDictionary.Add("code", AuthenticationConfig.Code);
paramsDictionary.Add("redirect_uri", "https://localhost:44379/Meeting/Reunion/ReceiveCode");
paramsDictionary.Add("grant_type", "authorization_code");
paramsDictionary.Add("client_secret", AuthenticationConfig.ClientSecret);
var url = string.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", "tenant");
var response = await httpClient.PostAsync(url, new FormUrlEncodedContent(paramsDictionary));
if (response.IsSuccessStatusCode)
{
var jsonResponse = await response.Content.ReadAsStringAsync();
var jsonResult = JsonConvert.DeserializeObject(jsonResponse) as JObject;
var accessToken = jsonResult.GetValue("access_token").ToString();
httpClient = new HttpClient();
var json = JsonConvert.SerializeObject(new { });
var defaultRequestHeaders = httpClient.DefaultRequestHeaders;
if (defaultRequestHeaders.Accept == null || !defaultRequestHeaders.Accept.Any(m => m.MediaType == "application/json"))
{
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
defaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var data = new StringContent(json);
response = await httpClient.PostAsync("https://graph.microsoft.com/v1.0/users/{user id}/events", data);
if (response.IsSuccessStatusCode)
{
// Nice
}
else
{
Console.WriteLine($"Failed to call the web API: {response.StatusCode}");
string content = await response.Content.ReadAsStringAsync();
}
}
else
{
Console.WriteLine($"Failed to call the web API: {response.StatusCode}");
string content = await response.Content.ReadAsStringAsync();
}
}
catch (Exception ex)
{
}
return View();
}
I'm able to the get the token, but when trying to create the event returns the next response.
{
"error": {
"code": "ResourceNotFound",
"message": "Resource could not be discovered.",
"innerError": {
"date": "2021-08-31T22:58:18",
"request-id": "c5c07afa-fa89-4948-a9f8-f80ca4cbafc3",
"client-request-id": "c5c07afa-fa89-4948-a9f8-f80ca4cbafc3"
}
}
}
Am I missing something? Maybe the wrong endpoint?
Please, help.
Thanks in advance.

Client unable to read respose from API

I created
Web api
Client.
I am trying to make a simple get request from client to Api
When I debug I can see that my client sends request to web api, web api receives it fine and returns a response. But seems like the response never reaches my client and client keeps waiting forever.
I tried using Postman tool to my Web api and received response fine in json form
I also tried using Fiddle to see where things are going wrong. It showed a downward arrow indicating that the Response was being read from the server. It did not show any error code.
Can someone please suggest what I could be doing wrong.
API:
// GET: api/Account
public IEnumerable<Account> Get()
{
//return new string[] { "value1", "value2" };
Account a = new Account(100, "RES", new Customer(1, "K", "M"), new Premise(1, "2225", "City A", "Ohio"));
Account a1 = new Account(101, "RES", new Customer(1, "R", "M"), new Premise(1, "Prior Road", "Texas", "US"));
Account a2 = new Account(102, "RES", new Customer(1, "A", "M"), new Premise(1, "estern Road", "NY", "US"));
List<Account> list = new List<Account>();
list.Add(a);
list.Add(a1);
list.Add(a2);
return (list);
}
CLIENT :
public async Task<List<Account>> SelectAllAccounts()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://localhost:62617/api/");
//HTTP GET
var response = await client.GetAsync("Account");
var myInstance = JsonConvert.DeserializeObject<Account>(await response.Content.ReadAsStringAsync());
List<Account> a= null;
a.Add(myInstance);
return a;
}
}
Some typos exist in your simple example, which should be modified:
// GET: api/Account
public List<Account> Get()
{
Account a = new Account(100, "RES", new Customer(1, "K", "M"), new Premise(1, "2225", "City A", "Ohio"));
// ...
// ... Your Code here
// ...
list.Add(a2);
return list;
}
And, you also need to modify your Client-Side:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:62617/");
HttpResponseMessage response = client.GetAsync("api/Account").Result;
string _content = await response.Content.ReadAsStringAsync();
List<Account> myInstance = JsonConvert.DeserializeObject<List<Account>>(_content);
return myInstance;
}
You can return myInstance or return View(myInstance), or return it as JsonResult, whichever suits your need. For instance:
return Json(new { Status = 200, LIST = myInstance}, JsonRequestBehavior.AllowGet);
However, sometimes it may be better to return _content as string and let De-serialization be done for the last moment.
For more info, following are simple Nice examples on how to create and consume Rest APIs in ASP.Net MVC framework:
https://www.c-sharpcorner.com/article/create-simple-web-api-in-asp-net-mvc/
https://www.c-sharpcorner.com/article/consuming-asp-net-web-api-rest-service-in-asp-net-mvc-using-http-client/
https://www.tutorialsteacher.com/webapi/consume-web-api-get-method-in-aspnet-mvc
Instead of returning IEnumerable I suggest return HttpResponseMessage and also set ContentType to application/json.
So your api will be like this,
HttpResponseMessage httpResponseMessage = this.Request.CreateResponse<List<Account>>(HttpStatusCode.OK, list);
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return httpResponseMessage;
In Client code you have to deserialize to List as you are returning collection instead of just Account. So changes in Client code will be
var myInstance = JsonConvert.DeserializeObject<List<Account>>(await response.Content.ReadAsStringAsync());
It's tried and tested.
:-)

Office 365 REST API - Adding a Contact with JSON in C#

I am trying to use the Office API to sync contacts from a few different sources. I have been having a problem trying to make a POST request with my JSON object to create a new contact. I have been looking at the MSDN pages but I feel like I should clarify I’m relatively new to C#, this is my first time trying to use REST protocols, and async methods in C#.
I have my code below, I tried to create a class that will add a new contact with a hard coded JSON string. I have tried a few various ways of trying to complete this request. Every request I have attempted gives me a 401 or 400 Error. I left a couple lines that I felt were closest to the solution but if those are not on the right track I have no problem trying something else. There is also a function that I believe could be useful but I couldn’t really find documentation on how to use it:
await client.Me.Contacts.AddContactAsync();
Again I said I am pretty new to this so if there is a way to create an IContact item from the JSON and use the above method or to just pass the JSON directly either would be extremely useful. Even links to documentation that could be useful I would love to see. I’m a pretty stuck on this problem I’ve never posted a question before but I’m stumped on this.
Below is the documentation for the Contacts API maybe it will make more sense to you guys than me.
http://msdn.microsoft.com/en-us/library/office/dn792115(v=office.15).aspx
If anybody can figure out how to make a post request from that JSON it will be much appreciated.
using Microsoft.Office365.Exchange;
using Microsoft.Office365.OAuth;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows;
using System.Net.Http;
using System.Net.Http.Headers;
namespace ContactSynchronization
{
class OfficeAPIWrite
{
private static string odata = "#odata.type";
private static string type = "#Microsoft.Exchange.Services.OData.Model.Contact";
const string ServiceResourceId = "https://outlook.office365.com";
static readonly Uri ServiceEndpointUri = new Uri("https://outlook.office365.com/ews/odata/Me/Contacts");
static string _lastLoggedInUser;
static DiscoveryContext _discoveryContext;
public static async Task OfficeWrite()
{
try
{
var client = await EnsureClientCreated();
string json = new JavaScriptSerializer().Serialize(new
{
odata = type,
GivenName = "Mara",
Surname = "Whitley",
EmailAddress1 = "mara#fabrikam.com",
BusinessPhone1 = "425-555-1313",
Birthday = "1974-07-22T07:00:00Z"
});
try
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, ServiceEndpointUri);
request.Content = new StringContent(json);
request.Headers.Add("Accept", "application/json;odata=minimalmetadata");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
catch (System.Net.WebException e)
{
MessageBox.Show(e.ToString());
}
}
catch (Microsoft.Office365.OAuth.AuthenticationFailedException)
{
MessageBox.Show("Authentication Failed Exception was thrown");
}
}
public static async Task<ExchangeClient> EnsureClientCreated()
{
if (_discoveryContext == null)
{
_discoveryContext = await DiscoveryContext.CreateAsync();
}
var dcr = await _discoveryContext.DiscoverResourceAsync(ServiceResourceId);
_lastLoggedInUser = dcr.UserId;
return new ExchangeClient(ServiceEndpointUri, async () =>
{
return (await _discoveryContext.AuthenticationContext.AcquireTokenSilentAsync(ServiceResourceId, _discoveryContext.AppIdentity.ClientId, new Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier(dcr.UserId, Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifierType.UniqueId))).AccessToken;
});
}
public static async Task SignOut()
{
if (string.IsNullOrEmpty(_lastLoggedInUser))
{
return;
}
if (_discoveryContext == null)
{
_discoveryContext = await DiscoveryContext.CreateAsync();
}
await _discoveryContext.LogoutAsync(_lastLoggedInUser);
}
}
}
Well I guess I figured out a work around. This uses a ContactObject that I created and newtonsoft's JSON serializer. I was hoping to see an example of the microsoft ExchangeClient in action, the only reason I am posting this is to help others that might have similar issues posting to the office API, the below code will run successfully. I'm still looking though if anybody can show me the correct way to use the ExchangeClient functions.
// your request must include these, and a given name,
// everything else is optional
private const string odata = "#odata.type";
private const string type = "#Microsoft.Exchange.Services.OData.Model.Contact";
public static async Task CreateContact(ContactObject officeContact, string userEmail, string userPassword)
{
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, new Uri("https://outlook.office365.com/ews/odata/Me/Contacts"));
// Add the Authorization header with the basic login credentials.
var auth = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(userEmail + ":" + userPassword));
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Authorization", auth);
var createResponse = new JObject();
createResponse[odata] = type; // this needs to be here for this to work
if (!String.IsNullOrEmpty(officeContact.officeDisplayName)) createResponse["DisplayName"] = officeContact.officeDisplayName;
if (!String.IsNullOrEmpty(officeContact.officeGivenName)) createResponse["GivenName"] = officeContact.officeGivenName;
if (!String.IsNullOrEmpty(officeContact.officeMiddleName)) createResponse["MiddleName"] = officeContact.officeMiddleName;
if (!String.IsNullOrEmpty(officeContact.officeNickName)) createResponse["NickName"] = officeContact.officeNickName;
if (!String.IsNullOrEmpty(officeContact.officeSurname)) createResponse["Surname"] = officeContact.officeSurname;
if (!String.IsNullOrEmpty(officeContact.officeEmailAddress1)) createResponse["EmailAddress1"] = officeContact.officeEmailAddress1;
if (!String.IsNullOrEmpty(officeContact.officeEmailAddress2)) createResponse["EmailAddress2"] = officeContact.officeEmailAddress2;
if (!String.IsNullOrEmpty(officeContact.officeEmailAddress3)) createResponse["EmailAddress3"] = officeContact.officeEmailAddress3;
if (!String.IsNullOrEmpty(officeContact.officeHomePhone1)) createResponse["HomePhone1"] = officeContact.officeHomePhone1;
if (!String.IsNullOrEmpty(officeContact.officeHomePhone2)) createResponse["HomePhone2"] = officeContact.officeHomePhone2;
if (!String.IsNullOrEmpty(officeContact.officeBusinessPhone1)) createResponse["BusinessPhone1"] = officeContact.officeBusinessPhone1;
if (!String.IsNullOrEmpty(officeContact.officeBusinessPhone2)) createResponse["BusinessPhone2"] = officeContact.officeBusinessPhone2;
if (!String.IsNullOrEmpty(officeContact.officeMobilePhone1)) createResponse["MobilePhone1"] = officeContact.officeMobilePhone1;
if (!String.IsNullOrEmpty(officeContact.officeOtherPhone)) createResponse["OtherPhone"] = officeContact.officeOtherPhone;
if (!String.IsNullOrEmpty(officeContact.officeId)) createResponse["Id"] = officeContact.officeId;
if (!String.IsNullOrEmpty(officeContact.officeCompanyName)) createResponse["CompanyName"] = officeContact.officeCompanyName;
request.Content = new StringContent(JsonConvert.SerializeObject(createResponse));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.SendAsync(request);
try
{
response.EnsureSuccessStatusCode();
}
catch (System.Net.WebException)
{
MessageBox.Show("BAD REQUEST");
}
}

C# OAuthWebSecurity Google Provider URL?

I've got an existing C# project with the following POST method:
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
}
Which uses:
OAuthWebSecurity.Login(provider, ...);
I'm kinda new to OAuth, and haven't done anything with it in this C# project. I do however implemented Google-authorization on an Android App, and I want to use the following class/method for the HttpPost:
public class TaskPostAPI extends AsyncTask<String, Void, String>
{
GoogleApiClient googleAPI;
public TaskPostAPI(GoogleApiClient googleAPI){
this.googleAPI = googleAPI;
}
#Override
protected String doInBackground(String... urls){
String response = "";
for(String url : urls){
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
try{
List<NameValuePair> nvPairs = new ArrayList<NameValuePair>(2); //(3);
//nvPairs.add(new BasicNameValuePair("personName", Plus.PeopleApi.getCurrentPerson(googleAPI).getDisplayName()));
//nvPairs.add(new BasicNameValuePair("personGooglePlusProfile", Plus.PeopleApi.getCurrentPerson(googleAPI).getUrl()));
//nvPairs.add(new BasicNameValuePair("personEmail", Plus.AccountApi.getAccountName(googleAPI)));
nvPairs.add(new BasicNameValuePair("provider", ???));
URL u = new URL(url);
nvPairs.add(new BasicNameValuePair("returnUrl", u.getProtocol() + "://" + u.getHost()));
post.setEntity(new UrlEncodedFormEntity(nvPairs));
HttpResponse execute = client.execute(post);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while((s = buffer.readLine()) != null)
response += s;
}
catch(Exception ex){
ex.printStackTrace();
}
}
return response;
}
}
So my question: What should I put at the POST-method's ???. So what is the Provider? In my Android App I log in using Google, and got the GoogleApiClient and Person (com.google.android.gms.plus.model.people.Person).
At this website I see the following url: https://accounts.google.com/o/oauth2/auth. Is this the url I should use as provider? Or should I add parameters to this url? Or should I use a completely different string as provider?
PS: If someone can send me a link to a list of provider-urls (like Google's, Facebook's, Twitter's, etc.) and how to use them for the C# OAuthWebSecurity I would appreciate it.
Thanks in advance for the responses.
Ok it turns out it was very simple.. The provider is just "Google", nothing more, nothing less.. This provider name I found at the RegisterClient method in de C# project:
OAuthWebSecurity.RegisterClient(client, "Google", extraData);
Now the POST works, except for the message "The required anti-forgery cookie "__RequestVerificationToken" is not present.", but at least I can continue. And adding a Cookie to a HttpPost isn't that hard I believe when using a CookieManager.

Categories

Resources