when I pushed the phone button to back previous page in Unity webviewScript - unity3d

using System.Collections;
using UnityEngine;
using System;
using System.Collections.Generic;
public class SampleWebView : MonoBehaviour
{
public string Url;
public GUIText status;
WebViewObject webViewObject;
IEnumerator Start()
{
webViewObject = (new GameObject("WebViewObject")).AddComponent<WebViewObject>();
webViewObject.Init(
cb: (msg) =>
{
Debug.Log(string.Format("CallFromJS[{0}]", msg));
status.text = msg;
status.GetComponent<Animation>().Play();
},
err: (msg) =>
{
Debug.Log(string.Format("CallOnError[{0}]", msg));
status.text = msg;
status.GetComponent<Animation>().Play();
},
started: (msg) =>
{
Debug.Log(string.Format("CallOnStarted[{0}]", msg));
},
ld: (msg) =>
{
Debug.Log(string.Format("CallOnLoaded[{0}]", msg));
#if UNITY_EDITOR_OSX || !UNITY_ANDROID
// NOTE: depending on the situation, you might prefer
// the 'iframe' approach.
// cf. https://github.com/gree/unity-webview/issues/189
#if true
webViewObject.EvaluateJS(#"
if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) {
window.Unity = {
call: function(msg) {
window.webkit.messageHandlers.unityControl.postMessage(msg);
}
}
} else {
window.Unity = {
call: function(msg) {
window.location = 'unity:' + msg;
}
}
}
");
#else
webViewObject.EvaluateJS(#"
if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) {
window.Unity = {
call: function(msg) {
window.webkit.messageHandlers.unityControl.postMessage(msg);
}
}
} else {
window.Unity = {
call: function(msg) {
var iframe = document.createElement('IFRAME');
iframe.setAttribute('src', 'unity:' + msg);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
}
}
}
");
#endif
#endif
webViewObject.EvaluateJS(#"Unity.call('ua=' + navigator.userAgent)");
},
//ua: "custom user agent string",
enableWKWebView: true);
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
webViewObject.bitmapRefreshCycle = 1;
#endif
webViewObject.SetMargins(10, 140, 10, Screen.height / 360);
webViewObject.SetVisibility(true);
#if !UNITY_WEBPLAYER
if (Url.StartsWith("http")) {
webViewObject.LoadURL(Url.Replace(" ", "%20"));
} else {
var exts = new string[]{
".jpg",
".js",
".html" // should be last
};
foreach (var ext in exts) {
var url = Url.Replace(".html", ext);
var src = System.IO.Path.Combine(Application.streamingAssetsPath, url);
var dst = System.IO.Path.Combine(Application.persistentDataPath, url);
byte[] result = null;
if (src.Contains("://")) { // for Android
var www = new WWW(src);
yield return www;
result = www.bytes;
} else {
result = System.IO.File.ReadAllBytes(src);
}
System.IO.File.WriteAllBytes(dst, result);
if (ext == ".html") {
webViewObject.LoadURL("file://" + dst.Replace(" ", "%20"));
break;
}
}
}
#else
if (Url.StartsWith("http")) {
webViewObject.LoadURL(Url.Replace(" ", "%20"));
} else {
webViewObject.LoadURL("StreamingAssets/" + Url.Replace(" ", "%20"));
}
webViewObject.EvaluateJS(
"parent.$(function() {" +
" window.Unity = {" +
" call:function(msg) {" +
" parent.unityWebView.sendMessage('WebViewObject', msg)" +
" }" +
" };" +
"});");
#endif
yield break;
}
#if !UNITY_WEBPLAYER
//void OnGUI()
//{
// GUI.enabled = webViewObject.CanGoBack();
// if (GUI.Button(new Rect(10, 10, 80, 80), "<")) {
// webViewObject.GoBack();
// }
// GUI.enabled = true;
// GUI.enabled = webViewObject.CanGoForward();
// if (GUI.Button(new Rect(100, 10, 80, 80), ">")) {
// webViewObject.GoForward();
// }
// GUI.enabled = true;
// GUI.TextField(new Rect(200, 10, 300, 80), "" + webViewObject.Progress());
//}
#endif
This is my webview Scirpt for my newspaper App in C#. I need code, when I pushed the phone button to go back previous page in the newspaper.
I tried,
if(Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
However it quits from the app. It does not go back previous page in the newspaper..
Thank you for your help...

if i understand it correctly you should be good if you replace
if(Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
by this:
if(Input.GetKeyDown(KeyCode.Escape))
{
webViewObject.GoBack();
}
According to the example you are using from here https://github.com/gree/unity-webview/blob/master/sample/Assets/Scripts/SampleWebView.cs this is the build in back function. You can see it in the commented out part in your code.

Related

LootLocker - How to show local rank

In my game, I am able to show the GlobalRank, however, I would also like to show the position of a player in Ranking according to the global results.
So in the bottom line, there should be the local (on this device) results.
Basically, on the left bottom corner, I want to get the RANK from the LootLocker, but I am struggling to get the rank...
IEnumerator ShowScores()
{
yield return new WaitForSeconds(2);
LootLockerSDKManager.GetScoreList(ID, maxScores, (response) =>
{
if (response.success)
{
LootLockerLeaderboardMember[] scores = response.items;
for (int i = 0; i < scores.Length; i++)
{
playerNames[i].text = (scores[i].member_id +"");
playerScores[i].text = (scores[i].score +"");
playerRank[i].text = (scores[i].rank + "");
//Rank of the localPlayer
Rank.text = (scores["here_Should_Be_This_Player_ID"].rank + "");
LootLockerSDKManager.GetPlayerName
// Entries[i].text = (scores[i].rank + ". " + scores[i].score + ". " + scores[i].member_id);
}
if (scores.Length < maxScores)
{
for (int i = scores.Length; i < maxScores; i++)
{
// Entries[i].text = (i + 1).ToString() + ". none";
}
}
}
else
{
}
});
}
Fixed it with the LootLocker support team
Step 1 - load LootLocker and get the resonse
Step 2 - load the rank and get the resonse2
Step 3 - use the "Response2.rank from the LootLocker
Rank.text = (response2.rank + "");
string playerIdentifier = "PlayerNameRecordOnThisDevice";
LootLockerSDKManager.StartSession(playerIdentifier, (response) =>
{
if (response.success)
{
Debug.Log("session with LootLocker started");
}
else
{
Debug.Log("failed to start sessions" + response.Error);
}
LootLockerSDKManager.GetMemberRank(ID, playerIdentifier, (response2) =>
{
if (response2.statusCode == 200)
{
Debug.Log("GetMemberRank Successful");
}
else
{
Debug.Log("GetMemberRank failed: " + response2.Error);
}
Rank.text = (response2.rank + "");
});
}); ```

Canvas not updating after camera used (Android / Ionic)

I am trying to draw a scaled photo onto a canvas. However, the canvas will not update after I use the camera object to take the photo. Here's my camera code:
public openCamera() {
// do we have permission to access the camera?
this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.CAMERA).then(
result => console.log('openCamera > has camera permission: ', result.hasPermission),
err => this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.CAMERA)
);
this.androidPermissions.requestPermissions([this.androidPermissions.PERMISSION.CAMERA, this.androidPermissions.PERMISSION.GET_ACCOUNTS]);
const options: CameraOptions = {
quality: 100,
correctOrientation: true,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
let file_ext: string = null;
if (options.encodingType == EncodingType.JPEG) {
file_ext = "jpg";
console.log("openCamera > file_ext: ", file_ext);
}
else if (options.encodingType == EncodingType.PNG) {
file_ext = "png";
console.log("openCamera > file_ext: ", file_ext);
}
else {
this.presentAlert("Warning", "Unsupported image encoding type.");
return;
}
// photo already taken?
if (this.photo == null) {
this.photo = new Photo();
this.photo.id = Guid.create().toString();
this.photo.file_extension = file_ext;
}
// image filename: image_id.jpg
const dt: Date = new Date();
let dt_day: string = dt.getDate().toString();
dt_day = dt_day.length == 1 ? "0" + dt_day : dt_day;
let dt_month: string = (dt.getMonth() + 1).toString();
dt_month = dt_month.length == 1 ? "0" + dt_month : dt_month;
const dt_string: string = dt_day + "/" +
dt_month + "/" +
dt.getFullYear() + ", " +
dt.getHours() + ":" +
dt.getMinutes() + ":" +
dt.getSeconds() + "." +
dt.getMilliseconds();
if (this.photo.id == null || this.photo.id == '' || this.photo.id.length == 0) {
this.presentAlert("Error", "image id not set");
return;
}
else if (this.user.id == null || this.user.id == Guid.EMPTY || this.user.id == '' || this.user.id.length == 0) {
this.presentAlert("Error", "user.id not set");
return;
}
else if (dt_string == null || dt_string == '' || dt_string.length == 0) {
this.presentAlert("Error", "dt_string not set");
return;
}
this.photo.taken = dt_string;
const fileName: string = this.photo.id + ".jpg";
this.camera.getPicture(options).then((imageData) => {
// delete previous image
this.filePath.resolveNativePath(imageData)
.then((path) => {
let imagePath = path.substr(0, path.lastIndexOf("/") + 1);
let imageName = path.substring(path.lastIndexOf("/") + 1, path.length);
this.file.moveFile(imagePath, imageName, this.file.dataDirectory, fileName)
.then(newFile => {
this.ngZone.run(() => this.info = "Tap 'Upload' to upload photo");
this.db.addOrUpdatePhoto(this.photo)
.then(() => this.updateCanvas());
})
.catch(err => {
console.log("openCamera: ", err);
})
})
.catch((err) => {
console.log("openCamera: ", err);
})
})
.catch((err) => {
console.log("openCamera: ", err);
});
}
In the process of debugging this, I wrote a method to check that the photo actually exists after the camera has saved the image:
public exists() {
try {
this.file.listDir(this.file.dataDirectory, '')
.then(files => {
for (let i = 0; i < files.length; i++) {
if (files[i].name.includes(this.photo.id)) {
files[i].getMetadata((metadata) => {
this.presentAlert("image found", "filename: " + files[i].name + ", size: " + metadata.size + " bytes")
.then(() => this.updateCanvas());
});
}
}
});
}
catch { }
}
And I noticed that displaying an ionic alert before calling updateCanvas causes the photo to be correctly displayed onto the canvas. Does anyone know what the issue might be here?
Also, not sure if relevant, but I am using cordova-plugin-ionic-webview 4.1.1
I managed to solve this - the problem was the device itself. I tested on another phone and my canvas code worked perfectly. Uninstalling my app and reinstalling it did not resolve the issue, but a factory reset did. The device in question is an Honor 10 Lite. Not sure how this could have happened, maybe the device's WebView became corrupt somehow?

what's the problem when integrating roxyfileman with tinymce in ABP

I want to use tinyMCE in ABP CoreMVC project,so I read the [http://www.iaspnetcore.com/Blog/BlogPost/5bd70fb5b169590f280f64dd/integrating-roxy-fileman-with-tinymce-in-aspnet-core], and add RoxyFilemanController.cs
in a normal netcore mvc project,and copy the tinymce and fileman directory to the www/lib directory,it works fine.but when I copy the same code to my ABP CoreMVC project,It not work. the controller code is:
[Produces("application/json")]
public class RoxyFilemanController : Controller
{
private string _systemRootPath;
private string _tempPath;
private string _filesRootPath;
private string _filesRootVirtual;
private Dictionary<string, string> _settings;
private Dictionary<string, string> _lang = null;
public RoxyFilemanController(IHostingEnvironment env)
{
// Setup CMS paths to suit your environment (we usually inject settings for these)
_systemRootPath = env.ContentRootPath;
_tempPath = _systemRootPath + "\\wwwroot\\CMS\\Temp";
_filesRootPath = "/wwwroot/CMS/Content";
_filesRootVirtual = "/CMS/Content";
// Load Fileman settings
LoadSettings();
}
private void LoadSettings()
{
_settings = JsonConvert.DeserializeObject<Dictionary<string, string>>(System.IO.File.ReadAllText(_systemRootPath + "/wwwroot/lib/fileman/conf.json"));
string langFile = _systemRootPath + "/wwwroot/lib/fileman/lang/" + GetSetting("LANG") + ".json";
if (!System.IO.File.Exists(langFile)) langFile = _systemRootPath + "/wwwroot/lib/fileman/lang/en.json";
_lang = JsonConvert.DeserializeObject<Dictionary<string, string>>(System.IO.File.ReadAllText(langFile));
}
// GET api/RoxyFileman - test entry point//]
[AllowAnonymous, Produces("text/plain"), ActionName("")]
public string Get() { return "RoxyFileman - access to API requires Authorisation"; }
#region API Actions
[HttpGet]
public IActionResult DIRLIST(string type)
{
try
{
DirectoryInfo d = new DirectoryInfo(GetFilesRoot());
if (!d.Exists) throw new Exception("Invalid files root directory. Check your configuration.");
ArrayList dirs = ListDirs(d.FullName);
dirs.Insert(0, d.FullName);
string localPath = _systemRootPath;
string result = "";
for (int i = 0; i < dirs.Count; i++)
{
string dir = (string)dirs[i];
result += (result != "" ? "," : "") + "{\"p\":\"" + MakeVirtualPath(dir.Replace(localPath, "").Replace("\\", "/")) + "\",\"f\":\"" + GetFiles(dir, type).Count.ToString() + "\",\"d\":\"" + Directory.GetDirectories(dir).Length.ToString() + "\"}";
}
return Content("[" + result + "]", "application/json");
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public IActionResult FILESLIST(string d, string type)
{
try
{
d = MakePhysicalPath(d);
CheckPath(d);
string fullPath = FixPath(d);
List<string> files = GetFiles(fullPath, type);
string result = "";
for (int i = 0; i < files.Count; i++)
{
FileInfo f = new FileInfo(files[i]);
int w = 0, h = 0;
// NO SUPPORT IN ASP.NET CORE! Per haps see https://github.com/CoreCompat/CoreCompat
//if (GetFileType(f.Extension) == "image")
//{
// try
// {
// //FileStream fs = new FileStream(f.FullName, FileMode.Open, FileAccess.Read);
// //Image img = Image.FromStream(fs);
// //w = img.Width;
// //h = img.Height;
// //fs.Close();
// //fs.Dispose();
// //img.Dispose();
// }
// catch (Exception ex) { throw ex; }
//}
result += (result != "" ? "," : "") +
"{" +
"\"p\":\"" + MakeVirtualPath(d) + "/" + f.Name + "\"" +
",\"t\":\"" + Math.Ceiling(LinuxTimestamp(f.LastWriteTime)).ToString() + "\"" +
",\"s\":\"" + f.Length.ToString() + "\"" +
",\"w\":\"" + w.ToString() + "\"" +
",\"h\":\"" + h.ToString() + "\"" +
"}";
}
return Content("[" + result + "]");
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public IActionResult COPYDIR(string d, string n)
{
try
{
d = MakePhysicalPath(d);
n = MakePhysicalPath(n);
CheckPath(d);
CheckPath(n);
DirectoryInfo dir = new DirectoryInfo(FixPath(d));
DirectoryInfo newDir = new DirectoryInfo(FixPath(n + "/" + dir.Name));
if (!dir.Exists) throw new Exception(LangRes("E_CopyDirInvalidPath"));
else if (newDir.Exists) throw new Exception(LangRes("E_DirAlreadyExists"));
else CopyDir(dir.FullName, newDir.FullName);
return Content(GetSuccessRes());
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public IActionResult COPYFILE(string f, string n)
{
try
{
f = MakePhysicalPath(f);
CheckPath(f);
FileInfo file = new FileInfo(FixPath(f));
n = FixPath(n);
if (!file.Exists) throw new Exception(LangRes("E_CopyFileInvalisPath"));
else
{
try
{
System.IO.File.Copy(file.FullName, Path.Combine(n, MakeUniqueFilename(n, file.Name)));
return Content(GetSuccessRes());
}
catch (Exception) { throw new Exception(LangRes("E_CopyFile")); }
}
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public IActionResult CREATEDIR(string d, string n)
{
try
{
d = MakePhysicalPath(d);
CheckPath(d);
d = FixPath(d);
if (!Directory.Exists(d)) throw new Exception(LangRes("E_CreateDirInvalidPath"));
else
{
try
{
d = Path.Combine(d, n);
if (!Directory.Exists(d)) Directory.CreateDirectory(d);
return Content(GetSuccessRes());
}
catch (Exception) { throw new Exception(LangRes("E_CreateDirFailed")); }
}
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public IActionResult DELETEDIR(string d)
{
try
{
d = MakePhysicalPath(d);
CheckPath(d);
d = FixPath(d);
if (!Directory.Exists(d)) throw new Exception(LangRes("E_DeleteDirInvalidPath"));
else if (d == GetFilesRoot()) throw new Exception(LangRes("E_CannotDeleteRoot"));
else if (Directory.GetDirectories(d).Length > 0 || Directory.GetFiles(d).Length > 0) throw new Exception(LangRes("E_DeleteNonEmpty"));
else
{
try
{
Directory.Delete(d);
return Content(GetSuccessRes());
}
catch (Exception) { throw new Exception(LangRes("E_CannotDeleteDir")); }
}
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public IActionResult DELETEFILE(string f)
{
try
{
f = MakePhysicalPath(f);
CheckPath(f);
f = FixPath(f);
if (!System.IO.File.Exists(f)) throw new Exception(LangRes("E_DeleteFileInvalidPath"));
else
{
try
{
System.IO.File.Delete(f);
return Content(GetSuccessRes());
}
catch (Exception) { throw new Exception(LangRes("E_DeletŠµFile")); }
}
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public ActionResult DOWNLOAD(string f)
{
try
{
f = MakePhysicalPath(f);
CheckPath(f);
FileInfo file = new FileInfo(FixPath(f));
if (file.Exists)
{
string contentType;
new FileExtensionContentTypeProvider().TryGetContentType(file.FullName, out contentType);
return PhysicalFile(file.FullName, contentType ?? "application/octet-stream", file.Name);
}
else return NotFound();
}
catch (Exception ex) { return Json(GetErrorRes(ex.Message)); }
}
public ActionResult DOWNLOADDIR(string d)
{
try
{
d = MakePhysicalPath(d);
d = FixPath(d);
if (!Directory.Exists(d)) throw new Exception(LangRes("E_CreateArchive"));
string dirName = new FileInfo(d).Name;
string tmpZip = _tempPath + "/" + dirName + ".zip";
if (System.IO.File.Exists(tmpZip)) System.IO.File.Delete(tmpZip);
ZipFile.CreateFromDirectory(d, tmpZip, CompressionLevel.Fastest, true);
return PhysicalFile(tmpZip, "application/zip", dirName + ".zip");
}
catch (Exception ex) { return Json(GetErrorRes(ex.Message)); }
}
public IActionResult MOVEDIR(string d, string n)
{
try
{
d = MakePhysicalPath(d);
n = MakePhysicalPath(n);
CheckPath(d);
CheckPath(n);
DirectoryInfo source = new DirectoryInfo(FixPath(d));
DirectoryInfo dest = new DirectoryInfo(FixPath(Path.Combine(n, source.Name)));
if (dest.FullName.IndexOf(source.FullName) == 0) throw new Exception(LangRes("E_CannotMoveDirToChild"));
else if (!source.Exists) throw new Exception(LangRes("E_MoveDirInvalisPath"));
else if (dest.Exists) throw new Exception(LangRes("E_DirAlreadyExists"));
else
{
try
{
source.MoveTo(dest.FullName);
return Content(GetSuccessRes());
}
catch (Exception) { throw new Exception(LangRes("E_MoveDir") + " \"" + d + "\""); }
}
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public IActionResult MOVEFILE(string f, string n)
{
try
{
f = MakePhysicalPath(f);
n = MakePhysicalPath(n);
CheckPath(f);
CheckPath(n);
FileInfo source = new FileInfo(FixPath(f));
FileInfo dest = new FileInfo(FixPath(n));
if (!source.Exists) throw new Exception(LangRes("E_MoveFileInvalisPath"));
else if (dest.Exists) throw new Exception(LangRes("E_MoveFileAlreadyExists"));
else if (!CanHandleFile(dest.Name)) throw new Exception(LangRes("E_FileExtensionForbidden"));
else
{
try
{
source.MoveTo(dest.FullName);
return Content(GetSuccessRes());
}
catch (Exception) { throw new Exception(LangRes("E_MoveFile") + " \"" + f + "\""); }
}
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public IActionResult RENAMEDIR(string d, string n)
{
try
{
d = MakePhysicalPath(d);
CheckPath(d);
DirectoryInfo source = new DirectoryInfo(FixPath(d));
DirectoryInfo dest = new DirectoryInfo(Path.Combine(source.Parent.FullName, n));
if (source.FullName == GetFilesRoot()) throw new Exception(LangRes("E_CannotRenameRoot"));
else if (!source.Exists) throw new Exception(LangRes("E_RenameDirInvalidPath"));
else if (dest.Exists) throw new Exception(LangRes("E_DirAlreadyExists"));
else
{
try
{
source.MoveTo(dest.FullName);
return Content(GetSuccessRes());
}
catch (Exception) { throw new Exception(LangRes("E_RenameDir") + " \"" + d + "\""); }
}
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
public IActionResult RENAMEFILE(string f, string n)
{
try
{
f = MakePhysicalPath(f);
CheckPath(f);
FileInfo source = new FileInfo(FixPath(f));
FileInfo dest = new FileInfo(Path.Combine(source.Directory.FullName, n));
if (!source.Exists) throw new Exception(LangRes("E_RenameFileInvalidPath"));
else if (!CanHandleFile(n)) throw new Exception(LangRes("E_FileExtensionForbidden"));
else
{
try
{
source.MoveTo(dest.FullName);
return Content(GetSuccessRes());
}
catch (Exception ex) { throw new Exception(ex.Message + "; " + LangRes("E_RenameFile") + " \"" + f + "\""); }
}
}
catch (Exception ex) { return Content(GetErrorRes(ex.Message)); }
}
[HttpPost, Produces("text/plain")]
public string UPLOAD(string d)
{
try
{
d = MakePhysicalPath(d);
CheckPath(d);
d = FixPath(d);
string res = GetSuccessRes();
bool hasErrors = false;
try
{
foreach (var file in HttpContext.Request.Form.Files)
{
if (CanHandleFile(file.FileName))
{
FileInfo f = new FileInfo(file.FileName);
string filename = MakeUniqueFilename(d, f.Name);
string dest = Path.Combine(d, filename);
using (var saveFile = new FileStream(dest, FileMode.Create)) file.CopyTo(saveFile);
//if (GetFileType(new FileInfo(filename).Extension) == "image")
//{
// int w = 0;
// int h = 0;
// int.TryParse(GetSetting("MAX_IMAGE_WIDTH"), out w);
// int.TryParse(GetSetting("MAX_IMAGE_HEIGHT"), out h);
// ImageResize(dest, dest, w, h);
//}
}
else
{
hasErrors = true;
res = GetSuccessRes(LangRes("E_UploadNotAll"));
}
}
}
catch (Exception ex) { res = GetErrorRes(ex.Message); }
if (IsAjaxUpload())
{
if (hasErrors) res = GetErrorRes(LangRes("E_UploadNotAll"));
return res;
}
else return "<script>parent.fileUploaded(" + res + ");</script>";
}
catch (Exception ex)
{
if (!IsAjaxUpload()) return "<script>parent.fileUploaded(" + GetErrorRes(LangRes("E_UploadNoFiles")) + ");</script>";
else return GetErrorRes(ex.Message);
}
}
/*
public string GENERATETHUMB(string type)
{
try
{
//int w = 140, h = 0;
//int.TryParse(_context.Request["width"].Replace("px", ""), out w);
//int.TryParse(_context.Request["height"].Replace("px", ""), out h);
//ShowThumbnail(_context.Request["f"], w, h);
}
catch (Exception ex) { return GetErrorRes(ex.Message); }
}
*/
#endregion
#region Utilities
private string MakeVirtualPath(string path)
{
return !path.StartsWith(_filesRootPath) ? path : _filesRootVirtual + path.Substring(_filesRootPath.Length);
}
private string MakePhysicalPath(string path)
{
return !path.StartsWith(_filesRootVirtual) ? path : _filesRootPath + path.Substring(_filesRootVirtual.Length);
}
private string GetFilesRoot()
{
string ret = _filesRootPath;
if (GetSetting("SESSION_PATH_KEY") != "" && HttpContext.Session.GetString(GetSetting("SESSION_PATH_KEY")) != null) ret = HttpContext.Session.GetString(GetSetting("SESSION_PATH_KEY"));
ret = FixPath(ret);
return ret;
}
private ArrayList ListDirs(string path)
{
string[] dirs = Directory.GetDirectories(path);
ArrayList ret = new ArrayList();
foreach (string dir in dirs)
{
ret.Add(dir);
ret.AddRange(ListDirs(dir));
}
return ret;
}
private List<string> GetFiles(string path, string type)
{
List<string> ret = new List<string>();
if (type == "#" || type == null) type = "";
string[] files = Directory.GetFiles(path);
foreach (string f in files) { if ((GetFileType(new FileInfo(f).Extension) == type) || (type == "")) ret.Add(f); }
return ret;
}
private string GetFileType(string ext)
{
string ret = "file";
ext = ext.ToLower();
if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".gif") ret = "image";
else if (ext == ".swf" || ext == ".flv") ret = "flash";
return ret;
}
private void CheckPath(string path)
{
if (FixPath(path).IndexOf(GetFilesRoot()) != 0) throw new Exception("Access to " + path + " is denied");
}
private string FixPath(string path)
{
path = path.TrimStart('~');
if (!path.StartsWith("/")) path = "/" + path;
return _systemRootPath + path;
}
private double LinuxTimestamp(DateTime d)
{
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0).ToLocalTime();
TimeSpan timeSpan = (d.ToLocalTime() - epoch);
return timeSpan.TotalSeconds;
}
private string GetSetting(string name)
{
string ret = "";
if (_settings.ContainsKey(name)) ret = _settings[name];
return ret;
}
private string GetErrorRes(string msg) { return GetResultStr("error", msg); }
private string GetResultStr(string type, string msg)
{
return "{\"res\":\"" + type + "\",\"msg\":\"" + msg.Replace("\"", "\\\"") + "\"}";
}
private string LangRes(string name) { return _lang.ContainsKey(name) ? _lang[name] : name; }
private string GetSuccessRes(string msg) { return GetResultStr("ok", msg); }
private string GetSuccessRes() { return GetSuccessRes(""); }
private void CopyDir(string path, string dest)
{
if (!Directory.Exists(dest)) Directory.CreateDirectory(dest);
foreach (string f in Directory.GetFiles(path))
{
FileInfo file = new FileInfo(f);
if (!System.IO.File.Exists(Path.Combine(dest, file.Name))) System.IO.File.Copy(f, Path.Combine(dest, file.Name));
}
foreach (string d in Directory.GetDirectories(path)) CopyDir(d, Path.Combine(dest, new DirectoryInfo(d).Name));
}
private string MakeUniqueFilename(string dir, string filename)
{
string ret = filename;
int i = 0;
while (System.IO.File.Exists(Path.Combine(dir, ret)))
{
i++;
ret = Path.GetFileNameWithoutExtension(filename) + " - Copy " + i.ToString() + Path.GetExtension(filename);
}
return ret;
}
private bool CanHandleFile(string filename)
{
bool ret = false;
FileInfo file = new FileInfo(filename);
string ext = file.Extension.Replace(".", "").ToLower();
string setting = GetSetting("FORBIDDEN_UPLOADS").Trim().ToLower();
if (setting != "")
{
ArrayList tmp = new ArrayList();
tmp.AddRange(Regex.Split(setting, "\\s+"));
if (!tmp.Contains(ext)) ret = true;
}
setting = GetSetting("ALLOWED_UPLOADS").Trim().ToLower();
if (setting != "")
{
ArrayList tmp = new ArrayList();
tmp.AddRange(Regex.Split(setting, "\\s+"));
if (!tmp.Contains(ext)) ret = false;
}
return ret;
}
private bool IsAjaxUpload()
{
return (!string.IsNullOrEmpty(HttpContext.Request.Query["method"]) && HttpContext.Request.Query["method"].ToString() == "ajax");
}
#endregion
/*
public bool ThumbnailCallback()
{
return false;
}
protected void ShowThumbnail(string path, int width, int height)
{
CheckPath(path);
FileStream fs = new FileStream(FixPath(path), FileMode.Open, FileAccess.Read);
Bitmap img = new Bitmap(Bitmap.FromStream(fs));
fs.Close();
fs.Dispose();
int cropWidth = img.Width, cropHeight = img.Height;
int cropX = 0, cropY = 0;
double imgRatio = (double)img.Width / (double)img.Height;
if(height == 0)
height = Convert.ToInt32(Math.Floor((double)width / imgRatio));
if (width > img.Width)
width = img.Width;
if (height > img.Height)
height = img.Height;
double cropRatio = (double)width / (double)height;
cropWidth = Convert.ToInt32(Math.Floor((double)img.Height * cropRatio));
cropHeight = Convert.ToInt32(Math.Floor((double)cropWidth / cropRatio));
if (cropWidth > img.Width)
{
cropWidth = img.Width;
cropHeight = Convert.ToInt32(Math.Floor((double)cropWidth / cropRatio));
}
if (cropHeight > img.Height)
{
cropHeight = img.Height;
cropWidth = Convert.ToInt32(Math.Floor((double)cropHeight * cropRatio));
}
if(cropWidth < img.Width){
cropX = Convert.ToInt32(Math.Floor((double)(img.Width - cropWidth) / 2));
}
if(cropHeight < img.Height){
cropY = Convert.ToInt32(Math.Floor((double)(img.Height - cropHeight) / 2));
}
Rectangle area = new Rectangle(cropX, cropY, cropWidth, cropHeight);
Bitmap cropImg = img.Clone(area, System.Drawing.Imaging.PixelFormat.DontCare);
img.Dispose();
Image.GetThumbnailImageAbort imgCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
_r.AddHeader("Content-Type", "image/png");
cropImg.GetThumbnailImage(width, height, imgCallback, IntPtr.Zero).Save(_r.OutputStream, ImageFormat.Png);
_r.OutputStream.Close();
cropImg.Dispose();
}
private ImageFormat GetImageFormat(string filename){
ImageFormat ret = ImageFormat.Jpeg;
switch(new FileInfo(filename).Extension.ToLower()){
case ".png": ret = ImageFormat.Png; break;
case ".gif": ret = ImageFormat.Gif; break;
}
return ret;
}
protected void ImageResize(string path, string dest, int width, int height)
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
Image img = Image.FromStream(fs);
fs.Close();
fs.Dispose();
float ratio = (float)img.Width / (float)img.Height;
if ((img.Width <= width && img.Height <= height) || (width == 0 && height == 0))
return;
int newWidth = width;
int newHeight = Convert.ToInt16(Math.Floor((float)newWidth / ratio));
if ((height > 0 && newHeight > height) || (width == 0))
{
newHeight = height;
newWidth = Convert.ToInt16(Math.Floor((float)newHeight * ratio));
}
Bitmap newImg = new Bitmap(newWidth, newHeight);
Graphics g = Graphics.FromImage((Image)newImg);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(img, 0, 0, newWidth, newHeight);
img.Dispose();
g.Dispose();
if(dest != ""){
newImg.Save(dest, GetImageFormat(dest));
}
newImg.Dispose();
}
public bool IsReusable {
get {
return false;
}
}
*/
}
In ABP CoreMVC,I change the About/index.html as follow:
#using testRoxyMan.Web.Startup
<script src="~/lib/tinymce/tinymce.min.js"></script>
<script type="text/javascript">
function RoxyFileBrowser(field_name, url, type, win) {
var roxyFileman = '/lib/fileman/index.html';
if (roxyFileman.indexOf("?") < 0) {
roxyFileman += "?type=" + type;
}
else {
roxyFileman += "&type=" + type;
}
roxyFileman += '&input=' + field_name + '&value=' + win.document.getElementById(field_name).value;
if (tinyMCE.activeEditor.settings.language) {
roxyFileman += '&langCode=' + tinyMCE.activeEditor.settings.language;
}
tinyMCE.activeEditor.windowManager.open({
file: roxyFileman,
title: 'Roxy Fileman',
width: 850,
height: 650,
resizable: "yes",
plugins: "media",
inline: "yes",
close_previous: "no"
}, { window: win, input: field_name });
return false;
}
tinymce.init({
selector: 'textarea', // change this value according to your HTML
theme: 'modern',
height: 200,
width: '100%',
plugins: [
"advlist autolink autoresize directionality lists link image charmap preview anchor",
"searchreplace visualblocks code fullscreen textcolor",
"insertdatetime media table contextmenu "
],
toolbar: 'ltr rtl | insertfile undo redo | styleselect | fontselect | fontsizeselect | bold italic | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
file_browser_callback: RoxyFileBrowser
});
</script>
<div class="row clearfix">
<textarea></textarea>
</div>
but when I click the addImg btn,It not work,
the wrong msg is:
An unhandled exception occurred while processing the request.
ComponentNotFoundException: No component for supporting the service testRoxyMan.Web.Mvc.Controllers.RoxyFilemanController was found
Castle.MicroKernel.DefaultKernel.Castle.MicroKernel.IKernelInternal.Resolve(Type service, IDictionary arguments, IReleasePolicy policy, bool ignoreParentContext)
so ,what's problem? Thanks a lot
Try to inherit AbpController
public class RoxyFilemanController : AbpController

Refresh sticky mobile leaderboard ad slot by changing the content URL in infinite scroll

I want to refresh sticky mobile leaderboard slot when the URL changes in infinite scroll. What do you think is the best way to go? Please let me know if you have any suggestions.
class DFPAds {
constructor() {
this.slots = [];
this.onScroll = throttle(this.loopAds, 300);
this.addEvents();
this.createAdObject = this.createAdObject.bind(this);
this.createSlotForAd = this.createSlotForAd.bind(this);
this.displayAd = this.displayAd.bind(this);
}
static get() {
return DFPAds._instance;
}
static set() {
if (!DFPAds._instance) {
DFPAds._instance = new DFPAds();
return DFPAds._instance;
} else {
throw new Error("DFPAds: instance already initialized");
}
}
addEvents() {
window.addEventListener("scroll", e => this.onScroll());
}
loopAds() {
this.slots.map(slot => this.displayAd(slot));
}
createAdObject(ad) {
let id = ad.id;
let attributes = getDataSet(ad);
let sizes = JSON.parse(attributes.sizes);
let sizeMapping;
if (attributes.sizemapping) {
attributes.sizemapping.length
? (sizeMapping = JSON.parse(attributes.sizemapping))
: (sizeMapping = null);
}
attributes.id = id;
attributes.sizes = sizes;
attributes.sizemapping = sizeMapping;
return attributes;
}
createSlotForAd(adObject) {
let {
id,
adtype,
position,
slotname,
sizes,
sizemapping,
shouldlazyload,
pagenumber,
pageid
} = adObject;
googletag.cmd.push(() => {
let slot = googletag.defineSlot(slotname, sizes, id);
if(position){
slot.setTargeting("position", position);
}
if(pagenumber){
slot.setTargeting("pagenumber", pagenumber);
}
if(pageid){
slot.setTargeting("PageID", pageid)
}
if (sizemapping) {
let mapping = googletag.sizeMapping();
sizemapping.map(size => {
mapping.addSize(size[0], size[1])
});
slot.defineSizeMapping(mapping.build());
}
slot.addService(googletag.pubads());
googletag.display(id);
shouldlazyload
? this.slots.push({ slot: slot, id: id })
: googletag.pubads().refresh([slot]);
console.log("SlotTop", slot)
});
}
displayAd(slot) {
console.log("Slottwo", slot)
let item = document.getElementById(slot.id);
if (item) {
let parent = item.parentElement;
let index = this.slots.indexOf(slot);
let parentDimensions = parent.getBoundingClientRect();
if (
(parentDimensions.top - 300) < window.innerHeight &&
parentDimensions.top + 150 > 0 &&
parent.offsetParent != null
) {
googletag.cmd.push(function() {
googletag.pubads().refresh([slot.slot]);
});
this.slots.splice(index, 1);
}
}
}
setUpAdSlots(context = document) {
let ads = [].slice.call(context.getElementsByClassName("Ad-data"));
if (ads.length) {
ads.map(ad => compose(this.createSlotForAd, this.createAdObject)(ad));
}
}
}
export default DFPAds;
And this is my Infinite Scroll code:
export default class InfiniteScroll {
constructor() {
this._end = document.getElementById('InfiniteScroll-End');
this._container = document.getElementById('InfiniteScroll-Container');
if(!this._end || !this._container)
return;
this._articles = { };
this._triggeredArticles = [];
this._currentArticle = '';
this._apiUrl = '';
this._count = 1;
this._timedOut = false;
this._loading = false;
this._ended = false;
this._viewedParameter = "&alreadyViewedContentIds=";
this._articleSelector = "InfiniteScroll-Article-";
this._articleClass = "Article-Container";
this.setStartData();
this.onScroll = throttle(this.eventScroll, 200);
this.addEvents();
}
addEvents(){
setTimeout(()=>{
window.addEventListener('scroll', (e) => this.onScroll() );
}, 2000);
}
addToStore(article){
this._articles["a" + article.id] = article;
}
addToTriggeredArticles(id){
this._triggeredArticles.push(id);
}
getRequestUrl(){
return this._apiUrl + this._viewedParameter + Object.keys(this._articles).map(key => this._articles[key].id).join();
}
getLastArticle(){
return this._articles[Object.keys(this._articles)[Object.keys(this._articles).length-1]];
}
setStartData() {
let dataset = getDataSet(this._container);
if(dataset.hasOwnProperty('apiurl')){
let article = Article.get();
if(article){
this._apiUrl = dataset.apiurl;
this._currentArticle = "a" + article.id;
this.addToStore(article);
}else{
throw(new Error('Infinite Scroll: Article not initialized.'));
}
}else{
throw(new Error('Infinite Scroll: Start object missing "apiurl" property.'));
}
}
eventScroll() {
if(this.isApproachingNext()){
this.requestNextArticle();
}
if(!this.isMainArticle(this._articles[this._currentArticle].node)){
this.updateCurrentArticle();
}
}
eventRequestSuccess(data){
this._loading = false;
if(data != ''){
if(data.hasOwnProperty('Id') && data.hasOwnProperty('Html') && data.hasOwnProperty('Url')){
this.incrementCount();
let node = document.createElement('div');
node.id = this._articleSelector + data.Id;
node.innerHTML = data.Html;
node.className = this._articleClass;
this._container.appendChild(node);
this.initArticleUpNext({
img: data.Img,
title: data.ArticleTitle,
category: data.Category,
target: node.id
});
this.addToStore(
new Article({
id: data.Id,
node: node,
url: data.Url,
title: data.Title,
count: this._count,
nielsenProps: {
section: data.NeilsenSection,
sega: data.NeilsenSegmentA,
segb: data.NeilsenSegmentB,
segc: data.NeilsenSegmentC
}
})
);
}else{
this._ended = true;
throw(new Error('Infinite Scroll: Response does not have an ID, Url and HTML property'));
}
}else{
this._ended = true;
throw(new Error('Infinite Scroll: No new article was received.'));
}
}
eventRequestError(response){
this._loading = false;
this._ended = true;
throw(new Error("Infinite Scroll: New article request failed."));
}
requestNextArticle(){
if(!this._loading){
this._loading = true;
return API.requestJSON(this.getRequestUrl())
.then(
(response)=>{this.eventRequestSuccess(response)},
(response)=>{this.eventRequestError(response)}
);
}
}
triggerViewEvent(article){
if(article.count > 1 && !this.isAlreadyTriggeredArticle(article.id)){
this.addToTriggeredArticles(article.id);
Tracker.pushView(article.url, article.count);
if(isFeatureEnabled('Nielsen') && Nielsen.get()){
Nielsen.get().eventInfiniteScroll({
id: article.id,
url: article.url,
section: article.nielsenProps.section,
sega: article.nielsenProps.sega,
segb: article.nielsenProps.segb,
segc: article.nielsenProps.segc
});
NielsenV60.trackEvent(article.title);
}
}
}
updateCurrentArticle(){
Object.keys(this._articles).map( key => {
if(this._currentArticle !== key && this.isMainArticle(this._articles[key].node)){
this._currentArticle = key;
this.updateUrl(this._articles[key]);
this.triggerViewEvent(this._articles[key]);
}
});
}
updateUrl(article){
try{
if(history.replaceState){
if(window.location.pathname !== article.url){
history.replaceState('', article.title, article.url);
}
}
}catch(e){}
}
incrementCount(){
this._count = this._count + 1;
}
initArticleUpNext(data){
this.getLastArticle().initUpNext(data);
}
isApproachingNext(){
return window.pageYOffset > this._end.offsetTop - (window.innerHeight * 2) && !this._ended && this._end.offsetTop >= 100;
}
isMainArticle(node){
if(node.getBoundingClientRect){
return (node.getBoundingClientRect().top < 80 && node.getBoundingClientRect().bottom > 70);
}else{
return false;
}
}
isAlreadyTriggeredArticle(id){
return this._triggeredArticles.indexOf(id) > -1;
}
}

chrome.serial receiveTimeout Not working.

Below code is a copy with minor edits from https://github.com/GoogleChrome/chrome-app-samples/tree/master/serial/ledtoggle. I am able to send a byte and receive a reply. I am not able to get an TimeoutError event in case of reply is not sent by the client. I have set timeout to 50 ms.
this.receiveTimeout = 50;
Entire code follows.
const DEVICE_PATH = 'COM1';
const serial = chrome.serial;
var ab2str = function(buf) {
var bufView = new Uint8Array(buf);
var encodedString = String.fromCharCode.apply(null, bufView);
return decodeURIComponent(escape(encodedString));
};
var str2ab = function(str) {
var encodedString = unescape((str));
var bytes = new Uint8Array(1);
bytes[0] = parseInt(encodedString);
}
return bytes.buffer;
};
var SerialConnection = function() {
this.connectionId = -1;
this.lineBuffer = "";
this.receiveTimeout =50;
this.boundOnReceive = this.onReceive.bind(this);
this.boundOnReceiveError = this.onReceiveError.bind(this);
this.onConnect = new chrome.Event();
this.onReadLine = new chrome.Event();
this.onError = new chrome.Event();
};
SerialConnection.prototype.onConnectComplete = function(connectionInfo) {
if (!connectionInfo) {
log("Connection failed.");
return;
}
this.connectionId = connectionInfo.connectionId;
chrome.serial.onReceive.addListener(this.boundOnReceive);
chrome.serial.onReceiveError.addListener(this.boundOnReceiveError);
this.onConnect.dispatch();
};
SerialConnection.prototype.onReceive = function(receiveInfo) {
if (receiveInfo.connectionId !== this.connectionId) {
return;
}
this.lineBuffer += ab2str(receiveInfo.data);
var index;
while ((index = this.lineBuffer.indexOf('$')) >= 0) {
var line = this.lineBuffer.substr(0, index + 1);
this.onReadLine.dispatch(line);
this.lineBuffer = this.lineBuffer.substr(index + 1);
}
};
SerialConnection.prototype.onReceiveError = function(errorInfo) {
log('Error');
if (errorInfo.connectionId === this.connectionId) {
log('Error');
this.onError.dispatch(errorInfo.error);
log('Error');
}
log('Error');
};
SerialConnection.prototype.connect = function(path) {
serial.connect(path, this.onConnectComplete.bind(this))
};
SerialConnection.prototype.send = function(msg) {
if (this.connectionId < 0) {
throw 'Invalid connection';
}
serial.send(this.connectionId, str2ab(msg), function() {});
};
SerialConnection.prototype.disconnect = function() {
if (this.connectionId < 0) {
throw 'Invalid connection';
}
serial.disconnect(this.connectionId, function() {});
};
var connection = new SerialConnection();
connection.onConnect.addListener(function() {
log('connected to: ' + DEVICE_PATH);
);
connection.onReadLine.addListener(function(line) {
log('read line: ' + line);
});
connection.onError.addListener(function() {
log('Error: ');
});
connection.connect(DEVICE_PATH);
function log(msg) {
var buffer = document.querySelector('#buffer');
buffer.innerHTML += msg + '<br/>';
}
document.querySelector('button').addEventListener('click', function() {
connection.send(2);
});
Maybe I'm reading the code incorrectly, but at no point do you pass receiveTimeout into chrome.serial. The method signature is chrome.serial.connect(string path, ConnectionOptions options, function callback), where options is an optional parameter. You never pass anything into options. Fix that and let us know what happens.