Skip to content

Commit

Permalink
FIX: I (hopefully) fixed issue #154 regarding a blocking exception wh…
Browse files Browse the repository at this point in the history
…en refreshing the event log (also modified the DataView binding as it was assigned by code instead of XAML).

IMP: Removed ResolvedHost from the CurrentConn class, as we already have a TargetHostName property on the parent class with the same goal. CurrentConn will be simplified further (and eventually renamed).
MISC: minor refactoring.
  • Loading branch information
wokhan committed Apr 2, 2023
1 parent 684bfae commit 5867959
Show file tree
Hide file tree
Showing 8 changed files with 39 additions and 131 deletions.
2 changes: 1 addition & 1 deletion Common/Processes/ProcessHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ public static string GetAppPkgId(uint pid)
public static string GetLocalUserOwner(uint pid)
{
//Based on: https://bytes.com/topic/c-sharp/answers/225065-how-call-win32-native-api-gettokeninformation-using-c
IntPtr hProcess = NativeMethods.OpenProcess(NativeMethods.ProcessAccessFlags.QueryInformation, false, (uint)pid);
IntPtr hProcess = NativeMethods.OpenProcess(NativeMethods.ProcessAccessFlags.QueryInformation, false, pid);
if (hProcess == IntPtr.Zero)
{
LogHelper.Warning($"Unable to retrieve process local user owner: process pid={pid} cannot be found!");
Expand Down
4 changes: 2 additions & 2 deletions Console/UI/Pages/Connections.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridTemplateColumn Header="Owner" SortMemberPath="Owner">
<DataGridTemplateColumn Header="Owner" SortMemberPath="Owner" Width="Auto">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
Expand All @@ -128,7 +128,7 @@
<Setter Property="Background" Value="Green" />
<Style.Triggers>
<DataTrigger Binding="{Binding Protocol,Mode=OneTime}" Value="UDP">
<Setter Property="Background" Value="OrangeRed" />
<Setter Property="Background" Value="Orchid" />
</DataTrigger>
</Style.Triggers>
</Style>
Expand Down
8 changes: 4 additions & 4 deletions Console/UI/Pages/EventsLog.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
<ContentControl Style="{StaticResource ToolBarPanel}">
<Grid IsEnabled="{Binding IsElevated,Source={x:Static Application.Current}}">
<StackPanel>
<Button ext:CustomAdorner.Image="{StaticResource Image_Refresh}" Content="Refresh" ToolTip="Reload to show the newest events" IsEnabled="{Binding EventsReader.NewMatchingEntriesCount,Converter={StaticResource objectToBool}}" Command="{Binding RefreshCommand}" />
<Button Content="Locate" ext:CustomAdorner.Image="{StaticResource Image_Locate}" Command="{Binding LocateCommand}" ToolTip="Locate the selected item" IsEnabled="{Binding SelectedItem,ElementName=gridLog,Converter={StaticResource objectToBool}}" />
<Button ext:CustomAdorner.Image="{StaticResource Image_Refresh}" Content="Refresh" ToolTip="Reload to show the newest events" IsEnabled="{Binding EventsReader.NewMatchingEntriesCount,Converter={StaticResource objectToBool},TargetNullValue=False}" Command="{Binding RefreshCommand}" />
<Button Content="Locate" ext:CustomAdorner.Image="{StaticResource Image_Locate}" Command="{Binding LocateCommand}" ToolTip="Locate the selected item" />
<Button x:Name="btnEventLogVwr" ext:CustomAdorner.Image="/WFN;component/Resources/Images/btnLEvents.Image.png" Content="Events log viewer" Command="{Binding OpenEventsLogViewerCommand}" />
<TextBlock VerticalAlignment="Center" Text="{Binding EventsReader.NewMatchingEntriesCount, StringFormat='{}{0} new event(s)', FallbackValue='',TargetNullValue=''}" />
</StackPanel>
Expand All @@ -37,7 +37,7 @@
<RowDefinition Height="Auto"/>
<RowDefinition Height="0.3*" />
</Grid.RowDefinitions>
<DataGrid VirtualizingPanel.VirtualizationMode="Recycling" BorderThickness="0" x:Name="gridLog" IsReadOnly="True" ColumnWidth="*" AutoGenerateColumns="False" HeadersVisibility="Column" GridLinesVisibility="None" Grid.ColumnSpan="3" SelectedItem="{Binding SelectedItem,Mode=TwoWay}">
<DataGrid VirtualizingPanel.VirtualizationMode="Recycling" BorderThickness="0" ItemsSource="{Binding DataView,Mode=OneWay}" IsReadOnly="True" ColumnWidth="*" AutoGenerateColumns="False" HeadersVisibility="Column" GridLinesVisibility="None" Grid.ColumnSpan="3" SelectedItem="{Binding SelectedItem,Mode=TwoWay}">
<DataGrid.Columns>
<DataGridTextColumn Header="Index" Binding="{Binding Index,Mode=OneTime}" Width="Auto">
<DataGridTextColumn.CellStyle>
Expand Down Expand Up @@ -99,7 +99,7 @@
<GridSplitter Grid.Row="1" Height="4" Background="LightGray" HorizontalAlignment="Stretch" />
<ScrollViewer Grid.Row="2">
<Grid Margin="10">
<StackPanel TextElement.Foreground="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}" DataContext="{Binding SelectedItem,ElementName=gridLog}">
<StackPanel TextElement.Foreground="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}" DataContext="{Binding SelectedItem,Mode=OneWay}">
<TextBlock><Run FontWeight="Bold" Text="Reason: "/><Run Text="{Binding Reason,Mode=OneTime,FallbackValue='-'}"/></TextBlock>
<TextBlock><Run FontWeight="Bold" Text="Filter: "/><Run Text="{Binding MatchingFilter.Name,Mode=OneWay, FallbackValue='-'}"/> (Id: <Run Text="{Binding MatchingFilter.FilterId,Mode=OneWay,FallbackValue='-'}"/>)</TextBlock>
<TextBlock><Run FontWeight="Bold" Text="Filter details : "/><Run Text="{Binding MatchingFilter.Description,Mode=OneWay,FallbackValue='-'}"/></TextBlock>
Expand Down
39 changes: 19 additions & 20 deletions Console/UI/Pages/EventsLog.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public sealed partial class EventsLog : Page, IDisposable
{
public EventLogAsyncReader<LogEntryViewModel>? EventsReader { get; set; }

[ObservableProperty]
public ICollectionView? dataView;

public int TCPOnlyOrAll
Expand Down Expand Up @@ -72,24 +73,20 @@ public EventsLog()
}
}

private void StartHandlingSecurityLogEvents(bool reset = false)
private void StartHandlingSecurityLogEvents()
{
try
{
if (reset || EventsReader is null)
EventsReader?.Dispose();
EventsReader = new EventLogAsyncReader<LogEntryViewModel>(EventLogAsyncReader.EVENTLOG_SECURITY, LogEntryViewModel.CreateFromEventLogEntry)
{
EventsReader?.Dispose();
EventsReader = new EventLogAsyncReader<LogEntryViewModel>(EventLogAsyncReader.EVENTLOG_SECURITY, LogEntryViewModel.CreateFromEventLogEntry)
{
FilterPredicate = EventLogAsyncReader.IsFirewallEvent
};
OnPropertyChanged(nameof(EventsReader));

dataView = CollectionViewSource.GetDefaultView(EventsReader.Entries);
gridLog.ItemsSource = dataView;
}
FilterPredicate = EventLogAsyncReader.IsFirewallEvent
};
OnPropertyChanged(nameof(EventsReader));

//eventsLogFilters.ResetTcpFilter();
// Fix for #159 - refreshing
var x = EventsReader.Entries;
DataView = CollectionViewSource.GetDefaultView(x);
}
catch (Exception exc)
{
Expand All @@ -100,12 +97,14 @@ private void StartHandlingSecurityLogEvents(bool reset = false)

private void StopHandlingSecurityLogEvents()
{
DataView = null;
EventsReader?.Dispose();
EventsReader = null;
}

public void Dispose()
{
DataView = null;
EventsReader?.Dispose();
}

Expand All @@ -126,7 +125,7 @@ private void OpenEventsLogViewer()
[RelayCommand]
private void Refresh()
{
StartHandlingSecurityLogEvents(true);
StartHandlingSecurityLogEvents();
}


Expand All @@ -143,15 +142,15 @@ private bool FilterTextPredicate(object entryAsObject)

internal void ResetTcpFilter()
{
if (dataView is null)
if (DataView is null)
{
return;
}

dataView.Filter -= TcpFilterPredicate;
DataView.Filter -= TcpFilterPredicate;
if (IsTCPOnlyEnabled)
{
dataView.Filter += TcpFilterPredicate;
DataView.Filter += TcpFilterPredicate;
}
}

Expand All @@ -166,12 +165,12 @@ internal async void ResetTextFilter()
await Task.Delay(500).ConfigureAwait(true);
if (!string.IsNullOrWhiteSpace(TextFilter))
{
dataView!.Filter -= FilterTextPredicate;
dataView.Filter += FilterTextPredicate;
DataView!.Filter -= FilterTextPredicate;
DataView.Filter += FilterTextPredicate;
}
else
{
dataView!.Filter -= FilterTextPredicate;
DataView!.Filter -= FilterTextPredicate;
}
_isResetTextFilterPending = false;
}
Expand Down
9 changes: 0 additions & 9 deletions Notifier/Helpers/CurrentConn.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

using System.Collections.Generic;
using System.ComponentModel;

using Wokhan.ComponentModel.Extensions;
using Wokhan.WindowsFirewallNotifier.Common.Config;
using Wokhan.WindowsFirewallNotifier.Common.UI.ViewModels;

Expand All @@ -26,13 +24,6 @@ public partial class CurrentConn : LogEntryViewModel, INotifyPropertyChanged
public string TargetInfoUrl => string.Format(Settings.Default.TargetInfoUrl, TargetIP); // eg: $"https://bgpview.io/ip/{Target}"
public string TargetPortUrl => string.Format(Settings.Default.TargetPortUrl, TargetPort); // eg: $"https://www.speedguide.net/port.php?port={TargetPort}"

private string _resolvedHost;
public string ResolvedHost
{
get => _resolvedHost;
set => this.SetValue(ref _resolvedHost, value, OnPropertyChanged);
}

//TODO: remove since it's now useless
public string[] PossibleServices { get; set; }
//TODO: remove since it's now useless
Expand Down
82 changes: 0 additions & 82 deletions Notifier/Helpers/WPFUtils.cs

This file was deleted.

2 changes: 1 addition & 1 deletion Notifier/UI/Windows/NotificationWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@
<TextBlock>
<Run Text="Target IP:" />
<Hyperlink NavigateUri="{Binding TargetInfoUrl,Mode=OneTime}" Foreground="{DynamicResource AccentColorBrush}" TextDecorations="None" RequestNavigate="hlk_Navigate">
<Run Text="{Binding TargetIP, FallbackValue='N/A',Mode=OneTime}" ToolTip="{Binding ResolvedHost}"/>
<Run Text="{Binding TargetIP, FallbackValue='N/A',Mode=OneTime}" ToolTip="{Binding TargetHostName,Mode=OneWay}"/>
</Hyperlink>
</TextBlock>
</CheckBox>
Expand Down
24 changes: 12 additions & 12 deletions Notifier/UI/Windows/NotificationWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -512,7 +512,7 @@ private bool createRule(CurrentConn activeConn, string[] services, bool createWi
{
bool success;
int Profiles = OptionsView.IsCurrentProfileChecked ? FirewallHelper.GetCurrentProfile() : FirewallHelper.GetGlobalProfile();
string finalRuleName = (createTempRule) ? Messages.RULE_TEMP_PREFIX + ruleName : ruleName;
string finalRuleName = createTempRule ? Messages.RULE_TEMP_PREFIX + ruleName : ruleName;
var newRule = new CustomRule(finalRuleName,
createWithAdvancedOptions || OptionsView.IsPathChecked ? activeConn.Path : null,
!createWithAdvancedOptions && OptionsView.IsAppChecked ? activeConn.CurrentAppPkgId : null,
Expand All @@ -538,15 +538,15 @@ private bool createRule(CurrentConn activeConn, string[] services, bool createWi
return success;
}

private static WinForms::NotifyIcon tempNotifyIcon_;
private List<CustomRule> tempRules_ = new List<CustomRule>();
private static WinForms::NotifyIcon _tempNotifyIcon;
private readonly List<CustomRule> _tempRules = new();
private void CreateTempRuleNotifyIcon(CustomRule newRule)
{
if (!tempRules_.Contains(newRule))
if (!_tempRules.Contains(newRule))
{
tempRules_.Add(newRule);
_tempRules.Add(newRule);
}
if (tempNotifyIcon_ is null)
if (_tempNotifyIcon is null)
{
// tray icon for temporary rule
WinForms::NotifyIcon ni = new WinForms::NotifyIcon();
Expand All @@ -562,7 +562,7 @@ private void CreateTempRuleNotifyIcon(CustomRule newRule)
ni.ShowBalloonTip(2000);
ni.Visible = true;

tempNotifyIcon_ = ni;
_tempNotifyIcon = ni;
}
}

Expand All @@ -577,15 +577,15 @@ private void iconClick(object sender, EventArgs e)
private bool RemoveTempRulesAndNotfyIcon()
{
bool success = true;
if (tempRules_.Count > 0)
if (_tempRules.Count > 0)
{
LogHelper.Info("Now going to remove temporary rule(s)...");
success = tempRules_.TrueForAll(r => FirewallHelper.RemoveRule(r.Name));
success = _tempRules.TrueForAll(r => FirewallHelper.RemoveRule(r.Name));
}
if (tempNotifyIcon_ is not null)
if (_tempNotifyIcon is not null)
{
tempNotifyIcon_.Dispose();
tempNotifyIcon_ = null;
_tempNotifyIcon.Dispose();
_tempNotifyIcon = null;
}
return success;
}
Expand Down

0 comments on commit 5867959

Please sign in to comment.