How to Evaluate JavaScript code from .NetCore - asp.net-core

I need to evaluate Javascript code from .netcore 2.1 project
string vRule = "var input = arguments[0]; if (!input) return \"\"; if(input.length != 7) return \"a fixed string length of 7 is required\"; else return \"\"";
string spResponse = "sdfsd23";
string errorText =
_jscriptEval.EvalToString(new List<object>
{
"var args = new Array('" + spResponse +
"');\r\n validateRule(args);\r\n function validateRule(arguments){" + vRule +
"}\r\n"
});

You can use Jint. Jint implements the ECMA 5.1 spec and can be use from any .NET implementation (Xamarin, .NET Framework, .NET Core). Just use the NuGet package and has no dependencies to other stuff - it’s a single .dll and you are done!
Just transform your javascript code into a function and run it like this (this is just an example, not your implementation):
var engine = new Engine()
.Execute("function MyFunction(a, b) { return a + b; }")
;
engine.Invoke("MyFunction", 1, 2); // -> 3
You have more explanations and examples on https://github.com/sebastienros/jint

Related

ASP.Net OnGet - URL encoded Parameters - Only some parameters are Decoded by ASP.Net Framework

Ola,
for some reason, it looks like ASP.Net Core Webserver (.Net 6) seems to url-decode some characters for the PageModel.OnGet Method and some characters are not url-decoded.
The request according URL in Internet Edge in the addressbar:
http://localhost:5000/ItemsOverview/Data/dm%3A%2F%2F%2Fxxx.ebs.data%3Fmetaclass%3Ddm%253A%252F%252F%252Fxxx.ebs%25232d73a22b-8505-4523-939d-7f524253f95b
This is what is sent to the OnGet Method:
ItemsOverview.cshtml: #page "/ItemsOverview/{workspace}/{extent}/{item?}"
ItemsOverview.cshtml.cs:
public void OnGet(string workspace, string extent, string? item)
{
Workspace = HttpUtility.UrlDecode(workspace);
Extent = HttpUtility.UrlDecode(extent);
Item = HttpUtility.UrlDecode(item);
}
The variable 'extent' as received by the debugger looks like the following:
dm:%2F%2F%2Fxxx.ebs.data?metaclass=dm%3A%2F%2F%2Fxxx.ebs%232d73a22b-8505-4523-939d-7f524253f95b
==> So, the server has changed %3F to '=' and %25 to '%', but not characters like %2F...
The url is generated by using the javascript function 'encodeURIComponent':
export function getLinkForNavigateToExtentItems(workspace: string, extentUri: string, parameter?: NavigationToExtentItemsParameter) {
let urlParameter = "";
let ampersand = '?';
if (parameter?.metaClass !== undefined) {
urlParameter += ampersand + "metaclass=" + encodeURIComponent(parameter.metaClass);
ampersand = '&';
}
return Settings.baseUrl + "ItemsOverview/" +
encodeURIComponent(workspace) + "/" +
encodeURIComponent(extentUri + urlParameter);
}
Expectation:
The OnGet Call is called with the parameter 'extent' is given in the Url by Browser.
Situation:
Some characters are already decoded by Browser(?) or ASP.Net Core Framework(?)
Resolved by:
public static string? DecodePath(string? pathToBeDecoded)
{
return pathToBeDecoded?
.Replace("%2F", "/")
.Replace("%2f", "/")
.Replace("%25", "#");;
}
I'm not convinced, but it seems to work.

SSRS Report executes directly but WCF ReportExporter.Export method returns null Result and no errors

I have a report that is hosted in SQL Server 2012 SSRS and it executes fine through the browser. I am trying to run it using WCF as a Service Reference for the SSRS 2005 asmx from a ASP.Net web project and return it as a PDF using the ReportExporter.Export() method; however, it is not returning a result at all and the warnings array is empty. So, how can I troubleshoot the process to see where the difficulty is? I did not find any errors in the SSRS Log file even when I set it to verbose; nor did I find any errors in the standard SQL Log.
Here is my code:
NOTE: the call ReportExporter.Export(..) is to a method that encapsulates the execution of the webServiceProxy to the Service Reference.
{
IList<SSRS_Reports.ParameterValue> parameters = new List<SSRS_Reports.ParameterValue>();
parameters.Add(new SSRS_Reports.ParameterValue { Name = "paramId", Value = _paramId.ToString() }); }
byte[] result = null;
string extension = string.Empty;
string mimeType = string.Empty;
string encoding = string.Empty;
string reportName = "/baseFolder/ReceiptReport";
SSRS_Reports.Warning[] warnings = null;
string[] streamIDs = null;
string uN = ConfigurationManager.AppSettings["rptUName"].ToString();
string uP = ConfigurationManager.AppSettings["rptPWD"].ToString();
string uD = ConfigurationManager.AppSettings["rptDomain"].ToString();
//NOTE: the call "ReportExporter.Export(..) is to a method that encapsulates the execution of the webServiceProxy to the Service Reference.
ReportExporter.Export("ReportExecutionServiceSoap",
new System.Net.NetworkCredential(uN, uP, uD),
reportName,
parameters.ToArray(),
ExportFormat.PDF,
out result,
out extension,
out mimeType,
out encoding,
out warnings,
out streamIDs);
if (result != null)
{
//create a file and then show in browser
_mPDFFile = randomName() + ".pdf";
_mPDFPath = HttpRuntime.AppDomainAppPath + "\\pdf\\" + _mPDFFile;
//clear files older than today
Lib.FileManager.ManageFiles(HttpRuntime.AppDomainAppPath + "\\pdf", "*.pdf", -1);
if (File.Exists(_mPDFPath))
{
File.Delete(_mPDFPath);
}
FileStream stream = File.Create(_mPDFPath, result.Length);
stream.Write(result, 0, result.Length);
stream.Close();
return true;
}
}

Efficient Way to do batch import XMI in Enterprise Architect

Our team are using Enterprise Architect version 10 and SVN for the repository.
Because the EAP file size is quite big (e.g. 80 MB), we exports each packages into separate XMI and stored it into SVN. The EAP file itself is committed after some milestone. The problem is to synchronize the EAP file with work from co worker during development, we need to import lots of XMI (e.g. total can be 500 files).
I know that once the EAP file is updated, we can use Package Control -> Get All Latest. Therefore this problem occurs only during parallel development.
We have used keyboard shorcuts to do the import as follow:
Ctrl+Alt+I (Import package from XMI file)
Select the file name to import
Alt+I (Import)
Enter (Yes)
Repeat step number 2 to 4 until module finished
But still, importing hundreds of file is inefficient.
I've checked that the Control Package has Batch Import/Export. The batch import/export are working when I explicitly hard-coded the XMI Filename, but the options are not available if using version control (batch import/export options are greyed).
Is there any better ways to synchronize EAP and XMI files?
There is a scripting interface in EA. You might be able to automate the import using that. I've not used it but its probably quite good.
I'm not sure I fully understand your working environment, but I have some general points that may be of interest. It might be that if you use EA in a different way (especially my first point below), the need to batch import might go away.
Multiworker
First, multiple people can work on the same EAP file at a time. The EAP file is nothing more than an Access database file, and EA uses locking to stop multiple people editing the same package at the same time. But you can comfortably have multiple people editing different packages in one EAP file at the same time. Putting the EAP file on a file share somewhere is a good way of doing it.
Inbuilt Revision Control
Secondly, EA can interact directly with SVN (and other revision control systems). See this. In short, you can setup your EAP file so that individual packages (and everything below them) is SVN controlled. You can then check out an individual package, edit it, check it back in. Or indeed you can check out the whole branch below a package (including sub packages that are themselves SVN controlled).
Underneath the hood EA is importing and exporting XMI files and checking them in and out of SVN, whilst the EAP file is always the head revision. Just like what you're doing by hand, but automated. It makes sense given that you can all use the one single EAP file. You do have to be a bit careful rolling back - links originating from objects in older versions of one package might be pointing at objects that no longer exist (but you can look at the import log errors to see if this is the case). It takes a bit of getting used to, but it works pretty well.
There's also the built in package baselining functionality - that might be all you need anyway, and works quite well especially if you're all using the same EAP file.
Bigger Database Engine
Thirdly, you don't have to have an EAP file at all. The model's database can be in any suitable database system (MySQL, SQL Server, Oracle, etc). So that gives you all sorts of options for scaling up how its used, what its like over a WAN/Internet, etc.
In short Sparx have been quite sensible about how EA can be used in a multi-worker environment, and its worth exploiting that.
I have created the EA script using JScript for the automation
Here is the script to do the export:
!INC Local Scripts.EAConstants-JScript
/*
* Script Name : Export List of SVN Packages
* Author : SDK
* Purpose : Export a package and all of its subpackages information related to version
* controlled. The exported file then can be used to automatically import
* the XMIs
* Date : 30 July 2013
* HOW TO USE : 1. Select the package that you would like to export in the Project Browser
* 2. Change the output filepath in this script if necessary.
* By default it is "D:\\EAOutput.txt"
* 3. Send the output file to your colleague who wanted to import the XMIs
*/
var f;
function main()
{
// UPDATE THE FOLLOWING OUTPUT FILE PATH IF NECESSARY
var filename = "D:\\EAOutput.txt";
var ForReading = 1, ForWriting = 2, ForAppending = 8;
Repository.EnsureOutputVisible( "Script" );
Repository.ClearOutput( "Script" );
Session.Output("Start generating output...please wait...");
var treeSelectedType = Repository.GetTreeSelectedItemType();
switch ( treeSelectedType )
{
case otPackage:
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.OpenTextFile(filename, ForWriting, true);
var selectedObject as EA.Package;
selectedObject = Repository.GetContextObject();
reportPackage(selectedObject);
loopChildPackages(selectedObject);
f.Close();
Session.Output( "Done! Check your output at " + filename);
break;
}
default:
{
Session.Prompt( "This script does not support items of this type.", promptOK );
}
}
}
function loopChildPackages(thePackage)
{
for (var j = 0 ; j < thePackage.Packages.Count; j++)
{
var child as EA.Package;
child = thePackage.Packages.GetAt(j);
reportPackage(child);
loopChildPackages(child);
}
}
function getParentPath(childPackage)
{
if (childPackage.ParentID != 0)
{
var parentPackage as EA.Package;
parentPackage = Repository.GetPackageByID(childPackage.ParentID);
return getParentPath(parentPackage) + "/" + parentPackage.Name;
}
return "";
}
function reportPackage(thePackage)
{
f.WriteLine("GUID=" + thePackage.PackageGUID + ";"
+ "NAME=" + thePackage.Name + ";"
+ "VCCFG=" + getVCCFG(thePackage) + ";"
+ "XML=" + thePackage.XMLPath + ";"
+ "PARENT=" + getParentPath(thePackage).substring(1) + ";"
);
}
function getVCCFG(thePackage)
{
if (thePackage.IsVersionControlled)
{
var array = new Array();
array = (thePackage.Flags).split(";");
for (var z = 0 ; z < array.length; z++)
{
var pos = array[z].indexOf('=');
if (pos > 0)
{
var key = array[z].substring(0, pos);
var value = array[z].substring(pos + 1);
if (key=="VCCFG")
{
return (value);
}
}
}
}
return "";
}
main();
And the script to do the import:
!INC Local Scripts.EAConstants-JScript
/*
* Script Name : Import List Of SVN Packages
* Author : SDK
* Purpose : Imports a package with all of its sub packages generated from
* "Export List Of SVN Packages" script
* Date : 01 Aug 2013
* HOW TO USE : 1. Get the output file generated by "Export List Of SVN Packages" script
* from your colleague
* 2. Get the XMIs in the SVN local copy
* 3. Change the path to the output file in this script if necessary (var filename).
* By default it is "D:\\EAOutput.txt"
* 4. Change the path to local SVN
* 5. Run the script
*/
var f;
var svnPath;
function main()
{
// CHANGE THE FOLLOWING TWO LINES ACCORDING TO YOUR INPUT AND LOCAL SVN COPY
var filename = "D:\\EAOutput.txt";
svnPath = "D:\\svn.xxx.com\\yyy\\docs\\design\\";
var ForReading = 1, ForWriting = 2, ForAppending = 8;
Repository.EnsureOutputVisible( "Script" );
Repository.ClearOutput( "Script" );
Session.Output("[INFO] Start importing packages from " + filename + ". Please wait...");
var fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.OpenTextFile(filename, ForReading);
// Read from the file and display the results.
while (!f.AtEndOfStream)
{
var r = f.ReadLine();
parseLine(r);
Session.Output("--------------------------------------------------------------------------------");
}
f.Close();
Session.Output("[INFO] Finished");
}
function parseLine(line)
{
Session.Output("[INFO] Parsing " + line);
var array = new Array();
array = (line).split(";");
var guid;
var name;
var isVersionControlled;
var xmlPath;
var parentPath;
isVersionControlled = false;
xmlPath = "";
for (var z = 0 ; z < array.length; z++)
{
var pos = array[z].indexOf('=');
if (pos > 0)
{
var key = array[z].substring(0, pos);
var value = array[z].substring(pos + 1);
if (key=="GUID") {
guid = value;
} else if (key=="NAME") {
name = value;
} else if (key=="VCCFG") {
if (value != "") {
isVersionControlled = true;
}
} else if (key=="XML") {
if (isVersionControlled) {
xmlPath = value;
}
} else if (key=="PARENT") {
parentPath = value;
}
}
}
// Quick check for target if already exist to speed up process
var targetPackage as EA.Package;
targetPackage = Repository.GetPackageByGuid(guid);
if (targetPackage != null)
{
// target exists, do not do anything
Session.Output("[DEBUG] Target package \"" + name + "\" already exist");
return;
}
var paths = new Array();
var packages = new Array(paths.Count);
for (var i = 0; i < paths.Count; i++)
{
packages[i] = null;
}
paths = (parentPath).split("/");
if (paths.Count < 2)
{
Session.Output("[INFO] Skipped root or level1");
return;
}
packages[0] = selectRoot(paths[0]);
packages[1] = selectPackage(packages[0], paths[1]);
if (packages[1] == null)
{
Session.Output("[ERROR] Cannot find " + paths[0] + "/" + paths[1] + "in Project Browser");
return;
}
for (var j = 2; j < paths.length; j++)
{
packages[j] = selectPackage(packages[j - 1], paths[j]);
if (packages[j] == null)
{
Session.Output("[DEBUG] Creating " + packages[j].Name);
// create the parent package
var parent as EA.Package;
parent = Repository.GetPackageByGuid(packages[j-1].PackageGUID);
packages[j] = parent.Packages.AddNew(paths[j], "");
packages[j].Update();
parent.Update();
parent.Packages.Refresh();
break;
}
}
// Check if name (package to import) already exist or not
var targetPackage = selectPackage(packages[paths.length - 1], name);
if (targetPackage == null)
{
if (xmlPath == "")
{
Session.Output("[DEBUG] Creating " + name);
// The package is not SVN controlled
var newPackage as EA.Package;
newPackage = packages[paths.length - 1].Packages.AddNew(name,"");
Session.Output("New GUID = " + newPackage.PackageGUID);
newPackage.Update();
packages[paths.length - 1].Update();
packages[paths.length - 1].Packages.Refresh();
}
else
{
// The package is not SVN controlled
Session.Output("[DEBUG] Need to import: " + svnPath + xmlPath);
var project as EA.Project;
project = Repository.GetProjectInterface;
var result;
Session.Output("GUID = " + packages[paths.length - 1].PackageGUID);
Session.Output("GUID XML = " + project.GUIDtoXML(packages[paths.length - 1].PackageGUID));
Session.Output("XMI file = " + svnPath + xmlPath);
result = project.ImportPackageXMI(project.GUIDtoXML(packages[paths.length - 1].PackageGUID), svnPath + xmlPath, 1, 0);
Session.Output(result);
packages[paths.length - 1].Update();
packages[paths.length - 1].Packages.Refresh();
}
}
else
{
// target exists, do not do anything
Session.Output("[DEBUG] Target package \"" + name + "\" already exist");
}
}
function selectPackage(thePackage, childName)
{
var childPackage as EA.Package;
childPackage = null;
if (thePackage == null)
return null;
for (var i = 0; i < thePackage.Packages.Count; i++)
{
childPackage = thePackage.Packages.GetAt(i);
if (childPackage.Name == childName)
{
Session.Output("[DEBUG] Found " + childName);
return childPackage;
}
}
Session.Output("[DEBUG] Cannot find " + childName);
return null;
}
function selectRoot(rootName)
{
for (var y = 0; y < Repository.Models.Count; y++)
{
root = Repository.Models.GetAt(y);
if (root.Name == rootName)
{
return root;
}
}
return null;
}
main();

eclipse JDT setting the project

I am a beginner to Eclipse JDT. I was going through some tutorial and found one good example for creating the java file. In this below example in which project they will create the package and java file. I could not see any code pointing to any of the project name. Please make me understand if I am wrong. I just run the below example. I could not see any output..
AST ast = AST.newAST(AST.JLS3);
CompilationUnit unit = ast.newCompilationUnit();
PackageDeclaration packageDeclaration = ast.newPackageDeclaration();
packageDeclaration.setName(ast.newSimpleName("example"));
unit.setPackage(packageDeclaration);
ImportDeclaration importDeclaration = ast.newImportDeclaration();
QualifiedName name =
ast.newQualifiedName(
ast.newSimpleName("java"),
ast.newSimpleName("util"));
importDeclaration.setName(name);
importDeclaration.setOnDemand(true);
unit.imports().add(importDeclaration);
TypeDeclaration type = ast.newTypeDeclaration();
type.setInterface(false);
type.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
type.setName(ast.newSimpleName("HelloWorld"));
MethodDeclaration methodDeclaration = ast.newMethodDeclaration();
methodDeclaration.setConstructor(false);
List modifiers = methodDeclaration.modifiers();
modifiers.add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
modifiers.add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));
methodDeclaration.setName(ast.newSimpleName("main"));
methodDeclaration.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
SingleVariableDeclaration variableDeclaration = ast.newSingleVariableDeclaration();
variableDeclaration.setType(ast.newArrayType(ast.newSimpleType(ast.newSimpleName("String"))));
variableDeclaration.setName(ast.newSimpleName("args"));
methodDeclaration.parameters().add(variableDeclaration);
org.eclipse.jdt.core.dom.Block block = ast.newBlock();
MethodInvocation methodInvocation = ast.newMethodInvocation();
name =
ast.newQualifiedName(
ast.newSimpleName("System"),
ast.newSimpleName("out"));
methodInvocation.setExpression(name);
methodInvocation.setName(ast.newSimpleName("println"));
InfixExpression infixExpression = ast.newInfixExpression();
infixExpression.setOperator(InfixExpression.Operator.PLUS);
StringLiteral literal = ast.newStringLiteral();
literal.setLiteralValue("Hello");
infixExpression.setLeftOperand(literal);
literal = ast.newStringLiteral();
literal.setLiteralValue(" world");
infixExpression.setRightOperand(literal);
methodInvocation.arguments().add(infixExpression);
ExpressionStatement expressionStatement = ast.newExpressionStatement(methodInvocation);
block.statements().add(expressionStatement);
methodDeclaration.setBody(block);
type.bodyDeclarations().add(methodDeclaration);
unit.types().add(type);
You may take a look at this. It uses Java Model, which means you will need to create a plug-in to make it work.
// create a project with name "TESTJDT"
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject("TESTJDT");
project.create(null);
project.open(null);
//set the Java nature
IProjectDescription description = project.getDescription();
description.setNatureIds(new String[] { JavaCore.NATURE_ID });
//create the project
project.setDescription(description, null);
IJavaProject javaProject = JavaCore.create(project);
//set the build path
IClasspathEntry[] buildPath = {
JavaCore.newSourceEntry(project.getFullPath().append("src")),
JavaRuntime.getDefaultJREContainerEntry() };
javaProject.setRawClasspath(buildPath, project.getFullPath().append(
"bin"), null);
//create folder by using resources package
IFolder folder = project.getFolder("src");
folder.create(true, true, null);
//Add folder to Java element
IPackageFragmentRoot srcFolder = javaProject
.getPackageFragmentRoot(folder);
//create package fragment
IPackageFragment fragment = srcFolder.createPackageFragment(
"com.programcreek", true, null);
//init code string and create compilation unit
String str = "package com.programcreek;" + "\n"
+ "public class Test {" + "\n" + " private String name;"
+ "\n" + "}";
ICompilationUnit cu = fragment.createCompilationUnit("Test.java", str,
false, null);
//create a field
IType type = cu.getType("Test");
type.createField("private String age;", null, true, null);

How I can use Shell32.dll in Silverlight OOB

I'd like to get the target information from a shortcut file using my silverlight OOB app, so I'm going to make the following code to work in my silverlight OOB. It seems I have to used P/Invoke to use Shell32.dll, but I'm not sure how I can use Folder, FolderItem, and ShellLinkObject? Most references explain how I can use the functions in the .dll using P/invoke:( Please give me any comments or sample code/links:)
public string GetShortcutTargetFile(string shortcutFilename)
{
string pathOnly = Path.GetDirectoryName(shortcutFilename);
string filenameOnly = Path.GetFileName(shortcutFilename);
Shell32.Shell shell = new Shell32.ShellClass();
Shell32.Folder folder = shell.NameSpace(pathOnly);
Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
MessageBox.Show(link.Path);
return link.Path;
}
return String.Empty; // Not found
}
I found a solution.
public string GetShortcutTargetFile(string shortcutFilename)
{
string pathOnly = System.IO.Path.GetDirectoryName(shortcutFile);
string filenameOnly = System.IO.Path.GetFileName(shortcutFile);
dynamic shell = AutomationFactory.CreateObject("Shell.Application");
dynamic folder = shell.NameSpace(pathOnly);
dynamic folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
dynamic link = folderItem.GetLink;
return "\""+link.Path +"\"" + " " + link.Arguments;
}
return String.Empty; // Not found
}