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

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

Related

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

moq mongodb InsertOneAsync method

I am using Mongodb database with .net core. I just want to moq insert method that using mongodbContext. Here is what I am trying to do but it's not working:
public void InsertEventAsync_Test()
{
//Arrange
var eventRepository = EventRepository();
var pEvent = new PlanEvent
{
ID = "testEvent",
WorkOrderID = "WorkOrderID",
IsDeleted = false,
IsActive = true,
EquipmentID = "EquipmentID"
};
////Act
//mockEventContext.Setup(mr => mr.PlanEvent.InsertOne(It.IsAny<PlanEvent>(), It.IsAny<InsertOneOptions>()))
mockEventContext.Setup(s => s.PlanEvent.InsertOneAsync(It.IsAny<PlanEvent>(), It.IsAny<InsertOneOptions>())).Returns("sdad");
var result = eventRepository.InsertEventAsync(pEvent);
////Assert
result.Should().NotBeNull();
}
Below is the method that I need to Moq:
public EventRepository(IFMPContext eventContext)
{
_eventContext = eventContext;
}
public async Task<string> InsertEventAsync(Model.EventDataModel.PlanEvent eventobj)
{
eventobj._id = ObjectId.GenerateNewId();
eventobj.CreatedDateTime = DateTime.UtcNow.ToString();
try
{
_eventContext.PlanEvent.InsertOne(eventobj);
return eventobj.ID;
}
catch (Exception ex)
{
string x = ex.Message;
}
return "";
}
Assuming
public class EventRepository {
private readonly IFMPContext eventContext;
public EventRepository(IFMPContext eventContext) {
this.eventContext = eventContext;
}
public async Task<string> InsertEventAsync(Model.EventDataModel.PlanEvent eventobj) {
eventobj._id = ObjectId.GenerateNewId();
eventobj.CreatedDateTime = DateTime.UtcNow.ToString();
try {
await eventContext.PlanEvent.InsertOneAsync(eventobj);
return eventobj.ID;
} catch (Exception ex) {
string x = ex.Message;
}
return "";
}
}
You need to configure the test to support the async nature of the method under test
public async Task InsertEventAsync_Test()
{
//Arrange
var expected = "testEvent";
var pEvent = new PlanEvent {
ID = expected,
WorkOrderID = "WorkOrderID",
IsDeleted = false,
IsActive = true,
EquipmentID = "EquipmentID"
};
var mockEventContext = new Mock<IFMPContext>();
mockEventContext
.Setup(_ => _.PlanEvent.InsertOneAsync(It.IsAny<PlanEvent>(), It.IsAny<InsertOneOptions>()))
.ReturnsAsync(Task.FromResult((object)null));
var eventRepository = new EventRepository(mockEventContext.Object);
//Act
var actual = await eventRepository.InsertEventAsync(pEvent);
//Assert
actual.Should().NotBeNull()
actual.Should().Be(expected);
}
The test method definition needed to be updated to be asynchronous to allow the method under test to be awaited. The mock dependency also needed to be setup in such a way to allow the async flow to continue as expected when invoked.
#Nkosi Thanks a lot for your help. Finally i found the way. i was missing extra moq param It.IsAny<System.Threading.CancellationToken>() below is the working test
public void InsertEventAsync_Test()
{
//Arrange
var eventRepository = EventRepository();
var pEvent = new PlanEvent
{
ID = "testEvent",
WorkOrderID = "WorkOrderID",
IsDeleted = false,
IsActive = true,
EquipmentID = "EquipmentID"
};
////Act
mockEventContext.Setup(s => s.PlanEvent.InsertOne(It.IsAny<PlanEvent>(), It.IsAny<InsertOneOptions>(),It.IsAny<System.Threading.CancellationToken>()));
var result = eventRepository.InsertEventAsync(pEvent);
////Assert
result.Should().NotBeNull();
Assert.AreEqual(pEvent.ID, result);
}

mybatis interceptor sql log process

i make mybatis sqllog intercepor in my project.
in case. #{__frch_CUST_0} #{__frch_CUST_1} ~~~ #{__frch_CUST_N}
how can i get parameters value "__frch_CUST_n" ?
// mybatis interceptor sql log function
public String getSqlLog(StatementHandler handler)
{
String sql = handler.getBoundSql().getSql();
Object param = handler.getParameterHandler().getParameterObject();
List<ParameterMapping> paramMapping = handler.getBoundSql().getParameterMappings();
// change \? value to replace point
for(ParameterMapping mapping:paramMapping)
{
sql = sql.replaceFirst("\\?", "#{"+mapping.getProperty()+"}");
}
for(ParameterMapping mapping:paramMapping)
{
String sqlparam = "#{"+mapping.getProperty()+"}";
String sqlparamname = mapping.getProperty();
Object sqlparamvalue = ((Map) param).get(sqlparamname);
if( !sqlparamname.startsWith("__frch_") )
{
if(isNull(sqlparamvalue))
{
sql = sql.replace(sqlparam, "NULL");
}
else
{
if(sqlparamvalue instanceof String)
{
try
{
sql = sql.replace(sqlparam, "'"+getSQLString(sqlparamvalue.toString())+"'");
}
catch(Exception e)
{
sql = sql.replace(sqlparam, "'"+getSQLString(sqlparamvalue.toString())+"'");
}
}
else
{
sql = sql.replace(sqlparam, sqlparamvalue.toString());
}
}
}
else
{
**// HOW CAN I DO HERE?**
}
}
return sql;
}
thank you for read my question..
i resolve my self.
mybatis make new arrayList parameter. and use it.
example list value
DATE = ['20180101','20180102','20180103'];
STEP = ['PLAN', 'MAKE', 'SETUP'];
__frch_DATE_0
__frch_DATE_1
__frch_DATE_2
__frch_STEP_3
__frch_STEP_4
__frch_STEP_5
mybatis __frch_ = ['20180101','20180102','20180103','PLAN', 'MAKE', 'SETUP']
so i use it. my question is resolved..
public String getSqlLog(StatementHandler handler)
{
String sql = handler.getBoundSql().getSql();
Object param = handler.getParameterHandler().getParameterObject();
List<ParameterMapping> paramMapping = handler.getBoundSql().getParameterMappings();
List foreachlist = new ArrayList();
for(ParameterMapping mapping:paramMapping)
{
sql = sql.replaceFirst("\\?", "#{"+mapping.getProperty()+"}");
}
for(ParameterMapping mapping:paramMapping)
{
String sqlparam = "#{"+mapping.getProperty()+"}";
String sqlparamname = mapping.getProperty();
Object sqlparamvalue = ((Map) param).get(sqlparamname);
if( !sqlparamname.startsWith("__frch_") )
{
if(isNull(sqlparamvalue))
{
sql = sql.replace(sqlparam, "NULL");
}
else
{
if(sqlparamvalue instanceof String)
{
try
{
sql = sql.replace(sqlparam, "'"+getSQLString(sqlparamvalue.toString())+"'");
}
catch(Exception e)
{
sql = sql.replace(sqlparam, "'"+getSQLString(sqlparamvalue.toString())+"'");
}
}
else
{
sql = sql.replace(sqlparam, sqlparamvalue.toString());
}
}
}
else
{
if( foreachlist.size() == 0 )
{
Map parammap = (Map)param;
Iterator iterator = parammap.keySet().iterator();
while(iterator.hasNext())
{
String key = iterator.next().toString();
Object value = (Object)parammap.get(key);
if( value instanceof List )
{
List valuelist = (List)value;
for(int i=0;i<valuelist.size();i++)
{
foreachlist.add(valuelist.get(i));
}
}
}
}
String buff = sqlparamname.split("__frch_")[1];
int index = Integer.parseInt(buff.substring(buff.lastIndexOf("_")+1));
try
{
sql = sql.replace(sqlparam, "'"+getSQLString((String)foreachlist.get(index))+"'");
}
catch(Exception e)
{
;
}
}
}
return sql;
}

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.

ADO.NET: ExecuteScalar() Connection problum

Here is my C# code
protected bool SaveItems(ObservableCollection<Model> Items, Int32 UserId)
{
if (sqlcon.State == ConnectionState.Closed)
sqlcon.Open();
foreach (Model Rate in Items)
{
SqlCommand sccmd = new SqlCommand("ItemsAdd", sqlcon);
sccmd.CommandType = CommandType.StoredProcedure;
sccmd.Parameters.Add("#ItemsId", SqlDbType.Int).Value = Rate.Id;
sccmd.Parameters.Add("#RMId", SqlDbType.Int).Value = Rate.HeadId;
sccmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = Rate.Date;
sccmd.Parameters.Add("#Price", SqlDbType.Decimal).Value = Rate.Price;
sccmd.Parameters.Add("#UserId", SqlDbType.Int).Value = UserId;
if (Rate.Id == 0)
{
Rate.Id = Convert.ToInt32(sccmd.ExecuteScalar());
}
else
sccmd.ExecuteScalar();
}
sqlcon.Close();
return true;
}
Repeated clicking on add button, this is giving me this error
Additional information: ExecuteScalar requires an open and available
Connection. The connection's current state is closed.
What is causing this error and how can I fix it?
Try Like this:
protected bool SaveItems(ObservableCollection<Model> Items, Int32 UserId)
{
if (sqlcon.State == ConnectionState.Closed)
{
sqlcon.Open();
foreach (Model Rate in Items)
{
SqlCommand sccmd = new SqlCommand("ItemsAdd", sqlcon);
sccmd.CommandType = CommandType.StoredProcedure;
sccmd.Parameters.Add("#ItemsId", SqlDbType.Int).Value = Rate.Id;
sccmd.Parameters.Add("#RMId", SqlDbType.Int).Value = Rate.HeadId;
sccmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = Rate.Date;
sccmd.Parameters.Add("#Price", SqlDbType.Decimal).Value = Rate.Price;
sccmd.Parameters.Add("#UserId", SqlDbType.Int).Value = UserId;
if (Rate.Id == 0)
{
Rate.Id = Convert.ToInt32(sccmd.ExecuteScalar());
}
else
sccmd.ExecuteScalar();
}
sqlcon.Close();
}
return true;
}