Click here to Skip to main content
16,009,255 members
Articles / Programming Languages / PowerShell
Tip/Trick

A PowerShell Form Generator

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
10 Jul 2024CPOL5 min read 34.8K   112   10   2
A PowerShell Form Generator.
This article is an evolution of the previous one, it regards not only the implementation of the package, but in particular shows the new paradigm with which the form objects are specified and the interaction with the WEB.

Introduction

This article is an evolution of the previous, it regards not only the implementation of the package, but in particular a new paradigm with which the form objects are specified; the article is not intended to be an exhaustive explanation of the product, for this please refer to the attached documentation.

Whit the experience gained over time on Form Generator (see the list here), I hope to have achieved a more lean package structure as well as a simpler description of the form objects.

The script has been developed in Windows 11 with Powershell version 7.3.7.

Image 1

Using the program

The script formgen.psm1 contains the function formGen that, when invoked, generates a form and returns the fGen object.

formGen is invoked with the parameters:

  • Widgets a mandatory string containing a list of widget description;
  • CallBack function a function that receive, when the form is closed, the data contained in the form;
  • Background a possibly background color of the form.
PS C:\Sviluppo\PowerShell> using module .\formgen.psm1
PS C:\Sviluppo\PowerShell> $parm = @"
Form '' dialog
Text psw Password password
Text repeatPassword '' password
Text mail
cmb Language '' IT=Italian,FR=French,EN=English,SP=Spanish value FR
Chk check '' 'Consent send info'
Control psw -eq repeatPassword 'Passwords not equals'
"@
PS C:\Sviluppo\PowerShell> $d = formgen $parm -background cyan
PS C:\Sviluppo\PowerShell> $d.fg_data
Name           Value
psw            EllenikePoliteia
mail           ellen@delfi.gr
Language       FR
check          On  
fg_form
fg_button      fg_Ok
repeatPassword EllenikePoliteia

Every control or widget description is characterized by a list of attributes separated by space(s) in this order:
Type, Field NameField Label and Extra(s). Every description starts in a new line.

The Extra field consist of a single parameter or a parameter value pair, some are common to all or nearly all widget like Default, ToolTip, Call function [parameter] etc... others are specific to widget  for example After widget, Center, Color, Format etc...

Furthermore, other informations, called pseudo type, have a slightly different syntax and they serve, among other things, to improve the presentation and control of the data.

The program inserts the buttons: Ok, Reset and Cancel; however if there is only one widget, no buttons are presents because the choice on the item or the item inserted exits the form.

Closing the form, the global variable $fg_data, an hash table where the key is the widget name, contains the input inserted plus a key fg_button whit the name of the button clicked, fg_Start and fg_End for timing purpose however, if the cancel button was pressed there is only fg_Start, fg_End and fg_button.

The widgets

  • Buttons
  • Comments
  • Check boxes
  • Lists
  • Menu
  • Radio buttons
  • Text fields i.e text, password, file, date, protected field ...
  • Timers
  • Track bars

There are no particular things to tell for widget type Text, password or check box. The data for the items of Lists, Combos  and RadioButtons are contained in the extra field each separated by comma; every item can have a possible key, which is returned if the item is selected.

The Pseudo Types

This is perhaps the most interesting part as the pseudo types, as already mentioned, they relate to the presentation of the form (Window and Label) or the event management (Event, Get, Timer) or for validate the data (Control and Required).

Data control

The Control command can perform comparison operations between fields and constants or formal checks via regular expressions, while the Required command imposes the presence of the data.

The controls occur when the form is closed.

T wTime 'Waiting time' Numeric Width 100
Control wTime -gt 0 'Waiting time must be greater 0'
Control wTime -le 1000 'Waiting time too long'
Text e_mail Mail
Control e_mail is mail 'Incorrect mail form'
Slider Min 'Min pressure' From 30 To 150
Slider Max 'Max pressure' From 40 To 220
Control Min -lt Max 'Minimum must be less of Maximum'
T Password '' Password
Control Password is '(?=.*\d)(?=.*[a-z]).{8,}' 'Almost eight character one numeric'
Required e_mail Password wTime

Form presentation

The Window, or the alias Form, command can provide a title, a background color, a position on the screen and the modality (dialogue and permanence); the Labels can be colored and right aligned by the Label command.

Buttons, check boxes and comments can be positioned after another widget.

Event management

Almost all widgets can include a call parameter which, associated with an event on the widget, calls a function (or starts an Internet transaction); the event in question is the most usual for the widget: Click for buttons, KeyDown with Enter key for texts ...
Other events can be set by the command Event; in the example below the event LostFocus invokes the control on the field when he loses focus (as well as when the form is submitted).

Window Controls background #FF00C0C0
label right color blue after ' :'
T wTime 'Waiting time' Numeric Width 100
Text e_mail Mail
Slider Min 'Min pressure' From 30 To 150
Slider Max 'Max pressure' From 40 To 220
Control Min -lt Max 'Minimum must be less of Maximum'
T Password '' hint 'Almost 8 characters' Password
Control Password is '^.{8,}$' 'Almost 8 characters' 
Event LostFocus on Password Call fg_wdgControl %%Password 
Control e_mail is mail 'Incorrect mail form' 
Control wTime -ge 0 'Number must be greater -1' 
Control wTime -le 1000 'waiting too long' 
Required e_mail Password wTime

WEB access

FormGen can send and receive data from the WEB.
The pseudo type Get asks data from internet to populate the form, also the Call parameter can interact with the WEB, the commands syntax are:

  • GET *|name URI [Every seconds]
  • ... Call URI Answer FieldName [Send fieldList]

formGen send an Internet request that depends on the presence of Answer or Send sub parameter. Answer generates a GET request for receive data; Send generates a POST request for transfers the fields indicated including also any file uploads.

The Get commands are executed before the form is displayed; the Call are activate by event.

# Web *****
List Languages
C Time ' ' after Languages
List Hellas
CMB Town
File File '' filter 'Graphic files(*.jpg;*.png;*.gif)|*.jpg;*.png;*.gif|Texts(*.txt)|*.txt' title 'Graphic file'
T Answer '' Width 501
H URI https://www.condorinformatique.com/nFormgen/getITCite.php?random&CR=PS
H URI2 https://www.condorinformatique.com/nFormgen/getSample.php?Type=Time
H URI3 https://www.condorinformatique.com/nFormgen/echo.php
H fields Time,Town,Languages,Hellas,Answer,File
B getQuote Quote Call %%URI Answer Answer After Answer
B Send '' Call %%URI3 Answer fg_HTML send %%fields ToolTip 'Send form data'
Get * https://www.condorinformatique.com/nFormgen/getSample.php?Type=PSDefaults
Get Town https://www.condorinformatique.com/nFormgen/getSample.php?Type=Towns
Get Hellas https://www.condorinformatique.com/nFormgen/getSample.php?Type=Hellas
GET Time %%URI2 Every %minute
GET Languages https://www.condorinformatique.com/nFormgen/getSample.php?Type=Lang
Timer Timer every 15 delay 20 Call %%URI Answer Answer
Required File

The response time of the Get command depends on the response of the WEB server, to minimize the response time formGen sends the command concurrently:

PowerShell
# handle gets ***********
$GetScript = {
   Param ([string]$URI,[string]$field)
   try {
       $answer = Invoke-RestMethod -Method 'GET' -Uri $URI -SkipHttpErrorCheck
   } catch {
       $answer = $_.Exception.Message
   }
   "{$field}$answer"
}
foreach ($h in $gets.Keys) {
   $x = Start-Job $GetScript -ArgumentList $this.decodeSymbol($gets[$h]), $h
}
$aGets = Get-Job | Wait-Job | Receive-Job
Foreach ($item in $aGets) {
...

Every Get command invoke a background job ($GetScript) by means of Start-Job command; the responses are accumulated in the $aGets array by Receive-Job command when all Jobs (Get-Job) are finished (Wait-Job).

An example

The example is based on generation of QRCodes obtained through the module QRCode.ps1 that i s a wrapper for the module QRCodeGenerator for generate QRCode for Geolocation, Text, Twitter, URI and VCard.
The script extracts the fields necessary for the chosen QRCode from the syntax of the call in QRCodeGenerator module (URI QRCode below):

PS C:\Sviluppo\PowerShell> Get-Command -Module QRCodeGenerator -name New-QRCodeURI -syntax
New-QRCodeURI (alias) -> New-PSOneQRCodeURI

New-QRCodeURI [-URI] <uri> [[-Width] <int>] [[-OutPath] <string>] [[-DarkColorRgba] <byte[]>] 
[[-LightColorRgba] <byte[]>] [-Show] [<CommonParameters>]
Image 2 Image 3

Note for user

In the attached documentation in addition to the formGen module (formgen.psm1) there are the script sandbox.ps1 which allows complete exploration of the form generator through some examples; it is sufficient to extract the contents into a folder and start the batch script powershell.bat.

Furthermore, the QRCode.ps1 script allows you to generate QRCodes such as texts, websites and geolocations.

The execution depends on machine execution policy that can be bypassed for the session by the command: Set-ExecutionPolicy Bypass -scope Process -Force;

Form generators

Language OS Source &
documentation
Try Code Project
B4A Android Download   CodeProject Article
JavaScript Browser Download Demo CodeProject Article
Basic AutoIt Windows Download  
B4J Basic Windows Download  
RFO-BASIC! Android Download    
Tcl-Tk Windows Linux Download   CodeProject Article
PowerShell Windows Download  
Julia Windows Linux Download  
Matlab/Octave Windows Linux Download   CodeProject Article

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Condor Informatique
Italy Italy
Computer literacy (software) : Languages: PHP, Javascript, SQL Autoit,Basic4Android; Frameworks: JOOMLA!
Teaching/Training skills on Office, WEB site development and programming languages.
Others : WEB site development.
UNDP Missions
feb – may 2003 Congo DR Bukavu: ground IT computer course
nov 2003 Burundi Bujumbura: Oracle Data Base course
feb 2005 Burundi Bujumbura: JAVA course
mar 2005 Mali Kati: MS Office course
oct 2006 Mali Kati: MS Office course
jun 2006 Burkina Faso Bobo Dioulasso: MS Office course
jun 2007 Burkina Faso Bobo Dioulasso: MS Office course
may 2007 Argentina Olavarria hospital: Internet application for access to medical records
apr 2008 Burkina Faso Ouagadougou: MS ACCESS and dynamic Internet applications
jun 2008 Niger Niamey: analysis of the computing needs of the Niamey hospital
may 2009 Burkina Faso Ouagadougou: MS ACCESS and dynamic Internet applications
oct 2010 Niger Niamey: analysis of the computing needs of the Niamey hospital (following)
Region Piedmont project Evaluation
mar 2006 Burkina Faso, Niger
mar 2007 Benin, Burkina Faso, Niger
sep 2008 Benin, Burkina Faso, Niger
Others
feb 2010 Burundi Kiremba hospital: MS Office course
feb 2011 Congo DR Kampene hospital: MS Office course

Comments and Discussions

 
GeneralMy vote of 5 Pin
@k@ ?26-Jul-14 3:35
professional@k@ ?26-Jul-14 3:35 
GeneralRe: My vote of 5 Pin
Member 420697426-Jul-14 4:40
Member 420697426-Jul-14 4:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.