I am trying to send text message to phone. Can someone tell me why my return statement is not working? If i write only string message in my return statement then it shows that message but if i use below mentioned return statement it doesn't work. Any suggestions?
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Twilio;
using Twilio.AspNet.Mvc;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace TwilioSendSMS.Controllers
{
public class SMSController : TwilioController
{
// GET: SMS ----- outbound----
public ActionResult SendSms()
{
// Find your Account Sid and Auth Token at twilio.com/user/account
const string accountSid = "ACxxxxxxxxx";
const string authToken = "71xxxxxxxxxx";
// Initialize the Twilio client
TwilioClient.Init(accountSid, authToken);
// make an associative array of people we know, indexed by phone number
var people = new Dictionary<string, string>() {
{"+18180000000", "Kim"},
{"+14401112222", "Raj"}
};
// Iterate over all our friends
foreach (var person in people)
{
// Send a new outgoing SMS by POSTing to the Messages resource
MessageResource.Create(
from: new PhoneNumber("+15005550006"), // From number, must be an SMS-enabled Twilio number
to: new PhoneNumber(person.Key), // To number, if using Sandbox see note above
// Message content
body: $"Hey {person.Value} Party is at 6PM! Don't forget to bring gift.");
}
//return Content($"Message has been sent!");
return Content($"Sent message to {person.Value}");
}
}
}
Below is the working code!
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Twilio;
using Twilio.AspNet.Mvc;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace TwilioSendSMS.Controllers
{
public class SMSController : TwilioController
{
// GET: SMS ----- outbound----
public ActionResult SendSms()
{
// Find your Account Sid and Auth Token at twilio.com/user/account
const string accountSid = "ACxxxxxxxxx";
const string authToken = "71xxxxxxxxxx";
// Initialize the Twilio client
TwilioClient.Init(accountSid, authToken);
// make an associative array of people we know, indexed by phone number
var people = new Dictionary<string, string>() {
{"+18180000000", "Kim"},
{"+14401112222", "Raj"}
};
// Iterate over all our friends
var name ="";
foreach (var person in people)
{
// Send a new outgoing SMS by POSTing to the Messages resource
MessageResource.Create(
from: new PhoneNumber("+15005550006"), // From number, must be an SMS-enabled Twilio number
to: new PhoneNumber(person.Key), // To number, if using Sandbox see note above
// Message content
body: $"Hey {person.Value} Party is at 6PM! Don't forget to bring gift.");
name = $"{name} {person.Value}";
}
return Content($"Sent message to {name}");
}
}
}
Related
I'm trying to integrate Firebase FCM into my app but i'm receiving messages
multiple times.
I send the messages trough a cloud function that triggers whenever a notice is added to the database like this:
import { DataSnapshot } from "firebase-functions/lib/providers/database";
import { EventContext } from "firebase-functions";
import * as admin from 'firebase-admin'
import { ResolvePromise } from "./misc";
export function doSendNoticeFCM(snapshot: DataSnapshot, context?: EventContext) {
const uid = context.params.uid;
const noticeid = String(context.params.noticeid);
const notice = snapshot.val();
return admin.database().ref('device-tokens').child(uid).child('0')
.on('value', (data) => {
const token = data.val();
if (token === null) {
return ResolvePromise();
}
const title = String(notice['Title']);
const body = String(notice['Body']);
console.log("Title: " + title);
console.log("Body: " + body);
const payload: admin.messaging.Message = {
data: {
notice_id: noticeid,
title: title,
body: body
},
android: {
ttl: 0
},
token: token
};
return admin.messaging().send(payload)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
});
}
This works fine i retrieve the device token, send the message and i receive it in my app in my messaging service.
using System;
using Android.App;
using Android.Support.V4.App;
using Firebase.Messaging;
using Android.Util;
using Doshi.Xamarin.Abstractions.StaticData;
using Android.Content;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using Android;
using Xamarin.Forms;
using Plugin.CurrentActivity;
using Acr.UserDialogs;
using Doshi.Xamarin.Core.Helpers;
using Doshi.Xamarin.Abstractions.Misc;
using Doshi.Xamarin.Android.Logic.Interfaces;
using Doshi.Xamarin.Android.Logic.Implementations;
namespace Doshi.Droid
{
[Service(Name = "com.doshi.droid.DoshiMessagingService")]
[IntentFilter(new[] {"com.google.firebase.MESSAGING_EVENT"})]
public class DoshiMessagingService : FirebaseMessagingService
{
INoticePresenter _noticePresenter = new DoshiNoticePresenter();
public override void OnMessageReceived(RemoteMessage message)
{
HandleNotice(message);
}
private void HandleNotice(RemoteMessage message)
{
int id = DateTime.Now.Millisecond;
//Create the hardware notice.
_noticePresenter.PresentNotice(this, message, id, Xamarin.Droid.Resource.Drawable.ic_logo, typeof(MainActivity));
}
}
The problem occurs when i log out of my app and then login again the same notices i received earlier are received again. I use google authentication with firebase in my app and i remove the device token from the database when i log out and add the current token when i login again. Could this be the problem?
from what i can see in the firebase logs the cloud function is only executed once for each message so i'm guessing somethings wrong on the client side. I read on a other stackoverflow post that setting ttl to 0 would resolve this issue but it's not effecting anything what i can see.
Has anybody else run into this issue or have any idea of what i'm doing wrong?
I'm using the latest "stable" version of the Xamarin.Firebase.* nugets.
Found my issue. I should use "once" instead of "on" in my firebase function which explains why it was sent multiple times as my listener was triggered when i add/removed device tokens
I need to retrieve all SMS logs from Twilio. The total number of record is expected to be large, aiming at around 100, 000 records. In previous library version, I can do the following to retrieve all the data:
//Set up twilio account
var twilio = new TwilioRestClient(AccountSid, AuthToken);
//Set up a request
var request = new MessageListRequest();
//Get sms logs based on the request filter
MessageResult messages = twilio.ListMessages(request);
//Loop through all the page uri by Twilio to retrieve the messages
while (messages.NextPageUri != null)
{
if (messages.Messages != null)
{
//Do something
}
if (messages.NextPageUri != null)
{
messages = twilio.GetNextPage<MessageResult>(messages);
}
}
How do I do the same with the current Twilio library version?
Looking at the current Twilio REST API:
// Download the twilio-csharp library from twilio.com/docs/libraries/csharp
using System;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
class Example
{
static void Main(string[] args)
{
// Find your Account Sid and Auth Token at twilio.com/console
const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const string authToken = "your_auth_token";
TwilioClient.Init(accountSid, authToken);
var messages = MessageResource.Read();
foreach (var message in messages)
{
Console.WriteLine(message.Body);
}
}
}
What i mean is to get a List that will be build like this format:
from to message
For example in the List in the first index i will see:
From: Daniel To: Jhon Message: hello world
In this code i'm using now all i'm getting in the result variable is 1445 messages and that's strange in my gmail.com account i see i have 374 emails in the inbox so why the variable result return all the time 1445 ? I tried to change in the JSON file to my gmail account then to my friend gmail account in both cases it return 1445. How can i make that it will return the number of emails according to the gmail account in the JASON file ?
And inside in the result list variable for example on index 0 when i stand with the mouse on it all i can get is the message Id and the message ThreadId but how do i get the From and To and the Message body/text ?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using System.Threading;
using System.IO;
using Google.Apis.Util.Store;
namespace Google_Gmail
{
public partial class Form1 : Form
{
static string[] Scopes = { GmailService.Scope.GmailReadonly };
static string ApplicationName = "Youtube Uploader";
public Form1()
{
InitializeComponent();
ListMessages(GmailServices(), "me", "");
}
private GmailService GmailServices()
{
UserCredential credential;
using (var stream =
new FileStream(#"C:\jason file\client_secrets.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
return service;
}
public static List<Google.Apis.Gmail.v1.Data.Message> ListMessages(GmailService service, String userId, String query)
{
List<Google.Apis.Gmail.v1.Data.Message> result = new List<Google.Apis.Gmail.v1.Data.Message>();
UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
request.Q = query;
do
{
try
{
ListMessagesResponse response = request.Execute();
result.AddRange(response.Messages);
request.PageToken = response.NextPageToken;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
} while (!String.IsNullOrEmpty(request.PageToken));
return result;
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
In my gmail.com account i see i have 374 emails in the inbox so why
the variable result return all the time 1445?
The Users.Messages.List(userId) will return the Id of all the messages you have in in your account, not just messages with the INBOX-label. Try the query Q = "in:INBOX"
And inside in the result list variable for example on index 0 when i
stand with the mouse on it all i can get is the message Id and the
message ThreadId but how do i get the From and To and the Message
body/text?
The Messages.List will only give you the Id of the message and the thread it belongs to. You need to use the Messages.Get request with every Id to get the actual message.
Then, you have to look at the From-header, To-header and the Body of the message to get the information you need.
I am new to Google Compute Engine. Some one please help me with creating Google Compute Engine VMs programmatically using REST APIs in C#.
Here [1] you can found the API documentation to create an instance and at the bottom of the document the C# examples [2]:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Compute.v1;
using Google.Apis.Services;
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;
using Data = Google.Apis.Compute.v1.Data;
namespace ComputeSample
{
public class ComputeExample
{
public static void Main(string[] args)
{
ComputeService computeService = new ComputeService(new BaseClientService.Initializer
{
HttpClientInitializer = GetCredential(),
ApplicationName = "Google-ComputeSample/0.1",
});
// Project ID for this request.
string project = "my-project"; // TODO: Update placeholder value.
// The name of the zone for this request.
string zone = "my-zone"; // TODO: Update placeholder value.
// TODO: Assign values to desired properties of `requestBody`:
Data.Instance requestBody = new Data.Instance();
InstancesResource.InsertRequest request = computeService.Instances.Insert(requestBody, project, zone);
// To execute asynchronously in an async method, replace `request.Execute()` as shown:
Data.Operation response = request.Execute();
// Data.Operation response = await request.ExecuteAsync();
// TODO: Change code below to process the `response` object:
Console.WriteLine(JsonConvert.SerializeObject(response));
}
public static GoogleCredential GetCredential()
{
GoogleCredential credential = Task.Run(() => GoogleCredential.GetApplicationDefaultAsync()).Result;
if (credential.IsCreateScopedRequired)
{
credential = credential.CreateScoped("https://www.googleapis.com/auth/cloud-platform");
}
return credential;
}
}
}
[1] https://cloud.google.com/compute/docs/reference/rest/v1/instances/insert
[2] https://cloud.google.com/compute/docs/reference/rest/v1/instances/insert#examples
Hi guys I'm having trouble fetching products from amazon web api.
I have used this code from the internet, adding all the neccessary references. I tried adding a view and chose itemsearchresponce as the model class but it does not display the product, I get the following error:
Unable to generate a temporary class (result=1).
error CS0029: Cannot implicitly convert type 'AmazonProduct.com.amazon.webservices.ImageSet' to
'AmazonProduct.com.amazon.webservices.ImageSet[]'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AmazonProduct.com.amazon.webservices;
namespace Forest.Controllers
{
public class AmazonController : Controller
{
private AmazonProduct.com.amazon.webservices.AWSECommerceService _Products;
public AmazonController()
{
_Products = new AmazonProduct.com.amazon.webservices.AWSECommerceService();
}
[HttpGet]
public ActionResult listProducts()
{
var searchIndex = "Shoes";
var keywords = "jordan";
// Create an ItemSearch wrapper
ItemSearch search = new ItemSearch();
search.AssociateTag = "[Your Associate ID]";
search.AWSAccessKeyId = "MyKey";
// search.Version= "2011-08-01";
// Create a request object
ItemSearchRequest request = new ItemSearchRequest();
// Fill the request object with request parameters
request.ResponseGroup = new string[] { "ItemAttributes" };
// Set SearchIndex and Keywords
request.SearchIndex = searchIndex;
request.Keywords = keywords;
// Set the request on the search wrapper
search.Request = new ItemSearchRequest[] { request };
ItemSearchResponse response = _Products.ItemSearch(search);
return View(response);
}
}
}
Go to the generated proxy and replace ImageSet[][] with ImageSet[].
Also take a look at Amazon Product Advertising API C# if you already haven't.