javascript to stop specific service - javascript

I have the following code in a script.
The problem is That I want to get information of scripts that starts in a specific name and are in a specific startmode.
var e = new Enumerator(GetObject("winmgmts:").InstancesOf("Win32_Service"))
var WSHShell = new ActiveXObject ("WScript.Shell");
var strPrefix = "TTTT";
for(;!e.atEnd(); e.moveNext()){
var Service = e.item();
var strName = Service.Name;
if (strName.substr (0, strPrefix.length) == strPrefix) {
if(Service.StartMode == 'mmManual') {
WScript.Echo("Yes");
}
if(e.StartMode == 'Manual') {
WScript.Echo("Yes");
}
}
}
In the above script I tried to know the start mode but it always return true.

McDowell is right, but note that you can get rid of prefix and start mode checks in your loop if you make them part of the WMI query:
SELECT * FROM Win32_Service WHERE Name LIKE 'TTTT%' AND StartMode = 'Manual'
Using this query, your script could look like this:
var strComputer = ".";
var oWMI = GetObject("winmgmts://" + strComputer + "/root/CIMV2");
var colServices = oWMI.ExecQuery("SELECT * FROM Win32_Service WHERE Name LIKE 'TTTT%' AND StartMode = 'Manual'");
var enumServices = new Enumerator(colServices);
for(; !enumServices.atEnd(); enumServices.moveNext())
{
var oService = enumServices.item();
WScript.Echo(oService.Name);
}

I'm not sure exactly what you're asking, but this...
if(Service.StartMode = 'mmManual')
...will always evaluate to true. You are missing an =. It should be:
if(Service.StartMode == 'mmManual')

Related

How to display HTML class of current node in JS

I have variables which:
display the result (result), and
reference the current node (thisNode).
What do I need to change in my code so that it would display the HTML class?
var thisNode = document.body.firstChild;
var result = document.getElementById("resultOfButton");
result.InnerHTML = thisNode.;
/* Here, in JS are there any ways like displaying the class name,
like nodeClass */
Please give recommendations for my code. There may be some errors. Thank you.
var thisNode = document.body.firstChild;
var result = document.getElementById("resultOfButton");
var block = false;
function buttonDown()
{
if(block == true)
{
thisNode = thisNode.parentElement.firstChild;
block = false;
}
thisNode = thisNode.nextSibling;
result.innerHTML = thisNode.nodeName;
if(thisNode == thisNode.parentNode.lastChild)
{
block = true
}
}
function buttonUp()
{
// not done now...
}
function buttonEnter()
{
thisNode = thisNode.firstChild;
result.innerHTML = thisNode.c;
}
function buttonBack()
{
// not done now...
}
I think you're asking for the className attribute. I copied your first sample and added some code so you can run it on this page. You'll get the second emoji replaced by the class name of the inserted element.
var thisNode = document.getElementById("thisNode"); // document.body.firstChild;
var result = document.getElementById("resultOfButton");
result.innerHTML = thisNode.className; /*Here, in JS are there any ways like displaying the class name, like nodeClass*/
<div id="thisNode" class="sample-class">🙂</div>
<div id="resultOfButton">🙃</div>
Quoting MDN:
"The className property of the Element interface gets and sets the value of the class attribute of the specified element."

Can't seem to move segment into repeating field

I have a piece of code that I'm trying to get to work on an interface. Basically we take some fields and drop into other segments. The problem seems to be that it leaves the data where it is instead of moving it to the indexed PID segment. Also the CP variable is returning 'undefined' for some reason.
var i = msg['PID']['PID.13'].length();
var homeNum;
var netNum;
var cpNum;
while(i--)
{
if (msg['PID']['PID.13'][i]['PID.13.2'].toString() == "PRN")
{
homeNum = msg['PID']['PID.13'][i]['PID.13.9'];
}
if (msg['PID']['PID.13'][i]['PID.13.2'].toString() == "NET")
{
netNum = msg['PID']['PID.13'][i]['PID.13.4'];
}
if (msg['PID']['PID.13'][i]['PID.13.2'].toString() == "CP")
{
cpNum = msg['PID']['PID.13'][i]['PID.13.9'];
}
msg['PID']['PID.13'][i] = "";
}
msg['PID']['PID.13'][0]['PID.13.1'] = homeNum;
msg['PID']['PID.13'][0]['PID.13.4'] = netNum;
msg['PID']['PID.13'][1]['PID.13.1'] = cpNum;
Sample HL7 msg I am using before transforms (from our test system, NOT live data)
It should resemble this instead:
|9999999999^^^test#test.com~99999999999~~~|
Any ideas/pointers on why it's not moving?
You are missing a toString() when you set the variables. A typical Mirth thing, because you get the E4X object back in the variable instead of the value you expected.
In addition to this, you should check the variables for undefined values before setting them on the new structure because otherwise you end up with "undefined" in the fields.
This is a working solution:
var i = msg['PID']['PID.13'].length();
var homeNum;
var netNum;
var cpNum;
while(i--)
{
if (msg['PID']['PID.13'][i]['PID.13.2'].toString() == "PRN")
{
homeNum = msg['PID']['PID.13'][i]['PID.13.9'].toString();
}
if (msg['PID']['PID.13'][i]['PID.13.2'].toString() == "NET")
{
netNum = msg['PID']['PID.13'][i]['PID.13.4'].toString();
}
if (msg['PID']['PID.13'][i]['PID.13.2'].toString() == "CP")
{
cpNum = msg['PID']['PID.13'][i]['PID.13.9'].toString();
}
msg['PID']['PID.13'][i] = "";
}
if(homeNum != null) msg['PID']['PID.13'][0]['PID.13.1'] = homeNum;
if(netNum != null) msg['PID']['PID.13'][0]['PID.13.4'] = netNum;
if(cpNum != null) msg['PID']['PID.13'][1]['PID.13.1'] = cpNum;

How to define "interface" in js

Good day.
My question is quite dumb, I guess, but I'm not familiar enough with the termins, to ask it properly (and to get an answer from Google).
So - please help...
Shortly - I'm trying to create some major class, which will be insanitated by instances, which will describe some methods, and some fields.
Major logick will be implemented in parent class.
So, lets say I have a parent
function CRUD_Grid_model(){
//Settings part
this.GridElement = "" ;
this.editModeFlagElement = "" ;
this.newRowElement = "";
//Save logicks all lies here.
this.commit = function (){
alert("PLEASE REDEFINE COMMIT FUNCTION IN YOUR CODE");
}
;
//Settings part
//Some more code.
}
And a way I'll use it
//Das modell
var JobberCRUD = new CRUD_Grid_model();
JobberCRUD.GridElement = $('#jobbers_dg');
JobberCRUD.editModeFlagElement = $('#jobbers_tb_edit');
JobberCRUD.newRowElement = {jobb_name:'Enter new unique name',jobb_status:'Y'};
JobberCRUD.commit = function (){
if (this.endEditing()){
var addrows = this.GridElement.datagrid('getChanges','inserted');
var remrows = this.GridElement.datagrid('getChanges','deleted');
var updrows = this.GridElement.datagrid('getChanges','updated');
console.log(addrows);
console.log(remrows);
console.log(updrows);
//Send changes?
alert("Got total of " +addrows.length + remrows.length + updrows.length + " rows changed.");
//Commit changes at local level
this.GridElement.datagrid('acceptChanges');
}
};
And, what I'd like to do, is smoething like this
I want a parent.commit function to allow me to do this in child
JobberCRUD.commit = function (apdrows,updrows,remrows){
//Send changes?
alert("Got total of " +addrows.length + remrows.length + updrows.length + " rows changed.");
};
So, I have no ideas what shoudl I do to achieve that. Please advice me with some tags, what it is at least :)
Thanks in advance.
There is not exactly what you need in JavaScript, but I would tend to use this pattern :
function CRUD_Grid_model() {
...
this.onCommit = null;
this.commit = function (){
if (this.endEditing()){
var addrows = this.GridElement.datagrid('getChanges','inserted');
var remrows = this.GridElement.datagrid('getChanges','deleted');
var updrows = this.GridElement.datagrid('getChanges','updated');
if(this.onCommit != null) this.onCommit(addrows,updrows,remrows);
this.GridElement.datagrid('acceptChanges');
}
}
...
}
var JobberCRUD = new CRUD_Grid_model();
JobberCRUD.onCommit = function(apdrows,updrows,remrows) {
alert("Got total of " +addrows.length + remrows.length + updrows.length + " rows changed.");
};
JobberCRUD.GridElement = ...
Javascript doesn't have a built in notion of interfaces. A javascript object effectively "implements an interface" by having all the needed methods defined, but there's no language "interface" construct
You could use "extends" like so:
Object.prototype.extends = function(clazz) {
var o = new clazz();
for (var f in o) {
if(f === "extends") {
continue;
}
this[f] = o[f];
}
this.super = o;
}
Now could type something like this:
var JobberCRUD = function() {
this.extends(CRUD_Grid_model);
var privateFunction = function() {
//...
}
// You probably don't want to do that,
// but you could override
this.commit = function() {
//...
}
// ...
}
Hope, that helps.
Edit: forgot, that you may call super.commit() then.
You can not have something similar like C# or Java interface or even class with Javascript.
Javascript is just a dynamic scripting language.

Cannot Find Function Contains in Object

I'm getting the following error when I call the code listed below it.
Cannot find function contains in object Is Patient Fasting?/# of Hours->Yes; 12 hours.
My code:
var i = 0;
var tempFastingQuest = "";
var tempFastingAns = msg['OBR']['OBR.39'].toString();
while (msg['NTE'][i] != null) {
tempFastingQuest = msg['NTE'][i]['NTE.3']['NTE.3.1'].toString();
if (tempFastingQuest.contains("Yes"))
tempFastingAns = "Y";
i = i + 1
}
What am I missing here?
Assuming this is JavaScript: Strings don't have a contains() method, which the error clearly states. Maybe you are looking for the search() method: if (tempFastingQuest.search('Yes') > -1) ...

Is there a way to manipulate included JS without eval()?

I know lots of people think "eval is evil," but I have to accomplish something and I'm having trouble figuring out how to do it without eval().
The situation is this: an external file (I have no control over it--EDIT: but it's not user-generated. It's from a trusted source! I imagine this is important) is spitting out JavaScript for me to use. This JavaScript contains some nice JSON data (which is what I need to get), but it's flanked by ordinary JavaScript statements declaring variables and calling functions and such. It looks kinda like this:
var foo = new Object();
foo['KEY'] = {Field1: 'Value1', Field2: 'Value2'};
eval('fooFunction(foo)');
If I eval() this, I can just parse foo['KEY'] and be done with it. The only way I can think to do this without eval() is with a bunch of annoying replace()ments, which hardly seems better. Am I missing some obvious way to do this? Most of the "you don't have to use eval()" alternatives I usually see assume I have complete control over everything, but in this case I have to work around this existing code.
EDIT: I should add that this code is being obtained via an AJAX call from a proxy script (cross-domain stuff), so none of the variables are accessible. If they were, I'd obviously just be able to parse foo['KEY'] and be on my merry.
SECOND EDIT: nothing conclusive yet! I'm getting dangerously close to concluding that eval() is the way to go. Can you stomach this outcome? I'm about to give in to evil(). Somebody stop me, because it's looking like the only way.
The external code better send back valid JSON. The value in your example is not valid JSON, as the keys must be wrapped with double quote.
I came up with small pure JavaScript parser, that can handle simple invalid JSON by adding double quotes by itself. It currently won't support non string values.
function ParseRawJSON(rawCode) {
var arrCandidates = [];
var lastOpenBracketIndex = -1;
for (var i = 0; i < rawCode.length; i++) {
var curChar = rawCode.charAt(i);
if (curChar === "}") {
if (lastOpenBracketIndex >= 0) {
arrCandidates.push(rawCode.substr(lastOpenBracketIndex, i - lastOpenBracketIndex + 1));
lastOpenBracketIndex = -1;
}
} else if (curChar === "{") {
lastOpenBracketIndex = i;
}
}
var arrJsonObjects = [];
for (var i = 0; i < arrCandidates.length; i++) {
var currentJSON = null;
try {
currentJSON = JSON.parse(arrCandidates[i]);
} catch (e) {
//try fixing
var fixedCandidate = TryFixJSON(arrCandidates[i]);
if (fixedCandidate) {
try {
currentJSON = JSON.parse(fixedCandidate);
} catch (e) {
currentJSON = null;
}
}
}
if (currentJSON != null) {
var keys = [];
for (var key in currentJSON)
keys.push(key);
if (keys.length > 0)
arrJsonObjects.push(currentJSON);
}
}
return arrJsonObjects;
function Trim(s, c) {
if (c instanceof Array) {
for (var i = 0; i < c.length; i++)
s = Trim(s, c[i]);
return s;
}
if (typeof c === "undefined")
c = " ";
while (s.length > 0 && s.charAt(0) === c)
s = s.substr(1, s.length - 1);
while (s.length > 0 && s.charAt(s.length - 1) === c)
s = s.substr(0, s.length - 1);
return s;
}
function TryFixJSON(strBlock) {
if (strBlock.indexOf(":") <= 0)
return false;
strBlock = strBlock.replace("{", "").replace("}", "");
var mainParts = strBlock.split(",");
for (var i = 0; i < mainParts.length; i++) {
var currentPart = Trim(mainParts[i]);
if (currentPart.indexOf(":") <= 0)
return false;
var subParts = currentPart.split(":");
if (subParts.length !== 2)
return false;
var currentKey = Trim(subParts[0], [" ", "'", "\""]);
var currentValue = Trim(subParts[1], [" ", "'", "\""]);
if (currentKey.length === 0)
return false;
subParts[0] = "\"" + currentKey + "\"";
subParts[1] = "\"" + currentValue + "\"";
mainParts[i] = subParts.join(":");
}
return "{" + mainParts.join(", ") + "}";
}
}
This will just look for anything between { and } and try to parse as JSON. No eval, in case of failure it'll just ignore the invalid block. Success? Great, it will return plain array of the valid JSON's it found.
Usage example:
var rawCode = "var foo = new Object(); { dummy here }}} function boo() {}" +
"foo['KEY'] = { \"Field1\": \"Value1\", \"Field2\": \"Value2\"}; hello {\"foo\": \"bar\"} and it's over ";
var jsonObjects = ParseRawJSON(rawCode);
for (var i = 0; i < jsonObjects.length; i++) {
for (var key in jsonObjects[i]) {
var value = jsonObjects[i][key];
//got key and value...
}
}
Live test case, using fixed version of your sample code.
A generally safer alternative to using eval is creating a new Function and passing it the string function body. That way (unless something is explicitly acessing the window object) you won't have access to the global scope and can keep it encapsulated in the function scope.
Let's say the first two lines of your example code are the JavaScript that you'd like to evaluate, if you know the name of the variable you want to retrieve as a JSON object you can just return it at the end of the created function and then call it:
var js = "var foo = {}; foo['KEY'] = {Field1: 'Value1', Field2: 'Value2'};";
var fn = new Function(js + ';return foo;');
var result = fn();
console.log(JSON.stringify(result));
This is also what MDN suggests doing in the documentation for eval:
More importantly, third party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways of which the similar Function is not susceptible.
If the JSON contains just data and not functions you can use JSON.parse()
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse for more detailed info.
As the method has been placed in to the global, then you can do
window["fooFunction"](foo)

Categories

Resources