What could possibly go wrong with this HTTP caching scheme? - c#

I know that rolling your own HTTP caching is probably ill-advised, but this is what is being used on a project. It appears to have cached a response that is odd, see below, as this request was for an image. It appears to have been a non-error response (otherwise it would not have been cached), however it was not the image, it was an HTML page.. What response codes could be interpreted as success by unity, other than 200?
IEnumerator ReallyDownloadFile(string url, string filename, System.Action<string> on_complete,System.Action<string> on_error, bool allow_caching)
{
WWW www = new WWW (url);
yield return www;
if ((www.error != "")&&(www.error != null)) {
on_error.Invoke (www.error);
} else {
System.IO.File.WriteAllBytes (Application.persistentDataPath + "/filecache/" + filename, www.bytes);
on_complete.Invoke (Application.persistentDataPath + "/filecache/" + filename);
}
}
This is the response. I have no idea where this came from. Router? CDN possibly. Can you explain what happened?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="csrf_token" content="2qe6UtbjdrA6e4ol/eNeo5988K4uoH7r"/>
<meta name="csrf_token" content="UHQ2/wbKRgNdaE14EMIHbKUsa2bLJurm"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv='Pragma' content='no-cache'/>
<script type="text/javascript">
/*
JQuery is not compatible with PSP & NDSi
script execution will stop when the jquery import.
we should put the following script before the jquery is imported
*/
var hardwarePlatform = navigator.platform.toLowerCase();
var agent = navigator.userAgent.toLowerCase();
var isPsp = (agent.indexOf("playstation") != -1);
var isNdsi = (agent.indexOf("nintendo dsi") != -1);
if (isPsp || isNdsi) {
window.location.href = "notsupported.html";
}
</script>
<script type="text/javascript" src="../lib/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="../lib/log4javascript_lite.js"></script>
<script type="text/javascript" src="../js/redirect.js"></script>
<title></title>
<script type="text/javascript">
var DEFAULT_GATEWAY_IP = "192.168.1.1";
var DEFAULT_GATEWAY_DOMAIN = new Array();
var GATEWAY_DOMAIN = new Array();
var AJAX_HEADER = '../';
var AJAX_TAIL = '';
var AJAX_TIMEOUT = 30000;
var MACRO_NO_SIM_CARD = '255';
var MACRO_CPIN_FAIL = '256';
var MACRO_PIN_READY = '257';
var MACRO_PIN_DISABLE = '258';
var MACRO_PIN_VALIDATE = '259';
var MACRO_PIN_REQUIRED = '260';
var MACRO_PUK_REQUIRED = '261';
var log = log4javascript.getNullLogger();
var hardwarePlatform = navigator.platform.toLowerCase();
var agent = navigator.userAgent.toLowerCase();
var isIpod = hardwarePlatform.indexOf("ipod") != -1;
var isIphone = hardwarePlatform.indexOf("iphone") != -1;
var isIpad = hardwarePlatform.indexOf("ipad") != -1;
var isAndroid = agent.indexOf("android") !=-1;
log.debug("INDEX : hardwarePlatform = " + hardwarePlatform);
log.debug("INDEX : agent = " + agent);
function gotoPageWithoutHistory(url) {
log.debug('MAIN : gotoPageWithoutHistory(' + url + ')');
window.location.replace(url);
}
// internal use only
function _recursiveXml2Object($xml) {
if ($xml.children().size() > 0) {
var _obj = {};
$xml.children().each(function() {
var _childObj = ($(this).children().size() > 0) ? _recursiveXml2Object($(this)) : $(this).text();
if ($(this).siblings().size() > 0 && $(this).siblings().get(0).tagName == this.tagName) {
if (_obj[this.tagName] == null) {
_obj[this.tagName] = [];
}
_obj[this.tagName].push(_childObj);
}
else {
_obj[this.tagName] = _childObj;
}
});
return _obj;
}
else {
return $xml.text();
}
}
// convert XML string to an Object.
// $xml, which is an jQuery xml object.
function xml2object($xml) {
var obj = new Object();
if ($xml.find('response').size() > 0) {
var _response = _recursiveXml2Object($xml.find('response'));
obj.type = 'response';
obj.response = _response;
}
else if ($xml.find('error').size() > 0) {
var _code = $xml.find('code').text();
var _message = $xml.find('message').text();
log.warn('MAIN : error code = ' + _code);
log.warn('MAIN : error msg = ' + _message);
obj.type = 'error';
obj.error = {
code: _code,
message: _message
};
}
else if ($xml.find('config').size() > 0) {
var _config = _recursiveXml2Object($xml.find('config'));
obj.type = 'config';
obj.config = _config;
}
else {
obj.type = 'unknown';
}
return obj;
}
function getAjaxData(urlstr, callback_func, options) {
var myurl = AJAX_HEADER + urlstr + AJAX_TAIL;
var isAsync = true;
var nTimeout = AJAX_TIMEOUT;
var errorCallback = null;
if (options) {
if (options.sync) {
isAsync = (options.sync == true) ? false : true;
}
if (options.timeout) {
nTimeout = parseInt(options.timeout, 10);
if (isNaN(nTimeout)) {
nTimeout = AJAX_TIMEOUT;
}
}
errorCallback = options.errorCB;
}
var headers = {};
headers['__RequestVerificationToken'] = g_requestVerificationToken;
$.ajax({
async: isAsync,
headers: headers,
//cache: false,
type: 'GET',
timeout: nTimeout,
url: myurl,
//dataType: ($.browser.msie) ? "text" : "xml",
error: function(XMLHttpRequest, textStatus) {
try {
if (jQuery.isFunction(errorCallback)) {
errorCallback(XMLHttpRequest, textStatus);
}
log.error('MAIN : getAjaxData(' + myurl + ') error.');
log.error('MAIN : XMLHttpRequest.readyState = ' + XMLHttpRequest.readyState);
log.error('MAIN : XMLHttpRequest.status = ' + XMLHttpRequest.status);
log.error('MAIN : textStatus ' + textStatus);
}
catch (exception) {
log.error(exception);
}
},
success: function(data) {
log.debug('MAIN : getAjaxData(' + myurl + ') sucess.');
log.trace(data);
var xml;
if (typeof data == 'string' || typeof data == 'number') {
if (-1 != this.url.indexOf('/api/sdcard/sdcard')) {
data = sdResolveCannotParseChar(data);
}
if (!window.ActiveXObject) {
var parser = new DOMParser();
xml = parser.parseFromString(data, 'text/xml');
}
else {
//IE
xml = new ActiveXObject('Microsoft.XMLDOM');
xml.async = false;
xml.loadXML(data);
}
}
else {
xml = data;
}
if (typeof callback_func == 'function') {
callback_func($(xml));
}
else {
log.error('callback_func is undefined or not a function');
}
}
});
}
function getConfigData(urlstr, callback_func, options) {
var myurl = '../' + urlstr + '';
//var myurl = urlstr + "";
var isAsync = true;
var nTimeout = AJAX_TIMEOUT;
var errorCallback = null;
if (options) {
if (options.sync) {
isAsync = (options.sync == true) ? false : true;
}
if (options.timeout) {
nTimeout = parseInt(options.timeout, 10);
if (isNaN(nTimeout)) {
nTimeout = AJAX_TIMEOUT;
}
}
errorCallback = options.errorCB;
}
$.ajax({
async: isAsync,
//cache: false,
type: 'GET',
timeout: nTimeout,
url: myurl,
//dataType: ($.browser.msie) ? "text" : "xml",
error: function(XMLHttpRequest, textStatus, errorThrown) {
try {
log.debug('MAIN : getConfigData(' + myurl + ') error.');
log.error('MAIN : XMLHttpRequest.readyState = ' + XMLHttpRequest.readyState);
log.error('MAIN : XMLHttpRequest.status = ' + XMLHttpRequest.status);
log.error('MAIN : textStatus ' + textStatus);
if (jQuery.isFunction(errorCallback)) {
errorCallback(XMLHttpRequest, textStatus);
}
}
catch (exception) {
log.error(exception);
}
},
success: function(data) {
log.debug('MAIN : getConfigData(' + myurl + ') success.');
log.trace(data);
var xml;
if (typeof data == 'string' || typeof data == 'number') {
if (!window.ActiveXObject) {
var parser = new DOMParser();
xml = parser.parseFromString(data, 'text/xml');
}
else {
//IE
xml = new ActiveXObject('Microsoft.XMLDOM');
xml.async = false;
xml.loadXML(data);
}
}
else {
xml = data;
}
if (typeof callback_func == 'function') {
callback_func($(xml));
}
else {
log.error('callback_func is undefined or not a function');
}
}
});
}
function getDomain(){
getConfigData("config/lan/config.xml", function($xml){
var ret = xml2object($xml);
if(ret.type == "config")
{
DEFAULT_GATEWAY_DOMAIN.push(ret.config.landns.hgwurl.toLowerCase());
if( typeof(ret.config.landns.mcdomain) != 'undefined' )
{
GATEWAY_DOMAIN.push(ret.config.landns.mcdomain.toLowerCase());
}
}
}, {
sync: true
});
}
function getQueryStringByName(item) {
var svalue = location.search.match(new RegExp('[\?\&]' + item + '=([^\&]*)(\&?)', 'i'));
return svalue ? svalue[1] : svalue;
}
function isHandheldBrowser() {
var bRet = false;
if(0 == login_status){
return bRet;
}
if (isIphone || isIpod) {
log.debug("INDEX : current browser is iphone or ipod.");
bRet = true;
}
else if (isPsp) {
log.debug("INDEX : current browser is psp.");
bRet = true;
}
else if (isIpad) {
log.debug("INDEX : current browser is ipad.");
bRet = true;
}
else if (isAndroid) {
log.debug("INDEX : current browser is android.");
bRet = true;
}
else {
log.debug("INDEX : screen.height = " + screen.height);
log.debug("INDEX : screen.width = " + screen.width);
if (screen.height <= 320 || screen.width <= 320) {
bRet = true;
log.debug("INDEX : current browser screen size is small.");
}
}
log.debug("INDEX : isHandheldBrowser = " + bRet);
return bRet;
}
function update_openNewWindow () {
if (window.location.href.indexOf('?updataredirect=') > -1) {
var tmpUrl = window.location.href.substring(window.location.href.indexOf("?updataredirect="));
var newUrl = "http://" + tmpUrl.substring(tmpUrl.indexOf("?updataredirect=") + 16) + '/';
document.getElementById("update_newPage").setAttribute("href", newUrl);
document.getElementById("update_newPage").setAttribute("target", "_blank");
if($.browser.msie) {
$("#update_newPage").get(0).click();
} else {
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, true);
document.getElementById('update_newPage').dispatchEvent(evt);
}
}
}
var g_requestVerificationToken = '';
function getAjaxToken() {
getAjaxData('api/webserver/token', function($xml) {
var ret = xml2object($xml);
if ('response' == ret.type) {
g_requestVerificationToken = ret.response.token;
}
}, {
sync: true
});
}
getAjaxToken();
var WangatewayAddr="";
var gatewayAddr = "";
var conntection_status = null;
var service_status = null;
var login_status = null;
// get current settings gateway address
getAjaxData("api/dhcp/settings", function($xml) {
var ret = xml2object($xml);
if ("response" == ret.type) {
gatewayAddr = ret.response.DhcpIPAddress;
}
}, {
sync : true
}
);
// get connection status
getAjaxData("api/monitoring/status", function($xml) {
var ret = xml2object($xml);
if ("response" == ret.type) {
conntection_status = parseInt(ret.response.ConnectionStatus,10);
service_status = parseInt(ret.response.ServiceStatus,10);
WangatewayAddr = ret.response.WanIPAddress;
}
}, {
sync : true
}
);
// get connection status
getAjaxData('config/global/config.xml', function($xml) {
var config_ret = xml2object($xml);
login_status = config_ret.config.login;
}, {
sync : true
}
);
if ("" == gatewayAddr) {
gatewayAddr = DEFAULT_GATEWAY_IP;
}
var href = "http://" + DEFAULT_GATEWAY_IP;
try {
href = window.location.href;
}
catch(exception) {
href = "http://" + DEFAULT_GATEWAY_IP;
}
// get incoming url from querystring
var incoming_url = href.substring(href.indexOf("?url=") + 5);
// truncate http://
if (incoming_url.indexOf("//") > -1) {
incoming_url = incoming_url.substring(incoming_url.indexOf("//") + 2);
}
//get *.html
var incoming_html = "";
if (incoming_url.indexOf(".html") > -1) {
incoming_html = incoming_url.substring(incoming_url.lastIndexOf("/") + 1, incoming_url.length);
}
// truncate tail
if (incoming_url.indexOf("/") != -1) {
incoming_url = incoming_url.substring(0, incoming_url.indexOf("/"));
}
incoming_url = incoming_url.toLowerCase();
var bIsSmallPage = isHandheldBrowser();
// var prefix = "http://" + gatewayAddr;
var g_indexIncomingUrlIsGateway = false;
// if incoming url == 192.168.1.1 or MobileWifi.home then goto login
// page
window.name = getQueryStringByName("version");
//check login status
var LOGIN_STATES_SUCCEED = "0";
var userLoginState = LOGIN_STATES_SUCCEED;
getAjaxData('api/user/state-login', function($xml) {
var ret = xml2object($xml);
if (ret.type == 'response') {
userLoginState=ret.response.State;
}
}, {
sync: true
});
$(document).ready(function() {
update_openNewWindow();
if(true == bIsSmallPage) {
if (userLoginState != LOGIN_STATES_SUCCEED) {
getAjaxData('config/global/config.xml', function($xml) {
var config_ret = xml2object($xml);
if(config_ret.type == 'config') {
if(config_ret.config.commend_enable == '1') {
gotoPageWithoutHistory("../html/commend.html");
g_indexIncomingUrlIsGateway = true;
}else {
g_indexIncomingUrlIsGateway = redirectOnCondition("",'index');
}
}
},{
sync: true
});
} else {
g_indexIncomingUrlIsGateway = redirectOnCondition("",'index');
}
} else {
g_indexIncomingUrlIsGateway = redirectOnCondition("",'index');
}
$( function() {
getDomain();
if (g_indexIncomingUrlIsGateway) {
return;
}
else if (conntection_status == 901 && service_status == 2) {
if ((incoming_url.indexOf(gatewayAddr)==0)
|| (incoming_url.indexOf(DEFAULT_GATEWAY_DOMAIN)==0)
|| (incoming_url.indexOf(WangatewayAddr)==0)
|| (incoming_url.indexOf(GATEWAY_DOMAIN)==0)){
gotoPageWithoutHistory("home.html");
}
else {
gotoPageWithoutHistory("update.html");
}
}
else {
gotoPageWithoutHistory("home.html");
}
});
});
</script>
</head>
<body style="background-color: #FFFFFF;">
<div>
<a id="update_newPage" href="#" target="_blank"></a>
</div>
<noscript>
Sorry, your browser does not support javascript.
</noscript>
</body>
</html>

This looks like a DNS intercept/attempted redirect by a router. It looks like a situation where a 200 is returned with content that is not what was requested. The question now becomes "How can this type of situation be detected?"
One approach would be to use http://clients1.google.com/generate_204 to tell whether you are behind a captive portal or not: since a 204 would be unlikely to be used by the router in this situation. However this seems like a flawed approach for this use case.
Perhaps this question would be a good example of why one should not roll one's own cache?
Anyway is this necessary at all? I'm starting to think HTTP caching in Unity may just work without this...

Related

Send multi ajax at the same time, time response is slowly

In my current project using ASP.Net vs AngularJs. Now I have a problem about time response of the server.
When load page I send 2 requests ajax to get data.
If I send at the same time function getTopicInfo() and getAnswerList()
$scope.init = function (categoryId, topicId, answerId, commentId, userId) {
$scope.categoryId = categoryId;
$scope.topicId = topicId;
$scope.answerId = answerId;
$scope.commentId = commentId;
$scope.userId = userId;
$scope.currentPage = 1;
$scope.itemsPerPage = 10;
$scope.orderBy = getTopicOrderBy();
getTopicInfo();
getAnswerList();
}
Time response is slowly.
If I call function getAnswerList() after 200ms
$scope.init = function (categoryId, topicId, answerId, commentId, userId) {
$scope.categoryId = categoryId;
$scope.topicId = topicId;
$scope.answerId = answerId;
$scope.commentId = commentId;
$scope.userId = userId;
$scope.currentPage = 1;
$scope.itemsPerPage = 10;
$scope.orderBy = getTopicOrderBy();
getTopicInfo();
setTimeout(function () {
getAnswerList()
}, 200);
}
Time response is quick
I really don't understand. I spend a lot of time on this.
Code of function getTopicInfo() and getAnswerList()
function getTopicInfo() {
var data = {};
data.CategoryId = $scope.categoryId;
data.TopicId = $scope.topicId;
$.ajax({
type: "POST",
url: link("/Topic/GetInfo"),
data: data,
success: function (data) {
$scope.topicInfo = data.Data.TopicInfo;
$scope.load += 1;
$scope.$apply();
addListener();
}
});
}
function getAnswerList(page, scroll) {
page = page || 0;
scroll = scroll != false ? true : false;
var data = {};
data.CategoryId = $scope.categoryId;
data.TopicId = $scope.topicId;
if (page == 0) {
data.CurrentPage = $scope.currentPage;
data.AnswerId = $scope.answerId;
data.CommentId = $scope.commentId;
} else {
data.CurrentPage = page;
data.AnswerId = 0;
data.CommentId = 0;
}
data.ItemsPerPage = $scope.itemsPerPage;
data.OrderBy = $scope.orderBy;
$.ajax({
type: "POST",
url: link("/Answer/GetList"),
data: data,
success: function (data) {
$scope.answerList = data.Data.AnswerList;
$scope.currentPage = data.Data.CurrentPage;
$scope.totalItems = data.Data.TotalItems;
$scope.load += 1;
$scope.$apply();
if (page == 0 && $scope.answerId != 0) {
setTimeout(function () {
scrollToId("answer" + $scope.answerId);
if ($scope.commentId != 0) {
var commentId = $scope.commentId;
if (!$("#comment" + commentId).isInViewport()) {
scrollToId("comment" + commentId);
}
$("#comment" + commentId).css("background-color", "orange")
$("#comment" + commentId).animate({ 'backgroundColor': 'rgba(0, 0, 0, 0)' }, 1000);
}
}, 10);
}
if (page != 0 && scroll) {
scrollToId("answers-header");
}
addListener();
}
});
}

How to show message or alert when record insertion success of fail in the controller

In my _Layout.cshtml page there is a textbox that allows user to type his/her email address(this is for newsletter).if typed email address exists it does not insert to the database and if not it insert to the database. at the same time if not inserted I want to show an error message and if insert I want to show success message.this is how I insert to the database,
public ActionResult getNewsLetterMail(string N_id, string N_EmailAdd)
{
Session["Ealert"] = null;
Random random = new Random();
int idONe = random.Next(99, 999);
int idTwo = random.Next(999, 9999);
string middle = "menuka";
string fullID = idONe.ToString() + middle + idTwo.ToString();
var N_ID = fullID;
var N_Email = N_EmailAdd;
TourCenterDBEntities NewsLetterEntities = new TourCenterDBEntities();
var existing = NewsLetterEntities.News_Letter.Where(l => l.N_Email == N_EmailAdd);
Debug.WriteLine(existing.Count());
if (existing.Count() == 0)
{
News_Letter NewsLetterDetails = new News_Letter();
NewsLetterDetails.N_id = N_ID;
NewsLetterDetails.N_Email = N_Email;
NewsLetterEntities.News_Letter.Add(NewsLetterDetails);
NewsLetterEntities.SaveChanges();
//want to send success text
}
else
{
//want to send error text
}
return Json(new { });
}
if success or error it returns to the same _Layout.csthml page.
how can I do that.hope your help.
You can use. return content.
if (existing.Count() == 0)
{
News_Letter NewsLetterDetails = new News_Letter();
NewsLetterDetails.N_id = N_ID;
NewsLetterDetails.N_Email = N_Email;
NewsLetterEntities.News_Letter.Add(NewsLetterDetails);
NewsLetterEntities.SaveChanges();
//return Content("Your information saved successfully");
return new JavascriptResult { Script = "alert('Your information saved successfully');" };
}
else
{
//return Content("Already exist. Please choose another.");
return new JavascriptResult { Script = "alert('Your information saved successfully');" };
}
public ActionResult getNewsLetterMail(string N_id, string N_EmailAdd)
{
Session["Ealert"] = null;
Random random = new Random();
int idONe = random.Next(99, 999);
int idTwo = random.Next(999, 9999);
string middle = "menuka";
string fullID = idONe.ToString() + middle + idTwo.ToString();
var N_ID = fullID;
var N_Email = N_EmailAdd;
TourCenterDBEntities NewsLetterEntities = new TourCenterDBEntities();
var existing = NewsLetterEntities.News_Letter.Where(l => l.N_Email == N_EmailAdd);
Debug.WriteLine(existing.Count());
string myMessage="";
if (existing.Count() == 0)
{
News_Letter NewsLetterDetails = new News_Letter();
NewsLetterDetails.N_id = N_ID;
NewsLetterDetails.N_Email = N_Email;
NewsLetterEntities.News_Letter.Add(NewsLetterDetails);
NewsLetterEntities.SaveChanges();
myMessage="success";
}
else
{
myMessage="failed";
}
return Json(myMessage, JsonRequestBehavior.AllowGet);
}
In your view.
$.post('#Url.Action("getNewsLetterMail", "yourControllerName")', { N_id: N_id, N_EmailAdd: N_EmailAdd }).done(function (data) {
if (data == "success") {
alert("Success!");
}
if( data== "failed") {
alert("Failed!");
}
}
I have no experience but I would try something like that:
in my viewmodel I would put
string info
then in my razor view
#Html.DisplayFor(m=>m.info)
and in controller
if(existing){info="success"}
You would have to pass info to the viewmodel in your controller
public ActionResult getNewsLetterMail(string N_id, string N_EmailAdd)
{
Session["Ealert"] = null;
Random random = new Random();
int idONe = random.Next(99, 999);
int idTwo = random.Next(999, 9999);
string middle = "menuka";
string fullID = idONe.ToString() + middle + idTwo.ToString();
var N_ID = fullID;
var N_Email = N_EmailAdd;
TourCenterDBEntities NewsLetterEntities = new TourCenterDBEntities();
var existing = NewsLetterEntities.News_Letter.Where(l => l.N_Email == N_EmailAdd);
Debug.WriteLine(existing.Count());
string myMessage="";
if (existing.Count() == 0)
{
News_Letter NewsLetterDetails = new News_Letter();
NewsLetterDetails.N_id = N_ID;
NewsLetterDetails.N_Email = N_Email;
NewsLetterEntities.News_Letter.Add(NewsLetterDetails);
NewsLetterEntities.SaveChanges();
myMessage="success!";
}
else
{
myMessage="Failed!";
}
return Json(myMessage, JsonRequestBehavior.AllowGet);
}
In Views, you can add jquery to display the message. Following is an example to retrieve the message in Views. You can edit the names in your form accordingly.
`<script type="text/javascript">
$(document).ready(function () {
$("#yourForm").submit(function (e) {
e.preventDefault();
var valid = $("#yourForm").valid();
if (valid) {
$.ajax({
url: "/getNewsLetterMail",
type: "POST",
data: {
Name: $("#N_id").val(),
Email: $("#N_EmailAdd").val(),
},
success: function (data) {
alert(data);
reset();
}
});
}
});
});
</script>'

SignalR disconnecting all Clients when a single client refresh the page

I have problem with signalR with multiple client and async background task.
Here is my Scenario:
I have multiple clients doing multiple downloads.. they can download files simultaneously, I use signalR to send them the progress of there download. I handled it fine but the problem is when a single user invokes the Disconnect Method or he leaves or refresh its page, signalR will Disconnect all its client not only the one who is disconnecting which will interrupt the progress report for other client. How will I resolve this issue.?? Is there Any other way handling it??
additional:
private async Task WriteRecords([DataSourceRequest] DataSourceRequest dataRequest,int countno, VMEXPORT[] arrVmExport, bool createHeaderyn, string filePath )
{
string fileName = filePath.Replace(System.Web.HttpContext.Current.Server.MapPath("~/") + "Csv\\", "").Replace(".csv", "");
int datapage = (countno / 192322)+1;
for (int i = 1; i <= datapage; )
{
dataRequest.Page = i;
dataRequest.PageSize = 192322;
var write = _serviceAgent.FetchByRole("", "", CurrentUser.Linkcd, CurrentUser.Rolecd).ToDataSourceResult(dataRequest);
await Task.Run(()=>write.Data.Cast<AGENT>().WriteToCSV(new AGENT(), createHeaderyn, arrVmExport, filePath));
createHeaderyn = false;
i = i + 1;
double percentage = (i * 100) / datapage;
SendProgress(percentage, countno,fileName);
}
}
Here is the set up in my BaseController which calls the hub context:
public void SendNotification(string fileNametx, bool createdyn)
{
var context = GlobalHost.ConnectionManager.GetHubContext<SignalRHubHelper>();
context.Clients.User(CurrentUser.Usernm + '-' + CurrentUser.GUID)
.receiveNotification("Export", CurrentUser.Usernm, "info", fileNametx, createdyn);
}
public void SendProgress(double recordCount, int totalCount,string fileName)
{
var context = GlobalHost.ConnectionManager.GetHubContext<SignalRHubHelper>();
context.Clients.User(CurrentUser.Usernm + '-' + CurrentUser.GUID).reportProgress(recordCount, totalCount,fileName);
}
And Here is my controller Method:
public async Task<ActionResult> _Export([DataSourceRequest] DataSourceRequest dataRequest, string columns,int countno, string menunm)
{
var fileNametx = AgentsPrompttx + DateTime.Now.ToString(GeneralConst.L_STRING_DATE4) + ".csv";
SendNotification(fileNametx, false);
var filePath = System.Web.HttpContext.Current.Server.MapPath("~/") + "Csv\\";
var vmexport = new JavaScriptSerializer().Deserialize<VMEXPORT[]>(columns);
dataRequest.GroupingToSorting();
dataRequest.PageSize = 0; // set to zero
await WriteRecords(dataRequest,countno, vmexport, true, filePath + fileNametx);
SendNotification(fileNametx, true);
return File(filePath + fileNametx, WebConst.L_CONTENTTYPE_APP_OCTET, fileNametx);
}
JavaSciprt:
init: function (element) {
var self = this;
self.msgno = undefined;
self.sfiHubConnection = $.connection.signalRHubHelper;
self.initSignalRClients();
$.connection.hub.logging = true;
$.connection.hub.start({ transport: "longPolling" }).done(function () {
setTimeout(function () {
self.sfiHubConnection.server.getAllStatus();
self.sfiHubConnection.server.brodcastLogIn($('#usernm').text());
}, 1000);
}).fail(function () {
alert("signal Failed")
});
},
triggerReconnect: function () {
var self = this;
$.connection.hub.stateChanged(function (change) {
if (change.newState === $.signalR.connectionState.disconnected) {
$.connection.hub.stop();
self.init();
}
});
},
deleteFile: function (controllertx, filenametx) {
$('#close_dl_link').on('click', function () {
$.get(GetAppPath() + controllertx + '/_DeleteFile/?Filenametx='+filenametx, function () {
return true;
});
});
},
initSignalRClients: function () {
var self = this;
self.sfiHubConnection = $.connection.signalRHubHelper
self.sfiHubConnection.client.setOnline = function (usernm) {
if ($('#user_kgrid').data('kendoGrid') != undefined)
$('#user_kgrid').data('kendoGrid').tbody.find('td:contains("' + usernm + '")').eq(0).parent('tr').find('td:contains("Offline")').html('<span><i class="icon-ok-sign"></i></span> Online')
};
self.sfiHubConnection.client.receiveNotification = function (controller, totx, type, fileNametx, createdyn) {
if (totx == $('#usernm').text()) {
if (!createdyn) {
self.init();
var fileId=fileNametx.replace(".csv","")
var icon = "icon-download";
var title = fileId +':'+ ' <span id="' + fileId + '"></span> <br>';
var message = "Creating file kindly wait..";
var delay = 0;
SfiNotify(icon, title, message, 'info', "", "", "", "", delay);
}
else if (createdyn && fileNametx !== "") {
console.log("download available: "+fileNametx)
var elementid = fileNametx.replace(".csv", "");
$('#' + elementid).parents(".alert").each(function () {
$(this).remove();
});
var icon = "icon-download";
var title = " File ready for download !<br>" + "<strong>" + fileNametx + "</strong><br>";
var message = "Click here to download the file!";
var url = GetAppPath() + controller + '/_Download/?filenametx=' + fileNametx;
var delay = 0;
SfiNotify(icon, title, message, 'info', url, "", "", "", delay);
if ($('#close_dl_link').length > 0) {
self.deleteFile(controller, fileNametx);
}
}
}
else
return false;
};
self.sfiHubConnection.client.reportProgress = function (recordCount, totalRecord, fileName) {
var progress = recordCount + "% of " + totalRecord;
console.log("PROGRESS FOR: " + fileName + "TOTAL: "+recordCount);
if ($('#' + fileName).length > 0) {
if (recordCount > 100)
return false;
$('#' + fileName).text(progress);
}
else if($('#' + fileName).length == 0)
{
if (recordCount > 100)
return false;
var icon = "icon-download";
var title = ' Processing Records <span id=' + fileName + '>' + progress + '</span> <br>';
var message = "Creating file kindly wait..";
var delay = 0;
SfiNotify(icon, title, message, 'info', "", "", "", "", delay);
}
};

upload image to server from javascript

I am using the below code to view the uploaded file using javascript. It display the fake path so i can't able to upload the files to server path. please help me to upload the images to server.mappath folder.
<input type='file' name='file' id='file' value='Choose Photo' accept='image/png,image/jpeg' onchange='handleFileSelect(this);' />
<script type="text/javascript">
function handleFileSelect(input) {
try {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById('hf_image').value = e.target.result
$('#preview').attr('src', document.getElementById('hf_image').value);
}
reader.readAsDataURL(input.files[0]);
}
}
catch (ex) {
alert('Image Preview : ' + ex.Message);
}
}
</script>
var attachments={};
function imageSelected(myFiles){
for (var i = 0, f; f = myFiles[i]; i++) {
var imageReader = new FileReader();
imageReader.onload = (function(aFile){
return function(e){
var tempFileData=e.target.result;
attachments[aFile.name]={};
attachments[aFile.name]["content_type"]=tempFileData.split(",")[0].split(":")[1].split(";")[0];
attachments[aFile.name]["data"]=tempFileData.split(",")[1];
};
})(f);
imageReader.readAsDataURL(f);
}
}
<input type='file' onchange="imageSelected(this.files)">
the above code may be helpful for you
attachments json holds the file details
Why you don't use AjaxFileUploader, that is easy to use
Follow this steps to approach your target,
Step 1:
dRAG Jquery files to Head tag.
add this code to a JavaScript file and dragged it into the head of your page.
jQuery.extend({
createUploadIframe: function (id, uri) {
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if (window.ActiveXObject) {
if (typeof uri == 'boolean') {
iframeHtml += ' src="' + 'javascript:false' + '"';
}
else if (typeof uri == 'string') {
iframeHtml += ' src="' + uri + '"';
}
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body);
return jQuery('#' + frameId).get(0);
},
createUploadForm: function (id, fileElementId, data) {
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if (data) {
for (var i in data) {
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
ajaxFileUpload: function (s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data));
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if (s.global && !jQuery.active++) {
jQuery.event.trigger("ajaxStart");
}
var requestDone = false;
// Create the request object
var xml = {}
if (s.global)
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function (isTimeout) {
var io = document.getElementById(frameId);
try {
if (io.contentWindow) {
xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
} else if (io.contentDocument) {
xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
}
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
if (xml || isTimeout == "timeout") {
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if (status != "error") {
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData(xml, s.dataType);
// If a local callback was specified, fire it and pass it the data
if (s.success)
s.success(data, status);
// Fire the global callback
if (s.global)
jQuery.event.trigger("ajaxSuccess", [xml, s]);
} else
jQuery.handleError(s, xml, status);
} catch (e) {
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if (s.global)
jQuery.event.trigger("ajaxComplete", [xml, s]);
// Handle the global AJAX counter
if (s.global && ! --jQuery.active)
jQuery.event.trigger("ajaxStop");
// Process result
if (s.complete)
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function () {
try {
jQuery(io).remove();
jQuery(form).remove();
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if (s.timeout > 0) {
setTimeout(function () {
// Check to see if the request is still happening
if (!requestDone) uploadCallback("timeout");
}, s.timeout);
}
try {
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if (form.encoding) {
jQuery(form).attr('encoding', 'multipart/form-data');
}
else {
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit();
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
jQuery('#' + frameId).load(uploadCallback);
return { abort: function () { } };
},
uploadHttpData: function (r, type) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if (type == "script")
jQuery.globalEval(data);
// Get the JavaScript object, if JSON is used.
if (type == "json")
eval("data = " + data);
// evaluate scripts within html
if (type == "html")
jQuery("<div>").html(data).evalScripts();
return data;
}
})
something like this:
<script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="Scripts/fileUploader.js" type="text/javascript"></script>
Step 2:
Add this tags into body page.
<input id="fileToUpload" type="file" size="45" name="fileToUpload" />
<button id="btnUploadNewLicense" onclick="return ajaxFileUpload('New');">
Upload</button><br />
<div id="loading" style="display: none;">
Please wait...</div>
Step 3:
Add a generic handler file named "FileUpload.ashx" into the your project root,
add this following code into "FileUplod.ashx"
public void ProcessRequest(HttpContext context)
{
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string action = request["Action"];
switch (action)
{
case "New":
string result = "failed";
try
{
string fileName = SaveCaper(context);
result = "successed";
response.Write("{\"result\":" + result.ToString().ToLower() + "}");
}
catch
{
response.Write("{\"result\":" + result.ToString().ToLower() + "}");
}
break;
default:
throw new Exception("Invalid sort column name!.");
}
}
private string SaveCaper(HttpContext context)
{
string fileName = string.Empty;
string path = context.Server.MapPath("~/NewImages");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
try
{
var file = context.Request.Files[0];
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
{
string[] files = file.FileName.Split(new char[] { '\\' });
fileName = files[files.Length - 1];
}
else
{
fileName = file.FileName;
}
string strFileName = fileName;
fileName = Path.Combine(path, fileName);
try
{
file.SaveAs(fileName);
}
catch (Exception exp)
{
//log the exception
}
}
catch (Exception exp)
{
//log the exception
}
return fileName;
}
public bool IsReusable
{
get
{
return false;
}
}
also you need to add System.IO in top of the handler code behind.
Step 4:
Add this script to your head after your JS files prototype
<script language="javascript" type="text/javascript">
$(document).ready(function () {
function ajaxFileUpload(mode) {
var fupl = 'fileToUpload';
var fileName = $('#fileToUpload').val();
if (fileName == "" || fileName == null)//if user doesn't select an image
{
$("#loading").html("");
$("#loading").append("<br/><b>Please select an image...</b>");
}
else {
var vars = fileName.split("."); //get file extension.
if (vars[1].toString().toLowerCase() != "jpg") {//check the file extension.
$("#loading").html("");
$("#loading").append("<br/>The image format is not valid !.");
return false;
}
$("#loading").ajaxStart(function () { $('#dialogUpdateLicense :input').attr('disabled', true); $(this).show(); })
.ajaxComplete(function () { $('#dialogUpdateLicense :input').removeAttr('disabled'); });
$("#loading").html("");
$("#loading").append("<br/><b>Please wait...</b>");
$.ajaxFileUpload
({
url: 'FileHandler.ashx',
secureuri: false,
fileElementId: 'fileToUpload',
dataType: 'json',
data: { Action: mode },
success: function (data) {
if (data.result == "successed")
$("#loading").html("The image uploaded successfully!.");
},
error: function (data, e) {
$("#loading").html("An error occured!.");
}
})
}
return false;
}
</script>
All thing was tested and works properly for me
I hope it will help you.

How to capture the video to the server using getusermedia

In my application, I want the user to record his video. Then the video should be downloaded to the Server disk. But it is downloading to the client browser. How can i save the 2 or 3 min video to the server. I have used getusermedia for this. I have written code like:
(function(exports) {
exports.URL = exports.URL || exports.webkitURL;
exports.requestAnimationFrame = exports.requestAnimationFrame ||
exports.webkitRequestAnimationFrame || exports.mozRequestAnimationFrame ||
exports.msRequestAnimationFrame || exports.oRequestAnimationFrame;
exports.cancelAnimationFrame = exports.cancelAnimationFrame ||
exports.webkitCancelAnimationFrame || exports.mozCancelAnimationFrame ||
exports.msCancelAnimationFrame || exports.oCancelAnimationFrame;
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia || navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
var ORIGINAL_DOC_TITLE = document.title;
var video = $('video');
var canvas = document.createElement('canvas');
var rafId = null;
var startTime = null;
var endTime = null;
function $(selector) {
return document.querySelector(selector) || null;
}
function toggleActivateRecordButton() {
var b = $('#record-me');
b.textContent = b.disabled ? 'Record' : 'Recording...';
b.classList.toggle('recording');
b.disabled = !b.disabled;
}
function turnOnCamera(e) {
e.target.disabled = true;
$('#record-me').disabled = false;
video.controls = false;
var finishVideoSetup_ = function() {
setTimeout(function() {
video.width = 320;
video.height = 240;
canvas.width = video.width;
canvas.height = video.height;
}, 1000);
};
navigator.getUserMedia({video: true}, function(stream) {
video.src = window.URL.createObjectURL(stream);
finishVideoSetup_();
}, function(e) {
video.src = 'Chrome_ImF.mp4';
finishVideoSetup_();
});
if (navigator.getUserMedia) {
navigator.getUserMedia({ audio: true }, onRecordSucces, onFail);
} else {
console.log('navigator.getUserMedia not to present');
}
};
function record() {
var elapsedTime = $('#elasped-time');
var ctx = canvas.getContext('2d');
var CANVAS_HEIGHT = canvas.height;
var CANVAS_WIDTH = canvas.width;
frames = []; // clear existing frames;
startTime = Date.now();
toggleActivateRecordButton();
$('#stop-me').disabled = false;
function drawVideoFrame_(time) {
rafId = requestAnimationFrame(drawVideoFrame_);
ctx.drawImage(video, 0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
document.title = 'Recording...' + Math.round((Date.now() - startTime) / 1000) + 's';
var url = canvas.toDataURL('image/webp', 1);
frames.push(url);
};
rafId = requestAnimationFrame(drawVideoFrame_);
startRecording();
};
function stop() {
cancelAnimationFrame(rafId);
endTime = Date.now();
$('#stop-me').disabled = true;
document.title = ORIGINAL_DOC_TITLE;
toggleActivateRecordButton();
embedVideoPreview();
};
function embedVideoPreview(opt_url) {
var url = opt_url || null;
var video = $('#video-preview video') || null;
var downloadLink = $('#video-preview a[download]') || null;
if (!video) {
video = document.createElement('video');
video.autoplay = true;
video.controls = true;
video.style.width = canvas.width + 'px';
video.style.height = canvas.height + 'px';
$('#video-preview').appendChild(video);
downloadLink = document.createElement('a');
downloadLink.download = 'capture.webm';
downloadLink.textContent = '[ download video ]';
downloadLink.title = 'Download your .webm video';
var p = document.createElement('p');
p.appendChild(downloadLink);
$('#video-preview').appendChild(p);
} else {
window.URL.revokeObjectURL(video.src);
}
if (!url) {
webmBlob = Whammy.fromImageArray(frames, 1000 / 60);
url = window.URL.createObjectURL(webmBlob);
video.src = url;
downloadLink.href = url;
}
function initEvents() {
$('#camera-me').addEventListener('click', turnOnCamera);
$('#record-me').addEventListener('click', record);
$('#stop-me').addEventListener('click', stop);
}
initEvents();
exports.$ = $;
})(window);
When i am clicking on the download link it is downloaded to the user browser. But i want to send the data to server and save it in the server disk. I have tried to pass the webmblob data to the controller and retrieve. But it is not accessing. I have written code like
$.ajax({
url: '/Home/VideoData',
type: 'POST',
dataType: 'blob',
cache: false,
data: {
data: webmblob
},
contentType: "application/json; charset=utf-8",
error: function (xhr, status, error) {
},
success: function () {
},
});
In the controller i have defined like
public ActionResult VideoData(string data)
{
return Json("success", JsonRequestBehavior.AllowGet);
}
But the data coming to the controller like [object blob].
Sorry for my English. Hope you understand my question. How can i convert it to the video. Any help is surely appreciated.
The Media Recorder API is now supported by both Chrome (49+) and Firefox (30+) and it relies on getUserMedia() to access the webcam.
The video data is stored locally in a JavaScript video/webm Blob object and can be:
played back in a <video> element
downloaded to the client computer as a .webm file
uploaded (POSTed) to a webserver for storage and conversion
This article covers the spec in detail and here's a live demo + GitHub project.
Spec is avb. at w3c
MediaStreamRecorder is a WebRTC API for recording getUserMedia() streams . It allows web apps to create a file from a live audio/video session.
<video autoplay></video>
<script language="javascript" type="text/javascript">
function onVideoFail(e) {
console.log('webcam fail!', e);
};
function hasGetUserMedia() {
// Note: Opera is unprefixed.
return !!(navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia || navigator.msGetUserMedia);
}
if (hasGetUserMedia()) {
// Good to go!
} else {
alert('getUserMedia() is not supported in your browser');
}
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
var video = document.querySelector('video');
var streamRecorder;
var webcamstream;
if (navigator.getUserMedia) {
navigator.getUserMedia({audio: true, video: true}, function(stream) {
video.src = window.URL.createObjectURL(stream);
webcamstream = stream;
// streamrecorder = webcamstream.record();
}, onVideoFail);
} else {
alert ('failed');
}
function startRecording() {
streamRecorder = webcamstream.record();
setTimeout(stopRecording, 10000);
}
function stopRecording() {
streamRecorder.getRecordedData(postVideoToServer);
}
function postVideoToServer(videoblob) {
var data = {};
data.video = videoblob;
data.metadata = 'test metadata';
data.action = "upload_video";
jQuery.post("http://www.foundthru.co.uk/uploadvideo.php", data, onUploadSuccess);
}
function onUploadSuccess() {
alert ('video uploaded');
}
</script>
<div id="webcamcontrols">
<button class="recordbutton" onclick="startRecording();">RECORD</button>
</div>
Spec:
http://www.w3.org/TR/mediastream-recording/
you can get recorder media file, send it to the server.

Categories