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

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

Related

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

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.

opcua session was closed by client

I have written the attached OpcUaConnector class for opc-ua connection related activities.
But it is not handling session. For example:
In opc ua configuration disabled the endpoint
In kepserver configuration did runtime > reinitializing
The windows service is throwing:
Source : system.Reactive.Core
InnerException : The session was closed by client
and stopping the windows service, as this error goes unhandled.
Can some one suggest how to handle session in opc-ua?
public class OpcUaConnector
{
private static SimplerAES simplerAES = new SimplerAES();
private DataContainer dataCointainer = null;
private UaTcpSessionChannel channel;
private string opcServerName = string.Empty;
private string opcUserId = string.Empty;
private string opcPassword = string.Empty;
private static ILog LogOpcStore;
private static System.IDisposable token;
private static uint id;
public OpcConnector(ILog Log)
{
IntializeLogOpcStore(Log);
}
private static void IntializeLogOpcStore(ILog Log)
{
LogOpcStore = Log;
}
public async Task OpenOpcConnection()
{
try
{
if ((!string.IsNullOrEmpty(this.opcServerName) & (this.opcServerName != AppMain.MyAppSettings.OpcServer)) ||
(!string.IsNullOrEmpty(this.opcUserId) & (this.opcUserId != AppMain.MyAppSettings.OpcUserId)) ||
(!string.IsNullOrEmpty(this.opcPassword) & (this.opcPassword != AppMain.MyAppSettings.OpcPassword)))
{
await channel.CloseAsync();
this.opcServerName = AppMain.MyAppSettings.OpcServer;
this.opcUserId = AppMain.MyAppSettings.OpcUserId;
this.opcPassword = AppMain.MyAppSettings.OpcPassword;
}
if (channel==null || (channel != null && (channel.State == CommunicationState.Closed || channel.State == CommunicationState.Faulted)))
{
var appDescription = new ApplicationDescription()
{
ApplicationName = "MyAppName",
ApplicationUri = $"urn:{System.Net.Dns.GetHostName()}:MyAppName",
ApplicationType = ApplicationType.Client,
};
//application data won't be deleted when uninstall
var certificateStore = new DirectoryStore(
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), MyAppName", "pki"),
true, true
);
//if the Ethernet cable unplugs or the Wifi drops out,
//you have some timeouts that can keep the session open for a while.
//There is a SessionTimeout (default of 2 min).
this.channel = new UaTcpSessionChannel(
appDescription,
certificateStore,
SignInOpc,
AppMain.MyAppSettings.OpcServer,
null,
options: new UaTcpSessionChannelOptions { SessionTimeout = 120000 });
await channel.OpenAsync();
//LogOpcStore.Info(String.Format("Opc connection sucessful"));
}
this.opcServerName = AppMain.MyAppSettings.OpcServer;
this.opcUserId = AppMain.MyAppSettings.OpcUserId;
this.opcPassword = AppMain.MyAppSettings.OpcPassword;
}
catch (Exception ex)
{
ServiceException serviceException = new ServiceException(ex.HResult + " " + ex.Message, "C052");
throw serviceException;
}
}
private static async Task RecursivelyFindNode(UaTcpSessionChannel channel, NodeId nodeid)
{
BrowseRequest browseRequest = new BrowseRequest
{
NodesToBrowse = new BrowseDescription[] { new BrowseDescription { NodeId = nodeid, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = NodeId.Parse(ReferenceTypeIds.HierarchicalReferences), NodeClassMask = (uint)NodeClass.Variable | (uint)NodeClass.Object, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All } },
};
BrowseResponse browseResponse = await channel.BrowseAsync(browseRequest);
foreach (var rd1 in browseResponse.Results[0].References ?? new ReferenceDescription[0])
{
uint chid = AppMain.MyTagDatabase.GetClientHandleByTag(rd1.DisplayName.ToString());
if (chid > 0)
{
AppMain.MyTagDatabase.UpdateNodeByClientHandle(chid, rd1.NodeId.ToString());
}
await RecursivelyFindNode(channel, ExpandedNodeId.ToNodeId(rd1.NodeId, channel.NamespaceUris));
}
}
public async Task CreateSubscription(DataContainer dc)
{
double curReadingValue;
try
{
dataCointainer = dc;
await RecursivelyFindNode(channel, NodeId.Parse(ObjectIds.RootFolder));
if (AppMain.MyTagDatabase.GetCntTagsNotInOpcServer() == AppMain.MyTagDatabase.GetTagCount())
{
//no need to create subscription
return;
}
//subscription timeout that is the product of PublishingInterval * LifetimeCount:
var subscriptionRequest = new CreateSubscriptionRequest
{
RequestedPublishingInterval = 1000f,
RequestedMaxKeepAliveCount = 30,
RequestedLifetimeCount = 30 * 3,
PublishingEnabled = true,
};
var subscriptionResponse = await channel.CreateSubscriptionAsync(subscriptionRequest);
id = subscriptionResponse.SubscriptionId;
var itemsToCreate = new MonitoredItemCreateRequest[AppMain.MyTagDatabase.GetTagHavingNodeCount()];
int i = 0;
foreach (var item in AppMain.MyTagDatabase.GetMyTagDatabase())
{
var itemKey = item.Key;
var itemValue = item.Value;
itemsToCreate[i] = new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = NodeId.Parse(itemValue.NodeId), AttributeId = AttributeIds.Value }, MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters { ClientHandle = itemKey, SamplingInterval = -1, QueueSize = 0, DiscardOldest = true } };
i++;
}
var itemsRequest = new CreateMonitoredItemsRequest
{
SubscriptionId = id,
ItemsToCreate = itemsToCreate,
};
var itemsResponse = await channel.CreateMonitoredItemsAsync(itemsRequest);
token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(pr =>
{
// loop thru all the data change notifications
// receiving data change notifications here
var dcns = pr.NotificationMessage.NotificationData.OfType<DataChangeNotification>();
foreach (var dcn in dcns)
{
foreach (var min in dcn.MonitoredItems)
{
MyTag MyTag = new MyTag();
bool hasValue = AppMain.MyTagDatabase.GetMyTag(min.ClientHandle, out MyTag);
if (hasValue)
{
if (double.TryParse(min.Value.Value.ToString(), out curReadingValue))
{
//LogOpcStore.Info(String.Format("ClientHandle : {0} TagName : {1} SourceTimestamp : {2} ServerTimeStamp : {3} curReadingValue : {4}", min.ClientHandle, MyTag.TagName, min.Value.SourceTimestamp, min.Value.ServerTimestamp, curReadingValue));
AddDataPointToContainer(1, MyTag.TagName, min.Value.SourceTimestamp, curReadingValue);
}
}
}
}
});
}
catch (Exception ex)
{
//If the interruption lasts longer than these timeouts then the SessionChannel and Subscriptions will need to be recreated.
channel = null;
FatalServiceException fatalserviceException = new FatalServiceException(ex.Message, "C052");
throw fatalserviceException;
}
}
public async Task DeleteSubscription()
{
try
{
var request = new DeleteSubscriptionsRequest
{
SubscriptionIds = new uint[] { id }
};
await channel.DeleteSubscriptionsAsync(request);
token.Dispose();
}
catch (Exception ex)
{
ServiceException serviceException = new ServiceException(ex.Message, "C052");
throw serviceException;
}
}
private static async Task<IUserIdentity> SignInOpc(EndpointDescription endpoint)
{
IUserIdentity userIdentity = null;
if (endpoint.UserIdentityTokens.Any(p => p.TokenType == UserTokenType.Anonymous))
{
userIdentity = new AnonymousIdentity();
}
else if (endpoint.UserIdentityTokens.Any(p => p.TokenType == UserTokenType.UserName))
{
var userName = AppMain.MyAppSettings.OpcUserId;
var password = simplerAES.Decrypt(AppMain.MyAppSettings.OpcPassword);
userIdentity = new UserNameIdentity(userName, password);
}
return userIdentity;
}
private void AddDataPointToContainer(int dataType, string source, DateTime SourceTimestampUTC, double value)
{
ConditionValue conditionValue = new ConditionValue();
long timestamp = AppMain.ServerSyncTimeStore.ConvertDateTimeToTimeStampUTC(SourceTimestampUTC);
conditionValue.dataType = dataType;
conditionValue.source = source;
conditionValue.timestamp = timestamp;
conditionValue.SourceTimestampUTC = SourceTimestampUTC;
conditionValue.LocalTime = SourceTimestampUTC.ToLocalTime();
conditionValue.value = value;
//LogOpcStore.Info(String.Format("TagName : {0} SourceTimestampUTC : {1} timestamp : {2} LocalTime : {3} curReadingValue : {4}", source, SourceTimestampUTC, timestamp, SourceTimestampUTC.ToLocalTime(), value));
dataCointainer.AddDataPoint(conditionValue);
}
}
I see you are using the project https://github.com/convertersystems/opc-ua-client.
When a server closes the session and socket (as happens when you reinitialize Kepware) the client receives immediate notification that causes the client channel to fault. A faulted channel cannot be reopened, it should be aborted and a new channel should be created.
I made this standalone test, to show that you may have to catch an exception and recreate the channel and subscription. The point of this test is to subscribe to the CurrentTime node and collect 60 datachanges. The test should last a minute. If you re-init the Kepware server in the middle of the test, the code catches the exception and recreates the channel and subscription.
[TestMethod]
public async Task OpcConnectorTest()
{
var count = 0;
UaTcpSessionChannel channel = null;
while (count < 60)
{
try
{
channel = new UaTcpSessionChannel(
this.localDescription,
this.certificateStore,
new AnonymousIdentity(),
EndpointUrl,
SecurityPolicyUris.None,
loggerFactory: this.loggerFactory);
await channel.OpenAsync();
// create the keep alive subscription.
var subscriptionRequest = new CreateSubscriptionRequest
{
RequestedPublishingInterval = 1000f,
RequestedMaxKeepAliveCount = 30,
RequestedLifetimeCount = 30 * 3,
PublishingEnabled = true,
};
var subscriptionResponse = await channel.CreateSubscriptionAsync(subscriptionRequest).ConfigureAwait(false);
var id = subscriptionResponse.SubscriptionId;
var token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(pr =>
{
// loop thru all the data change notifications
var dcns = pr.NotificationMessage.NotificationData.OfType<DataChangeNotification>();
foreach (var dcn in dcns)
{
foreach (var min in dcn.MonitoredItems)
{
Console.WriteLine($"sub: {pr.SubscriptionId}; handle: {min.ClientHandle}; value: {min.Value}");
count++;
}
}
});
var itemsRequest = new CreateMonitoredItemsRequest
{
SubscriptionId = id,
ItemsToCreate = new MonitoredItemCreateRequest[]
{
new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = NodeId.Parse("i=2258"), AttributeId = AttributeIds.Value }, MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters { ClientHandle = 12345, SamplingInterval = -1, QueueSize = 0, DiscardOldest = true } }
},
};
var itemsResponse = await channel.CreateMonitoredItemsAsync(itemsRequest);
while (channel.State == CommunicationState.Opened && count < 60)
{
await Task.Delay(1000);
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.GetType()}. {ex.Message}");
}
}
if (channel != null)
{
Console.WriteLine($"Closing session '{channel.SessionId}'.");
await channel.CloseAsync();
}
}
I know this is an old post, but I stumbled upon this problem as well. For those interested:
The problem is related to the subscription(s).
When the following code is run:
token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(pr =>
{
// loop thru all the data change notifications
// receiving data change notifications here
var dcns = pr.NotificationMessage.NotificationData.OfType<DataChangeNotification>();
foreach (var dcn in dcns)
{
foreach (var min in dcn.MonitoredItems)
{
MyTag MyTag = new MyTag();
bool hasValue = AppMain.MyTagDatabase.GetMyTag(min.ClientHandle, out MyTag);
if (hasValue)
{
if (double.TryParse(min.Value.Value.ToString(), out curReadingValue))
{
//LogOpcStore.Info(String.Format("ClientHandle : {0} TagName : {1} SourceTimestamp : {2} ServerTimeStamp : {3} curReadingValue : {4}", min.ClientHandle, MyTag.TagName, min.Value.SourceTimestamp, min.Value.ServerTimestamp, curReadingValue));
AddDataPointToContainer(1, MyTag.TagName, min.Value.SourceTimestamp, curReadingValue);
}
}
}
}
});
Observable.subscribe() takes multiple arguments. You should include what to do in case of an error. For example:
token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(
pr => { code to run normally... },
ex => { Log.Info(ex.Message); },
() => { }
);
See http://reactivex.io/documentation/operators/subscribe.html for more information.

DB2ResultSet.Read(). ERROR [24000] [IBM] CLI0115E Invalid cursor state. SQLSTATE=24000

We have problem with the application run DB2ResultSet.Read(). Sometime will get ERROR :
[24000] [IBM] CLI0115E Invalid cursor state. SQLSTATE=24000.
Database : DB2 for Linux, UNIX and Windows V10.5
Client: Windows 7 64bit
Method:
public int EventGetEvSegmentCnt(string SegmentID, string strEvntGroup)
{
int strGroupCnt = 0;
string strSQL = string.Empty;`enter code here`
DB2ResultSet objRs;
if (string.IsNullOrEmpty(SegmentID) || string.IsNullOrEmpty(strEvntGroup))
{
strGroupCnt = 0;
}
else
{
strSQL = " SELECT COUNT(EVNT_CODE) AS EVNT_GROUP_COUNT FROM E_SEGMENT_EVENT WHERE C_SEGMENT_ID = " + SegmentID + " AND EVNT_GROUP = " + strEvntGroup;
Common.DatabaseHelper helper = new Common.DatabaseHelper();
objRs = helper.ExecuteResultSet(strSQL);
if (objRs.Read())
{
strGroupCnt = 0;
}
else
{
strGroupCnt = int.Parse(objRs["EVNT_GROUP_COUNT"].ToString());
}
}
return strGroupCnt;
}
Error Message:
[Information] System.Web.HttpUnhandledException (0x80004005):
Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> IBM.Data.DB2.DB2Exception (0x80004005): ERROR [24000] [IBM] CLI0115E Invalid cursor state. SQLSTATE=24000
at IBM.Data.DB2.DB2DataBuffer.FetchScroll(FetchType fetchType, Int64 offset, Int32 numRows)
at IBM.Data.DB2.DB2DataBuffer.FetchNext()
at IBM.Data.DB2.DB2DataReader.Fetch(FetchDirection direction, Int64 offset, Boolean& isDeleted)
at IBM.Data.DB2.DB2ResultSet.Read()
Please help.
DatabaseHelper:
public class DatabaseHelper
{
public DatabaseHelper()
{
}
public DataSet ExecuteDataSet(string commandText, List<DB2Parameter> parameters = null)
{
var command = GetCommand(commandText, parameters);
var adapter = new DB2DataAdapter();
adapter.SelectCommand = command;
var ds = new DataSet();
adapter.Fill(ds);
adapter.Dispose();
return ds;
}
public DB2DataReader ExecuteReader(string commandText, List<DB2Parameter> parameters = null)
{
var command = GetCommand(commandText, parameters);
return command.ExecuteReader(CommandBehavior.CloseConnection);
}
public DB2ResultSet ExecuteResultSet(string commandText, List<DB2Parameter> parameters = null)
{
var command = GetCommand(commandText, parameters);
//DB2ResultSet result = command.ExecuteResultSet(CommandBehavior.Default, DB2CursorType.Dynamic);
DB2ResultSet result = command.ExecuteResultSet(CommandBehavior.CloseConnection, DB2CursorType.Dynamic);
return result;
}
public DB2ResultSet ExecuteResultSetStatic(string commandText, List<DB2Parameter> parameters = null)
{
var command = GetCommand(commandText, parameters);
// DB2ResultSet result = command.ExecuteResultSet(CommandBehavior.Default, DB2CursorType.Static);
DB2ResultSet result = command.ExecuteResultSet(CommandBehavior.CloseConnection, DB2CursorType.Static);
return result;
}
public int ExecuteNonQuery(string commandText, List<DB2Parameter> parameters = null)
{
var command = GetCommand(commandText, parameters);
int result = command.ExecuteNonQuery();
command.Connection.Close();
return result;
}
public void ExecuteSQLArray(string[] arrSQL)
{
var command = new DB2Command();
command.Connection = GetConnection();
command.CommandType = CommandType.Text;
command.CommandTimeout = 600;
command.Transaction = command.Connection.BeginTransaction();
try
{
foreach (string strSQL in arrSQL)
{
if (!string.IsNullOrEmpty(strSQL))
{
command.CommandText = strSQL;
command.ExecuteNonQuery();
}
}
command.Transaction.Commit();
}
catch (Exception)
{
command.Transaction.Rollback();
throw;
}
command.Connection.Close();
command.Dispose();
}
public DB2Connection GetConnection()
{
var conn = new DB2Connection(System.Configuration.ConfigurationManager.ConnectionStrings["DB2_Conn"].ConnectionString);
conn.Open();
return conn;
}
public DB2Command GetCommand(string commandText, List<DB2Parameter> parameters)
{
var command = new DB2Command(commandText);
command.Connection = GetConnection();
command.CommandTimeout = 600;
if (parameters != null)
{
foreach (var parameter in parameters)
{
command.Parameters.Add(parameter);
}
}
return command;
}
}
try this :
public int EventGetEvSegmentCnt(string SegmentID, string strEvntGroup)
{
if (string.IsNullOrEmpty(SegmentID) || string.IsNullOrEmpty(strEvntGroup)) return 0;
int strGroupCnt = 0;
DataSet objDS=null;
string strSQL = string.Format(" SELECT COUNT(EVNT_CODE) AS EVNT_GROUP_COUNT FROM E_SEGMENT_EVENT WHERE C_SEGMENT_ID ={0} AND EVNT_GROUP = {0}", SegmentID, strEvntGroup);
try
{
Common.DatabaseHelper helper = new Common.DatabaseHelper();
objDS = helper.ExecuteDataSet(strSQL);
if (objRs.Table[0].Rows.Count > 0)
{
strGroupCnt = int.Parse(objDS.Tables[0].Rows[0]["EVNT_GROUP_COUNT"].ToString());
}
}
finally
{
if (objDS != null) objDS.Dispose()
return strGroupCnt;
}
}

How can update contact in existing contact update to postal address

This is my code to existing contact to change the postal address code
ops = new ArrayList<ContentProviderOperation>();
rawContactID = ops.size();
///Insert code are working/////
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,rawContactID)
.withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET,addr)
.withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, edtcity.getText().toString())
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, edtpostcode.getText().toString())
enter code here
`enter code here` .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, edtcountry.getText().toString()).build());
//// I am trying this update record code but not working///
btn_upcontacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withSelection(String.valueOf(CONTENT_URI), new String[]{CommonDataKinds.StructuredPostal.RAW_CONTACT_ID + " = " + rawContactID})
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, addr)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withSelection(String.valueOf(CONTENT_URI), new String[]{CommonDataKinds.StructuredPostal.RAW_CONTACT_ID + " = " + rawContactID})
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, scity)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withSelection(String.valueOf(CONTENT_URI), new String[]{CommonDataKinds.StructuredPostal.RAW_CONTACT_ID + " = " + rawContactID})
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, scode)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withSelection(String.valueOf(CONTENT_URI), new String[]{CommonDataKinds.StructuredPostal.RAW_CONTACT_ID + " = " + rawContactID})
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,scountry)
.build());
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
I am update the record coding to btn_upcontacts listner but not working,Please Help me
I am trying the many code use are but not working
I have a simply edit the text andd update to the exsiting contact the postal address without the sqllite datbase
Advance in Thanks
int _contact_id = 10110; // your Conatct id
Uri rawContactUri = null;
Cursor rawContactCursor = null;
try {
// if some fields not available use rawContactUri as ID
rawContactUri = null;
rawContactCursor = context.getContentResolver().query(
ContactsContract.RawContacts.CONTENT_URI,
new String[]{ContactsContract.RawContacts._ID},
ContactsContract.RawContacts.CONTACT_ID + " = " + _contact_id,
null,
null);
if (!rawContactCursor.isAfterLast()) {
rawContactCursor.moveToFirst();
rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendPath("" + rawContactCursor.getLong(0)).build();
}
rawContactCursor.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rawContactCursor != null) {
rawContactCursor.close();
}
}
Boolean noAddress = true;
Cursor currAddr = null;
try {
Uri URI_ADDRESS = ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI;
String SELECTION_ADDRESS = ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.StructuredPostal.MIMETYPE + " = ?";
String[] SELECTION_ARRAY_ADDRESS = new String[]{
String.valueOf(_contact_id),
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
currAddr = context.getContentResolver().query(URI_ADDRESS, null, SELECTION_ADDRESS, SELECTION_ARRAY_ADDRESS, null);
if (currAddr.getCount() > 0) {
currAddr.moveToFirst();
while (!currAddr.isAfterLast()) {
noAddress = false;
currAddr.moveToNext();
}
} else {
noAddress = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (currAddr != null) {
currAddr.close();
}
}
if (noAddress) {
// address is not available
try {
String street_name = "strt";
String number ="num";
String apartment = "app";
String postal_code = "7777";
String state ="state";
String city = "cityty";
String country = "countrrry";
ContentValues adrsValues = new ContentValues();
adrsValues.put(ContactsContract.Data.RAW_CONTACT_ID, ContentUris.parseId(rawContactUri));
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, "1");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
(street_name.length() > 0 || number.length() > 0) ? number + " " + street_name : number + " " + street_name);
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD,
(apartment.length() > 0) ? apartment : "");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
(city.length() > 0) ? city : "");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
(state.length() > 0) ? state : "");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
(postal_code.length() > 0) ? postal_code : "");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
(country.length() > 0) ? country : "");
adrsValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, adrsValues);
} catch (Exception e) {
isError = true;
e.printStackTrace();
}
} else {
// address is already available
try {
String street_name = "strt";
String number ="num";
String apartment = "app";
String postal_code = "7777";
String state ="state";
String city = "cityty";
String country = "countrrry";
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where1, AryStructuredAdd1)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
(street_name.length() > 0 || number.length() > 0) ? number + " " + street_name : number + " " + street_name)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD,
(apartment.length() > 0) ? apartment : "")
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
(city.length() > 0) ? city : "")
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
(state.length() > 0) ? state : "")
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
(postal_code.length() > 0) ? postal_code : "")
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
(country.length() > 0) ? country : "")
.build());
} catch (Exception e) {
isError = true;
e.printStackTrace();
}
}

video overwriting using ffmpeg - I want to Add video rotation code and rewrite the existing file..How can i do that?

I want to rotate the .mov file which is in portrait mode by 90 degrees, for that i used the following code..
It works but, it results in loss of video frames...
My code is,
public void encode(File source, File target, EncodingAttributes attributes,
EncoderProgressListener listener, Integer i) throws IllegalArgumentException,
InputFormatException, EncoderException {
String formatAttribute = attributes.getFormat();
Float offsetAttribute = attributes.getOffset();
Float durationAttribute = attributes.getDuration();
QualityScale qualityScale = attributes.getQualityScale();
AudioAttributes audioAttributes = attributes.getAudioAttributes();
VideoAttributes videoAttributes = attributes.getVideoAttributes();
if (audioAttributes == null && videoAttributes == null) {
throw new IllegalArgumentException(
"Both audio and video attributes are null");
}
target = target.getAbsoluteFile();
target.getParentFile().mkdirs();
FFMPEGExecutor ffmpeg = locator.createExecutor();
if (offsetAttribute != null) {
ffmpeg.addArgument("-ss");
ffmpeg.addArgument(String.valueOf(offsetAttribute.floatValue()));
}
ffmpeg.addArgument("-i");
ffmpeg.addArgument(source.getAbsolutePath());
if (durationAttribute != null) {
ffmpeg.addArgument("-t");
ffmpeg.addArgument(String.valueOf(durationAttribute.floatValue()));
}
if (qualityScale != null) {
ffmpeg.addArgument("-qscale:"+qualityScale.getQualityStreamSpecifier());
ffmpeg.addArgument(String.valueOf(qualityScale.getQualityValue()));
}
if (videoAttributes == null) {
ffmpeg.addArgument("-vn");
} else {
String codec = videoAttributes.getCodec();
if (codec != null) {
ffmpeg.addArgument("-vcodec");
ffmpeg.addArgument(codec);
}
String tag = videoAttributes.getTag();
if (tag != null) {
ffmpeg.addArgument("-vtag");
ffmpeg.addArgument(tag);
}
Integer bitRate = videoAttributes.getBitRate();
if (bitRate != null) {
ffmpeg.addArgument("-b");
ffmpeg.addArgument(String.valueOf(bitRate.intValue()));
}
Integer frameRate = videoAttributes.getFrameRate();
if (frameRate != null) {
ffmpeg.addArgument("-r");
ffmpeg.addArgument(String.valueOf(frameRate.intValue()));
}
VideoSize size = videoAttributes.getSize();
if (size != null) {
ffmpeg.addArgument("-s");
ffmpeg.addArgument(String.valueOf(size.getWidth()) + "x"
+ String.valueOf(size.getHeight()));
}
FilterGraph filterGraph = videoAttributes.getFilterGraph();
if (filterGraph != null) {
ffmpeg.addArgument("-vf");
if(videoAttributes.getRotate() != null && videoAttributes.getRotate() == 90){
ffmpeg.addArgument("transpose=1");
}else if(videoAttributes.getRotate() != null && videoAttributes.getRotate() == 180){
ffmpeg.addArgument("vflip,hflip");
}
else {
if (filterGraph.isUseExpression()) {
ffmpeg.addArgument(filterGraph.getFilterGraphExpression());
}
}
}
}
if (audioAttributes == null) {
ffmpeg.addArgument("-an");
} else {
String codec = audioAttributes.getCodec();
if (codec != null) {
ffmpeg.addArgument("-acodec");
ffmpeg.addArgument(codec);
}
Integer bitRate = audioAttributes.getBitRate();
if (bitRate != null) {
ffmpeg.addArgument("-ab");
ffmpeg.addArgument(String.valueOf(bitRate.intValue()));
}
Integer channels = audioAttributes.getChannels();
if (channels != null) {
ffmpeg.addArgument("-ac");
ffmpeg.addArgument(String.valueOf(channels.intValue()));
}
Integer samplingRate = audioAttributes.getSamplingRate();
if (samplingRate != null) {
ffmpeg.addArgument("-ar");
ffmpeg.addArgument(String.valueOf(samplingRate.intValue()));
}
Integer volume = audioAttributes.getVolume();
if (volume != null) {
ffmpeg.addArgument("-vol");
ffmpeg.addArgument(String.valueOf(volume.intValue()));
}
}
ffmpeg.addArgument("-f");
ffmpeg.addArgument(formatAttribute);
ffmpeg.addArgument("-y");
ffmpeg.addArgument(target.getAbsolutePath());
try {
ffmpeg.execute();
} catch (IOException e) {
throw new EncoderException(e);
}
try {
String lastWarning = null;
long duration;
long progress = 0;
RBufferedReader reader = null;
reader = new RBufferedReader(new InputStreamReader(ffmpeg
.getErrorStream()));
MultimediaInfo info = parseMultimediaInfo(source, reader);
if (durationAttribute != null) {
duration = (long) Math
.round((durationAttribute.floatValue() * 1000L));
} else {
duration = info.getDuration();
if (offsetAttribute != null) {
duration -= (long) Math
.round((offsetAttribute.floatValue() * 1000L));
}
}
if (listener != null) {
listener.sourceInfo(info);
}
int step = 0;
String line;
while ((line = reader.readLine()) != null) {
System.out.println("line::::"+line);
if (step == 0) {
if (line.startsWith("WARNING: ")) {
if (listener != null) {
listener.message(line);
}
} else if (!line.startsWith("Output #0")) {
//throw new EncoderException(line);
} else {
step++;
}
} else if (step == 1) {
if (!line.startsWith(" ")) {
step++;
} else {
System.out.println("line>>>>>>"+line);
Hashtable table1 = new Hashtable();
Matcher m = ROTATE_INFO_PATTERN.matcher(line);
while (m.find()) {
if (table1 == null) {
table1 = new Hashtable();
}
String key = m.group(1);
String value = m.group(2);
table1.put(key, value);
}
System.out.println("Table values"+table1.get("rotate"));
if(table1.get("rotate") != null){
Object videoRotateValue = table1.get("rotate");
int rotate = Integer.valueOf(videoRotateValue.toString());
switch(rotate){
case 90:
videoAttributes.setRotate(rotate);
if(i == 0){
i++;
encode(source, target, attributes, null, i);
}
break;
case 180:
videoAttributes.setRotate(rotate);
if(i == 0){
i++;
encode(source, target, attributes, null, i);
}
break;
case 270: System.out.println("case 3 :: "+videoRotateValue);
break;
}
}
}
}
if (step == 2) {
if (!line.startsWith("Stream mapping:")) {
throw new EncoderException(line);
} else {
step++;
}
} else if (step == 3) {
if (!line.startsWith(" ")) {
step++;
}
}
if (step == 4) {
line = line.trim();
if (line.length() > 0) {
Hashtable table = parseProgressInfoLine(line);
if (table == null) {
if (listener != null) {
listener.message(line);
}
lastWarning = line;
} else {
if (listener != null) {
String time = (String) table.get("time");
if (time != null) {
int dot = time.indexOf('.');
if (dot > 0 && dot == time.length() - 2
&& duration > 0) {
String p1 = time.substring(0, dot);
String p2 = time.substring(dot + 1);
try {
long i1 = Long.parseLong(p1);
long i2 = Long.parseLong(p2);
progress = (i1 * 1000L)
+ (i2 * 100L);
int perm = (int) Math
.round((double) (progress * 1000L)
/ (double) duration);
if (perm > 1000) {
perm = 1000;
}
listener.progress(perm);
} catch (NumberFormatException e) {
;
}
}
}
}
lastWarning = null;
}
}
}
}
if (lastWarning != null) {
if (!SUCCESS_PATTERN.matcher(lastWarning).matches()) {
throw new EncoderException(lastWarning);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
ffmpeg.destroy();
}
}
Please advise, how to achieve video rotation without any video Frame loss
Thanks In Advance
Lakshmi Priya . K
Worked for couple of days and finally tried to write the rotated video in different target file then i got the video output without any loss and video is also rotated....
Thanks
Lakshmi Priya. K