Write a GUI in Powershell – Part 3

3a. Create data module in C#, This is useful when doing data binding. Don’t know if Powershell is able to create a custom object inherit a C# interface. But Powershell can use Add-Type to add a C# class. Then we just create a simple C# class, and add it to Powershell.

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Dynamic;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.ComponentModel;
using System.Management.Automation;

public class DynamicViewModel : DynamicObject, INotifyPropertyChanged
{
private Hashtable properties;
public event PropertyChangedEventHandler PropertyChanged;
public int debugLevel=0;

public DynamicViewModel()
{
this.properties = new Hashtable();
}

public DynamicViewModel(Hashtable data)
{
this.properties = data;
}

public int Count
{
get
{
return properties.Count;
}
}

public System.Collections.ICollection Keys
{
get
{
return properties.Keys;
}
}

public System.Collections.ICollection Values
{
get
{
return properties.Values;
}
}

// If you try to get a value of a property
// not defined in the class, this method is called.
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
DebugPrint("Get: " + binder.Name + " = " +  " | " + binder.Name.GetType());
result = properties.ContainsKey(binder.Name) ? properties[binder.Name] : null;
return true;
}

// If you try to set a value of a property that is
// not defined in the class, this method is called.
public override bool TrySetMember(SetMemberBinder binder, object value)
{
DebugPrint("TrySetMember: " + binder.Name + " = " + value + " | " + binder.Name.GetType() + " = " + value.GetType());
properties[binder.Name] = value;
RaisePropertyChanged(binder.Name);
return true;
}

// Get the property value by index.
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
DebugPrint("TryGetIndex: " + indexes[0] + " = " + " | " + indexes[0].GetType());
result = properties.ContainsKey(indexes[0].ToString()) ? properties[indexes[0].ToString()] : null;
return true;
}

// Set the property value by index.
public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
{
try
{
DebugPrint("TrySetIndex: " + indexes[0] + " = " + value + " | " + indexes[0].GetType() + " = " + value.GetType());
//properties[indexes[0].ToString()] = value;
properties[(String)indexes[0]] = value;
RaisePropertyChanged((String)indexes[0]);
return true;
}
catch (Exception e)
{
DebugPrint("TrySetIndex Exception: " + e);
return false;
}

}

public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
DebugPrint("TryInvokeMember: ");
try
{
if (properties.ContainsKey(binder.Name))
{
DebugPrint("TryInvokeMember Key Found: " + binder.Name + " | " + properties[binder.Name].GetType());
result = ((ScriptBlock)properties[binder.Name]).InvokeReturnAsIs(args);
//result = ((Func<object[], object>)properties[binder.Name]).Invoke(args);
DebugPrint("TryInvokeMember Key Found - result: " + result);
}
else
{
DebugPrint("TryInvokeMember Key Not Found: " + binder.Name);
result = null;
return false;
}
return true;
}
catch (Exception e)
{
DebugPrint("TryInvokeMember Exception: " + e);
result = null;
return false;
}
}

// Converting an object to a specified type.
public override bool TryConvert(ConvertBinder binder, out object result)
{
// Converting to string.
if (binder.Type == typeof(String))
{
result = "DynamicViewModel with " +
((properties.Count > 1) ? ("" + properties.Count + " Dynamic Properties") :
("" + properties.Count + " Dynamic Property"));
return true;
}

// In case of any other type, the binder
// attempts to perform the conversion itself.
// In most cases, a run-time exception is thrown.
return base.TryConvert(binder, out result);
}

public override IEnumerable<String> GetDynamicMemberNames()
{
return properties.Keys.Cast<String>() ;
}

public override string ToString()
{
return "DynamicViewModel with " +
((properties.Count > 1) ? ("" + properties.Count + " Dynamic Properties") :
("" + properties.Count + " Dynamic Property"));
}

public bool Remove(string name)
{
if (properties.ContainsKey(name))
{
properties.Remove(name);
return true;
}
else
{
return false;
}
}

public void Print()
{
foreach (DictionaryEntry pair in properties)
{
if (pair.Value != null)
{
Console.WriteLine(pair.Key + " \t" + pair.Value + " \t" + pair.Value.GetType());
}
else
{
Console.WriteLine(pair.Key + " \t" + pair.Value + " \tNull Value");
}

}

if (properties.Count == 0)
Console.WriteLine("No elements in the dictionary.");
}

protected void RaisePropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}

protected void DebugPrint(String s)
{
if (debugLevel == 1)
{
Console.WriteLine(s);
}
}
}

3b. Add DynamicViewModel.cs to Powershell

$csharp1=Get-Content (Join-Path $path "DynamicViewModel.cs") -Raw
Add-Type -TypeDefinition $csharp1

Advertisements
Posted in C#, Powershell, XAML | Leave a comment

Write a GUI in Powershell – Part 2

2. Convert XAML to powershell

[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
[xml]$xaml = Get-Content -Raw -Path (Join-Path $path "autoshutdown.xaml")

#Read XAML
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
try{$Form=[Windows.Markup.XamlReader]::Load( $reader )}
catch{Write-Host "Unable to load Windows.Markup.XamlReader. Some possible causes for this problem include: .NET Framework is missing PowerShell must be launched with PowerShell -sta, invalid XAML code was encountered."; exit}

$manager = New-Object System.Xml.XmlNamespaceManager $xaml.NameTable;
$manager.AddNamespace("xaml", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
$manager.AddNamespace("x", "http://schemas.microsoft.com/winfx/2006/xaml");
$xaml.SelectNodes("//*[@x:Name]", $manager ) | %{Set-Variable -Name ($_.Name) -Value $Form.FindName($_.Name)}

Posted in C#, Powershell, XAML | Leave a comment

Write a GUI in Powershell – Part 1

1. Create XAML interface in Visual Studio.  This will be fast and less coding.  Delete x:class property in Window tag and save the file.

Codes:


<Window
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:Collections="clr-namespace:System.Collections;assembly=mscorlib"
x:Name="window" Title="Shutdown PC" Height="436.098" Width="544">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="298*"/>
<RowDefinition Height="107*"/>
</Grid.RowDefinitions>
<Grid IsEnabled="{Binding Stopped}" Margin="0,0,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="46*"/>
<RowDefinition Height="34*"/>
<RowDefinition Height="34*"/>
<RowDefinition Height="29*"/>
<RowDefinition Height="37*"/>
<RowDefinition Height="79*"/>
<RowDefinition Height="39*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="102*"/>
<ColumnDefinition Width="135*"/>
<ColumnDefinition Width="113*"/>
<ColumnDefinition Width="36*"/>
<ColumnDefinition Width="148*"/>
</Grid.ColumnDefinitions>
<RadioButton x:Name="rbCountDown" Content="Count Down" HorizontalAlignment="Left" Margin="10,25,0,0" VerticalAlignment="Top" Height="15" Width="85" GroupName="Type" IsChecked="True"/>
<RadioButton x:Name="rbEndTime" Content="End Time" HorizontalAlignment="Left" Margin="10,12,0,0" VerticalAlignment="Top" Height="15" Width="85" GroupName="Type" Grid.Row="1"/>
<RadioButton x:Name="rbIdleTime" Content="Idle Time" HorizontalAlignment="Left" Margin="10,10,0,0" Grid.Row="2" VerticalAlignment="Top" Height="15" Width="68" GroupName="Type"/>
<RadioButton x:Name="rbKeepAwake" Content="Keep Awake" HorizontalAlignment="Left" Margin="10,9,0,0" Grid.Row="3" VerticalAlignment="Top" Height="15" Width="84" GroupName="Type"/>
<Label Content="Hours" Grid.Column="1" HorizontalAlignment="Left" Margin="10,-5,0,0" VerticalAlignment="Top" Width="78" Height="26"/>
<Label Content="Minutes" Grid.Column="2" HorizontalAlignment="Left" Margin="10,-5,0,0" VerticalAlignment="Top" Height="26" Width="74"/>
<Label Content="Seconds" Grid.Column="4" HorizontalAlignment="Left" Margin="10,-5,0,0" VerticalAlignment="Top" Height="26" Width="93"/>
<ComboBox x:Name="cbHours" Grid.Column="1" Margin="10,21,10,0" Height="22" VerticalAlignment="Top" IsEditable="True" SelectedIndex="0"/>
<ComboBox x:Name="cbMinutes" Grid.Column="2" Margin="10,21,10,0" Height="22" VerticalAlignment="Top" IsEditable="True" SelectedIndex="1" Grid.ColumnSpan="2"/>
<ComboBox x:Name="cbSeconds" Grid.Column="4" Margin="10,21,10,0" Height="22" VerticalAlignment="Top" IsEditable="True" SelectedIndex="0"/>
<Label Content="To:" Grid.Column="1" HorizontalAlignment="Left" Margin="8,6,0,0" Grid.Row="1" VerticalAlignment="Top" Width="55" Height="26"/>
<TextBox x:Name="tbEndTime" Grid.Column="1" Margin="45,8,11,0" Grid.Row="1" VerticalAlignment="Top" Height="22" Grid.ColumnSpan="2" />
<Button x:Name="btNow" Content="Now+1hr" Grid.Column="3" HorizontalAlignment="Left" Margin="9,9,0,0" Grid.Row="1" VerticalAlignment="Top" Width="75" Height="20" Grid.ColumnSpan="2"/>
<ComboBox x:Name="cbIdleTime" Grid.Column="1" Margin="10,8,0,0" Grid.Row="2" VerticalAlignment="Top" Height="22"  IsEditable="True" Text="{Binding IdleTime}">
<ComboBoxItem Content="15"/>
<ComboBoxItem Content="20"/>
<ComboBoxItem Content="25"/>
<ComboBoxItem Content="30"/>
<ComboBoxItem Content="45"/>
<ComboBoxItem Content="60"/>
<ComboBoxItem Content="120"/>
</ComboBox>
<Label Content="Interval" VerticalAlignment="Top" Margin="12,3,0,0" Grid.Row="4" Height="26" HorizontalAlignment="Left" Width="80"/>
<ComboBox x:Name="cbInterval" Text="{Binding DataContext[Interval], Mode=TwoWay, RelativeSource={RelativeSource Self}}" Grid.Column="1" Margin="10,7,102,0" Grid.Row="4" VerticalAlignment="Top" Height="22" IsEditable="True" SelectedIndex="0" Grid.ColumnSpan="2" >
<ComboBoxItem Content="1" />
<ComboBoxItem Content="2" />
<ComboBoxItem Content="3" />
<ComboBoxItem Content="4" />
<ComboBoxItem Content="5" />
</ComboBox>
<TextBox x:Name="tbStatus" Grid.ColumnSpan="5" Margin="22,10,23,3" VerticalScrollBarVisibility="Visible" Grid.Row="5" TextWrapping="Wrap" IsReadOnly="True" IsReadOnlyCaretVisible="True"/>
<ProgressBar x:Name="pbStatus" Value="{Binding Running.TotalSeconds, Mode=OneWay}" Minimum="0" FlowDirection="RightToLeft" Margin="22,9,23,0" Grid.Row="6" Grid.ColumnSpan="5" Height="21" VerticalAlignment="Top">
<ProgressBar.Foreground>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<LinearGradientBrush.RelativeTransform>
<TransformGroup>
<ScaleTransform CenterY="0.5" CenterX="0.5"/>
<SkewTransform CenterY="0.5" CenterX="0.5"/>
<RotateTransform Angle="90" CenterY="0.5" CenterX="0.5"/>
<TranslateTransform/>
</TransformGroup>
</LinearGradientBrush.RelativeTransform>
<GradientStop Color="Yellow" Offset="1"/>
<GradientStop Color="Lime"/>
</LinearGradientBrush>
</ProgressBar.Foreground>
</ProgressBar>
<TextBox x:Name="cbRunning" Grid.Column="1" Margin="17,9,10,0" Grid.Row="6" Grid.ColumnSpan="3" Text="{Binding Running, StringFormat=hh\\:mm\\:ss}" IsEnabled="False" TextAlignment="Center" BorderThickness="0" Background="{x:Null}" Foreground="#FFFF0000" FontWeight="Bold" Height="22" VerticalAlignment="Top"/>
<Label Content="Minutes" Grid.Column="2" Margin="11,6,0,0" Grid.Row="2" Height="26" VerticalAlignment="Top" HorizontalAlignment="Left" Width="53"/>
<Label Content="Seconds" Grid.Column="2" HorizontalAlignment="Right" Margin="0,5,39,0" Grid.Row="4" VerticalAlignment="Top" RenderTransformOrigin="0.974,-0.808"/>
</Grid>
<Grid Margin="0,0" Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition Height="16*"/>
<RowDefinition Height="91*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="21*"/>
<ColumnDefinition Width="86*"/>
<ColumnDefinition Width="221*"/>
<ColumnDefinition Width="208*"/>
</Grid.ColumnDefinitions>
<Label Content="Command to be executed when time is reached" HorizontalAlignment="Left" Margin="0,-6,0,0" VerticalAlignment="Top" Grid.ColumnSpan="3" Width="491" Height="26" Grid.RowSpan="2" Grid.Column="1"/>
<TextBox x:Name="tbCmd" Margin="0,3,23,35" TextWrapping="Wrap" AcceptsReturn="True"  VerticalScrollBarVisibility="Visible" IsEnabled="True" Grid.ColumnSpan="3" Grid.Row="1" SpellCheck.IsEnabled="True" Grid.Column="1" Text="{Binding Text, ElementName=cbCmds, Mode=OneWay}"/>
<Button x:Name="btExec" Content="Exec" Margin="0,0,0,10" Height="20" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="75" Grid.Column="1" Grid.Row="1"/>
<ComboBox x:Name="cbCmds" SelectedIndex="0" Grid.Column="2" Margin="10,0,10,10" Grid.Row="1" VerticalAlignment="Bottom">
<ComboBoxItem Content="Write-Host ($viewModel.Display() -join &quot;`n&quot;)" />
<ComboBoxItem Content="Shutdown -t 30 -s" />
<ComboBoxItem Content="Shutdown -a"/>
</ComboBox>
<Button x:Name="btReset" Content="Reset" Grid.Column="3" HorizontalAlignment="Left" Margin="10,0,0,10" Width="75" Height="20" VerticalAlignment="Bottom" Grid.Row="1"/>
<Button x:Name="btStart" Content="Start" Margin="0,0,40,10" Height="20" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="75" Grid.Column="3" Grid.Row="1"/>
</Grid>
</Grid>
</Window>

 

Posted in C#, Powershell, XAML | Leave a comment

Command Line to Uninstall IE xx

For IE 9
FORFILES /P %WINDIR%\servicing\Packages /M Microsoft-Windows-InternetExplorer-*9.*.mum /c "cmd /c echo Uninstalling package @fname && start /w pkgmgr /up:@fname /norestart"

For IE 10
FORFILES /P %WINDIR%\servicing\Packages /M Microsoft-Windows-InternetExplorer-*10.*.mum /c "cmd /c echo Uninstalling package @fname && start /w pkgmgr /up:@fname /norestart"

For IE 11
FORFILES /P %WINDIR%\servicing\Packages /M Microsoft-Windows-InternetExplorer-*11.*.mum /c "cmd /c echo Uninstalling package @fname && start /w pkgmgr /up:@fname /norestart"

Posted in Windows | Leave a comment

Disable the ActiveX Prompts

Option 1:

ActiveX controls are essentially mini-programs that can be shared by different Windows applications.
Note: ActiveX controls are the most common tools for loading viruses, spyware and other malicious software onto computers. Because of this, every time a website tries to install an ActiveX control, Internet Explorer asks you whether you want to allow it. These prompts can prevent harm to your computer

Follow the steps mentioned below to disable the ActiveX prompts.

1. Click on Internet explorer icon to open Internet explorer.
2. Click on Tools and then select Internet Options form the list.
3. Click on the Security tab and click on Custom Level button.
4. This opens a “Security Settings” window with a list of actions that could compromise yourcomputer’s security. For each one, you can tell Explorer to automatically block the action in all instances (“Disable”), allow it in all instances (“Enable”) or ask you whether to block it (“Prompt”).
5. Scroll down to the section marked “ActiveX Controls and Plug-ins.
6. Select “Enable” for the following actions:
a. “Allow previously unused ActiveX controls to run without prompt”
b. “Download signed ActiveX controls”
c. “Download unsigned ActiveX controls”
d. “Initialize and script ActiveX controls not marked as safe for scripting”
e. “Run ActiveX controls and plug-ins”
f. “Script ActiveX controls marked safefor scripting.”
7. Select “Disable” for the action “Automatic prompting for ActiveX controls.”
8. Click “OK” to close the Security Settings window, then “OK” again to close the Internet Options window.
9. Restart your computer,the new security settings are in effect, and you should no longer see ActiveX prompts.

Thank you and Regards.
Thahaseena M
Microsoft Answers Support Engineer.

Option 2:
Approved ActiveX stored in
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Ext\Stats]
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Ext\Stats\{CLSID}]
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Ext\Stats\{CLSID}\iexplore]
"Count"=dword:00000002
"Flags"=dword:00000004
"Type"=dword:00000001
"Time"=hex:d8,07,01,00,02,00,0f,00,12,00,31,00,1c,00,4e,03
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Ext\Stats\{CLSID}\iexplore\AllowedDomains]
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Ext\Stats\{CLSID}\iexplore\AllowedDomains\*]

Example:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Ext\Stats\{CLSID}\iexplore\AllowedDomains]
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Ext\Stats\{CLSID}\iexplore\AllowedDomains\msn.com]
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Ext\Stats\{CLSID}\iexplore\AllowedDomains\microsoft.com]

Disabled ActiveX Stored in
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Ext\Settings\{CLSID}]
"Flags"=dword:00000001

Posted in Windows | Leave a comment

Lost All App Store Apps from SpringBoard

Lost All App Store Apps from SpringBoard, but the apps are still in the system.

Fixed:
Delete the file located at /var/mobile/Library/Preferences/com.apple.SpringBoard.plist.
Then reboot.

Posted in iPhone | Leave a comment

Turn on Number Lock by Login Screen and Default Users

Copy following code to notepad and save it as numlock.bat, then run it with administrator right.

@echo off
:: For Login Screen
reg add "HKEY_USERS\.DEFAULT\Control Panel\Keyboard" /v InitialKeyboardIndicators /t REG_SZ /d 2 /f
:: For Default Profile
reg load HKLM\DefaultProfile %SystemDrive%\Users\Default\NTUSER.DAT
reg add "HKEY_LOCAL_MACHINE\DefaultProfile\Control Panel\Keyboard" /v InitialKeyboardIndicators /t REG_SZ /d 2 /f
reg unload HKLM\DefaultProfile
exit
Posted in Windows | Leave a comment