MVC 3 Async Controller for video conversion - asp.net

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

Related

Event Handler for A Rebus Topic

As we know that Rebus provides Topic Based routing in addition to the familiar TypeBased routing although we are told that the TypeBased routing follows the same principle.
On my side however unfortunately I have not seen a good example on how to create a handler that processes messages published to a particular topic.
Suppose I publish my message as follows
var message=new Student { StudentID=90008,FirstName="Chilipo",LastName="Mjengo" };
await bus.Advanced.Topics.Publish("rebus_example_topic", message);
In another endpoint I have subscribed to the topic as follows
await bus.Advanced.Topics.Subscribe("rebus_example_topic");
My interest is to know how do I then implement the Handler that will process the messages published to the rebus_example_topic.
Regards
It's quite simple, actually 🙂 the preferred way of writing message handlers is to implement IHandleMessage<TMessage>, where TMessage is your message type.
In your case that would be
public class StudentHandler : IHandleMessages<Student>
{
public async Task Handle(Student message)
{
// handle your message in here
}
}
How you then activate your message handler depends on which handler activator, you're using. The "handler activator" is what you use to instantiate message handlers, so you just need to register your handler in that to make it available to Rebus.
Some container integrations even come with additional help in the form of registration extensions, so e.g. if you're using Autofac, you can register your handler like this:
containerBuilder.RegisterHandler<StudentHandler>();

Twilio voice recording in ASP.Core

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

Clarifying RxJava Observable Threading with Retrofit

At http://square.github.io/retrofit/ where it talks about asynchronous, there is a phrase "Observable requests are subscribed asynchronously and observed on the same thread that executed the HTTP request" where I wanted to clarify.
So in this case which thread that actually will execute the Http Request: Lets say main thread makes a call to Observable getUserPhoto(#Path("id") int id)? Will it be the main thread or thread that subscribe the request that execute the http request?
Regarding to the documentation, it will be the thread which execute the request.
If the result of your request change something in the view, you may need to observe (consume) your result in the main thread. In this case, add a call to the observeOn method before you subscribe to your observable.
The answer is yes, when you execute your method by using a service, using the observeOn method will create an "Observer" that will be waiting for an opportunity to execute the request once the mainThread has an opportunity to do so.
So first use .observeOn(AndroidSchedulers.mainThread()) to observe the main thread, and then subscribe the action or callback that will execute once you got a response from your remote API.
supposing you use this annotation in your API interface
#GET("/home")
Observable<Response> getHome();
this would be an example:
service.getHome().observeOn(AndroidSchedulers.mainThread()).subscribe(
new Action1<Response>() {
#Override
public void call(Response response) {
System.out.println("Response home");
System.out.println(response.getStatus());
System.out.println(response.getBody().mimeType());
System.out.println(response.getReason());
System.out.println(response.getUrl());
StringWriter w = new StringWriter();
try{
IOUtils.copy(response.getBody().in(),w,"UTF-8");
System.out.println(w.toString());
}catch (IOException e){}
}
});
For more information you may check this RxJava(the one that Retrofits uses of course) link where it states that it uses Android's Handler(which is a class for handling threads)
"It provides a Scheduler that schedules an Observable on a given Android Handler thread, particularly the main UI thread."

spring-mvc, websockets push integration

I've followed this link http://spring.io/guides/gs/messaging-stomp-websocket/ and got the app up and running.
What I wanted was a little more than that, I wanted to to be able to push the data back to the client without the client having to send any thing.
So I've setup a long running task with a listener similar to the below
GreetingController implements RunnableListener
and the RunnableListener has a method
public Greeting greeting(HelloMessage message);
The implementation of the method is to kick off a thread and then call the listener method..
I see the output on the console when that happens, but I don't see anything on the browser.
Could anyone please show me how to kick off a running task and let the server push the content to the browser using Spring instead of poll (setTimeout stuff in javascript?)
Regards
Tin
What is this RunnableListener interface?
What is triggering this task - is it scheduled regularly?
Once the client has subscribed to a given topic (here, /topic/greetings), you can send messages to that topic whenever you want using a MessagingTemplate. For example, you could schedule this task and let it send messages regularly on a given topic:
#Service
public class GreetingService {
private SimpMessagingTemplate template;
#Autowired
public GreetingService(SimpMessagingTemplate template) {
this.template = template;
}
#Scheduled(fixedDelay=10000)
public void greet() {
this.template.convertAndSend("/topic/greetings", "Hello");
}
}
Check out the reference documentation for more details.

ASP.NET MVC - Real time updates using Web Service

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

Resources