TextBox shows "System.Windows.Controls.TextBox" when opening PS1 file via .lnk - wpf

I made a small application in WPF and powershell using XML for the gui template.
The whole application works fine when i open it with right-mouse click and open with powershell of even when i open it true a .exe file that i made for it.
But when i try to open it with a .lnk file it does not show its velue's but instead it presents me with "System.Windows.Controls.TextBox".
I can not show all of my code due to security reasons but i can on collaborate when needed.
P.s I don't often post on stack overflow, if i did something wrong please let me know.
In the XML:
[xml]$04Instellingen = #"
<Grid
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="470" Width="852">
<Grid.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFEEFAFF" Offset="1"/>
<GradientStop Color="White" Offset="0.4"/>
</LinearGradientBrush>
</Grid.Background>
<TabControl x:Name="tabControl" HorizontalAlignment="Left" Height="291" Margin="32,14,0,0" VerticalAlignment="Top" Width="801" Background="{x:Null}">
<TabItem Header="Algemeen">
<Grid>
<Label x:Name="label1_Copy" Content="Benaming:" HorizontalAlignment="Left" Margin="5,47,0,0" VerticalAlignment="Top" Width="119"/>
<Label x:Name="label1_Copy1" Content="Ip adres:" HorizontalAlignment="Left" Margin="146,47,0,0" VerticalAlignment="Top" Width="119"/>
<TextBox x:Name="ipnaam1" HorizontalAlignment="Left" Height="23" Margin="10,77,0,0" TextWrapping="Wrap" Text="Server1" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="ip1" HorizontalAlignment="Left" Height="23" Margin="150,77,0,0" TextWrapping="Wrap" Text="Server1 ip adres" VerticalAlignment="Top" Width="165"/>
<TextBox x:Name="ipnaam2" HorizontalAlignment="Left" Height="23" Margin="10,110,0,0" TextWrapping="Wrap" Text="Server2" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="ip2" HorizontalAlignment="Left" Height="23" Margin="150,110,0,0" TextWrapping="Wrap" Text="Server2 ip adres" VerticalAlignment="Top" Width="165"/>
<TextBox x:Name="ipnaam3" HorizontalAlignment="Left" Height="23" Margin="10,144,0,0" TextWrapping="Wrap" Text="Server3" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="ip3" HorizontalAlignment="Left" Height="23" Margin="150,144,0,0" TextWrapping="Wrap" Text="Server2 ip adres" VerticalAlignment="Top" Width="165"/>
<Label x:Name="label5" Content="Stel hieronder de servernamen en ip andressen in die automatisch op conetiviteid worden getest." HorizontalAlignment="Left" Margin="5,13,0,0" VerticalAlignment="Top" Width="545"/>
</Grid>
</TabItem>
#More code here but is irrelevant#
</Grid>
"#
Code powershell:
$ipnaam1 = $AboutXaml.FindName("ipnaam1")
$ipnaam1.Text = $global:ipnaam1
$ipnaam2 = $AboutXaml.FindName("ipnaam2")
$ipnaam2.Text = $global:ipnaam2
$ipnaam3 = $AboutXaml.FindName("ipnaam3")
$ipnaam3.Text = $global:ipnaam3
$ip1 = $AboutXaml.FindName("ip1")
$ip1.Text = $global:ipadres1
$ip2 = $AboutXaml.FindName("ip2")
$ip2.Text = $global:ipadres2
$ip3 = $AboutXaml.FindName("ip3")
$ip3.Text = $global:ipadres3
Where it gets its velue's from:
function Import-Config {
#If a config file exists for the current user in the expected location, it is imported
#and values from the config file are placed into global variables
if (Test-Path -Path "$loc\instellingen\Config.config") {
try {
#Imports the config file and saves it to variable $Config
$Config = Import-Clixml -Path "$loc\instellingen\Config.config"
#Creates global variables for each config property and sets their values
$global:ServerBericht = $Config.ServerBericht
$global:DownloadVan = $Config.DownloadVan
$global:DownloadNaar = $Config.DownloadNaar
$global:LogBestandLocatie = $Config.LogBestandLocatie
$global:InfoTextElias = $Config.InfoTextElias
$global:ipnaam1 = $Config.ipnaam1
$global:ipnaam2 = $Config.ipnaam2
$global:ipnaam3 = $Config.ipnaam3
$global:ipadres1 = $Config.ipadres1
$global:ipadres2 = $Config.ipadres2
$global:ipadres3 = $Config.ipadres3
}
catch {
[System.Windows.Forms.MessageBox]::Show("An error occurred importing your Config file. A new Config file will be generated for you. $_", 'Import Config Error', 'OK', 'Error')
New-Config
}
} #end if config file exists
else {
New-Config
}
} #end function Import-Config
.Config File population
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
<Obj RefId="0">
<TN RefId="0">
<T>System.Collections.Hashtable</T>
<T>System.Object</T>
</TN>
<DCT>
<En>
<S N="Key">ipadres3</S>
<S N="Value">127.0.0.1</S>
</En>
<En>
<S N="Key">LogBestandLocatie</S>
<S N="Value">C:\temp</S>
</En>
<En>
<S N="Key">ipadres1</S>
<S N="Value">127.0.0.1</S>
</En>
<En>
<S N="Key">ipadres2</S>
<S N="Value">127.0.0.1</S>
</En>
<En>
<S N="Key">ServerBericht</S>
<S N="Value">Er zijn geen netwerk berichten.</S>
</En>
<En>
<S N="Key">DownloadNaar</S>
<S N="Value">C:\maps</S>
</En>
<En>
<S N="Key">ipnaam3</S>
<S N="Value">Ongedefinieerd</S>
</En>
<En>
<S N="Key">ipnaam1</S>
<S N="Value">Ongedefinieerd</S>
</En>
<En>
<S N="Key">InfoTextElias</S>
<S N="Value">Als de app vast lijkt te lopen dan is deze druk aan het werk, Wees geduldig. (Hier word aan gewerkt)</S>
</En>
<En>
<S N="Key">DownloadVan</S>
<S N="Value">\MAPS-HIER</S>
</En>
<En>
<S N="Key">ipnaam2</S>
<S N="Value">Ongedefinieerd</S>
</En>
</DCT>
</Obj>
</Objs>
This is how i call the script from the .lnk
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -windowstyle hidden -ExecutionPolicy Bypass -File System.App.ps1

Related

Bind variables to combobox and textbox in Powershell

I'm coming with more problems to you.
I've built a simple GUI to create a printer or change the driver on a print server. However, when I click the button RUN, it does not make anything just only pops up the message that the operation was successful. May somebody help me checking the code and tell me what I am doing wrong?
#region pop up the gui
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
Add-Type -AssemblyName PresentationFramework
[xml]$xaml = #"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Print Queue Configuration Tool" Height="800" Width="800" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Topmost="True">
<Grid>
<TextBlock HorizontalAlignment="Left" Margin="24,85,0,0" TextWrapping="Wrap" Text="Welcome to Print Queue Configuration Tool" VerticalAlignment="Top" Width="456" FontSize="22" FontWeight="Bold"/>
<Image HorizontalAlignment="Left" Height="41" Margin="537,36,0,0" VerticalAlignment="Top" Width="257" Source="logo.png"/>
<TextBlock HorizontalAlignment="Left" Margin="72,140,0,0" TextWrapping="Wrap" Text="What do you want to do?" VerticalAlignment="Top" RenderTransformOrigin="0.422,0.157" Height="31" Width="257" FontSize="16"/>
<RadioButton x:Name="RadioCreate" Content="Create a print queue." HorizontalAlignment="Left" Margin="102,194,0,0" VerticalAlignment="Top" IsChecked="True"/>
<RadioButton x:Name="RadioChange" Content="Change driver to a print queue." HorizontalAlignment="Left" Margin="311,194,0,0" VerticalAlignment="Top"/>
<ComboBox x:Name="ComboMaker" HorizontalAlignment="Left" Margin="460,260,0,0" VerticalAlignment="Top" Width="290">
<ComboBoxItem Content="Dascom"/>
<ComboBoxItem Content="HP"/>
<ComboBoxItem Content="Kyocera"/>
<ComboBoxItem Content="Lexmark"/>
<ComboBoxItem Content="Zebra"/>
</ComboBox>
<ComboBox x:Name="ComboModel" HorizontalAlignment="Left" Margin="460,310,0,0" VerticalAlignment="Top" Width="290">
</ComboBox>
<ComboBox x:Name="ComboTray" HorizontalAlignment="Left" Margin="460,360,0,0" VerticalAlignment="Top" Width="290">
</ComboBox>
<ComboBox x:Name="ComboDriver" HorizontalAlignment="Left" Margin="460,410,0,0" VerticalAlignment="Top" Width="290">
</ComboBox>
<TextBox x:Name="TextBoxPQ" HorizontalAlignment="Left" Height="22" Margin="460,460,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="290" SelectionOpacity="4"/>
<TextBox x:Name="TextBoxServer" HorizontalAlignment="Left" Height="22" Margin="460,510,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="290"/>
<TextBox x:Name="TextBoxHostname" HorizontalAlignment="Left" Height="22" Margin="460,560,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="290"/>
<TextBox x:Name="TextBoxLocation" HorizontalAlignment="Left" Height="22" Margin="460,610,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="290"/>
<TextBlock HorizontalAlignment="Left" Margin="72,260,0,0" TextWrapping="Wrap" Text="Select the maker:" VerticalAlignment="Top" Width="304" Height="22" FontWeight="Bold"/>
<TextBlock HorizontalAlignment="Left" Margin="72,310,0,0" TextWrapping="Wrap" Text="Select the model:" VerticalAlignment="Top" Width="304" Height="22" FontWeight="Bold"/>
<TextBlock HorizontalAlignment="Left" Margin="72,360,0,0" TextWrapping="Wrap" Text="Select the no. of additional trays (only for model CX825, CX921, CX922, MX910, X950):" VerticalAlignment="Top" Width="304" Height="32" FontWeight="Bold"/>
<TextBlock HorizontalAlignment="Left" Margin="72,410,0,0" TextWrapping="Wrap" Text="Select the driver:" VerticalAlignment="Top" Width="304" Height="22" FontWeight="Bold"/>
<TextBlock HorizontalAlignment="Left" Margin="72,460,0,0" TextWrapping="Wrap" Text="Add the print queue name:" VerticalAlignment="Top" Width="304" Height="22" FontWeight="Bold"/>
<TextBlock HorizontalAlignment="Left" Margin="72,510,0,0" TextWrapping="Wrap" Text="Add the server name:" VerticalAlignment="Top" Width="304" Height="22" FontWeight="Bold"/>
<TextBlock HorizontalAlignment="Left" Margin="72,560,0,0" TextWrapping="Wrap" Text="Add the hostname:" VerticalAlignment="Top" Width="304" Height="22" FontWeight="Bold"/>
<TextBlock HorizontalAlignment="Left" Margin="72,610,0,0" TextWrapping="Wrap" Text="Add the location (i.e. DE-Eltmann):" VerticalAlignment="Top" Width="304" Height="22" FontWeight="Bold"/>
<Button x:Name="ButtonRun" Content="Run" HorizontalAlignment="Left" Margin="660,710,0,0" VerticalAlignment="Top" Width="90" Height="35"/>
</Grid>
</Window>
"#
#Read XAML
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$window = [Windows.Markup.XamlReader]::Load($reader)
#Add actions to button Run
$RadioCreate = $window.FindName("RadioCreate")
$RadioChange = $window.FindName("RadioChange")
$ComboMaker = $window.FindName("ComboMaker")
$ComboModel = $window.FindName("ComboModel")
$ComboDriver = $window.FindName("ComboDriver")
$ComboMaker.Add_DropdownClosed({
$ComboModel.Items.Clear()
$ComboDriver.Items.Clear()
switch ($ComboMaker.Text) {
"Dascom" {
$ComboModel.Items.Add("Dascom T2150s")
$ComboModel.Items.Add("Dascom T2380")
}
"HP" {
$ComboModel.Items.Add("HP LaserJet M507dn")
$ComboModel.Items.Add("HP LaserJet M700 M712dn")
$ComboModel.Items.Add("HP Color LaserJet M553dn")
$ComboModel.Items.Add("HP OfficeJet Pro 8210")
$ComboModel.Items.Add("HP PageWide Pro 452dw")
$ComboModel.Items.Add("HP PageWide Enterprise Color 556dn")
$ComboModel.Items.Add("HP DesignJet T1600")
}
"Kyocera" {
$ComboModel.Items.Add("Kyocera P3155dn")
}
"Lexmark" {
$ComboModel.Items.Add("Lexmark CX625adhe")
$ComboModel.Items.Add("Lexmark CX825dte")
$ComboModel.Items.Add("Lexmark CX921de")
$ComboModel.Items.Add("Lexmark CX922de")
$ComboModel.Items.Add("Lexmark MX722adhe")
$ComboModel.Items.Add("Lexmark MS725dvn")
$ComboModel.Items.Add("Lexmark MX910de")
$ComboModel.Items.Add("Lexmark X950de")
}
"Zebra" {
$ComboModel.Items.Add("Zebra ZD620t 300 dpi")
$ComboModel.Items.Add("Zebra ZT620 300 dpi")
$ComboModel.Items.Add("Zebra 220Xi4 300 dpi")
$ComboModel.Items.Add("Zebra ZT610-300 dpi")
$ComboModel.Items.Add("Zebra ZQ630 Mobile Printer")
}
}
switch ($ComboMaker.Text) {
"Dascom" {
$ComboDriver.Items.Add("Tally T2150_")
}
"HP" {
$ComboDriver.Items.Add("HP DesignJet HPGL2 Driver")
$ComboDriver.Items.Add("HP Designjet T790ps 44in PS3")
$ComboDriver.Items.Add("HP DesignJet T930 HPGL2")
$ComboDriver.Items.Add("HP DesignJet Universal Print Driver HPGL2")
$ComboDriver.Items.Add("HP DesignJet Universal Print Driver HPGL2(v4.5.0)")
$ComboDriver.Items.Add("HP Universal Printing PS")
$ComboDriver.Items.Add("HP Universal Printing PS (v6.3.0)")
$ComboDriver.Items.Add("HP Universal Printing PS (v6.4.1)")
}
"Kyocera" {
$ComboDriver.Items.Add("Kyocera Classic Universaldriver KPDL")
$ComboDriver.Items.Add("Kyocera Classic Universaldriver KPDL (A4 models)")
}
"Lexmark" {
$ComboDriver.Items.Add("Lexmark Universal v2 PS3")
$ComboDriver.Items.Add("Lexmark Universal v2 PS3 (2.10.0.0)")
$ComboDriver.Items.Add("Lexmark Universal v2 PS3 (2.11.0.0)")
$ComboDriver.Items.Add("Lexmark Universal v2 PS3 (2.13.0.0)")
$ComboDriver.Items.Add("Lexmark Universal v2 PS3 (2.14.0.0)")
$ComboDriver.Items.Add("Lexmark Universal v2 PS3 (2.14.1.0)")
}
"Zebra" {
$ComboDriver.Items.Add("ZDesigner 110Xi4 203 dpi")
$ComboDriver.Items.Add("ZDesigner ZDesigner 110Xi4 300 dpi")
$ComboDriver.Items.Add("ZDesigner 220Xi4 300 dpi")
$ComboDriver.Items.Add("ZDesigner GX430t")
$ComboDriver.Items.Add("ZDesigner QLn420 (CPCL)")
$ComboDriver.Items.Add("ZDesigner QLn420 (ZPL)")
$ComboDriver.Items.Add("ZDesigner S4M-203dpi ZPL")
$ComboDriver.Items.Add("ZDesigner ZD620-300dpi ZPL")
$ComboDriver.Items.Add("ZDesigner ZM400 200 dpi (EPL)")
$ComboDriver.Items.Add("ZDesigner ZM400 200 dpi (ZPL)")
$ComboDriver.Items.Add("ZDesigner ZM400 300 dpi (ZPL)")
$ComboDriver.Items.Add("ZDesigner ZM600 200 dpi (ZPL)")
$ComboDriver.Items.Add("ZDesigner ZQ510 (ZPL)")
$ComboDriver.Items.Add("ZDesigner ZQ630 (ZPL)")
$ComboDriver.Items.Add("ZDesigner ZT230-200dpi ZPL")
$ComboDriver.Items.Add("ZDesigner ZT410-300dpi ZPL")
$ComboDriver.Items.Add("ZDesigner ZT420-300dpi ZPL")
$ComboDriver.Items.Add("ZDesigner ZT610-300dpi ZPL")
$ComboDriver.Items.Add("ZDesigner ZT610R-203dpi ZPL")
$ComboDriver.Items.Add("ZDesigner ZT610R-300dpi ZPL")
}
}
switch ($ComboModel.Text) {
"Lexmark CX825dte" {
$ComboTray.Items.Add("3")
}
"Lexmark CX921de" {
$ComboTray.Items.Add("0")
$ComboTray.Items.Add("1")
$ComboTray.Items.Add("2")
$ComboTray.Items.Add("3")
}
"Lexmark CX922de" {
$ComboTray.Items.Add("0")
$ComboTray.Items.Add("1")
$ComboTray.Items.Add("2")
$ComboTray.Items.Add("3")
}
"Lexmark MX910de" {
$ComboTray.Items.Add("0")
$ComboTray.Items.Add("1")
$ComboTray.Items.Add("2")
$ComboTray.Items.Add("3")
}
"Lexmark X950de" {
$ComboTray.Items.Add("0")
$ComboTray.Items.Add("1")
$ComboTray.Items.Add("2")
$ComboTray.Items.Add("3")
}
}
})
<# this part contains the variable assignment but not working
$maker = $ComboMaker.SelectedItem
$modelfull = $ComboModel.SelectedItem
$tray = $ComboTray.SelectedItem
$driver = $ComboDriver.SelectedItem
$TextBoxPQ = $window.FindName("TextBoxPQ")
$PQ = $TextBoxPQ.Text
$TextBoxServer = $window.FindName("TextBoxServer")
$server = $TextBoxServer.Text
$TextBoxHostname = $window.FindName("TextBoxHostname")
$hostname = $TextBoxHostname.Text
$TextBoxLocation = $window.FindName("TextBoxLocation")
$location = $TextBoxLocation.Text
#>
$ButtonRun = $window.FindName("ButtonRun")
$ButtonRun.Add_Click({
# here variables are not working as well
$maker = $ComboMaker.SelectedItem
$modelfull = $ComboModel.SelectedItem
$tray = $ComboTray.SelectedItem
$driver = $ComboDriver.SelectedItem
$TextBoxPQ = $window.FindName("TextBoxPQ")
$PQ = $TextBoxPQ.Text
$TextBoxServer = $window.FindName("TextBoxServer")
$server = $TextBoxServer.Text
$TextBoxHostname = $window.FindName("TextBoxHostname")
$hostname = $TextBoxHostname.Text
$TextBoxLocation = $window.FindName("TextBoxLocation")
$location = $TextBoxLocation.Text
if ($RadioCreate.Checked -eq $true){
PortCreation
PrinterCreation
if ($maker -eq 'Lexmark') {
ApplyConfigLexmark
}
}
if ($RadioChange.Checked -eq $true) {
ChangeDriver
if ($maker -eq 'Lexmark') {
ApplyConfigLexmark
}
}
[System.Windows.MessageBox]::Show('Operation completed!')
})
#Show form
$window.ShowDialog() | Out-Null
#endregion
Also I would like to link the model selection to another variable called 'model' that will use a shortcut of the model to deploy some specific settings and once the Operation success mesasge' pops up and you press OK, all comboboxes and texboxes reset to blank.
FYI: PortCreation, PrinterCreation, ChangeDriver and ApplyConfigLexmark are functions that execute code in Powershell so I am not putting the whole code. Variables that I am using are below:
$maker # choose the brand of the physical device
$model # short name of the device model
$modelfull # Full device model
$tray # number of the trays the device has
$driver # Driver name
$PQ # print queue name
$server # hostname of the server
$hostname # hostname of the printer
$location # location of the device
I tested your code and changed this line to show the maker and it works. Why do you say the variable is not binding?
[System.Windows.MessageBox]::Show('Operation completed!' + $maker)
Also Checked should be IsChecked
if ($RadioCreate.IsChecked -eq $true){

Powershell GUI - Add variables to a radio button once it's selected

I am doing a GUI in Visual Studuio for a script I made for Powershell and I need to use radio buttons to add variables to make this script works, like for example, the script works with 5 printer brands, so the user needs to select one of this to progress. Then, for each brand you have inside the models. At the end, will execute the code to create a print queue on a selected server, which includes the variables held on the radio buttons below:
$maker - brand of the device.
$model - model of the device.
$modelfull - full model name for comment purposes.
$driver - print driver to assign to the print queue.
How can I add those variables to each radio button? I.e. I have two models, Deskjet 3050 and Deskjet 3045, how can I convert those models into a variable once user select the radio button and press Next on the window?
Below you can see example of the code from Visual Studio where is the frame with the radio buttons:
<Page x:Class="Print_Queue_Configuration_Tool.Maker_2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Print_Queue_Configuration_Tool"
mc:Ignorable="d"
d:DesignHeight="570" d:DesignWidth="754"
Title="Maker_2">
<Grid x:Name="Maker_2_Grid">
<Button x:Name="Maker_2_ButtonBack" Content="Back" HorizontalAlignment="Left" Margin="360,525,0,0" VerticalAlignment="Top" Width="120" Height="35"/>
<Button x:Name="Maker_2_ButtonNext" Content="Next" HorizontalAlignment="Left" Margin="485,525,0,0" VerticalAlignment="Top" Width="120" Height="35"/>
<Button x:Name="Maker_2_ButtonCancel" Content="Cancel" HorizontalAlignment="Left" Margin="610,525,0,0" VerticalAlignment="Top" Width="120" Height="35" IsCancel="True"/>
<Image x:Name="Maker_2_ImageLogo" HorizontalAlignment="Left" Height="44.264" Margin="480.157,30.312,0,0" VerticalAlignment="Top" Width="273.843" Source="logo.png" RenderTransformOrigin="0.5,0.5"/>
<TextBlock x:Name="Maker_2_TextMaker_2" HorizontalAlignment="Left" Margin="70,140,0,0" TextWrapping="Wrap" Text="Please select the maker of the device:" VerticalAlignment="Top"/>
<RadioButton x:Name="Maker_2_RadioMaker1" Content="Canon" VerticalAlignment="Center" Margin="272.25,220.25,351.75,333.75" Height="16" Width="130" GroupName="Makers_2" FontWeight="Bold"/>
<RadioButton x:Name="Maker_2_RadioMaker2" Content="Epson" VerticalAlignment="Center" Margin="272.25,260.25,351.75,293.75" Height="16" Width="130" GroupName="Makers_2" FontWeight="Bold"/>
</Grid>
</Page>
Here you can see how I have assigned the variables to each button, but of course it's not working:
$wpf.Maker_2_RadioMaker1.add_Checked({
$maker = 'Canon'
})
$wpf.Maker_2_RadioMaker2.add_Checked({
$maker = 'Epson'
})
Thank you!!
PS: I am new in this so I am still learning. Please be polite, remember that you were in my position once :)
Here your Page is working... I had to adapt the xml a bit.
Note the FindName to Address the Radiobuttons
[xml]$xaml = #"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="Window"
Title="Maker_2" Height="770" Width="800">
<Grid x:Name="Maker_2_Grid">
<Button x:Name="Maker_2_ButtonBack" Content="Back" HorizontalAlignment="Left" Margin="360,525,0,0" VerticalAlignment="Top" Width="120" Height="35"/>
<Button x:Name="Maker_2_ButtonNext" Content="Next" HorizontalAlignment="Left" Margin="485,525,0,0" VerticalAlignment="Top" Width="120" Height="35"/>
<Button x:Name="Maker_2_ButtonCancel" Content="Cancel" HorizontalAlignment="Left" Margin="610,525,0,0" VerticalAlignment="Top" Width="120" Height="35" IsCancel="True"/>
<Image x:Name="Maker_2_ImageLogo" HorizontalAlignment="Left" Height="44.264" Margin="480.157,30.312,0,0" VerticalAlignment="Top" Width="273.843" Source="logo.png" RenderTransformOrigin="0.5,0.5"/>
<TextBlock x:Name="Maker_2_TextMaker_2" HorizontalAlignment="Left" Margin="70,140,0,0" TextWrapping="Wrap" Text="Please select the maker of the device:" VerticalAlignment="Top"/>
<RadioButton x:Name="Maker_2_RadioMaker1" Content="Canon" VerticalAlignment="Center" Margin="272.25,220.25,351.75,333.75" Height="16" Width="130" GroupName="Makers_2" FontWeight="Bold"/>
<RadioButton x:Name="Maker_2_RadioMaker2" Content="Epson" VerticalAlignment="Center" Margin="272.25,260.25,351.75,293.75" Height="16" Width="130" GroupName="Makers_2" FontWeight="Bold"/>
</Grid>
</Window>
"#
function Check-Radios
{
if($this.Name -eq "Maker_2_RadioMaker1") {Write-Host "Canon"}
if($this.Name -eq "Maker_2_RadioMaker2") {Write-Host "Epson"}
}
$reader = (New-Object System.Xml.XmlNodeReader $xaml)
$window = [Windows.Markup.XamlReader]::Load($reader)
$window.FindName("Maker_2_RadioMaker1").add_Checked({Check-Radios})
$window.FindName("Maker_2_RadioMaker2").add_Checked({Check-Radios})
$window.ShowDialog()
Now it's working as requested. In Function Check-Radios you can set your variables depending on choosen Radiobutton
This example meets your requirements that when you press "Next" the correct selection of the radio button is displayed. This should take you further.
[xml]$xaml = #"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="Window"
Title="Maker_2" Height="770" Width="800">
<Grid x:Name="Maker_2_Grid">
<Button x:Name="Maker_2_ButtonBack" Content="Back" HorizontalAlignment="Left" Margin="360,525,0,0" VerticalAlignment="Top" Width="120" Height="35"/>
<Button x:Name="Maker_2_ButtonNext" Content="Next" HorizontalAlignment="Left" Margin="485,525,0,0" VerticalAlignment="Top" Width="120" Height="35"/>
<Button x:Name="Maker_2_ButtonCancel" Content="Cancel" HorizontalAlignment="Left" Margin="610,525,0,0" VerticalAlignment="Top" Width="120" Height="35" IsCancel="True"/>
<Image x:Name="Maker_2_ImageLogo" HorizontalAlignment="Left" Height="44.264" Margin="480.157,30.312,0,0" VerticalAlignment="Top" Width="273.843" Source="logo.png" RenderTransformOrigin="0.5,0.5"/>
<TextBlock x:Name="Maker_2_TextMaker_2" HorizontalAlignment="Left" Margin="70,140,0,0" TextWrapping="Wrap" Text="Please select the maker of the device:" VerticalAlignment="Top"/>
<RadioButton x:Name="Maker_2_RadioMaker1" Content="Canon" VerticalAlignment="Center" Margin="272.25,220.25,351.75,333.75" Height="16" Width="130" GroupName="Makers_2" FontWeight="Bold"/>
<RadioButton x:Name="Maker_2_RadioMaker2" Content="Epson" VerticalAlignment="Center" Margin="272.25,260.25,351.75,293.75" Height="16" Width="130" GroupName="Makers_2" FontWeight="Bold"/>
</Grid>
</Window>
"#
function Check-Radios
{
$Global:radioSelected = $this;
}
$radioSelected = $null
$reader = (New-Object System.Xml.XmlNodeReader $xaml)
$window = [Windows.Markup.XamlReader]::Load($reader)
$window.FindName("Maker_2_RadioMaker1").add_Checked({Check-Radios})
$window.FindName("Maker_2_RadioMaker2").add_Checked({Check-Radios})
$window.FindName("Maker_2_ButtonNext").add_Click({Write-Host "You have selected: $($radioSelected.Content)"});
$window.ShowDialog()
EDIT:
here an example for an object that holds your printerdata
$printerList = [System.Collections.ArrayList]::new()
$printerList.Add([pscustomobject]#{Maker = "Canon";Model = "Pixma";ModelFull="Pixma0815";driver = "driverxyz1"})
$printerList.Add([pscustomobject]#{Maker = "Epson";Model = "Workforce";ModelFull="Workforce2020";driver = "driverxyz2"})
You can simply rewrite your "next button ClickMethod" like this...
$window.FindName("Maker_2_ButtonNext").add_Click({ Write-Host $($printerList | where Maker -eq $($radioSelected.Content)) });
it will give you the printers with selected maker
With Navigationwindow and pages you can now go to the page depending in selected printer.
Best Regards
Unfortunately, importing wpf as xaml for powershell is for me not entirely functional
I designed an example for you in which all elements were created in the code and also realized that you first select the manufacturer (radio buttons) and on the next page the model or full model, both are listed as an example. But you actually only need the combo with the full model.
here it is with Powershell
using namespace System.Windows
using namespace System.Windows.Controls
using namespace System.Windows.Navigation
[System.Reflection.Assembly]::LoadWithPartialName("PresentationFramework")
[System.Reflection.Assembly]::LoadWithPartialName("PresentationCore")
[System.Reflection.Assembly]::LoadWithPartialName("WindowsBase")
function Check-Radios
{
$Global:selectedMaker = $this.Content
}
$printerList = [System.Collections.ArrayList]::new()
$printerList.Add([pscustomobject]#{Maker = "Canon";Model = "Pixma";ModelFull="Pixma0815";driver = "driverxyz1"})
$printerList.Add([pscustomobject]#{Maker = "Canon";Model = "Pixma";ModelFull="Pixma1615";driver = "driverxyz1"})
$printerList.Add([pscustomobject]#{Maker = "Epson";Model = "Workforce";ModelFull="Workforce2020";driver = "driverxyz2"})
$selectedMaker = "Canon";
$navigationWindow = [NavigationWindow]::new()
$navigationPage1 = [Page]::new()
$navigationPage2 = [Page]::new()
#Page with printers
$printerLabel = [Label]::new()
$printerLabel.Content = ($printerList | where Maker -eq $selectedMaker | Select -First 1).Maker
$printerModelCombo = [ComboBox]::new()
$printerModelFullCombo = [ComboBox]::new()
$printerStackPanel = [StackPanel]::new()
$printerStackPanel.AddChild($printerLabel)
$printerStackPanel.AddChild($printerModelCombo)
$printerStackPanel.AddChild($printerModelFullCombo)
$navigationPage2.Content = $printerStackPanel
#Page with radiobuttons
$radioButton1 = [RadioButton]::new()
$radioButton1.Content ="Canon"
$radioButton1.Name = "RadioCanon"
$radioButton2 = [RadioButton]::new()
$radioButton2.Content ="Epson"
$radioButton2.Name = "RadioEpson"
$radioButton1.add_Checked({Check-Radios})
$radioButton2.add_Checked({Check-Radios})
$button1 = [Button]::new()
$button1.Content = "Next"
$button1.add_Click(
{
foreach($entry in ($printerList | where Maker -eq $selectedMaker))
{
# Model
if($printerModelCombo.Items.IsEmpty -or !$printerModelCombo.Items.Content.Contains($entry.Model))
{
$printerModelComboItem = [ComboBoxItem]::new()
$printerModelComboItem.Content = $entry.Model
$printerModelCombo.AddChild($printerModelComboItem)
}
# Model Full
$printerModelFullComboItem = [ComboBoxItem]::new()
$printerModelFullComboItem.Content = $entry.ModelFull
$printerModelFullCombo.AddChild($printerModelFullComboItem)
}
$printerModelCombo.SelectedIndex = 0
$printerModelFullCombo.SelectedIndex = 0
$navigationWindow.NavigationService.Content = $navigationPage2
})
$grid = [Grid]::new()
$gridRowDef1 = [RowDefinition]::new()
$gridRowDef2 = [RowDefinition]::new()
$gridRowDef1.Height ="4*"
$gridRowDef2.Height ="1*"
$grid.RowDefinitions.Add($gridRowDef1)
$grid.RowDefinitions.Add($gridRowDef2)
$stackPanel = [StackPanel]::new()
$stackPanel.AddChild($radioButton1)
$stackPanel.AddChild($radioButton2)
$grid.AddChild($stackPanel)
$grid.AddChild($button1)
[Grid]::SetRow($stackPanel,0)
[Grid]::SetRow($button1,1)
$navigationPage1.Content = $grid;
$navigationWindow.Title = "Navigation"
$navigationWindow.Width = 960
$navigationWindow.Height = 600
$navigationWindow.NavigationService.Content = $navigationPage1
$navigationWindow.ShowsNavigationUI = $false
$navigationWindow.ShowDialog()

Null-valued expression error in Powershell script with GUI Runspace

I have a configuration script in powershell that I am trying to marry with a WFP GUI. After a few failed forays with code and gui in the same thread I have been reading a number of pages about running the GUI in its own runspace. Below is the code that I have pieced together.
The form runs but I get this error related to the button click I am trying to use to hide/unhide grids.
You cannot call a method on a null-valued expression.
At C:\Projects\AVPC Setup\Working Files\MT Trial 3.ps1:218 char:18
+ $syncHash.fullConfig.Add_Click({
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
With the form running these variables are visible in the syncHash so I am not sure what I am missing.
$Global:syncHash = [hashtable]::Synchronized(#{})
$newRunspace =[runspacefactory]::CreateRunspace()
$newRunspace.ApartmentState = "STA"
$newRunspace.Name = "Config GUI"
$newRunspace.ThreadOptions = "ReuseThread"
$newRunspace.Open()
$newRunspace.SessionStateProxy.SetVariable("syncHash",$syncHash)
$psCmd = [PowerShell]::Create().AddScript({
[xml]$xaml = #"
<Window x:Class="psguiconfig.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:psguiconfig"
mc:Ignorable="d"
Title="Config" Height="175" Width="500">
<Grid x:Name="mainGrid" HorizontalAlignment="Left" Height="144" Margin="0,1,0,0" VerticalAlignment="Top" Width="490">
<Grid x:Name="choiceGrid" HorizontalAlignment="Left" Height="144" Margin="0,1,0,0" VerticalAlignment="Top" Width="490" Visibility="Visible">
<Label Content="Choose Config Type" HorizontalAlignment="Center" Height="26" Margin="0,0,0,60" VerticalAlignment="Center" FontWeight="SemiBold"/>
<Button x:Name="fullConfig" Content="Full" HorizontalAlignment="Center" Margin="0,45,250,0" VerticalAlignment="Center" Width="75"/>
<Button x:Name="stepConfig" Content="Step By Step" HorizontalAlignment="Center" Margin="0,45,0,0" VerticalAlignment="Center" Width="75"/>
<Button x:Name="upgradeConfig" Content="Upgrade" HorizontalAlignment="Center" Margin="250,45,0,0" VerticalAlignment="Center" Width="75" IsEnabled="False"/>
</Grid>
<Grid x:Name="fullGrid" HorizontalAlignment="Left" Height="144" Margin="0,1,0,0" VerticalAlignment="Top" Width="490" Visibility="Hidden">
<Label x:Name="fullLabel" Content="Full Config" HorizontalAlignment="Center" Height="26" Margin="0,0,0,60" VerticalAlignment="Center" FontWeight="SemiBold"/>
<ProgressBar x:Name="fullProgress" HorizontalAlignment="Center" Height="20" Margin="0,40,0,0" VerticalAlignment="Center" Width="400"/>
<Label x:Name="fullProgressLabel" Content="Tasking Stuffs" Foreground="#FFFFFF" HorizontalAlignment="Center" Height="20" Margin="45,82,245,42" VerticalAlignment="Center" FontWeight="SemiBold" FontSize="7" Width="200"/>
<Label x:Name="fullProgressPercentageLabel" Content="0%" Foreground="#FFFFFF" HorizontalContentAlignment="Right" Height="20" Margin="419,82,45,42" VerticalAlignment="Center" FontWeight="SemiBold" FontSize="7" Width="26"/>
</Grid>
</Grid>
</Window>
"#
$AttributesToRemove = #(
'x:Class',
'mc:Ignorable'
)
foreach ($Attrib in $AttributesToRemove) {
if ( $xaml.Window.GetAttribute($Attrib) ) {
$xaml.Window.RemoveAttribute($Attrib)
}
}
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$syncHash.Window=[Windows.Markup.XamlReader]::Load( $reader )
[xml]$XAML = $xaml
$xaml.SelectNodes("//*[#*[contains(translate(name(.),'n','N'),'Name')]]") | %{
#Find all of the form types and add them as members to the synchash
$syncHash.Add($_.Name,$syncHash.Window.FindName($_.Name) )
}
$syncHash.Window.ShowDialog() | Out-Null
$syncHash.Error = $Error
})
$psCmd.Runspace = $newRunspace
$data = $psCmd.BeginInvoke()
Function Update-Window {
Param (
$Control,
$Property,
$Value,
[switch]$AppendContent
)
If ($Property -eq "Close") {
$syncHash.Window.Dispatcher.invoke([action]{$syncHash.Window.Close()},"Normal")
Return
}
$syncHash.$Control.Dispatcher.Invoke([action]{
If ($PSBoundParameters['AppendContent']) { $syncHash.$Control.AppendText($Value) } Else { $syncHash.$Control.$Property = $Value }
}, "Normal")
}
$syncHash.fullConfig.Add_Click({
Update-Window -Control choiceGrid -Property Visibility -Value Hidden
Update-Window -Control fullGrid -Property Visibility -Value Visible
})

Weird PowerShell+WPF error with ShowDialog()

So I'm developing a Powershell based WPF application and I am receiving the following error:
Exception calling "ShowDialog" with "0" argument(s): "Unidentified: USB_Disable="
At C:\Users\miste\OneDrive\Documents\Visual Studio 2015\Projects\Vaccinate-USB\Vaccinate-USB\Vaccinate-USB.ps1:344 char:5
+ $Form.ShowDialog() | out-null
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : RuntimeException
Now the fairly odd thing is that the "USB_Disable=" string is only found in a hereString that never comes into contact with $Form.ShowDialog(). Below is an excerpt of the initializer function that contains the hereString, then the form loader function. If you need the full code let me know(it's about 800 lines)
The initializer:
function Initialize-ARD
{
if (-not (Test-Admin))
{
$wshpop = New-Object -ComObject Wscript.Shell
$wshpop.Popup('Please run as an administrator.',0,'Error!',0x0)
exit
}
if(-not (Test-Path -Path $ARDHome))
{
if(-not (Test-IsNetConnected))
{
$wshpop = New-Object -ComObject Wscript.Shell
$wshpop.Popup('Please make sure you have an internet connection for first run. Connect to the internet and the re-run the program.',0,'Error!',0x0)
exit
}
New-Item -Path $ARDHome -ItemType 'Directory' -Force
New-Item -Path "$ARDHome\config.ini" -ItemType 'File' -Force
#HERESTRING STARTS HERE!
Set-Content -Path "$ARDHome\config.ini" -Force -Value #'
[USB]
USB_Block=False
USB_Lock=False
USB_Delete=False
USB_Disable=False
[CD]
CD_Block=False
CD_Lock=False
CD_Delete=False
CD_Disable=False
[Firewall]
Firewall_Enabled=False
Firewall_Disabled=True
Firewall_UpdateFreq=0.5
'#
#New-Download -URL 'http://ha.x10.bz/package.zip/' -Destination "$ARDHome\package.zip"
#Expand-ZIPFile -File "$ARDHome\package.zip" -Destination $ARDHome
#Import-Module "$ARDHome\DeviceManagment\DeviceManagement.psd1" -Force
}
else{}
$script:ini = Get-IniFile -FilePath "$ARDHome\config.ini"
$USBBlock = $ini.USB.USB_Block
$USBLock = $ini.USB.USB_Lock
$USBDelete = $ini.USB.USB_Delete
$USBDisable = $ini.USB.USB_Disable
$CDBlock = $ini.CD.CD_Block
$CDLock = $ini.CD.CD_Lock
$CDDelete = $ini.CD.CD_Delete
$CDEject = $ini.CD.CD_Eject
$FirewallEnabled = $ini.Firewall.Firewall_Enabled
$FirewallDisabled = $ini.Firewall.Firewall_Disabled
$FirewallValue = $ini.Firewall.Firewall_UpdateFreq
if($USBBlock -eq "True")
{
$USBBlock = $true
}
else
{
$USBBlock = $false
}
if($USBLock -eq "True")
{
$USBLock = $true
}
else
{
$USBLock = $false
}
if($USBDelete -eq "True")
{
$USBDelete = $true
}
else
{
$USBDelete = $false
}
if($USBDisable -eq "True")
{
$USBDisable = $true
}
else
{
$USBDisable = $false
}
if($CDBlock -eq "True")
{
$CDBlock = $true
}
else
{
$CDBlock = $false
}
if($CDDelete -eq "True")
{
$CDDelete = $true
}
else
{
$CDDelete = $false
}
if($CDEject -eq "True")
{
$CDEject = $true
}
else
{
$CDEject = $false
}
if($CDLock -eq "True")
{
$CDLock = $true
}
else
{
$CDLock = $false
}
if($FirewallEnabled -eq "True")
{
$FirewallEnabled = $true
}
else
{
$FirewallEnabled = $false
}
if($FirewallDisabled -eq "True")
{
$FirewallDisabled = $true
}
else
{
$FirewallDisabled = $false
}
$USB_Block.IsChecked = $USBBlock
$USB_Lock.IsChecked = $USBLock
$USB_Delete.IsChecked = $USBDelete
$USB_Disable.IsChecked = $USDisable
$CD_Block.IsChecked = $CDBlock
$CD_Lock.IsChecked = $CDLock
$CD_Delete.IsChecked = $CDDelete
$CD_Eject.IsChecked = $CDEject
$Firewall_Enabled.IsChecked = $FirewallEnabled
$Firewall_Disabled.IsChecked = $FirewallDisabled
$Firewall_UpdateFreq.Value = $FirewallValue
}
The form and its loader:
function Initialize-Window
{
[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
[xml]$XAML = #"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Autorun Defender" Height="376" Width="528" WindowStartupLocation="CenterScreen" ResizeMode="CanMinimize" Background="Black" Opacity="1">
<Grid Margin="0,10,4,1">
<TabControl Name="tabControl" HorizontalAlignment="Left" Height="285.5" VerticalAlignment="Top" Width="493" Margin="10,0,0,0" Background="#FF2E2E2E">
<TabItem Header="Welcome" Background="#FF2E2E2E" Margin="-2,0,2,0" Width="80">
<Grid Background="#FF2E2E2E">
<Viewbox HorizontalAlignment="Left" Margin="10,0,0,87.5" Width="116">
<Image Name="image" Height="100" Width="100" Source="$(Get-ScriptDirectory)\Logo.png"/>
</Viewbox>
<Label Name="title1" Content="Autorun" HorizontalAlignment="Left" Margin="126,0,0,0" VerticalAlignment="Top" Height="67" Width="191" FontSize="48" FontStyle="Italic" FontWeight="Bold" FontFamily="Harlow Solid Italic"/>
<Label Name="title2" Content="Defender" HorizontalAlignment="Left" Margin="206,67,0,87.5" Width="205" FontSize="48" FontStyle="Italic" FontWeight="Bold" FontFamily="Harlow Solid Italic"/>
<Label Name="copyright" Content="© 2015 LogoiLab" VerticalAlignment="Bottom" FontSize="12" Height="26.5" HorizontalAlignment="Left" Width="101" Foreground="#FFD4D4D4"/>
</Grid>
</TabItem>
<TabItem Header="USB" Background="#FF2E2E2E" Margin="-2,0,2,0" Width="80">
<Grid Background="#FF2E2E2E">
<GroupBox Name="USB_Passive" Header="Passive" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="224" Width="230" Foreground="#FFD4D4D4">
<Grid>
<CheckBox Name="USB_Block" Content="Block Autorun" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Foreground="#FFD4D4D4" Background="black"/>
<CheckBox Name="USB_Lock" Content="Lock Autorun Edits" Margin="10,30,89.656,0" VerticalAlignment="Top" Foreground="#FFD4D4D4" Background="black"/>
</Grid>
</GroupBox>
<GroupBox Name="USB_Active" Header="Active" HorizontalAlignment="Left" Margin="249,10,0,0" VerticalAlignment="Top" Height="224" Width="230" Foreground="#FFD4D4D4">
<Grid>
<CheckBox Name="USB_Delete" Content="Delete Autorun.inf Files" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Foreground="#FFD4D4D4" Background="black"/>
<CheckBox Name="USB_Disable" Content="Disable USBs With Autorun" HorizontalAlignment="Left" Margin="10,30,0,0" VerticalAlignment="Top" Foreground="#FFD4D4D4" Background="black"/>
</Grid>
</GroupBox>
</Grid>
</TabItem>
<TabItem Header="CD/DVD" Background="#FF2E2E2E" Margin="-2,0,2,0" Width="80">
<Grid Background="#FF2E2E2E">
<GroupBox Name="CD_Passive" Header="Passive" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="224" Width="230" Foreground="#FFD4D4D4">
<Grid>
<CheckBox Name="CD_Block" Content="Block Autorun" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Foreground="#FFD4D4D4" Background="black"/>
<CheckBox Name="CD_Lock" Content="Lock Autorun Edits" Margin="10,30,89.656,0" VerticalAlignment="Top" Foreground="#FFD4D4D4" Background="black"/>
</Grid>
</GroupBox>
<GroupBox Name="CD_Active" Header="Active" HorizontalAlignment="Left" Margin="249,10,0,0" VerticalAlignment="Top" Height="224" Width="230" Foreground="#FFD4D4D4">
<Grid>
<CheckBox Name="CD_Delete" Content="Delete Autorun.inf Files" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Foreground="#FFD4D4D4" Background="black"/>
<CheckBox Name="CD_Eject" Content="Eject CDs With Autorun" HorizontalAlignment="Left" Margin="10,30,0,0" Width="227" Height="26" VerticalAlignment="Top" Foreground="#FFD4D4D4" Background="black"/>
</Grid>
</GroupBox>
</Grid>
</TabItem>
<TabItem Header="Firewall" Background="#FF2E2E2E" Margin="-2,0,2,0" Width="80">
<Grid Background="#FF2E2E2E">
<TextBlock TextWrapping="WrapWithOverflow" Foreground="#FFD4D4D4">
This is a device firewall. It will block new devices from being "Pluged and Played". This type of firewall is meant to prevent such attacks as "BadUSB" or other hardware attacks. Please note that this may cause system errors(especially if your system has a lot of software defined devices).
</TextBlock>
<RadioButton Background="black" Name="Firewall_Enabled" Content="Enable Device Firewall" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="30,83.04,0,0" Foreground="#FFD4D4D4"/>
<RadioButton Background="black" Name="Firewall_Disabled" Content="Disable Device Firewall" HorizontalAlignment="Left" Margin="30,103,0,111.54" Foreground="#FFD4D4D4"/>
<TextBlock TextWrapping="WrapWithOverflow" Height="87.12" Margin="10,0" VerticalAlignment="Bottom" Foreground="#FFD4D4D4">
Check Frequency:
<LineBreak/>
This is how often the firewall checks for new devices, set this very low if you're afraid of BadUSB or its variants.
</TextBlock>
<Slider Minimum=".50" Maximum="300" TickPlacement="BottomRight" TickFrequency="5" IsSnapToTickEnabled="True" Name="Firewall_UpdateFreq" Margin="10,0,75,10" Height="29.96" VerticalAlignment="Bottom" Value="{Binding Count}"/>
<Label Name="SliderValue_Label" Content="" Height="29.96" Margin="0,0,10,10" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="60" Foreground="#FFD4D4D4"/>
</Grid>
</TabItem>
<TabItem Header="Info" Background="#FF2E2E2E" Margin="-2,0,2,-1" RenderTransformOrigin="0.137,0.501" Height="46" VerticalAlignment="Top" Width="80" >
<Grid Background="#FF2E2E2E">
<Viewbox HorizontalAlignment="Left" Height="97.389" Margin="10,10,0,0" VerticalAlignment="Top" Width="100">
<Image Name="Avatar" Height="100" Width="100" Source="$(Get-ScriptDirectory)\LogoiLab.png"/>
</Viewbox>
<Label Name="username" Content="© 2015 LogoiLab" Margin="115,10,10,0" VerticalAlignment="Top" FontSize="24" FontWeight="Bold" FontStyle="Italic" Foreground="#FFD4D4D4"/>
<Label Name="quote" Content="~ The logos behind the pathos." Margin="115,51.923,10,0" VerticalAlignment="Top" FontWeight="Bold" FontStyle="Italic" Foreground="#FFD4D4D4"/>
<Button Name="link" Content="http://www.github.com/LogoiLab" VerticalAlignment="Top" Margin="115,79.656,10,0" Cursor="Hand" FontStyle="Oblique"/>
<WebBrowser Margin="10,115,10,10" Source="http://ha.x10.bz/AutorunDefender/changelog.html"/>
</Grid>
</TabItem>
<TabItem Header="Feedback" Background="#FF2E2E2E" Margin="-2,0,2,-1" RenderTransformOrigin="0.137,0.501" Height="46" VerticalAlignment="Top" Width="80" >
<Grid Background="#FF2E2E2E">
<WebBrowser Margin="10,10,10,10" Source="http://goo.gl/forms/B77vvnhLPV"/>
</Grid>
</TabItem>
</TabControl>
<Button Name="Apply" Content="Apply" HorizontalAlignment="Left" Margin="353,290.5,0,0" VerticalAlignment="Top" Width="150" Height="35.5"/>
<Label Name="Status_Label" VerticalContentAlignment="Center" Content="" Margin="10,0,170,10" VerticalAlignment="Bottom" Height="35.5" Foreground="White"/>
</Grid>
</Window>
"#
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$form=[Windows.Markup.XamlReader]::Load($reader)
$xaml.SelectNodes("//*[#Name]") | %{Set-Variable -Name ($_.Name) -Value $Form.FindName($_.Name) -Scope Script }
$Firewall_Enabled.Add_Click({
$Firewall_Enabled.IsChecked = $True
$FireWall_Disabled.IsChecked = $False
})
$Firewall_Disabled.Add_Click({
$Firewall_Enabled.IsChecked = $False
$FireWall_Disabled.IsChecked = $True
})
$link.Add_Click({
Start-Process 'http://www.github.com/LogoiLab'
})
$Firewall_UpdateFreq.Add_ValueChanged({
$SliderValue_Label.Content = ($Firewall_UpdateFreq.value).ToString() + " Sec"
})
$Apply.Add_Click({
$Status_Label.ForeGround = 'yellow'
$Status_Label.Content = 'Applying Changes...'
Start-Handler
})
$Status_Label.Foreground = 'green'
$Status_Label.Content = 'Ready...'
$Form.Add_ContentRendered({
Initialize-ARD
})
#$Form.Add_Loaded({
# Initialize-ARD
#})
$Form.Add_Closing({
Deinitialize-Window
})
$Form.ShowDialog() | out-null
}
This is a very strange error that I have never encountered before, somehow the ShowDialog method is getting hold of a string that should never be parsed like that(not to mention not even be allowed to access).
Any help would be greatly appreciated!
The issue is with a .NET memory management bug, run a CCleaner and reboot your system.

WPF - How can I validate a new instance of an object?

I have this class
public class Doctor
{
private string licenseNumber;
public string LicenseNumber
{
get
{
return this.licenseNumber;
}
set
{
if (value.Length > 4)
throw new MyException("License Number can't be more then 4 digits.\n");
if (!new Regex("^[0-9]*$").Match(value).Success) // Allow only numbers
throw new MyException("Only numbers are allowed in a License Number.\n");
this.licenseNumber = value.PadLeft(4,'0'); // Pad with zeros to 4 digits
}
}
private string name;
public string Name
{
get
{
return this.name;
}
set
{
if (!new Regex("^[a-zA-Z ]*$").Match(value).Success) // Allow only letters and spaces
throw new MyException("Only letters and spaces are allowed in a name.\n");
this.name = value;
}
}
private string phoneNumber;
public string PhoneNumber
{
get
{
return this.phoneNumber;
}
set
{
{
if (!new Regex("^0[2-9]-[0-9]{7}$").Match(value).Success) // allow only numbers in format 0[2-9]-xxxxxxx
throw new MyException("ERROR: only numbers in format 0[2-9]-xxxxxxx are legal\n");
this.phoneNumber = value;
}
}
}
}
and much more properties inside it.
Of course the ctor of this class accepts only form of ctor with values inside, and enter the values to the props.
Now, I've created a form, which within the user can add a new Doctor.
Thing is - I want to validate the form before the user click on 'Add'.
This is a shorted version of my 'add' form in XML:
<Window x:Class="PLForms.AddDoctor"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="AddDoctor" Height="431" Width="381" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:my="clr-namespace:BE;assembly=BE" Loaded="Window_Loaded" Background="White" ResizeMode="CanResizeWithGrip" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Margin="12" HorizontalAlignment="Left" VerticalAlignment="Top">
<Window.Resources>
<CollectionViewSource x:Key="doctorViewSource" d:DesignSource="{d:DesignInstance my:Doctor, CreateList=True}" />
</Window.Resources>
<Grid Height="367" Name="grid1" Width="296" Margin="12" HorizontalAlignment="Center" VerticalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="29" />
</Grid.RowDefinitions>
<Grid DataContext="{StaticResource doctorViewSource}" HorizontalAlignment="Left" Margin="19,13,0,0" Name="grid2" VerticalAlignment="Top">
<Label Content="Name:" Grid.Column="0" Grid.Row="0" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Grid.Row="0" Height="23" HorizontalAlignment="Left" Margin="3" Name="nameTextBox" Text="{Binding Path=Name, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
<Label Content="Phone Number:" Grid.Column="0" Grid.Row="3" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Grid.Row="3" Height="23" HorizontalAlignment="Left" Margin="3" Name="phoneNumberTextBox" Text="{Binding Path=PhoneNumber, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
</Grid>
<Button Content="Add" Name="Add" BorderBrush="#FF612355" Foreground="White" Click="Add_Click" Margin="0,326,0,0" Grid.RowSpan="2">
<Button.Background>
<LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
<GradientStop Color="Black" Offset="0" />
<GradientStop Color="#85081DDA" Offset="0.893" />
</LinearGradientBrush>
</Button.Background>
</Button>
</Grid>
Now, I think that the validation of data will activated only if I set "DataContext" somehow. I've tried to set a sample Doctor object in the form, assign DataContext to the instance of this object, and then - when the user update the data to illegal one - it activate the validation, and red border is marked around the textbox.
But I'm looking how to 'activate' validation even if there's no instance of Doctor before - when the user got a blank form, fill it by himself, and only then try to click on 'Add'.
My problem is that in this way, I can't attach DataContext property to anything, since I don't have a Doctor instance, and of course I can't create an empty one, because all of the exceptions I created myself...
I'll be happy to know what's the logic of Adding data to database, and validate it before, not just in update.
T
Have you looked at validation attributes? That should make your code cleaner and you don't have to throw exceptions anymore since the user won't be able to add invalid data to the database.

Resources