Following this tutorial, I am attempting to display the progress of various steps in a long operation. I was able to successfully simulate a long operation within the hub based on the example, reporting updates back to the client with each step.
Taking this a step further, I now want to display the status of a realtime, long-running process that occurs in an MVC action method with the [HttpPost]
attribute.
The problem is that I cant seem to update the client from a hub context. I realize that I must create a hub context to communicate using the hub. One difference that I know of is that I must use hubContext.Clients.All.sendMessage();
VS. hubContext.Clients.Caller.sendMessage();
listed in the example. Based on my findings in ASP.NET SignalR Hubs API Guide - Server
I should be able to use Clients.Caller
as stated in the example but I am limited to only using it in the hub class. Mainly, I just want to understand why I cant get a signal from the action method.
I appreciate the help in advance.
I have created my OWIN Startup()
class like so...
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(HL7works.Startup))]
namespace HL7works
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
My hub is written as such...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace HL7works
{
public class ProgressHub : Hub
{
public string msg = string.Empty;
public int count = 0;
public void CallLongOperation()
{
Clients.Caller.sendMessage(msg, count);
}
}
}
My Controller...
// POST: /Task/ParseToExcel/
[HttpPost]
public ActionResult ParseToExcel(HttpPostedFileBase[] filesUpload)
{
// Initialize Hub context
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProgressHub>();
hubContext.Clients.All.sendMessage("Initalizing...", 0);
double fileProgressMax = 100.0;
int currentFile = 1;
int fileProgress = Convert.ToInt32(Math.Round(currentFile / fileProgressMax * 100, 0));
try
{
// Map server path for temporary file placement (Generate new serialized path for each instance)
var tempGenFolderName = SubstringExtensions.GenerateRandomString(10, false);
var tempPath = Server.MapPath("~/" + tempGenFolderName + "/");
// Create Temporary Serialized Sub-Directory
System.IO.FileInfo thisFilePath = new System.IO.FileInfo(tempPath + tempGenFolderName);
thisFilePath.Directory.Create();
// Iterate through PostedFileBase collection
foreach (HttpPostedFileBase file in filesUpload)
{
// Does this iteration of file have content?
if (file.ContentLength > 0)
{
// Indicate file is being uploaded
hubContext.Clients.All.sendMessage("Uploading " + Path.GetFileName(file.FileName), fileProgress);
file.SaveAs(thisFilePath + file.FileName);
currentFile++;
}
}
// Initialize new ClosedXML/Excel workbook
var hl7Workbook = new XLWorkbook();
// Start current file count at 1
currentFile = 1;
// Iterate through the files saved in the Temporary File Path
foreach (var file in Directory.EnumerateFiles(tempPath))
{
var fileNameTmp = Path.GetFileName(file);
// Update status
hubContext.Clients.All.sendMessage("Parsing " + Path.GetFileName(file), fileProgress);
// Initialize string to capture text from file
string fileDataString = string.Empty;
// Use new Streamreader instance to read text
using (StreamReader sr = new StreamReader(file))
{
fileDataString = sr.ReadToEnd();
}
// Do more work with the file, adding file contents to a spreadsheet...
currentFile++;
}
// Delete temporary file
thisFilePath.Directory.Delete();
// Prepare Http response for downloading the Excel workbook
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=\"hl7Parse_" + DateTime.Now.ToString("MM-dd-yyyy") + ".xlsx\"");
// Flush the workbook to the Response.OutputStream
using (MemoryStream memoryStream = new MemoryStream())
{
hl7Workbook.SaveAs(memoryStream);
memoryStream.WriteTo(Response.OutputStream);
memoryStream.Close();
}
Response.End();
}
catch (Exception ex)
{
ViewBag.TaskMessage =
"<div style=\"margin-left:15px;margin-right:15px\" class=\"alert alert-danger\">"
+ "<i class=\"fa fa-exclamation-circle\"></i> "
+ "An error occurred during the process...<br />"
+ "-" + ex.Message.ToString()
+ "</div>"
;
}
return View();
}
In My View (Updated to reflect Detail's answer)...
@using (Html.BeginForm("ParseToExcel", "Task", FormMethod.Post, new { enctype = "multipart/form-data", id = "parseFrm" }))
{
<!-- File Upload Row -->
<div class="row">
<!-- Select Files -->
<div class="col-lg-6">
<input type="file" multiple="multiple" accept=".adt" name="filesUpload" id="filesUpload" />
</div>
<!-- Upload/Begin Parse -->
<div class="col-lg-6 text-right">
<button id="beginParse" class="btn btn-success"><i class="fa fa-download"></i> Parse and Download Spreadsheet</button>
</div>
</div>
}
<!-- Task Progress Row -->
<div class="row">
<!-- Space Column -->
<div class="col-lg-12">
</div>
<!-- Progress Indicator Column -->
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('.progress').hide();
$('#beginParse').on('click', function () {
$('#parseFrm').submit();
})
$('#parseFrm').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: '/Task/ParseToExcel',
type: "POST",
//success: function () {
// console.log("done");
//}
});
// initialize the connection to the server
var progressNotifier = $.connection.progressHub;
// client-side sendMessage function that will be called from the server-side
progressNotifier.client.sendMessage = function (message, count) {
// update progress
UpdateProgress(message, count);
};
// establish the connection to the server and start server-side operation
$.connection.hub.start().done(function () {
// call the method CallLongOperation defined in the Hub
progressNotifier.server.callLongOperation();
});
});
});
function UpdateProgress(message, count) {
// get status div
var status = $("#status");
// set message
status.html(message);
// get progress bar
if (count > 0) {
$('.progress').show();
}
$('.progress-bar').css('width', count + '%').attr('aria-valuenow', count);
$('.progress-bar').html(count + '%');
}
</script>
<div class="col-lg-12">
<div id="status">Ready</div>
</div>
<div class="col-lg-12">
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="min-width:20px;">
0%
</div>
</div>
</div>
</div>
<!-- Task Message Row -->
<div class="row">
<div clss="col-lg-12">
@Html.Raw(ViewBag.TaskMessage)
</div>
</div>
Update: The solution to my problem ended up being Detail's answer but with the AJAX post method modified slightly to pass files to my action method ..
e.preventDefault();
$.ajax({
url: '/Task/ParseToExcel',
type: "POST",
data: new FormData( this ),
processData: false,
contentType: false,
//success: function () {
// console.log("done");
//}
});
Reference.. http://portfolio.planetjon.ca/2014/01/26/submit-file-input-via-ajax-jquery-easy-way/