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");
}
}
}
Related
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;
}
}
}
I am using Visual studio. This is for Asp.net web application (.net framework)
this solution as a webcore application is acceptable as well.
I would like to be able to enter the information for message and to phone number dynamically , but i dont know how to "pause" the program so that this can happen. I understand the dynamic part, and can use Javascript to do that,
Basically what I want is an app that brings up a webpage where the end user enters the to number and the message, and then clicks send to send.
I thought it would be simple, but not so much :(
I have the quick start code for C# as -
// Install the C# / .NET helper library from twilio.com/docs/csharp/install
using System;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
class Program
{
static void Main(string[] args)
{
// Find your Account Sid and Token at twilio.com/console
const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const string authToken = "your_auth_token";
TwilioClient.Init(accountSid, authToken);
var message = MessageResource.Create(
body: "Join Earth's mightiest heroes. Like Kevin Bacon.",
from: new Twilio.Types.PhoneNumber("+15017122661"),
to: new Twilio.Types.PhoneNumber("+15558675310")
);
Console.WriteLine(message.Sid);
}
}
Okay I'm going to assume you want to send SMS. Further, I'm going to assume you're using Asp.Net MVC. Twilio voice is a little bit more complex, as Twilio calls back several times to get voice scripts and update statuses. More complex if you need phone tree behavior.
SMS Callbacks happen more than once too, but they're calling the same callback URL over and over, nothing fancy there.
The flow should look like this:
Web interface -> Asp.Net MVC Controller Action -> Database -> Twilio
I'll leave the web interface to you, and give some examples of the backend stuff.
You'll want a database, with one table 'Message'
Message should have these columns (at a minimum, you may need more):
message_id_pk
twilio_sid (nullable)
message_content (160 character limit if you want to keep messages in one SMS segment, this has considerations on operating cost)
status (nullable)
recipient_phone
Controller Action:
[Authorize] //assuming you'll want to have users authenticate before they can send the sms
[RequireHttps]
public async Task<ActionResult> SendSMS(
[Bind(Include = "message_id_pk, message_content, recipient_phone"] Message message)
{
db.Messages.Add(message);
TwilioSmsSender.SendSMS(message);
return RedirectToAction("Success");
}
And in TwilioSender.cs
public static void SendSMS(Message message)
{
const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const string authToken = "your_auth_token";
TwilioClient.Init(accountSid, authToken);
var message = MessageResource.Create(
body: message.message_content,
from: new Twilio.Types.PhoneNumber("+15017122661"), //note: you can let your Twilio Messaging service handle the phone number, I recommend you look into that
to: new Twilio.Types.PhoneNumber(message.recipient_phone)
statusCallback: new Uri(TwilioCallBackController.SMSCallBackURL)
);
message.twilio_sid = message.Sid;
db.SaveChanges();
}
And in TwilioCallBackController.cs (You need to handle callbacks from Twilio here)
[ValidateTwilioRequest]
public ActionResult TwilioSMSCallback()
{
string sid = Request.Form["SmsSid"];
List<Message> msg = db.Message.Where(x=> x.twilio_sid == sid).ToListAsync();
if(msg.Count > 0)
{
Message message = msg.First();
message.status = Request.Form["SmsStatus"];
}
}
I am in the "verify integration" stage of setting up SendGrid and am using the code below to send my first email. I have copied the code from their instructions:
// using SendGrid's C# Library
// https://github.com/sendgrid/sendgrid-csharp
using SendGrid;
using SendGrid.Helpers.Mail;
using System;
using System.Threading.Tasks;
using System.Threading;
namespace Example
{
internal class Example
{
private static async Task Main()
{
await Execute();
Thread.Sleep(10000);
}
static async Task Execute()
{
var apiKey = "myapikey";
var client = new SendGridClient(apiKey);
var from = new EmailAddress("test#example.com", "Example User");
var subject = "Sending with SendGrid is Fun";
var to = new EmailAddress("test#example.com", "Example User");
var plainTextContent = "and easy to do anywhere, even with C#";
var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var response = await client.SendEmailAsync(msg);
}
}
}
I am running this in a console app targeting netcoreapp2.0, from a mac. The code runs with no errors; its says "Accepted", but I never receive an email through SendGrid web console. What am I doing wrong?
Edit: P.S. I'm running this from my local machine, not a web server.
I am currently working with the Braintree API to try and upload a database of users as customers to their server using their gateway functions. Right now I can create a customer through our C# code.
But any time I try and call the request a second time when we get to the next stage of the loop I get an unhandled web exception on this line :
Result<Customer> result = gateway.Customer.Create(request);
An unhandled exception of type 'System.Net.WebException' occurred in Braintree-2.59.0.dll
Additional information: The request was aborted: Could not create SSL/TLS secure channel.
I've changed the code so that we are setting up our gateway connection each time inside our foreach loop but still it errors out. We speculated that we might need to tear down the connection and reinitialize but I can't find any documentation regarding this.
Any ideas?
EDIT: Here is a test case that reproduces the error, you will need to have a sandbox account with your own MerchantId, PublicKey, and PrivateKey to test. I've also already tested creating customers who have the identical Company name and that works fine, Braintree will still create a new account with a unique ID for me so that isn't the issue.
using Braintree;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace BraintreeFailExample
{
class Program
{
static void Main(string[] args)
{
string companyName = "Test Company";
for (int i = 0; i < 3; i++)
{
// Initialization information (Replace with AppConfig settings)
var gateway = new BraintreeGateway
{
Environment = Braintree.Environment.SANDBOX,
MerchantId = "Insert Sandbox MerchantId here",
PublicKey = "Insert Sandbox PublicKey here",
PrivateKey = "Insert Sandbox PrivateKey here"
};
// setup data for a customer request object
var request = new CustomerRequest
{
Company = companyName
};
// send the request to the Braintree gateway
// Braintree doesn't care about duplicate company requests for new customer
Result<Customer> result = gateway.Customer.Create(request);
}
}
}
}
I was able to resolve this issue. It turns out we had firewall issues that were preventing us from receiving further responses after the first.
This seems like a simple question. I'm using a server-side app written in C# to do a simple api key connection to youtube from a Windows Server 2008 server. When I run it without an ip referer restriction it works fine. So I set up an ip referer restriction. I ran ipconfig on my server and used the main ip address listed, and I got an ipreferer blocked error. I also tried the other ip addresses listed. I've included a screenshot of my ipconfig with notes.
So I know the program is passing youtube some referer ip, and it's not the right one. How can I tell what the referer ip it is passing?
The code is below:
/*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
namespace Google.Apis.YouTube.Samples
{
/// <summary>
/// YouTube Data API v3 sample: search by keyword.
/// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
/// See https://code.google.com/p/google-api-dotnet-client/wiki/GettingStarted
///
/// Set ApiKey to the API key value from the APIs & auth > Registered apps tab of
/// https://cloud.google.com/console
/// Please ensure that you have enabled the YouTube Data API for your project.
/// </summary>
internal class Search
{
List<string> HTMLText = new List<string>();
Boolean openDiv = true;
string mainVideoTarget = "main_video";
string menuDiv = "video_menu_images";
string thumbnailDiv = "thumb";
[STAThread]
static void Main(string[] args)
{
try
{
new Search().Run().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("Error: " + e.Message);
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private async Task Run()
{
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "API_KEY_HERE",
ApplicationName = this.GetType().ToString()
});
var channelsListRequest = youtubeService.Channels.List("contentDetails");
channelsListRequest.Id = "CHANNEL_ID_HERE";
// Retrieve the contentDetails part of the channel resource for the authenticated user's channel.
var channelsListResponse = await channelsListRequest.ExecuteAsync();
//a bunch of stuff down here to read the data from youtube
//write it into an html file which I left out because it's irrelevant
}
}
}
ipconfig is returning the internal IP address. Try a site like http://whatismyip.com and use the IP address that site returns as the Referer address.
Thanks for the help and suggestions, especially pointing out that the ip from ipconfig is not what the router is passing. I know about whatsmyip but I wasn't 100% sure if that's the same ip that a console app would be using. Turns out it was. I was able to find the ip passed by running this simple little script:
using System;
using System.IO;
using System.Net;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest htwr = (HttpWebRequest)WebRequest.Create("[any url that can get an http connection]");
WebResponse response = htwr.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
response.Close();
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
One of the variables returned is REMOTE_ADDR which is what I was looking for.