I am working on a project which starts with a GUI Wizard to get some info from the user such as EndPoint FQDN, Username, Password, etc..
Once the User has provided all required info and reach to the final page in the GUI, a start button will be ready for him to click. Once this Start button is clicked, the tool will call 32 different scripts that are located into separate files.
To make the GUI more responsive and overcome the hanging issues as well as adding multithreading and better performance, I am using Runspace and RunspcaePools. So the GUI itself is running in a Runspace and once the user clicks on start a RunspacePool will be created and for each script form the 32 scripts there would be a Powershell session created and invoked.
The GUI is working fine and everything is working as expected untill the start button. My issue is that I am not able to call those script files when I am adding the script to the PowerShell Session. it is just nothing happen. If I use Wait-Debugger, I do not see any errors it is as if the ScriptBlock I am passing to the Powershell session (that has the value of the path to the script I want to execute) is just a sting and not a ScriptBlock.
My Code is as follow:
# This Section will add all the required Subscript Files into variables to be called by the main code of the tool.
$SubScriptFolderPath = $CurrentWorkingDirectory + "SubCode\Scripts\"
$SubscriptFilePath = #{}
$SubscriptFilePath.BasicVspherePowerCliData = $SubScriptFolderPath + "BasicVspherePowerCliData.ps1"
$SubscriptFilePath.NsxManagerPowerCliData = $SubScriptFolderPath + "NsxManagerPowerCliData.ps1"
$SubscriptFilePath.NsxManagerPowerNsxData = $SubScriptFolderPath + "NsxManagerPowerNsxData.ps1"
$SubscriptFilePath.NsxManagerNsxCliData = $SubScriptFolderPath + "NsxManagerNsxCliData.ps1"
$SubscriptFilePath.ControllerPowerCliData = $SubScriptFolderPath + "ControllerPowerCliData.ps1"
$SubscriptFilePath.ControllerPowerNsxData = $SubScriptFolderPath + "ControllerPowerNsxData.ps1"
$SubscriptFilePath.ControllerNsxCliData = $SubScriptFolderPath + "ControllerNsxCliData.ps1"
$SubscriptFilePath.ControllerSshData = $SubScriptFolderPath + "ControllerSshData.ps1"
$SubscriptFilePath.ClusterPowerCliData = $SubScriptFolderPath + "ClusterPowerCliData.ps1"
$SubscriptFilePath.ClusterPowerNsxData = $SubScriptFolderPath + "ClusterPowerNsxData.ps1"
$SubscriptFilePath.ClusterNsxApiData = $SubScriptFolderPath + "ClusterNsxApiData.ps1"
$SubscriptFilePath.HostPowerCliData = $SubScriptFolderPath + "HostPowerCliData.ps1"
$SubscriptFilePath.HostPowerNsxData = $SubScriptFolderPath + "HostPowerNsxData.ps1"
$SubscriptFilePath.HostEsxCliData = $SubScriptFolderPath + "HostEsxCliData.ps1"
$SubscriptFilePath.HostNsxCliData = $SubScriptFolderPath + "HostNsxCliData.ps1"
$SubscriptFilePath.DvsPowerCliData = $SubScriptFolderPath + "DvsPowerCliData.ps1"
$SubscriptFilePath.DvsPowerNsxData = $SubScriptFolderPath + "DvsPowerNsxData.ps1"
$SubscriptFilePath.LogicalSwitchPowerCliData = $SubScriptFolderPath + "LogicalSwitchPowerCliData.ps1"
$SubscriptFilePath.LogicalSwitchPowerNsxData = $SubScriptFolderPath + "LogicalSwitchPowerNsxData.ps1"
$SubscriptFilePath.TransportZonePowerCliData = $SubScriptFolderPath + "TransportZonePowerCliData.ps1"
$SubscriptFilePath.TransportZonePowerNsxData = $SubScriptFolderPath + "TransportZonePowerNsxData.ps1"
$SubscriptFilePath.DlrPowerCliData = $SubScriptFolderPath + "DlrPowerCliData.ps1"
$SubscriptFilePath.DlrPowerNsxData = $SubScriptFolderPath + "DlrPowerNsxData.ps1"
$SubscriptFilePath.DlrNsxCliData = $SubScriptFolderPath + "DlrNsxCliData.ps1"
$SubscriptFilePath.EsgPowerCliData = $SubScriptFolderPath + "EsgPowerCliData.ps1"
$SubscriptFilePath.EsgPowerNsxData = $SubScriptFolderPath + "EsgPowerNsxData.ps1"
$SubscriptFilePath.EsgNsxCliData = $SubScriptFolderPath + "EsgNsxCliData.ps1"
$SubscriptFilePath.DfwPowerCliData = $SubScriptFolderPath + "DfwPowerCliData.ps1"
$SubscriptFilePath.DfwPowerNSXData = $SubScriptFolderPath + "DfwPowerNSXData.ps1"
$SubscriptFilePath.DumpEndPoints = $SubScriptFolderPath + "DumpEndPoints.ps1"
# Create Sync HashTable (GuiHash) to allow readability across different Runscpases and add required variables.
$Global:GuiHash = [hashtable]::Synchronized(#{ })
$Global:GuiHash.IPCehckPattern = $IPRegex # Add the IPCehckPattern Variable to be used within other runspaces
$Global:GuiHash.SubscriptFilePath = $SubscriptFilePath # Add the SubCodePaths Variable to be used within other runspaces
# Crate the Runspace that will be used for the GUI and configure settings. After, Open the Runspace and import variables.
# You must import variables that will be used in other Runspaces, thus importing the required variables to this Runspace.
$GuiRunspace =[runspacefactory]::CreateRunspace()
$GuiRunspace.ApartmentState = "STA"
$GuiRunspace.ThreadOptions = "ReuseThread"
$GuiRunspace.Open()
$GuiRunspace.SessionStateProxy.SetVariable("GuiHash",$Global:GuiHash)
$GuiRunspace.SessionStateProxy.SetVariable("XamlFilesArray",$XamlFilesArray)
# Create a PowerShell Session and add it to the Runspace.
$GuiPSSession = [PowerShell]::Create()
$GuiPSSession.Runspace = $GuiRunspace
# Create the GUI PowerShell Session ScriptBlock. This will be the main code of the tool.
[void]$GuiPSSession.AddScript({
[Some code that is taking care of GUI]
$GuiHash.WizardFinalPageStart.Add_Click({
# Create Session State Object and Add GuiHash Variable to it
$InitialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
$RunHash = New-object System.Management.Automation.Runspaces.SessionStateVariableEntry -ArgumentList 'RunHash',$Global:GuiHash,$Null
$InitialSessionState.Variables.Add($RunHash)
# Create Runspace Pool
$RunspacePool = [RunspaceFactory]::CreateRunspacePool(1, [int]$env:NUMBER_OF_PROCESSORS + 1, $InitialSessionState, $Host)
$RunspacePool.ApartmentState = "MTA"
$RunspacePool.Open()
ForEach ($ScriptBlock in $Global:GuiHash.SubscriptFilePath) {
$PowerShellSession = [PowerShell]::Create()
$PowerShellSession.RunspacePool = $RunspacePool
$PowerShellSession.AddScript({$ScriptBlock})
$PowerShellSession.BeginInvoke()
}
})
# Show Wizard Window.
$Global:GuiHash.WizardMainWindow.ShowDialog() | Out-Null
})
$ShowGui = $GuiPSSession.BeginInvoke()
I have tried many things such as:
Adding & to the beginning of the script path.
Adding . to the beginning of the script path.
Using Get-Content
Using the ScriptBlock System Object
$Scriptblock = [scriptblock]::Create((Get-Content $ScriptPath))
Nothing seems to work.
I would appreciate your help over this one.
Thanks
I think I did the same mistake again, Sorry this project is making my mind to hang sometimes. You need to remove the brackets when calling a script block. so you need to call the script block as below
$PowerShellSession.AddScript($ScriptBlock)
Related
For example , the connection string required by the ODBC connection is placed in the configuration file for easy maintenance.
connDict = dict(`ip`port`db`uid`pwd`driver, [`192.168.xxx.xxx, `xxxxx, `xxxx, `user, "passwd", `MySQL])
odbcconn = odbc::connect("Driver={" + connDict.driver + "};Server=" + connDict.ip + ";Port=" + connDict.port + ";Database=" + connDict.db + "; Uid=" + connDict.uid + ";Pwd=" + connDict.pwd + ";")
Execute the following script to convert the dictionary into JSON format data conforming to the DolphinDB specification and put it in a JSON file.
connDict = dict(`ip`port`db`uid`pwd`driver, [`192.168.xxx.xxx, `xxxxx, `xxxx, `user, "passwd", `MySQL])
toJson(connDict)
Custom functions, read JSON files and convert them into dictionaries.
def getMysqlConnDictFrom Json(filePath) {
f = file(filePath)
arr = f.readLines()
json = reduce(concat, trim(arr[arr != string(NULL)]))
return fromJson(json)
}
connDict = getMysqlConnDictFromJson("/data/software/dolphin/server/mysqlconn.json")
I have a question about running cmd from winform.
I have managed to connect and get information from the remote machine(infotrend disk server).
However I could not make a operation on the remote machine such "create disk part
below I have written these code....
InfotrendProcess.StartInfo.UseShellExecute = false;
InfotrendProcess.StartInfo.RedirectStandardInput = true;
InfotrendProcess.StartInfo.RedirectStandardOutput = true;
InfotrendProcess.StartInfo.RedirectStandardError = true;
InfotrendProcess.StartInfo.WorkingDirectory = workingPath;
InfotrendProcess.StartInfo.FileName = "C:\\Windows\\System32\\cmd.exe";
InfotrendProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
InfotrendProcess.StartInfo.CreateNoWindow = true;
const string quote = "\"";
cmd_message = "java -jar " + quote + "runCLI" + quote; (MANAGED TO START CLI RUN COMMAND STEP 1)
InfotrendProcess.StartInfo.Arguments = "/K " + cmd_message;
InfotrendProcess.OutputDataReceived += InfotrendProcess_OutputDataReceived1;
InfotrendProcess.ErrorDataReceived += InfotrendProcess_ErrorDataReceived;
InfotrendProcess.Start();
using (StreamWriter sw = InfotrendProcess.StandardInput) (MANAGED TO CONNECT AND SEND DELETE
PART COMMAND STEP 2)
{
sw.WriteLine("connect " + IPNumber);
Thread.Sleep(1000);
sw.WriteLine("del part 01D9F2C6614DF837"); (COULD NOT SEND RESPOND y/s, MAKES NEW LINE)
sw.WriteLine("y")
}
I could not send the "y/n" respond because I have to send it in the same line after a period. Instead it makes a new line. Should I use a different way? Could anyone help me, how I can run the final command.
I want to create scenario where i want use data from jar file into Jmeter Loop logic.
My jar looks like:
public String Australia()
{
String a = "{"
+ "\"location\": {"
+ "\"lat\": -33.8669710,"
+ "\"lng\": 151.1958750"
+ "},"
+ "\"accuracy\": 50,"
+ "\"name\": \"Google Shoes!\","
+ "\"phone_number\": \"(02) 9374 4000\","
+ "\"address\": \"48 Pirrama Road, Pyrmont, NSW 2009, Australia\","
+ "\"types\": [\"shoe_store\"],"
+ "\"website\": \"http://www.google.com.au/\","
+ "\"language\": \"en-AU\""
+
"}";
return a;
}
public String canada()
{
String c = "{"
+ "\"location\": {"
+ "\"lat\": -33.8669710,"
+ "\"lng\": 151.1958750"
+ "},"
+ "\"accuracy\": 50,"
+ "\"name\": \"Google Shoes!\","
+ "\"phone_number\": \"(02) 9374 4000\","
+ "\"address\": \"48 Pirrama Road, Pyrmont, NSW 2009, Canada\","
+ "\"types\": [\"shoe_store\"],"
+ "\"website\": \"http://www.google.com.ca/\","
+ "\"language\": \"en-CA\""
+
"}";
return c;
}
1) with above data i want to 'feed' Jmeter call as described on the bellow picture
2) every time i add new country at the jar file, loop be increased accordingly.
Some thought how this could be done, what should i use as variable and how i can tell the loop to increase?
Add JSR223 PreProcessor as a child of the 002_2_send payment request
Put the following code into "Script" area:
def testData = new com.example.TestData()
def methods = testData.class.getDeclaredMethods()
def payload = org.apache.commons.lang.reflect.MethodUtils.invokeExactMethod(testData, methods[vars.get('__jm__Loop Controller__idx') as int].getName())
sampler.addNonEncodedArgument('',payload,'')
sampler.setPostBodyRaw(true)
Define "Loop Count" in the Loop Controller using __groovy() function like:
${__groovy(com.example.TestData.getDeclaredMethods().size(),)}
Change com.example to your own package name and TestData to your class name
Once you drop the new version of .jar to JMeter Classpath you will need to restart JMeter to pick up the changes
That's it, each iteration of the Loop Controller the JSR223 PreProcessor will execute the next function in your class and update the request body with the returned data:
References:
Java Reflection API
Apache Groovy - Why and How You Should Use It
For my application on Openshift, I am trying to write a pre_build script that accesses the database. The goal is to have migration scripts between database versions that are executed when the code is deployed. The script would compare the current database version with the version needed by the application code and then run the correct script to migrate the database.
Now the problem is that apparently the pre_build script is executed on Jenkins and not on the destination cartridge and therefore the environment variables with the database connection arguments are not available.
This is the pre_build script that I've written so far:
#!/usr/bin/env python
print "*** Database migration script ***"
# get goal version
import os
homedir = os.environ["OPENSHIFT_HOMEDIR"]
migration_scripts_dir = homedir + "app-root/runtime/repo/.openshift/action_hooks/migration-scripts/"
f = open(migration_scripts_dir + "db-version.txt")
goal = int(f.read())
f.close()
print "I need database version " + str(goal)
# get database connection details
# TODO: find a solution of not hard coding the connection details here!!!
# Maybe by using jenkins environment variables like OPENSHIFT_APP_NAME and JOB_NAME
db_host = "..."
db_port = "..."
db_user = "..."
db_password = "..."
db_name = "..."
import psycopg2
try:
conn = psycopg2.connect("dbname='" + db_name + "' user='" + db_user + "' host='" + db_host + "' password='" + db_password + "' port='" + db_port + "'")
print "Successfully connected to the database"
except:
print "I am unable to connect to the database"
cur = conn.cursor()
def get_current_version(cur):
try:
cur.execute("""SELECT * from db_version""")
except:
conn.set_isolation_level(0)
cur.execute("""CREATE TABLE db_version (db_version bigint NOT NULL)""")
cur.execute("""INSERT INTO db_version VALUES (0)""")
cur.execute("""SELECT * from db_version""")
current_version = cur.fetchone()[0]
print "The current database version is " + str(current_version)
return current_version
def recursive_execute_migration(cursor):
current_version = get_current_version(cursor)
if (current_version == goal):
print "Database is on the correct version"
return
elif (current_version < goal):
sql_filename = "upgrade" + str(current_version) + "-" + str(current_version + 1) + ".sql"
print "Upgrading database with " + sql_filename
cursor.execute(open(migration_scripts_dir + sql_filename, "r").read())
recursive_execute_migration(cursor)
else:
sql_filename = "downgrade" + str(current_version) + "-" + str(current_version - 1) + ".sql"
print "Downgrading database with " + sql_filename
cursor.execute(open(migration_scripts_dir + sql_filename, "r").read())
recursive_execute_migration(cursor)
conn.set_isolation_level(0)
recursive_execute_migration(cur)
cur.close()
conn.close()
Is there another way of doing automatic database migrations?
Thanks for your help.
I'm trying to get Dynamic Arrays from my ActiveX component trough Visual FoxPro 9, but with no luck. (Edited and Working example)
LOCAL objMain, objAdapt
#define CrLf CHR(13) + CHR(10)
stMsg = ""
objMain = CREATEOBJECT('nnetsdk.oMain')
objMain.UnlockComponent("xxx-xxxxx-xxxxx-xx")
objAdapt = CREATEOBJECT('nnetsdk.oNetworkAdapter')
objAdapt.GetNetworkAdapters && Collects Network Adapter information
vrAdapters = objAdapt.cName && cName holds collected Network Adapter names
FOR EACH vrAdapter IN vrAdapters
stMsg = stMsg + vrAdapter + CrLf
ENDFOR
MESSAGEBOX(stMsg,64,"List Network Adapters")
RELEASE objAdapt
RELEASE objMain
Can someone explain me what is wrong with this code?
I don't know what your "nnetcom.oMain" ActiveX control is, but you can get directly from VFP via
lcComputerName = "."
loWMIService = GETOBJECT("winmgmts:\\" + lcComputerName + "\root\cimv2")
loItems = loWMIService.ExecQuery("Select * from Win32_NetworkAdapter",,48)
FOR EACH loItem IN loItems
lcMACAddress = loItem.MACAddress
IF !ISNULL(lcMACAddress)
*/ then, you can look at the object properties, such as
lcDescription = loItem.Description
lcMacAddress = loItem.MACAddress
lcNetConnectionID = NVL( loItem.NetConnectionID, "" )
ENDIF
ENDFOR
the For Each loop cycles through class instances of the [Win32_NetworkAdapter] class structure. You can get almost anything you want from that list.
1