Send multi ajax at the same time, time response is slowly - c#

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

Related

What could possibly go wrong with this HTTP caching scheme?

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

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

How to call a C# method using ajax in asp.net C#?

I have a meeting table data and i am using it to send to server side page check my url and tell me why call is not sucessfull even data is passed correctly
here is my ajax call
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'AddNewMeeting.aspx/SaveMeetingShechudar',
dataType: 'json',
data: JSON.stringify(Meeting),
success: function (response) {
alert("success ");
},
error: function (jqXHR, textStatus, errorThrown) //what to do if fails
{
// alert('bad, ' + errorThrown + ", " + jqXHR.responseText + ", " + textStatus);
alert("success failed ");
},
});
here is my code of AddNewMeeting.aspx file
public static void SaveMeetingShechudar(string MDate, string MTime, int MPurpose, int masterID, int RowNumber, string[] name, string[] nic, string[] designation, string[] company, string[] address)
{
int mID = 0;
try
{
#region master part save
MeetingSchedulMaster master = new MeetingSchedulMaster();
master.m_date = Convert.ToDateTime(MDate);
master.m_datetime = MTime;
master.m_host = UserID;
master.m_puposeid = Convert.ToInt32(MPurpose);
master.m_entry_date = DateTime.Now;
if (masterID == 0)
saveDataMaster(master);
else
{
master.mid = masterID;
UpdateData(master);
}
#endregion
#region detail part save
if (MasterIDForUpdation == 0)
mID = GetMaxMeetinNumber_ID("2");
else
mID = masterID;
for (int i = 1; i <= RowNumber; i++)
{
MeetingSchedulDetail detail = new MeetingSchedulDetail();
//TableRow row = tbladdnewmeeting.Rows[i-1];
detail.name = name[i];
detail.cnic = nic[i];
detail.designation = designation[i];
detail.company = company[i];
detail.address = address[i];
detail.mid = mID;
saveDataDetail(detail);
}
}
catch (Exception e) { }
}
error
http://localhost:57927/forms/AddNewMeeting.aspx/SaveMeetingShechudar
500 (Internal Server Error)
Try adding the [WebMethod] attribute.Which is in the System.Web.Services namespace:
**[WebMethod]**
public static void SaveMeetingShechudar(string MDate, string MTime, int MPurpose, int masterID, int RowNumber, string[] name, string[] nic, string[] designation, string[] company, string[] address)
{
int mID = 0;
try
{
#region master part save
MeetingSchedulMaster master = new MeetingSchedulMaster();
master.m_date = Convert.ToDateTime(MDate);
master.m_datetime = MTime;
master.m_host = UserID;
master.m_puposeid = Convert.ToInt32(MPurpose);
master.m_entry_date = DateTime.Now;
if (masterID == 0)
saveDataMaster(master);
else
{
master.mid = masterID;
UpdateData(master);
}
#endregion
#region detail part save
if (MasterIDForUpdation == 0)
mID = GetMaxMeetinNumber_ID("2");
else
mID = masterID;
for (int i = 1; i <= RowNumber; i++)
{
MeetingSchedulDetail detail = new MeetingSchedulDetail();
//TableRow row = tbladdnewmeeting.Rows[i-1];
detail.name = name[i];
detail.cnic = nic[i];
detail.designation = designation[i];
detail.company = company[i];
detail.address = address[i];
detail.mid = mID;
saveDataDetail(detail);
}
}
catch (Exception e) { }
}

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

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