log4net configuration error - cant find app.config - winforms

I am trying to implement log4net in a helper project (AC.Helpers), and when it runs the configuration, I get the following error in the Output window -
log4net:ERROR Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the and elements. The configuration section should look like:
LoggerBase.cs -
public abstract class LoggerBase
{
#region Member Variables
/// <summary>
/// Member variable to hold the <see cref="ILog"/> instance.
/// </summary>
private readonly log4net.ILog logger = null;
#endregion
#region Properties
/// <summary>
/// Abstract property which must be overridden by the derived classes.
/// The logger prefix is used to create the logger instance.
/// </summary>
protected abstract System.Type LogPrefix
{
get;
}
#endregion
#region Constructors
private static bool isConfigured = false;
/// <summary>
/// Constructor of the class.
/// </summary>
public LoggerBase()
{
// initiate logging class
if (!isConfigured)
{
log4net.Config.XmlConfigurator.Configure();
isConfigured = true;
}
logger = log4net.LogManager.GetLogger(this.LogPrefix);
}
#endregion
App.config -
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="Console" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level: %message%newline" />
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="Console" />
</root>
</log4net>
</configuration>
Any ideas why I am getting this? Other posts suggest moving the log4net config to its own file and use the following in AssemblyInfo.cs (tried, without success)
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]

Related

Two main windows loaded for WPF after adding legacy Prism

I am having problem where my application is using very old Prism v4.x reference with added region manager and module. As result it shows two windows instead and they are linked together so doing any action on second shows in the first screen or the first screen is not fully loaded.
App.xaml.cs file:
using System;
using System.Windows;
namespace WpfTestApp
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
[STAThread]
public static void Main(string[] args)
{
try
{
var app = new App();
app.InitializeComponent();
app.Run();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Fatal Exception occurred!");
}
}
/// <inheritdoc />
protected override void OnStartup(StartupEventArgs e)
{
try
{
base.OnStartup(e);
var bootstrapper = new AppBootstrapper();
bootstrapper.Run();
base.OnStartup(e);
}
catch (Exception ex)
{
try
{
MessageBox.Show(ex.ToString(), "App startup");
}
finally
{
Current.Shutdown();
}
}
}
}
}
AppBootstrapper.cs file:
using System.Windows;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.UnityExtensions;
using Microsoft.Practices.ServiceLocation;
namespace WpfTestApp
{
public class AppBootstrapper : UnityBootstrapper
{
protected override DependencyObject CreateShell()
{
InitializeModules();
return ServiceLocator.Current.GetInstance<MainWindow>();
}
/// <summary>
/// Runs the initialization steps to ensure that the shell is ready to be displayed. The shell application
/// object is created and set as the main window of the application.
/// </summary>
protected override void InitializeShell()
{
base.InitializeShell();
App.Current.MainWindow = (Window)Shell;
App.Current.MainWindow.Show();
}
protected override void ConfigureModuleCatalog()
{
ModuleCatalog.AddModule(new ModuleInfo()
{
ModuleName = OutlookModule.NAME,
ModuleType = typeof(OutlookModule).AssemblyQualifiedName,
InitializationMode = InitializationMode.WhenAvailable
});
}
}
}
Dummy module OutlookModule.cs file:
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.Unity;
namespace WpfTestApp
{
[Module(ModuleName = NAME)]
public class OutlookModule : IModule
{
internal const string NAME = "OutlookModule";
public OutlookModule(IUnityContainer container, IRegionManager regionManager)
{
}
public void Initialize()
{
}
}
}
A non standard WPF project file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup Label="Globals">
<SccProjectName>SAK</SccProjectName>
<SccProvider>SAK</SccProvider>
<SccAuxPath>SAK</SccAuxPath>
<SccLocalPath>SAK</SccLocalPath>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net48</TargetFramework>
<OutputType>WinExe</OutputType>
<RootNamespace>SpreadsheetOwnerErrorSampleV3</RootNamespace>
<AssemblyName>SpreadsheetOwnerErrorSampleV3</AssemblyName>
<GenerateAssemblyInfo>False</GenerateAssemblyInfo>
<ExpressionBlendVersion>12.0.51020.0</ExpressionBlendVersion>
<OutputPath>..\bin\</OutputPath>
<StartupObject>WpfTestApp.App</StartupObject>
<EnableDefaultEmbeddedResourceItems>false</EnableDefaultEmbeddedResourceItems>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<Prefer32Bit>true</Prefer32Bit>
<DebugType>full</DebugType>
<DebugSymbols>True</DebugSymbols>
</PropertyGroup>
<ItemGroup>
<None Remove="WpfTestApp.csproj.vspscc" />
</ItemGroup>
<ItemGroup>
<Page Include="App.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Compile Include="AppBootstrapper.cs" />
<Compile Include="OutlookModule.cs" />
<Page Include="MainWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Compile Include="MainWindow.xaml.cs">
<DependentUpon>MainWindow.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<AppDesigner Include="Properties\" />
</ItemGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Core" />
<Reference Include="System.Xaml" />
<Reference Include="UIAutomationProvider" />
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Prism.Desktop.Net40" Version="4.1.1" />
<PackageReference Include="Prism.UnityExtensions.Net40" Version="4.1.1" />
<PackageReference Include="System.Windows.Interactivity.WPF" Version="2.0.20525" />
<PackageReference Include="Unity" Version="2.1.505" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.0">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4 %28x86 and x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<PropertyGroup>
<LanguageTargets>$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Bin\Microsoft.CSharp.targets</LanguageTargets>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<Target Name="WorkaroundForXAMLIntellisenseBuildIssue" AfterTargets="_CheckCompileDesignTimePrerequisite">
<PropertyGroup>
<BuildingProject>false</BuildingProject>
</PropertyGroup>
</Target>
<Choose>
<When Condition="'$(MSBuildProjectExtension)' != '.csproj' and '$(MSBuildProjectExtension)' != '.vbproj'">
<PropertyGroup>
<LanguageTargets Condition="Exists('$(MSBuildProjectDirectory)\$(AssemblyName).csproj')">$(MSBuildToolsPath)\Microsoft.CSharp.targets</LanguageTargets>
<LanguageTargets Condition="Exists('$(MSBuildProjectDirectory)\$(AssemblyName).vbproj')">$(MSBuildToolsPath)\Microsoft.VisualBasic.targets</LanguageTargets>
</PropertyGroup>
</When>
</Choose>
</Project>
Please help identify why two Windows are loaded when it should be only first one. I know that Prism used is outdated and we will upgrade in future. However, I need a working sample based on this version. All this legacy code was implemented based on fallowing articles a while ago:
http://www.infragistics.com/community/blogs/blagunas/archive/2012/09/13/xamdockmanager-a-prism-regionadapter.aspx
http://brianlagunas.com/xamdockmanageran-updated-prism-region-adapter/
http://brianlagunas.com/xamdockmanager-prism-region-adapter-update-3/
Both windows loaded from App.xaml.cs Main method during app.Run() execution on CreateShell or later. However, this is required to work for application as per documentation:
https://prismlibrary.com/docs/wpf/legacy/Initializing.html
Thanks in advance
As #mm8 suggested the problem appeared to be in App.xaml itself which is by default injecting startup line with main view:
<Application x:Class="WpfTestApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfTestApp"
!-> StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>

Where to Load AppSettings and Set ViewModel Properties Using MEF and Prism

I created a WPF MVVM app using MEF and Prism 5.0. I have MEF loading a module at startup called MobileRecruiterModule (below). I need to read some settings from App.config (or any config file really) and update the ViewModel properties with those config values so the View can pick them up.
Where is the appropriate place to load settings here? Do I do it in the MEF module (the thing that implements Microsoft.Practices.Prism.Modularity.IModule or in my View?
MobileRecruiterModule.cs
[ModuleExport(typeof (MobileRecruiterModule))]
public class MobileRecruiterModule : IModule
{
/// <summary>
/// The region manager
/// </summary>
[Import] public IRegionManager Region;
/// <summary>
/// Notifies the module that it has be initialized.
/// </summary>
public void Initialize()
{
Region.RegisterViewWithRegion(RegionNames.MainContentRegion, typeof (MobileRecruiterView));
}
...
}
MobileRecruiterView.xaml.cs
[Export("MobileRecruiterView")]
[PartCreationPolicy(CreationPolicy.Shared)]
[RegionMemberLifetime(KeepAlive = false)]
[Export]
public partial class MobileRecruiterView : UserControl
{
[Import]
public MobileRecruiterViewModel ViewModel
{
get { return (MobileRecruiterViewModel)DataContext; }
set { DataContext = value; }
}
[ImportingConstructor]
public MobileRecruiterView(MobileRecruiterViewModel vm)
{
InitializeComponent();
DataContext = vm;
}
}
MobileRecruiterViewModel.cs
[Export]
public class MobileRecruiterViewModel : BindableBase
{
public string DatabaseServer { get; set; }
... and a few other properties that the XAML view binds to ...
}
I would suggest that you should load your settings in ViewModel constructor. Because your ViewModel is the DataContext for the View, you have to initialize it before you show it. I hope that you do not store any BLOB in it, so the time for *.config loading will be small enough to do it on UI thread.

WPF ToggleButton.IsChecked binding does not work

is there an issue with two way binding to the IsChecked property on a ToggleButton in .NET 3.5?
I have this XAML:
<ToggleButton
Name="tbMeo"
Command="{Binding FilterOnSatelliteTypeCmd}"
IsChecked="{Binding ShowMeoDataOnly, Mode=TwoWay}"
ToolTip="Show MEO data only">
<Image Source="../images/32x32/Filter_Meo.png" Height="16" />
</ToggleButton>
I have a ViewModel with the following property:
private bool _showMeoDataOnly;
public bool ShowMeoDataOnly
{
get { return _showMeoDataOnly; }
set
{
if (_showMeoDataOnly != value)
{
_showMeoDataOnly = value;
RaisePropertyChangedEvent("ShowMeoDataOnly");
}
}
}
If I click on the ToggleButton, the value of ShowMeoDataOnly is set accordingly. However, if I set ShowMeoDataOnly to true from code behind, the ToggleButton's visual state does not change to indicate that IsChecked is true. However, if I manually set the ToggleButton's IsChecked property instead of setting ShowMeoDataOnly to true in code behind, the button's visual state changes accordingly.
Unfortunately, switching over to .NET 4/4.5 is not an option right now, so I cannot confirm if this is a .NET 3.5 problem.
Is there anything wrong with my code?
Using a .NET 3.5 project to test this and the binding seems to work for me. Do you have INotifyPropertyChanged implemented on your ViewModel and use it appropriately when ShowMeoDataOnly gets set? You didn't post all your code, so it's hard to tell what the ViewModel is doing.
Here's what I have that worked. When I run the application, the button is selected. That's because ViewModelBase implements INotifyPropertyChanged and I do base.OnPropertyChanged("ShowMeoDataOnly") when the property is set.
MainWindow.xaml
<Window x:Class="ToggleButtonIsCheckedBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ToggleButtonIsCheckedBinding"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<Grid>
<ToggleButton IsChecked="{Binding ShowMeoDataOnly, Mode=TwoWay}">
Show Meo Data Only
</ToggleButton>
</Grid>
</Window>
MainWindowViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ToggleButtonIsCheckedBinding
{
class MainWindowViewModel : ViewModelBase
{
bool _showMeoDataOnly;
public bool ShowMeoDataOnly {
get
{
return _showMeoDataOnly;
}
set
{
_showMeoDataOnly = value;
base.OnPropertyChanged("ShowMeoDataOnly");
}
}
public MainWindowViewModel()
{
ShowMeoDataOnly = true;
}
}
}
ViewModelBase.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.ComponentModel;
namespace ToggleButtonIsCheckedBinding
{
/// <summary>
/// Base class for all ViewModel classes in the application.
/// It provides support for property change notifications
/// and has a DisplayName property. This class is abstract.
/// </summary>
public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable
{
#region Constructor
protected ViewModelBase()
{
}
#endregion // Constructor
#region DisplayName
/// <summary>
/// Returns the user-friendly name of this object.
/// Child classes can set this property to a new value,
/// or override it to determine the value on-demand.
/// </summary>
public virtual string DisplayName { get; protected set; }
#endregion // DisplayName
#region Debugging Aides
/// <summary>
/// Warns the developer if this object does not have
/// a public property with the specified name. This
/// method does not exist in a Release build.
/// </summary>
[Conditional("DEBUG")]
[DebuggerStepThrough]
public void VerifyPropertyName(string propertyName)
{
// Verify that the property name matches a real,
// public, instance property on this object.
if (TypeDescriptor.GetProperties(this)[propertyName] == null)
{
string msg = "Invalid property name: " + propertyName;
if (this.ThrowOnInvalidPropertyName)
throw new Exception(msg);
else
Debug.Fail(msg);
}
}
/// <summary>
/// Returns whether an exception is thrown, or if a Debug.Fail() is used
/// when an invalid property name is passed to the VerifyPropertyName method.
/// The default value is false, but subclasses used by unit tests might
/// override this property's getter to return true.
/// </summary>
protected virtual bool ThrowOnInvalidPropertyName { get; private set; }
#endregion // Debugging Aides
#region INotifyPropertyChanged Members
/// <summary>
/// Raised when a property on this object has a new value.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises this object's PropertyChanged event.
/// </summary>
/// <param name="propertyName">The property that has a new value.</param>
protected virtual void OnPropertyChanged(string propertyName)
{
this.VerifyPropertyName(propertyName);
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
#endregion // INotifyPropertyChanged Members
#region IDisposable Members
/// <summary>
/// Invoked when this object is being removed from the application
/// and will be subject to garbage collection.
/// </summary>
public void Dispose()
{
this.OnDispose();
}
/// <summary>
/// Child classes can override this method to perform
/// clean-up logic, such as removing event handlers.
/// </summary>
protected virtual void OnDispose()
{
}
#if DEBUG
/// <summary>
/// Useful for ensuring that ViewModel objects are properly garbage collected.
/// </summary>
~ViewModelBase()
{
string msg = string.Format("{0} ({1}) ({2}) Finalized", this.GetType().Name, this.DisplayName, this.GetHashCode());
System.Diagnostics.Debug.WriteLine(msg);
}
#endif
#endregion // IDisposable Members
}
}
(Note: ViewModelBase is pulled from this project: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx )
Verify that you DataContext is set up correctly.
DataContext = this;
... in your MainWindow.xaml.cs constructor is the easiest way, assuming the code we're looking at is in the MainWindow class.

Show/Hide views using Visual State Manager silverlight & PRISM

I have an application that display different datasets (users, nationality, etc) on the screen using radOutlookbar.
I have manage to load the required views in each item to display the data with no problem.
I then built views for each dataset (users, nationality, etc) to display the details about each selected item (i.e:user) within the displayed datasets.
Case:
First, I need to display the respective view for each dataset when I click on it's item.
Second, The displayed view will have an option to edit/add the displayed details.
I want to achieve this scenario using state-base-navigation.
So,
I have a PRISM region inside ItemsControl with ItemsPanelTemplate of grid to host the loaded views, basically I load the views for each dataset.
Question,
How should I show/hide the respective view according to the selected dataset using VSM?
Question 2:
Should I be able to define another nested state inside the loaded view to enable the scenario of edit/add details for each view?
If someone have any idea to do this, will be of great help to have a starting code.
Best regards
May be there's other schemes to access VSM but I prefer to create AttachedProperty for it. Let me explain.
Here is VisualState manager
/// <summary>
/// Class will allow to change VisualSate on ViewModel via attached properties
/// </summary>
public static class VisualStateManagerEx
{
private static PropertyChangedCallback callback = new PropertyChangedCallback(VisualStateChanged);
/// <summary>
/// Gets the state of the visual.
/// </summary>
/// <param name="obj">The obj.</param>
/// <returns></returns>
public static string GetVisualState(DependencyObject obj)
{
return (string)obj.GetValue(VisualStateProperty);
}
/// <summary>
/// Sets the state of the visual.
/// </summary>
/// <param name="obj">The obj.</param>
/// <param name="value">The value.</param>
public static void SetVisualState(DependencyObject obj, string value)
{
obj.SetValue(VisualStateProperty, value);
}
/// <summary>
/// DP for 'VisualState'
/// </summary>
public static readonly DependencyProperty VisualStateProperty =
DependencyProperty.RegisterAttached(
"VisualState",
typeof(string),
typeof(VisualStateManagerEx),
new PropertyMetadata(null, VisualStateManagerEx.callback)
);
/// <summary>
/// Visuals the state changed.
/// </summary>
/// <param name="d">The d.</param>
/// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
public static void VisualStateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//Control changeStateControl = d as Control;
FrameworkElement changeStateControl = d as FrameworkElement;
if (changeStateControl == null)
throw (new Exception("VisualState works only on Controls type"));
if (Application.Current.Dispatcher.CheckAccess() == false)
{
// Wrong thread
System.Diagnostics.Debug.WriteLine("[VisualStateManagerEx] 'VisualStateChanged' event received on wrong thread -> re-route via Dispatcher");
Application.Current.Dispatcher.BeginInvoke(
//() => { VisualStateChanged(d, e); }
VisualStateManagerEx.callback
, new object[] { d, e }); //recursive
}
else
{
if (string.IsNullOrEmpty(e.NewValue.ToString()) == false)
{
//VisualStateManager.GoToState(changeStateControl, e.NewValue.ToString(), true);
VisualStateManager.GoToElementState(changeStateControl, e.NewValue.ToString(), true);
System.Diagnostics.Debug.WriteLine("[VisualStateManagerEx] Visual state changed to " + e.NewValue.ToString());
}
}
}
}
now - in XAML you attach it to your ViewModel like this:
<UserControl
xmlns:VSManagerEx=clr-namespace:Namespace.namespace;assembly=Assembly01"
VSManagerEx:VisualStateManagerEx.VisualState="{Binding Path=ViewModelVisualState, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
...
...
Now your VSM in XAML is bound to ViewModelVisualState property in ViewModelBase (or whatever will be bound to DataContext of this UserControl. So Actually in your ViewModelBase you using is like this:
/// <summary>
/// Base class for all 'view-models'
/// </summary>
[Export(typeof(ViewModelBase))]
public abstract class ViewModelBase : INavigationAware, INotifyPropertyChanged
{
private SynchronizationContext parentSyncContent;
#region VisualState
private string viewModelVisualState = string.Empty;
/// <summary>
/// Gets or sets the state of the view model visual.
/// </summary>
/// <value>
/// The state of the view model visual.
/// </value>
public virtual string ViewModelVisualState
{
get { return viewModelVisualState; }
set
{
viewModelVisualState = value;
RaisePropertyChanged(this, "ViewModelVisualState");
}
}
#endregion
/// <summary>
/// Raises the property changed.
/// </summary>
/// <param name="Sender">The sender.</param>
/// <param name="PropertyName">Name of the property.</param>
public void RaisePropertyChanged(object Sender, string PropertyName)
{
parentSyncContent.Post((state) =>
{
if (PropertyChanged != null)
PropertyChanged(Sender, new PropertyChangedEventArgs(PropertyName));
}, null);
}
...
...
So - in any ViewModel that inherit from this ViewModelBase could declare it own VMS states and manage them like this:
[Export(typeof(IViewModel1))
public ViewModel1 : ViewModelBase, IViewModel1
{
private const string VM_STATE_WORKING = "WorkingState";
internal void StartWorking()
{
this.ViewModelVisualState = VM_STATE_WORKING;
...
...
Regards question 2: No - you don't need to declare any additional Views inside anything. Read PRISM documentation about Navigation. There's great examples on how to create View/ViewModel that support various presentation logic.
Is this helpful to you ?

Set the Localizable property of all my forms

Is there a way to automate the set of this property ? we have hundreds of forms that needs to be localized and it will be a nightmare going through all of them setting this property to true.
is there a way to make visual studio set all forms in the solution / project to Localizable = true some how ?
When you create a new Windows Form, it does not have have *.resx file and the related code in the designer.cs file. When you set the Form's Localizable property to True, VS adds the following code to the designer.cs but it also then generates and adds the *.resx file.
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form2));
this.SuspendLayout();
//
// Form2
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Name = "Form2";
this.ResumeLayout(false);
Since VS adds the *.resx file, there is no way to find and replace or cut and paste only code.
I tried to record a VS Macro to automate it however, it would not record changing the Localizable property to True (not sure why)
This temp macro maybe a start for you. You could write get the list of your form filenames and loop through them with the macro code below.
DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer).Activate()
DTE.ActiveWindow.Object.GetItem("WindowsFormsApplication1\WindowsFormsApplication1\Form3.cs").Select(vsUISelectionType.vsUISelectionTypeSelect)
DTE.ActiveWindow.Object.DoDefaultAction()
DTE.Windows.Item(Constants.vsWindowKindProperties).Activate()
It's represented by an entry like the following (adjusted for .NET Framework version) in the form's .resx file:
<metadata name="$this.Localizable" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
The easiest way to automate toggling all the values to true would probably be to run through the Form subclass files, loading their .resx files as XML to test for the presence of the element, and add it if it isn't. Alternately, you could use a ResXResourceReader and ResXResourceWriter to read and write the file contents.
The custom Designer Attribute we set on the DummyUserControl is only used by more derived classes. Suppose you open the DummyUserControl in the designer. In that case, nothing changes cause it looks for the Designer attribute on the BaseType in this case on the UserControl and ignores the one we specified. It applies to Forms as well. So you need a dummy base class where you just set the Designer Attribute.
public class BaseUserControl : DummyUserControl
{
}
[Designer(typeof(MyCustomDesigner), typeof(IRootDesigner))]
public class DummyUserControl : UserControl
{
}
public class MyCustomDesigner : DocumentDesigner
{
/// <inheritdoc />
public override void Initialize(IComponent component)
{
base.Initialize(component);
}
protected override void PreFilterProperties(IDictionary properties)
{
base.PreFilterProperties(properties);
// We set the Localizable property to true then we return a fake property descriptor to disable changing it in the designer.
var localizableDescriptor = properties["Localizable"] as PropertyDescriptor;
if (localizableDescriptor != null)
{
if (localizableDescriptor.GetValue(Component) as bool? == false)
{
localizableDescriptor.SetValue(Component, true);
}
properties["Localizable"] = new LocalizablePropertyDescriptor(localizableDescriptor);
}
}
/// <summary>
/// A simple wrapper where we disallow to change this property in the designer by marking it ReadOnly.
/// </summary>
public class LocalizablePropertyDescriptor : PropertyDescriptor
{
private readonly PropertyDescriptor _source;
/// <inheritdoc />
public LocalizablePropertyDescriptor(PropertyDescriptor source) : base(source) => _source = source;
/// <inheritdoc />
public override bool CanResetValue(object component) => _source.CanResetValue(component);
/// <inheritdoc />
public override object GetValue(object component) => _source.GetValue(component);
/// <inheritdoc />
public override void ResetValue(object component) { }
/// <inheritdoc />
public override void SetValue(object component, object value) => _source.SetValue(component, value);
/// <inheritdoc />
public override bool ShouldSerializeValue(object component) => true;
/// <inheritdoc />
public override Type ComponentType => _source.ComponentType;
/// <inheritdoc />
public override bool IsReadOnly => true;
/// <inheritdoc />
public override Type PropertyType => _source.PropertyType;
}
}

Resources