Sms notifications with Twilio .netcore Blazor server side - c#

I’m looking to add sms notifications to my Blazor server side application. My plan is to create a windows service that runs on a specified frequency; this service will check data in an Azure sql database (the data is inserted via a web api using entity framework) and send sms notifications to users if certain criteria is met.
My question is, what does integrating Twilio into this look like?( I’ve never used Twilio)
Also, how do I setup a console app to run as a service at a specified frequency?
Lastly, what is best practices as far as the console app accessing my database?

what does integrating Twilio into this look like?( I’ve never used Twilio)
Send SMS Messages with a Messaging Service in C#
// 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
// DANGER! This is insecure. See http://twil.io/secure
const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const string authToken = "your_auth_token";
TwilioClient.Init(accountSid, authToken);
var message = MessageResource.Create(
body: "This is the ship that made the Kessel Run in fourteen parsecs?",
from: new Twilio.Types.PhoneNumber("+15017122661"),
to: new Twilio.Types.PhoneNumber("+15558675310")
);
Console.WriteLine(message.Sid);
}
}
how do I setup a console app to run as a service at a specified
frequency?
The right solution for scheduling simple processes is Windows Task Scheduler.
There are lots of examples about How to create an automated task using Task Scheduler
Lastly, what is best practices as far as the console app accessing my
database?
Nothing especial but connection string.
"ConnectionStrings": {
"Database": "Server=(url);Database=CoreApi;Trusted_Connection=True;"
},
Create connection string

Related

Accessing a local instance of the bot framework using DirectLine

I have a bot (basically a clone of the echo bot) and I'm running the service locally. Is it possible to use the Direct Line API to access it (I'm using the NuGet package: Microsoft.Bot.Connector.DirectLine), and I'm trying to access it like this:
DirectLineClient client = new DirectLineClient();
client.BaseUri = new Uri($"http://localhost:3978/api/messages");
var conversation = await client.Conversations.StartConversationAsync().ConfigureAwait(false);
However, conversation is always null. Is it possible to connect to the service locally, or does it have to be deployed to Azure? If the former, then what could I be doing wrong?
Any help would be appreciated.
The Offline-directline package is a way to set up a node server and use directline/webchat to connect to it as if it were a azure endpoint.
You're basically going to follow the usage instructions as they're laid out:
1) Install offline-directline (OD) package
2) Create the OD server using node
3) Run your bot
4) Connect to your bot through a custom webchat that looks to the OD server from step 2 instead of localhost or an azure endpoint

Programmatically create service bus subscription using .net standard

My scenario: Website hosted on the cloud, where each instance creates a subscription to a Service Bus Topic for itself to listen for messages.
My question: How do I programmatically create subscriptions?
Microsoft.Azure.ServiceBus.3.1.0 allows to create a ManagementClient using the ConnectionString.
private async Task CreateTopicSubscriptions()
{
var client = new ManagementClient(ServiceBusConnectionString);
for (int i = 0; i < Subscriptions.Length; i++)
{
if (!await client.SubscriptionExistsAsync(TopicName, Subscriptions[i]))
{
await client.CreateSubscriptionAsync(new SubscriptionDescription(TopicName, Subscriptions[i]));
}
}
}
Original plan for the new Azure Service Bus client was not to include management plane at all and use Azure Active Directory route instead. This has proven to be too problematic, just like you've pointed out. Microsoft messaging team has put together a sample to demonstrate the basic operations.
Note that there's a pending PR to get it working with .NET Core 2.0
Moving forward, it was recognized that developers prefer to access Service Bass using a connection string like they used to over Azure Active Directory option. Management Operations issue is raised to track requests. Current plan is to provide a light weight management library for the .NET Standard client.
For now, the options are either to leverage the old client to create entities or use Microsoft.Azure.Management.ServiceBus (or Fluent) until the management package is available.
Update
Management operations were released as part of 3.1.0 version of the client.
Microsoft.Azure.ServiceBus has been deprecated. The new option is Azure.Messaging.ServiceBus and ManagementClient has been replaced by ServiceBusAdministrationClient.
string connectionString = "<connection_string>";
ServiceBusAdministrationClient client = new ServiceBusAdministrationClient(connectionString);
This new package also supports ManagedIdentity:
string fullyQualifiedNamespace = "yournamespace.servicebus.windows.net";
ServiceBusAdministrationClient client = new ServiceBusAdministrationClient(fullyQualifiedNamespace, new DefaultAzureCredential());
A little example:
var queueExists = await _administrationClient.QueueExistsAsync(queueName);
if(!queueExists)
await _administrationClient.CreateQueueAsync(queueName);
More info here.

Need help related internal network communication using an asp.net mvc solution

In a new project as frontend developer the team I joined is using ASP.NET MVC for the backend. I am running a mac, so this means I can only compile the C# sources on Windows to run the application locally.
I have a Win10 setup inside a VM using virtual box. The sources are on the host and shared to the guest via a samba share (On Z:\ in the guest) and a host-only network adapter. Goal is to reach the app then from the host using the IP of the Guest, i.e. https://192.168.56.102:44301/ (it`s a single page application written in angular)
In the guest I compile from the command line using msbuild and then I start the REST API and the "Web App" using iisexpress.exe: (because visual studio is way to slow in the guest)
commands to build & start:
msbuild Z:\TheApp.sln
:: shell #1
iisexpress.exe" /config:Z:\.vs\config\applicationhost.config /site:"AppName.Api"
:: shell #2
iisexpress.exe" /config:Z:\.vs\config\applicationhost.config /site:"AppName.Web"
In Web.config of the Solution AppName.Web I have the following option:
<add key="ApiEndpointBase" value="https://192.168.56.102:44302/" />
The REST API is listening on port 44302, the "web app" on port 44301
So when I enter https://192.168.56.102:44301/ I get the app served.
The problem:
For each page reload the web app (HomeController.cs) does an http request against the API, so this means it is internally communicating to https://192.168.56.102:44302/
// HomeController.cs
// this fails with an exception like "An error occurred while processing your request.":
private readonly HttpClient client = new HttpClient();
...
/// <returns>The index view.</returns>
public async Task<ActionResult> Index() {
var response = await clientclient.GetAsync("api/foo?someId=" + someId);
client.BaseAddress is https://192.168.56.102:44302/
So there are two apps running in the guest using iisexpress, and one of them does an http request against the other using the Address https://192.168.56.102:44302/.... - and this request times out, or fails somehow and I don't get why.
It works if:
<add key="ApiEndpointBase" value="https://localhost:44302/" />
I visit https://localhost:44301/ in a browser inside the guest
But I want to access it from a browser on the host. Would really appreciate if some asp.net devs may help me here :)
EDIT:
External requests are already working. Else I would not get the app served on the host. I also registered the URLs using netsh and windows firewall is disabled on the guest. So I think this is not a duplicate of IIS Express enable external request

Azure Mobile Service Nodejs on Local Machine Error with Push

I am following Azure's Mobile Quickstart Tutorial (Xamarin.Android) and I was able to have the Facebook Authentication and Push Notification running.
Now, I wanted to know how to have a local development environment or have the Mobile App Service (Nodejs) run on my local machine instead (not on Azure Cloud). And I followed this tutorial:
https://shellmonger.com/2016/04/01/30-days-of-zumo-v2-azure-mobile-apps-day-2-local-development/
However, things break just after I open the app. See screenshots below:
Error:
Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOperationException: Cannot PUT /push/installations/cc69e3d2-5d18-4077-a23a-56a845a73698
Couple of notes:
- This app works as it should if I connect it to the remote app service on Azure Cloud.
- Yes, I have the app server (nodejs) cloned in my local machine - installed required modules, and is running as it should (screenshot)
// This is a base-level Azure Mobile App SDK.
var express = require('express'),
azureMobileApps = require('azure-mobile-apps');
// Set up a standard Express app
var app = express();
// If you are producing a combined Web + Mobile app, then you should handle
// anything like logging, registering middleware, etc. here
// Configuration of the Azure Mobile Apps can be done via an object, the
// environment or an auxiliary file. For more information, see
// http://azure.github.io/azure-mobile-apps-node/global.html#configuration
var mobileApp = azureMobileApps({
// Explicitly enable the Azure Mobile Apps home page
homePage: true,
// Explicitly enable swagger support. UI support is enabled by
// installing the swagger-ui npm module.
// swagger: true,
// App will use MS_SqliteFilename or MS_TableConnectionString to choose the SQLite or SQL data provider
data: {
dynamicSchema: true
}
});
// Import the files from the tables directory to configure the /tables endpoint
mobileApp.tables.import('./tables');
// Import the files from the api directory to configure the /api endpoint
mobileApp.api.import('./api');
// Initialize the database before listening for incoming requests
// The tables.initialize() method does the initialization asynchronously
// and returns a Promise.
mobileApp.tables.initialize()
.then(function () {
app.use(mobileApp); // Register the Azure Mobile Apps middleware
app.listen(process.env.PORT || 3000); // Listen for requests
});
- And also yes, I changed the mobile app client's needed ApplicationURL to the one I have running locally (screenshot)
...
const string applicationURL = #"http://192.168.1.221:3000";
const string localDbFilename = "newlocalstore.db";
protected override async void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Activity_To_Do);
CurrentPlatform.Init();
...
- Lastly, I have my IP address already white-listed on the firewall setting of the MS SQL Server. So it shouldn't be an issue since I was also able to fully up my local app service (nodejs).
What do you think causes the error?
When you run locally, you must provide ALL the connection strings required - including ones that are automatically generated for you in the cloud. In this case, you have not defined the Notification Hubs connection string in the local
environment.
Go to Kudu (https://yoursite.scm.azurewebsites.net) and look at the environment variables for connection strings. They are rather obvious when you look for them. Make sure you have all the connection strings defined as the same environment variables.

Calling SpeechAPI for text to speech on Azure

I have the following very basic TTS code running on my local server
using System.Speech.Synthesis;
...
SpeechSynthesizer reader = new SpeechSynthesizer();
reader.Speak("This is a test");
This code has a dependency on System.Speech for which I have added a Reference in my VS 2015 project.
Works fine but from what I have read and from trying it I know this will not work when the code is hosted on Azure.
I have read several posts on SO querying if it is actually possible to do TTS on azure. Certainly 2 yrs ago it did not appear to be possible. How to get System.Speech on windows azure websites?
All roads seem to lead to the Microsoft Speech API
https://azure.microsoft.com/en-gb/marketplace/partners/speechapis/speechapis/
I have signed up and have gotten my private and sec keys for calling into this API.
However my question is this. How do I actually call the SpeechAPI? What do I have to change in the simple code example above so that this will work when running on azure?
The speech API you referred to at the Azure marketplace is part of an AI Microsoft project called ProjectOxford which offers an array of APIs for computer vision, speech and language.
These are all RESTful APIs, meaning that you will be constructing HTTP requests to send to a hosted online service in the cloud.
The speech-to-text documentation is available here and you can find sample code for various clients on github. Specifically for C# you can see some code in this sample project.
Please note that ProjectOxford is still in preview (Beta). Additional support for using these APIs can be found on the ProjectOxford MSDN forum.
But just to give you an idea of how your program will look like (taken from the above code sample on github):
AccessTokenInfo token;
// Note: Sign up at http://www.projectoxford.ai for the client credentials.
Authentication auth = new Authentication("Your ClientId goes here", "Your Client Secret goes here");
...
token = auth.GetAccessToken();
...
string requestUri = "https://speech.platform.bing.com/synthesize";
var cortana = new Synthesize(new Synthesize.InputOptions()
{
RequestUri = new Uri(requestUri),
// Text to be spoken.
Text = "Hi, how are you doing?",
VoiceType = Gender.Female,
// Refer to the documentation for complete list of supported locales.
Locale = "en-US",
// You can also customize the output voice. Refer to the documentation to view the different
// voices that the TTS service can output.
VoiceName = "Microsoft Server Speech Text to Speech Voice (en-US, ZiraRUS)",
// Service can return audio in different output format.
OutputFormat = AudioOutputFormat.Riff16Khz16BitMonoPcm,
AuthorizationToken = "Bearer " + token.access_token,
});
cortana.OnAudioAvailable += PlayAudio;
cortana.OnError += ErrorHandler;
cortana.Speak(CancellationToken.None).Wait();

Categories

Resources