I'm building a new application and one of the its function is communication between seller and customer. For this reason I want to use Twilio API.
So let's imagine we have two person: seller and customer, and they are going to communicate. My idea is that these two person shouldn't know real phone number each other, so I buy two phone numbers from Twilio, one for seller and one for customer and connect them with real phones in my app. For convenience I've created TwiML App in Twilio console and set REQUEST and STATUS CALLBACK URLs for Voice calls, these urls are pointed to Webhook in my app. My application is based on .Net Core, but I still use full .Net4.6 framework, because there are no some .dlls for .Net Core and seems Twilio helpers for C# have also been built for full .Net framework. Any way, my webhook method looks like:
[HttpPost("call")]
public IActionResult IncomingCall(VoiceRequest request) {
// some logic
VoiceResponse response = new VoiceResponse();
response.Dial({real_seller_number}, callerId: {virtual_customer_number}, record: "record-from-ringing-dual");
return Content(response.ToString(), "application/xml");
}
Here, let's imagine I'm customer, I want to call seller, I call its virtual Twilio number, Twilio makes a request to this webhook and it make a call to real seller's number from virtual customer number. This is OK and works as intended.
When the call ends, Twilio makes a request to STATUS CALLBACK url, and this methos looks like:
[HttpPost("call/callback")]
public IActionResult IncomingCallCallback(StatusCallbackRequest request) {
// some logic
return Ok("Handled");
}
In a first method you can see I want to record conversation for internal reason, and I expected RecordingSid and RecordingUrl in second method, but I always get them null. I can see the recording in Twilio console, but cannot get them via API, that's my problem. I spent a lot of time and read a lot of docs, but didn't find clear explanation how to do it right. Can someone help me?
Twilio developer evangelist here.
When recording calls the recording might not be ready by the time you receive the statusCallback request. Instead you should set a recordingStatusCallback URL which will be called when the recording is complete and ready.
[HttpPost("call")]
public IActionResult IncomingCall(VoiceRequest request) {
// some logic
VoiceResponse response = new VoiceResponse();
response.Dial({real_seller_number},
callerId: {virtual_customer_number},
record: "record-from-ringing-dual",
recordingStatusCallback: {url_in_your_application_that_processes_recordings}
);
return Content(response.ToString(), "application/xml");
}
Related
I have a web application which has few charts on dashboard. The data for charts is fetched on document.ready function at client side invoking a WCF service method.
What i want is now to use SignalR in my application. I am really new to SignalR. How can i call WCF methods from SignalR Hub or what you can say is that instead of pulling data from server i want the WCF service to push data to client every one minute.
Is there a way of communication between signalR and WCF service.
Also another approach can be to force client to ask for data from WCF Service every minute.
Any help will be really appreciated.
I have done following as of yet.
Client Side Function on my Dashboard page
<script src="Scripts/jquery.signalR-2.0.3.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>
<a id="refresh">Refresh</a>
$(function() {
var dashboardHubProxy = $.connection.dashboardHub;
$.connection.hub.start().done(function() {
// dashboardHubProxy.server.refreshClient(parameters);
$("#refresh").click(function() {
dashboardHubProxy.server.refreshClient(parameters);
});
});
dashboardHubProxy.client.refreshChart = function (chartData) {
debugger;
DrawChart(chartData, 'Hourly Call Count For Last ' + Duration + ' Days', '#chartHourly', 'StackedAreaChart');
};
});
and my Dashboard Hub class is as follows
public class DashboardHub : Hub
{
private readonly ReportService ReportService = new ReportService();
public void RefreshClient(string parameters)
{
var chartData = ReportService.GenerateHourlyCallsTrendGraphicalReport(parameters);
Clients.All.refreshChart(chartData);
}
}
My SignalR startup class is as follows
[assembly: OwinStartup(typeof(CallsPortalWeb.Startup), "Configuration")]
namespace CallsPortalWeb
{
public static class Startup
{
public static void Configuration(IAppBuilder app)
{
ConfigureSignalR(app);
}
public static void ConfigureSignalR(IAppBuilder app)
{
app.MapSignalR();
}
}
}
When i click on refresh button and a debugger on RefreshClient method on hub the debugger doesn't get to the method which means i am unable to call server side method of SignalR.
Is there anything needs to be done in web.config?
I agree with AD.Net's comment. To elaborate slightly more though, the SignalR hubs can be hosted directly in your web project kinda the same way controllers are used. There is also a package out there so you can host the SignalR library on its own so it can act as a service all on its own. Either way you will need to hit the SignalR hub first as that is how it communicates then you would call your WCF service methods from within the hubs.
Brief explanation
Your HUB will have methods used by both your USER Client and your WCF Client. You may use something like UserConnected() for the user to call in and setup your logging of the connection. Then the WCF service may call your HUB with an UpdateUserStats(Guid connnectionId, UserStats stats) which would in turn call the USER client directly and provide the stats passed in like so Clients.Client(connectionId).updateStats(stats) which in turn would have a method on the USERS client named updateStats() that would handle the received information.
Initial page landing
What AD.Net provided is basic code that will be called when the user lands on the page. At this point you would want to log the ConnectionId related to that user so you can directly contact them back.
First contact with your hub touching WCF
From your Hub, you could call your WCF service as you normally would inside any normal C# code to fetch your data or perform action and return it to your user.
Method of updating the user periodically
SignalR removes the need for your client code to have to continually poll the server for updates. It is meant to allow you to push data out to the client with out them asking for it directly. This is where the persistence of the connections come into play.
You will probably want to create a wrapper to easily send messages to the hub from your application, since you are using WCF I would assume you have your business logic behind this layer so you will want the WCF service reaching out to your Hub whenever action X happens. You can do that by utilizing the Client side C# code as in this case your client is actually the user and the WCF service. With a chat application the other user is basically doing what you want your WCF service to do, which is send a message to the other client.
Usage example
You are running an online store. The dashboard displays how many orders there have been for the day. So you would wire up a call to the hub to send a message out to update the products ordered when a user places a new order. You can do this by sending it to the admin group you have configured and any admins on the dashboard would get the message. Though if these stats are very user specific, you will more then likely instead reach into the database, find the ConnectionId that the user has connected with and send the update message directly to that connectionid.
WCF Client Code Example
Just incase you want some code, this is directly from MS site on connecting with a .net client. You would use this in your WCF service, or wherever in your code you plan on connecting and then sending an update to your user.
var hubConnection = new HubConnection("http://www.contoso.com/");
IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("StockTickerHub");
stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock => Console.WriteLine("Stock update for {0} new price {1}", stock.Symbol, stock.Price));
await hubConnection.Start();
Here is a link directly to the .Net Client section: http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-net-client
I am sure you have seen this link but it really holds all the good information you need to get started. http://www.asp.net/signalr
Here is a more direct link that goes into usages with code for you. http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-server
ADDED: Here is a blog specific to Dashboards with SignalR and their polling.
http://solomon-t.blogspot.com/2012/12/signalr-and-interval-polling-for.html
ADDED: Here is a page on managing users signalR connections.
http://www.asp.net/signalr/overview/signalr-20/hubs-api/mapping-users-to-connections
Update for your code update
The .Net Client library (in NuGet) gives your .net code access to the hub. Since you are a client you will need to connect to the hub just like the User who is also a client. Your hub would act as the server for this. So with the .Net Client I am assuming you would setup a windows service that would internally poll, or something event based that would call the .Net Client code portion of it which would reach out to your hub. Your hub would take the information provided, more than likely a ConnectionId or GroupId and broad cast the User (which is perhaps on a website so it would be the JS client) a method that would update the front end for the user client. Basically what I mention under "Brief Explanation".
Now, to directly respond to the code you posted. That is Javascript, I would expect a connect like you have done. Updating the chart on initial connection is fine as well. If this is all the code signalR wise though you are missing a client side method to handle the refresh. Technically, instead of calling Clients.Caller.RefreshChart() you could just return that data and use it, which is what your javascript is doing right now. You are returning void but it is expecting a your date.
Now, I would actually say correct your javascript instead of correcting the hub code. Why? Because having a method in JS on your client that is called "refreshChart()" can be reused for when you are having your server reach out and update the client.
So I would recommend, dropping anything that is related to updating the dashboard in your JS done statement. If you want to do a notification or something to the user that is fine but dont update the grid.
Now create a JS client function called "refreshChart", note the lower case R, you can call it with a big R in c# but the js library will lowercase it so when you make the function have it will receive your dashboard information.
Now, on the server polling, or executing on some action, your WCF would call a method on the hub that would be say "UpdateDashboar(connectionId,dashInfo)" and that method would then inside of it call the "refreshChart" just like you are doing in your RefreshClient method, accept instead of doing Clients.Caller you would use Clients.Client(connectionId).refreshChart(chartInfo).
Directly the reason your code is not working is because you need to turn that Void into the type you expect to be returned. If the rest is coded right you will have it update once. You will need to implement the other logic I mentioned if you want it constantly updating. Which is again why I asked about how you are persisting your connections. I added a link to help you with that if you are not sure what I am talking about.
You should use the SignalR Hub to push data to the client. Your hub can consume a WCF service (the same way your client can) to get the data.
from client:
hub.VisitingDashBoard();
on the hub in the VisitingDashBoard method:
var data = wcfClient.GetDashboardData()//may be pass the user id from the context
Clients.Caller.UpdateDashboard(data)
Of course your client will have a handler for UpdateDashboard call
I'm trying to find examples on how to get real time updates using a web service in ASP.NET MVC (Version doesn't matter) and posting it back to a specific user's browser window.
A perfect example would be a type of chat system like that of facebooks' where responses are send to the appropriate browser(client) whenever a message has been posted instead of creating a javascript timer on the page that checks for new messages every 5 seconds. I've heard tons of times about types of sync programs out there, but i'm looking for this in code, not using a third party software.
What i'm looking to do specifically:
I'm trying to create a web browser chat client that is SQL and Web Service based in ASP.NET MVC. When you have 2-4 different usernames logged into the system they chat and send messages to each other that is saved in an SQL database, then when there has been a new entry (or someone sent a new message) the Web Service see's this change and then shows the receiving user the new updated message. E.G Full Chat Synced Chat using a Web Service.
The thing that really stomps me in general is I have no idea how to detect if something new is added to an SQL table, and also I have no idea how to send information from SQL to a specific user's web browser. So if there are people userA, userB, userC all on the website, i don't know how to only show a message to userC if they are all under the username "guest". I would love to know hot to do this feature not only for what i'm trying to create now, but for future projects as well.
Can anyone point me into the right direction please? I know SQL pretty well, and web services i'm intermediate with.
You can use SignalR for this task.
Via Scott Hanselman:
Create Asp.net mvc empty application
install nuget package of SignalR
Add new Controller (as example HomeController):
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
Create view Index with javascript references:
#Url.Content("~/Scripts/jquery-1.6.4.min.js")"
"#Url.Content("~/Scripts/jquery.signalR.js")"
and function:
$(function () {
var hub = $.connection.chatHub;
hub.AddMessage = function (msg) {
$('#messages').append('<li>' + msg + '</li>');
};
$.connection.hub.start().done(function() {
$('#send').click(function() {
hub.send($('#msg').val());
});
});
});
Create class ChatHub:
public class ChatHub:Hub
{
public void Send(string message)
{
Clients.AddMessage(message);
}
}
I'm not really to up on Async controller, I'm currently reading what I can but I thought I'd try and save myself some time as I'm on a rather tight deadline.
I'm working on a project that allows users to upload video clips but I then want to convert them to different formats for playback on different devices. I was thinking of doing this straight after the upload has happened but the down side is the user will be waiting for that to finish before they can navigate away.
So to my question, would using a async controller and action allow the conversion process to happen with out the user having to wait at the upload page?
Apologies if this is a stupid question, like I said I've only just started reading about async controllers
Thanks
No. AsyncController frees up the thread executing the controller to do other things when there is low CPU usage (for example heavy I/O). A result will not be returned to the client until the action method returns.
You are better off starting your conversion in a separate thread, if you want to return a page quickly. We use this approach when sending emails, so that the user does not have to wait for the email to be sent before we return a view to them.
Here is how we send emails.
// this can go in an action method, or you can DI this code as a service
var sender = new SmtpEmailSender(message);
var thread = new Thread(sender.Send);
thread.Start();
...
return View(model);
// this is the code run by the new thread
// (EmailMessage is a custom type in our app)
public class SmtpEmailSender
{
public SmtpEmailSender(EmailMessage emailMessage)
{
// arg to instance field
}
public void Send()
{
// construct System.Net mail and send over SMTP
}
}
I have a database of email subscribers; approx. 1800 in the list. We have our own exchange server. I'm using the code below to grab each email address from the DB and send email, one at a time. I'm using an ASP.NET 4.0 Web Form to do this.
I notice the page hanging when the emails are being sent. What would be the best approach for implementing this - use a console app? How would I go about stress testing something like this?
I'm also getting an unhandled error message in the server log:
Event code: 3001
Event message: The request has been aborted.
// Call data access method via business class
TaxSalesBusiness bizClass = new TaxSalesBusiness();
DataSet ds = bizClass.GetSubscribers();
foreach (DataRow row in ds.Tables[0].Rows)
{
// Check well-formedness of each email adddress
if (!IsWellformedEmailAddr(row["Email"].ToString()))
{
// Ignore and log mal-formed email address
LogError(row["Email"].ToString()
+ " is a malformed email address. Message was not sent to this subscriber "
+ row["Name"].ToString() + ".", "");
continue;
}
else
{
string toAddress = row["Email"].ToString();
smtpClient.Send(fromAddress, toAddress, message.Subject, message.Body);
}
}
I notice the page hanging when the emails are being sent. What would
be the best approach for implementing this - use a console app?
Yes.
And you can SendAsync instead of waiting for one email to be sent before you send the next one. I don't know how much your Exchange server will like that, though.
The problem with your current approach is that sending 1800 emails one by one is going to take a lot of time and using a web page to perform such a long operation will probably timeout the request. You can perhaps do it on an async page and launch everything on its own thread, but that's just complicating things more than it needs to when you can perfectly do this in a Console App with far less lines of code and complications. Remember the KISS principle.
Another (more stable) solution could be to forward the mails to a (database?) queue, and have a Windows Service poll that queue once in a while. If there are new things on the queue the Windows Service is responsible for sending the e-mails.
This approach will help you steer clear from performance issues in your website, and it could make the delivery of the mails to be more reliable.
I have a Tomcat service running on localhost:8080 and I have installed BlazeDS. I created and configured a simple hello world application like this...
package com.adobe.remoteobjects;
import java.util.Date;
public class RemoteServiceHandler {
public RemoteServiceHandler()
{
//This is required for the Blaze DS to instantiate the class
}
public String getResults(String name)
{
String result = “Hi ” + name + “, the time is : ” + new Date();
return result;
}
}
With what query string can I invoke RemoteServiceHandler to my Tomcat instance via just a browser? Something like... http://localhost:8080/blazeds/?xyz
Unfortunately you can't. First the requests (and responses) are encoded in AMF and second I believe they have to be POSTs. If you dig through the BlazeDS source code and the Flex SDK's RPC library you can probably figure out what it's sending. But AFAIK this hasn't been documented anywhere else.
I think that AMFX (which is AMF in XML) will work for you, using HTTPChannel instead of AMFChannel.
From http://livedocs.adobe.com/blazeds/1/blazeds_devguide/help.html?content=lcarch_2.html#1073189, Channels and channel sets:
Flex clients can use different channel
types such as the AMFChannel and
HTTPChannel. Channel selection depends
on a number of factors, including the
type of application you are building.
If non-binary data transfer is
required, you would use the
HTTPChannel, which uses a non-binary
format called AMFX (AMF in XML). For
more information about channels, see
Channels and endpoints.
This way you can use simple netcat to send the request.
Not sure how authentication will be handled though, you will probably need do a login using Flash, extract the authentication cookie and then submit it as part of your request.
Please update this thread once you make progress so that we all can learn.