Analysis Services - TMSL - Execute from C# - service

I looking for a way to execute (what I think is called) TMSL against a Microsoft Analysis Services. I am trying to Process one single table, from a Dot.Net C# application. The JOSN I need to send to the Analysis Service looks something like this:
{
"refresh": {
"type": "full",
"objects": [
{
"database": "BaseName",
"table": "TableName"
}
]
}
}
how do I do? are there something like ado.net that can do the job?
Peter

I found that this works:
StringBuilder qry = new StringBuilder();
qry.Clear();
qry.AppendLine(" ");
qry.AppendLine("{ ");
qry.AppendLine(" \"refresh\": { ");
qry.AppendLine(" \"type\": \"full\", ");
qry.AppendLine(" \"objects\": [ ");
bool AddTegn = false;
foreach (string TableName in TableNames)
{
if (AddTegn)
{
qry.AppendLine(" , ");
}
AddTegn = true;
qry.AppendLine(" { ");
qry.AppendLine(" \"database\": \"" + DataBaseName + "\", ");
qry.AppendLine(" \"table\": \"" + TableName + "\" ");
qry.AppendLine(" } ");
}
qry.AppendLine(" ] ");
qry.AppendLine(" } ");
qry.AppendLine("} ");
AdomdConnection con = "[Connection String]";
con.Open();
AdomdCommand cmd = con.CreateCommand(); //new AdomdCommand(qry.ToString(), con);
cmd.CommandText = qry.ToString();
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.Text;
try
{
int result = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (con != null)
{
con.Close();
}
if (cmd != null)
{
cmd.Dispose();
}
if (con != null)
{
con.Dispose();
}
}

Related

Fixing my code to prevent sql injection

I made a login with authentication in DotNet windows forms app and I'm trying to do my best to guard the database from SQL injection attacks, but it seems like there was a wrong logic in my code. Any help would be appreciated.
/* -UNSAFE command-
sql = #"SELECT employee_no FROM public.tb_userlogin where
username ='" + Convert.ToString(userText.Text) + "' AND password ='" + Convert.ToString(passText.Text) + "'";
*/
conn.Open();
sql = "SELECT employee_no FROM public.tb_userlogin where username = _username AND Decoypass = _password";
EmpNo = code.Converter_string(sql).ToString();
cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.AddWithValue("_username", userText.Text);
cmd.Parameters.AddWithValue("_password", passText.Text);
if (userText.Text == String.Empty || passText.Text == String.Empty)
{
MessageBox.Show("Field cannot be empty!");
}
if (EmpNo != "0")//log in successfully
{
this.Hide();
new ClientCrudFrm().Show();
}
else
{
MessageBox.Show("Please check your username or password", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
return;
}
if (conTable.Rows.Count == 1)
{
MessageBox.Show("login successfully");
}
else
{
MessageBox.Show("Error");
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message,
"Something went wrong", MessageBoxButtons.OK, MessageBoxIcon.Error);
conn.Close();
}
`
This is the full code inside the login button:
private void BtnLogin_Click(object sender, EventArgs e) //user login authentication
{
bool userValidated = validateUserInput(userText.Text);
bool passValidated = validateUserInput(passText.Text);
if (userValidated && passValidated)
{
getConnection();
}
try
{
NpgsqlConnection conn = new NpgsqlConnection("Host=localhost;Database=UserLogin;Username=postgres;Password=adminAdmin1");
NpgsqlDataAdapter conDataAdapter = new NpgsqlDataAdapter();
//NpgsqlDataAdapter conDataAdapter = new NpgsqlDataAdapter("select * from public.tb_userlogin where username='" + userText.Text + "'and password='" + passText.Text + "'", conn);
DataTable conTable = new DataTable();
conDataAdapter.Fill(conTable);
/* -UNSAFE command-
sql = #"SELECT employee_no FROM public.tb_userlogin where
username ='" + Convert.ToString(userText.Text) + "' AND password ='" + Convert.ToString(passText.Text) + "'";
*/
string username = userText.Text;
string password = passText.Text;
conn.Open();
conDataAdapter.SelectCommand = cmd;
cmd = new NpgsqlCommand(sql, conn);
cmd = new NpgsqlCommand("SELECT * FROM public.tb_userlogin where username = $username AND password = $password", conn);
EmpNo = code.Converter_string(sql).ToString();
cmd.Parameters.AddWithValue("$username", userText.Text);
cmd.Parameters.AddWithValue("$username", passText.Text);
NpgsqlDataReader dr = cmd.ExecuteReader();
if (userText.Text == String.Empty || passText.Text == String.Empty)
{
MessageBox.Show("Field cannot be empty!");
}
if (EmpNo != "0")//log in successfully
{
this.Hide();
new ClientCrudFrm().Show();
}
else
{
MessageBox.Show("Please check your username or password", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
return;
}
if (conTable.Rows.Count == 1)
{
MessageBox.Show("login successfully");
}
else
{
MessageBox.Show("Error");
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message,
"Something went wrong", MessageBoxButtons.OK, MessageBoxIcon.Error);
conn.Close();
}
}
with the updated code above, here saying a new error when I log in:
"The SelectCommand property has not been initialized before calling Fill"
From: the Npgsql documentation, use $1, $2, etc. as the placeholders for your parameters, something like this:
sql = "SELECT employee_no"
+ "FROM public.tb_userlogin"
+ "where username = $1"
+ "AND Decoypass = $2"
;

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

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.

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

How can i get ram serial number?

I need to know how I can get RAM (Physical memory) serial number. I am using C# and I used WMI to get Hardware information but serial Number return null on another computers. I want to know how can I get it and work on any computer (not WMI) and if there is no another way can I write it in C++ and make connection between this function and my application?
This is some of my code:
WqlObjectQuery Memory3_objectQuery = new WqlObjectQuery("Select * from Win32_PhysicalMemory");
ManagementObjectSearcher Memory3_Searcher = new ManagementObjectSearcher(Memory3_objectQuery);
foreach (ManagementObject MO2 in Memory3_Searcher.Get())
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Component_Type", "RAM");
try
{
Model = MO2["Model"].ToString();
if (Model != null)
{
cmd.Parameters.AddWithValue("#Model", Model);
}
else { }
}
catch (NullReferenceException) { }
try
{
Capacity = MO2["Capacity"].ToString();
if (Capacity != null)
{
cmd.Parameters.AddWithValue("#Capacity", Capacity);
}
else { }
}
catch (NullReferenceException)
{ }
try
{
Serial = MO2["SerialNumber"].ToString();
if (Serial != null)
{
cmd.Parameters.AddWithValue("#SerialNumber", Serial);
}
else { }
}
catch (NullReferenceException)
{
}
try
{
Manufacturer = MO2["Manufacturer"].ToString();
if (Manufacturer != null)
{
cmd.Parameters.AddWithValue("#Manufacturer", Manufacturer);
}
else { }
}
catch (NullReferenceException)
{
}
// Console.WriteLine("Serial Number Bank" + count + ": " + s);
try
{
s = MO2["MemoryType"].ToString();
if (s.Equals("21"))
{
s = "DDr2";
cmd.Parameters.AddWithValue("#Memory_Type", s);
}
else if (s.Equals("20"))
{
s = "DDr";
cmd.Parameters.AddWithValue("#Memory_Type", s);
}
else if (s.Equals("17"))
{
s = "SDRAM";
cmd.Parameters.AddWithValue("#Memory_Type", s);
}
}
catch (NullReferenceException) { }
cmd.Parameters.AddWithValue("#Computer_Name", myHost);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
//SEE http://licensetoolkit.com/blog/hardware-identification-using-ram/
//using System.Management;
public static void OutputRamInformation()
{
// Create our WMI searcher to do our query
ManagementObjectSearcher searcher = new
ManagementObjectSearcher( "select * from Win32_PhysicalMemory" );
// Now loop through all the item found with the query
int ram = 1;
foreach ( ManagementObject obj in searcher.Get() )
{
Console.WriteLine( String.Format( "RAM #{0}:" , ram ) );
// Now step through each of the properties and output their values
foreach ( PropertyData property in obj.Properties )
{
if ( property.Value != null )
{
Console.WriteLine( property.Name + " = " +
property.Value.ToString() );
}
}
Console.WriteLine( "---------------------------------" );
// Increment our ram chip count
ram++;
}
// Wait for a keypress before continuting
Console.WriteLine( "Press any key to continue..." );
Console.ReadKey();
}