SignalR disconnecting all Clients when a single client refresh the page - c#

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

Related

Xamarin forms Crash when user exit screen and come back after PUT process

My XF app crash when user try to open any screen after finishing update data in one specific screen, the others works well.
Only I got is :
"08-20 23:41:19.211 W/art (15347): JNI RegisterNativeMethods: attempt to register 0 native methods for android.runtime.JavaProxyThrowable".
No HokeyApp message received in my email and no extra information appears so I can solve the problem, just crash and close the app.
I tried to decrease the amount of requests to local database, tried to follow step by step the execution process so I could get any clue about causes.
Task act = Task.Run(async () => await App.DataService.UpdateItemAsync(CP, ToServer, "Contact_Party/EditContact_Party/" + CP.Id));
await act.ContinueWith(async (antecedent) =>
{
foreach (var sam in specialty)
{
if (CP.Id > 0)
{
sam.Cntct_SEQ = CP.Id;
}
else
{
sam.Tmp_Cntct_SEQ = CP.Cntct_SEQ;
}
if (sam.Id == 0)
{
if (sam.Cntct_Spec_SEQ == 0)
await App.DataService.CreateItemAsync(sam, ToServer, "Contact_Specialty/AddContact_Specialty");
else
{
await App.DataService.UpdateItemAsync(sam, ToServer, "Contact_Specialty/EditContact_Specialty/" + sam.Id);
}
}
else
{
await App.DataService.UpdateItemAsync(sam, ToServer, "Contact_Specialty/EditContact_Specialty/" + sam.Id);
}
}
}, TaskContinuationOptions.None);
Below is the other code or the final step in Update data...
public async Task<T> UpdateItemAsync<T>(T item, bool ToServer, string url) where T : BaseModel, new()
{
try
{
HttpResponseMessage hrm = new HttpResponseMessage();
if (!CrossConnectivity.Current.IsConnected)
ToServer = false;
if (ToServer)
{
RestURL = PrimaryRestURL;
RestURL += url;
var content = JsonConvert.SerializeObject(item);
content = content.Replace("null", " ");
try
{
hrm = await _client.PutAsync(RestURL, new StringContent(content, System.Text.Encoding.UTF8, "application/json"));
RestURL = PrimaryRestURL;
}
catch (Exception hre)
{
RestURL = PrimaryRestURL;
ContentPage page = new ContentPage();
string inner = "", source = "", trace = "", data = "";
if (hre.InnerException != null)
inner = hre.InnerException.Message;
data = hre.Data.ToString();
source = hre.Source;
trace = hre.StackTrace;
string msg = "RestURL: " + RestURL + "\n\n Data: " + data + "\n\n Message: " + hre.Message + "\n\n Source: " + source + "\n\n Trace: " + trace + "\n\n Inner Message: " + inner;
await page.DisplayAlert("Error", msg, "Ok");
}
if (hrm.StatusCode == System.Net.HttpStatusCode.OK || hrm.StatusCode == System.Net.HttpStatusCode.NoContent)
{
item.Updated = true;
await database.UpdateAsync(item);
DependencyService.Get<IMessage>().LongAlert("Completed");
}
else
{
item.Changed = true;
await database.UpdateAsync(item);
DependencyService.Get<IMessage>().LongAlert("Error connection to server");
}
}
else
{
item.Changed = true;
await database.UpdateAsync(item);
DependencyService.Get<IMessage>().LongAlert("Completed");
}
}
catch (Exception xc)
{
ContentPage page = new ContentPage();
string inner = "", source = "", trace = "", data = "";
if (xc.InnerException != null)
inner = xc.InnerException.Message;
data = xc.Data.ToString();
source = xc.Source;
trace = xc.StackTrace;
string msg = "RestURL: " + RestURL + "\n\n Data: " + data + "\n\n Message: " + xc.Message + "\n\n Source: " + source + "\n\n Trace: " + trace + "\n\n Inner Message: " + inner;
await page.DisplayAlert("Error", msg, "Ok");
}
return item;
}
Finally, I solved the issue, it was because I wanted to make the process of updating in a task so being continues with sub updates, after implementeing each update process alone it work ... the code that produced the issue is:
Task act = Task.Run(async () => await App.DataService.UpdateItemAsync(CP, ToServer, "Contact_Party/EditContact_Party/" + CP.Id));
await act.ContinueWith(async (antecedent) =>
{
foreach (var sam in specialty)
{
if (CP.Id > 0)
{
sam.Cntct_SEQ = CP.Id;
}
else
{
sam.Tmp_Cntct_SEQ = CP.Cntct_SEQ;
}
if (sam.Id == 0)
{
if (sam.Cntct_Spec_SEQ == 0)
await App.DataService.CreateItemAsync(sam, ToServer, "Contact_Specialty/AddContact_Specialty");
else
{
await App.DataService.UpdateItemAsync(sam, ToServer, "Contact_Specialty/EditContact_Specialty/" + sam.Id);
}
}
else
{
await App.DataService.UpdateItemAsync(sam, ToServer, "Contact_Specialty/EditContact_Specialty/" + sam.Id);
}
}
}, TaskContinuationOptions.None);

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

Execute Task.Run() in ASP.NET ActionResult without waiting for result

Below is the function where I am trying to execute a function in the background and then carry on without waiting for a result from it.
When debugging the task itself is executed but the actual function within it does not. The rest of the code then carries on like normal.
What could be the issue as there is no error produced after that to indicate otherwise?
This is on a page load.
public ActionResult ExceptionReport(int? id)
{
var ExceptionList = db.Invoices.Where(m => m.ExceptionFlag == true && m.GlobalInvoiceID == id);
if (ExceptionList.Count() == 0)
{
globalInvoice.Status = "Exception Verification";
db.Entry(globalInvoice).State = EntityState.Modified;
db.SaveChanges();
Task.Run(() => ExceptionFinalTests(globalInvoice)); //Function To run in the background
TempData["warning"] = "Verifying all exceptions fixed. A notification will be sent when the verifications are complete.";
return RedirectToAction("Index", "GlobalInvoices");
}
return View(ExceptionList);
}
private void ExceptionFinalTests(GlobalInvoice globalInvoice)
{
RunTests(globalInvoice, true);
decimal TotalPaymentAmount = db.Invoices.Where(m => m.GlobalInvoiceID == globalInvoice.Id).Sum(m => m.Invoice_Amount) ?? 0;
}
GlobalInvoicesController globalInvoicesController = new GlobalInvoicesController();
var ApproverList = globalInvoicesController.GetUserEmailsInRole(globalInvoice, "Reviewer");
globalInvoicesController.Dispose();
var exceptionExistCompulsoryTest = db.Invoices.Where(m => m.ExceptionFlag == true && m.GlobalInvoiceID == globalInvoice.Id);
if (exceptionExistCompulsoryTest.Count() > 0)
{
try
{
string baseUrl = ConfigurationManager.AppSettings["site"];
EmailExtension emailExtension = new EmailExtension();
foreach (var approver in ApproverList)
{
string approvalLink = baseUrl + "/Invoices/ExceptionReport/" + globalInvoice.Id;
StringBuilder mailbody = new StringBuilder();
mailbody.AppendFormat("Hi<br/>");
mailbody.AppendFormat("There are " + exceptionExistCompulsoryTest.Count() + " exceptions for invoice #" + globalInvoice.Id + "that need attention before proceeding. - <a href='" + approvalLink + "'>Click Here</a> <br/><br/>");
mailbody.AppendFormat("Exception Count: {0}<br/>", exceptionExistCompulsoryTest.Count());
mailbody.AppendFormat("Invoice Amount: {0}<br/>", TotalPaymentAmount.ToString("C"));
mailbody.AppendFormat("Reviewed By: {0} <br/>", "");
mailbody.AppendFormat("Approved By: {0} <br/>", "");
EmailVM emailVM = new EmailVM()
{
Subject = "Invoice - #" + globalInvoice.Id,
EmailAddress = approver,
Message = mailbody.ToString()
};
emailExtension.SendEmail(emailVM);
}
}
catch (Exception ex)
{
LogWriter.WriteLog(ex.Message);
LogWriter.WriteLog(ex.StackTrace);
}
}
}
private void RunTests(GlobalInvoice globalInvoice, bool retestFlag = false)
{
List<Invoice> invoices;
var vendorTests = globalInvoice.Vendor.VendorTests;
string[] testsToRun = vendorTests.Split(',');
if (retestFlag == true)
{
if (globalInvoice.Vendor.VendorHasHierarchy == true)
{
testsToRun = new string[] { "Account Number", "Hierarchy" };
}
else
{
testsToRun = new string[] { "Account Number" };
}
}
using (var context = new MyContext())
{
invoices = context.Invoices.Where(m => m.GlobalInvoiceID == globalInvoiceToTestID).ToList();
}
foreach (var test in testsToRun)
{
if (test == "Account Number")
{
LogWriter.WriteLog("Starting Account Number Check : Invoice Batch ID - " + globalInvoice.Id);
AccountNumberCheck(invoices, globalInvoice.VendorID);
LogWriter.WriteLog("Account Number Check Complete : Invoice Batch ID - " + globalInvoice.Id);
}
if (test == "Hierarchy")
{
LogWriter.WriteLog("Starting Hierarchy Check : Invoice Batch ID - " + globalInvoice.Id);
BillingHierarchyCheck(invoices);
LogWriter.WriteLog("Hierarchy Check Complete : Invoice Batch ID - " + globalInvoice.Id);
}
}
}

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

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.

Categories