upload image to server from javascript - c#

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.

Related

MVC Web Api + ajax to create and download Zip File

I am working on a application that has a button, when that button is clicked it calls a web api GET method. This method takes files and creates a zip folder using System.IO.Compression. This part works great. I see the folder it creates and I am able to open / extract that folder with its files. The problem i have is when the file gets returned to the browser and the browser downloads the file I get the following error: " The Compressed (zipped) folder '...pathToTheDownloadedFile.zip' is invalid. I don't understand what I am doing wrong. All other non-zipped files download and open fine.
Here is my web api GET method:
[HttpGet]
[Route("api/OrderManager/ExtractAllDocuments/{orderNum}/{mappingId}/")]
public HttpResponseMessage ExtractAllDocuments(int orderNum, int mappingId)
{
try
{
var docPath = #"" + HttpContext.Current.Server.MapPath("MyPath");
var files = Directory.GetFiles(docPath);
string zipName = #"supportingdocuments_order" + orderNum + ".zip";
FileStream zipToOpen = new FileStream(docPath + zipName, FileMode.Create);
using (var zipArchive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
{
foreach (var fPath in files)
{
if (!fPath.Contains(".zip"))
{
zipArchive.CreateEntryFromFile(fPath, Path.GetFileName(fPath), CompressionLevel.Fastest);
}
}
}
zipToOpen.Close();
//At this point the directory is created and saved as it should be
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
var fullZipPath = docPath + zipName;
byte[] bytes = File.ReadAllBytes(fullZipPath);
response.Content = new ByteArrayContent(bytes);
response.Content.Headers.ContentLength = bytes.LongLength;
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = zipName;
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(MimeMapping.GetMimeMapping(zipName));
return response;
}
catch (Exception e)
{
var b = e.Message;
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.NotFound);
response.ReasonPhrase = string.Format("Failed To Extract Files");
throw new HttpResponseException(response);
}
}
Here is my $.ajax call:
$.ajax({
url: 'myApiUrl',
method: 'GET'
}).done(function (data, status, xmlHeaderRequest) {
var downloadLink = document.createElement('a');
var blob = new Blob([data],
{
type: xmlHeaderRequest.getResponseHeader('Content-Type')
});
var url = window.URL || window.webkitURL;
var downloadUrl = url.createObjectURL(blob);
var fileName = '';
// get the file name from the content disposition
var disposition = xmlHeaderRequest.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
fileName = matches[1].replace(/['"]/g, '');
}
}
// Blob download logic taken from: https://stackoverflow.com/questions/16086162/handle-file-download-from-ajax-post
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007" and "Access Denied" error.
window.navigator.msSaveBlob(blob, fileName);
} else {
if (fileName) {
if (typeof downloadLink.download === 'undefined') {
window.location = downloadUrl;
} else {
downloadLink.href = downloadUrl;
downloadLink.download = fileName;
document.body.appendChild(downloadLink);
downloadLink.click();
}
} else {
window.location = downloadUrl;
}
setTimeout(function () {
url.revokeObjectURL(downloadUrl);
},
100);
}
}).fail(function (data) {
$.notify({
// options
message:
'<i class="fas fa-exclamation-circle"></i> Could not download all documents.'
},
{
// settings
type: 'danger',
placement: {
from: "top",
align: "left"
},
delay: 2500,
z_index: 10031
});
});
I'm at a total and complete loss on this one. Thank you in advance for any help you can provide as it is greatly appreciated.
So after searching I have found a solution that works. $.ajax doesn't like binary data and thinks everything is UTF-8 text encoding apparently. So I used an XMLHttpRequest (xhr). For those that need it below is as copy of the c# and the javascript solution.
C# WebApi Controller:
public HttpResponseMessage ExtractAllDocuments(int orderNum, int mappingId)
{
try
{
var docPath = #"" + HttpContext.Current.Server.MapPath("myPath");
var files = Directory.GetFiles(docPath);
string zipName = #"Supporting-Documents-Order-" + orderNum + ".zip";
FileStream zipToOpen = new FileStream(docPath + zipName, FileMode.Create);
using (var zipArchive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
{
foreach (var fPath in files)
{
if (!fPath.Contains(".zip"))
{
zipArchive.CreateEntryFromFile(fPath, Path.GetFileName(fPath), CompressionLevel.Fastest);
}
}
}
zipToOpen.Close();
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new FileStream(docPath + zipName, FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = zipName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
return response;
}
catch (Exception e)
{
var b = e.Message;
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.NotFound);
response.ReasonPhrase = string.Format("Failed To Extract Files");
throw new HttpResponseException(response);
}
}
Front End JavaScript:
function extractAllDocuments() {
let xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', function (e) {
if (xhr.readyState == 2 && xhr.status == 200) {
// Download is being started
}
else if (xhr.readyState == 3) {
// Download is under progress
}
else if (xhr.readyState == 4) {
//operation done
// Create a new Blob object using the response data of the onload object
var blob = new Blob([this.response], { type: 'application/zip' });
//Create a link element, hide it, direct it towards the blob, and then 'click' it programatically
let a = document.createElement("a");
a.style = "display: none";
document.body.appendChild(a);
//Create a DOMString representing the blob and point the link element towards it
let url = window.URL.createObjectURL(blob);
a.href = url;
// get the file name from the content disposition
var fileName = '';
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
fileName = matches[1].replace(/['"]/g, '');
}
}
a.download = fileName;
//programatically click the link to trigger the download
a.click();
//Remove From Server
$.ajax({
url: 'myUrl',
method: 'DELETE'
}).done(function (data) {
}).fail(function (data) {
});
setTimeout(function () {
window.URL.revokeObjectURL(url);
}, 60 * 1000);
} else if (xhr.status == 400){
$.notify({
// options
message:
'<i class="fas fa-exclamation-circle"></i> Could not download all documents.'
},
{
// settings
type: 'danger',
placement: {
from: "top",
align: "left"
},
delay: 2500,
z_index: 10031
});
}
});
//set the request type to post and the destination url to '/convert'
xhr.open('GET', 'MyUrl');
//set the reponse type to blob since that's what we're expecting back
xhr.responseType = 'blob';
xhr.send();
return false;
}

How to call method using jQuery in mvc razor page at 10 sec interval and append output to html

Below code read messages from iot hub one by one as it comes.
private async void MonitorEventHubAsync(DateTime startTime, CancellationToken ct, string consumerGroupName)
{
EventHubClient eventHubClient = null;
EventHubReceiver eventHubReceiver = null;
try
{
string mesageData = string.Empty;
int eventHubPartitionsCount;
string selectedDevice = "";
eventHubClient = EventHubClient.CreateFromConnectionString("activeIoTHubConnectionString", "messages/events");
mesageData = "Receiving events...\r\n";
eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
string partition = EventHubPartitionKeyResolver.ResolveToPartition(selectedDevice, eventHubPartitionsCount);
eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, startTime);
//receive the events from startTime until current time in a single call and process them
while (true)
{
var eventData = eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(1)).Result;
if (eventData != null)
{
var data = Encoding.UTF8.GetString(eventData.GetBytes());
var enqueuedTime = eventData.EnqueuedTimeUtc.ToLocalTime();
var connectionDeviceId = eventData.SystemProperties["iothub-connection-device-id"].ToString();
if (string.CompareOrdinal(selectedDevice.ToUpper(), connectionDeviceId.ToUpper()) == 0)
{
mesageData += $"{enqueuedTime}> Device: [{connectionDeviceId}], Data:[{data}]";
if (eventData.Properties.Count > 0)
{
mesageData += "Properties:\r\n";
foreach (var property in eventData.Properties)
{
mesageData += $"'{property.Key}': '{property.Value}'\r\n";
}
}
mesageData += "\r\n";
}
}
}
}
catch (Exception ex)
{
}
}
I want to show messages one by one on mvc cshtml page using above code, how can I do that ?
One approach I can use like below:
In cshtml
<p id="pValue"></p>
In script
var someRootPath = "#Url.Content("~")";
(function randomGenerator() {
$.ajax({
url: someRootPath + 'Home/GetValue',
success: function (data) {
$('#pValue').html(data.someValue);
},
complete: function () {
setTimeout(randomGenerator, 1000);
}
});
})();
Controller
[HttpGet]
public JsonResult GetValue()
{
return Json( // call winform method which gives message data);
}
Something like this
var someRootPath = "#Url.Content("~")";
$(function(){
randomGenerator();
setTimeout(randomGenerator, 1000);
});
function randomGenerator() {
$.ajax({
url: someRootPath + 'Home/GetValue',
success: function (data) {
$('#pValue').html(data.someValue);
}
});
}

invoke api from ajax asp.net

I have a web Api that allow me to add a multiple Image with with another parameter
(place_Id , is_Main)
I use this code bellow to upload the image
[Route("api/Image")]
[HttpPost]
public async Task<IHttpActionResult> PostImage()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/Images/Places");
var provider = new CustomMultipartFormDataStreamProvider(root);
try
{
// Read the form data.
var task = await Request.Content.ReadAsMultipartAsync(provider).ContinueWith<IEnumerable<FileDesc>>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
var fileInfo = provider.FileData.Select(d =>
{
var info = new FileInfo(d.LocalFileName);
//return new FileDesc(info.Name);
return new FileDesc(info.Name);
});
return fileInfo;
});
int placeId = int.Parse(provider.FormData["placeId"]);
bool isMain = Convert.ToBoolean(provider.FormData["isMain"]);
var listOfAttchments = task.ToList();
string attachmentsPath = Request.RequestUri.Scheme +
System.Uri.SchemeDelimiter +
Request.RequestUri.Host +
(Request.RequestUri.IsDefaultPort ? "" : ":" + Request.RequestUri.Port) +
"/Images/Places/";
Images i = new Images();
if (listOfAttchments.Count > 0)
{
foreach (var item in listOfAttchments)
{
i.FileLocation = item.name;
i.FromUser = true;
i.TableName = "Places";
i.IsMain = isMain;
i.TableId = placeId;
db.Images.Add(i);
}
}
await db.SaveChangesAsync();
return Ok(new
{
result = true,
listAttachmment = listOfAttchments
}
);
}
catch (System.Exception e)
{
return BadRequest(e.StackTrace + "\nTest" + e.Data + "\nTest" + e.InnerException + "\nTest" + e.Message + "\nTest" + e.Source + "\nTest" + e.TargetSite);
}
}
The previous api is in another domain,
and I have a web forms application , that want to upload image from it, using the previous api
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function (i, file) {
data.append(" placeId: 7, isMain: 1");
data.append('image1' + i, file);
});
$("#btn2").click(function () {
jQuery.ajax({
url: '{url}/api/api/Image',
data: data,
contentType: false,
processData: false,
method: 'POST',
type: 'POST', // For jQuery < 1.9
success: function (data) {
alert(data);
}
});
});
I used the above code to invoke it, but I have a problem,
can you help me
Please ensure that you are not receiving XSS Error message (normally other domains are configured that you will not be able to trigger calls from a different domain addresses).
In the below code, i am not sure why do you have /api/api
url: '{url}/api/api/Image',
Please post us the error message you are receiving

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

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

Categories