WinForms Designer Exception - winforms

A WinForms form that includes a UserControl throws an exception when I attempt to display it in design mode, but runs properly when the program is ran or debugged.
The designer says:
The variable 'fpInfoA' is either undeclared or was never assigned.
ResearchTool fMain.Designer.cs Line:282 Column:1
Call Stack
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.Error(IDesignerSerializationManager manager, String exceptionText, String helpLink)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager manager, CodeStatement statement)
However, it looks like the variable is assigned as I would expect in InitializeComponent
private void InitializeComponent()
{
// ... (Order of statements is same as in actual code) ...
this.tpFpA = new System.Windows.Forms.TabPage();
this.fpInfoA = new ResearchTool.FPInfo();
// ...
this.tpFpA.Controls.Add(this.fpInfoA); // THIS LINE BLOWS UP IN DESIGN MODE
}
Thoughts on how to track down this issue? For example, is there a way to debug initialization of the designer?

One workaround in case you can't fix the issue, would be to surround the offending bits of code with checks for DesignMode.
As in:
private void InitializeComponent()
{
...
if(!DesignMode)
{
this.fpInfoA = new ResearchTool.FPInfo();
}
...
}
This can also speed it up a little bit if it's doing things that aren't needed in design mode and that are quite slow, like connecting to databases or similar.

As Hans Olsson said, this potentially could be resolved by checking for design-mode and disabling offending logic.
This error will also trigger if there is any issue with the constructor of your UserControl. If there is an exception caused when the designer instantiates your UserControl, the designer will fail. In my case, the failure resulted in the same "[...] is either undeclared or was never assigned" error.
For example, see the following user control:
public class MyUserControl : UserControl {
public MyUserControl()
{
InitializeComponent();
throw new Exception(); //Causes a designer error.
}
}
Now, when observing the designer for a form that contains this MyUserControl, we will see something similar to the following:
I cannot say if the designer is like this for previous versions of Visual Studio; but as for Visual Studio 2017, you can clearly see what happened.
The designer failed because a System.Exception was thrown. As a result, the variable [REDACTED] was thought to be undeclared or never assigned when in fact the auto-generated designer code was correct. The issue was with the MyUserControl's constructor.
Now, if you need to put logic that depends on external services/resources inside the control's constructor, you need to indicate that it should only occur during runtime. Alternatively, you can provide mock-up resources for design-time.
To do this, you can use the LicenseManager and check its current UsageMode.
The modified code below only throws the exception in runtime now, and the designer doesn't have the error anymore.
public class MyUserControl : UserControl {
public MyUserControl()
{
InitializeComponent();
if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
{
throw new Exception(); //No longer fails in design-time.
}
}
}

You will find the information on how to trace design time code execution at:
What information do you need to fix a problem, which occurs with your products at design time?

Related

Why Can't I Use My DbContext Type?

I'd like to access some static properties of my DbContext type in a WPF Window. I thought I could use the same XAML that I use to refer to individual entities:
<Window.Resources>
<entity:Account x:Key="account"/> //Works fine
<entity:MyEntities x:Key="myEntities"/> //Throws an error!
</Window.Resources>
I get this error:
No connection string named 'MyEntities' could be found in the application config file.
Why is it treating the DbContext type (MyEntities) differently than the Account entity? Is there an easy way I can access the static properties of my MyEntities type?
The syntax you used is for creating instances, not static properties. If you want to access a static property you need to use the x:Static markup extension
<Window.Resources>
<entity:Account x:Key="account" SomeProperty={x:Static entity:MyEntities.MyProperty}/>
</Window.Resources>
The above xaml would be similar to the C# code
var account = new Account()
{
SomeProperty = MyEntities.MyProperty
};
this.Resources["account"] = account;
See that you are calling new Account(), if you called new MyEntites() (like your original example did) you get the error you where getting.
It appears that particular error results due to the static constructor that I placed in my DbContext. When I remove the static constructor the error changes to:
Object reference not set to an instance of an object.
As it turns out, the original error doesn't prevent me from compiling or running my application. I changed my code to use Scott Chamberlain's suggestion (which produces a similar ignorable error) because it is much cleaner and I can access the static properties on the DbContext just fine in spite of Visual Studio's complaints. Thanks, everyone, for the help and suggestions.

How can I initialize my WPF Monogame ContentManager?

I have followed the monogame wpf sample and the old XNA wpf sample to create a view in WPF with a loaded model through monogame (I'm also using mvvmlight but that shouldn't matter much I hope).
Everything else works except the contentManager I.e. Making a cube out of vertices is displayed fine with a local instance of GraphicsDevice
Depending on whether I use IntPtr.Zero or the actual window handle to create the instance of GraphicsDevice I get a different error and neither give many details so I don't know which I should persue...
When I use IntPtr.Zero
_services = new ServiceContainer();
_services.AddService(typeof(IGraphicsDeviceService), _graphicsDeviceService);
ContentManager content = new ContentManager(_services, "");
var model = content.Load<Model3D>("psp"); // At this line
I get an error about
"The type initializer for 'Microsoft.Xna.Framework.TitleContainer' threw an exception."
Inner Exception: The process has no package identity. (Exception from HRESULT: 0x80073D54)
But when I use the Actual WindowPointer I get this error
Managed Debugging Assistant 'FatalExecutionEngineError' has detected a problem in 'E:\Documents\Visual Studio 2013\Projects\XSITE2DEV\xSite2Dev\MvvmMonogameTest\bin\Debug\MvvmMonogameTest.vshost.exe'.
Additional information: The runtime has encountered a fatal error. The address of the error was at 0x71985144, on thread 0x5f38. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.
In the GraphicsDeviceService creating the first instance of GraphicsDevice
I get my window pointer by using these methods
/// <summary>
/// Gets a reference to the singleton instance.
/// </summary>
public static GraphicsDeviceService AddRef(int width, int height)
{
var singletonInstance = SimpleIoc.Default.GetService(typeof(IGraphicsDeviceService)) as GraphicsDeviceService;
// Increment the "how many controls sharing the device" reference count.
if (Interlocked.Increment(ref _referenceCount) == 1)
{
// If this is the first control to start using the
// device, we must create the device.
singletonInstance.EnsureGraphicsDevice();
}
return singletonInstance;
}
private void EnsureGraphicsDevice()
{
if (_graphicsDevice != null)
return;
//CreateDevice(IntPtr.Zero, 1, 1);
CreateDevice(new WindowInteropHelper(Application.Current.MainWindow).Handle, 1, 1);
}
private void CreateDevice(IntPtr windowHandle, int width, int height)
{
_parameters = new PresentationParameters
{
BackBufferWidth = Math.Max(width, 1),
BackBufferHeight = Math.Max(height, 1),
BackBufferFormat = SurfaceFormat.Color,
DepthStencilFormat = DepthFormat.Depth24,
DeviceWindowHandle = windowHandle,
PresentationInterval = PresentInterval.Immediate,
IsFullScreen = false
};
_graphicsDevice = new GraphicsDevice(
GraphicsAdapter.DefaultAdapter,
GraphicsProfile.HiDef,
_parameters);
if (DeviceCreated != null)
DeviceCreated(this, EventArgs.Empty);
}
I feel like using the actual window pointer is the correct approach but the error has no further details so I can't go anywhere with it..
I came across a similar error while using an implementation as yours. For me, it occured because Game.Instance was null and if you look up the source code of GraphicsDevice at the MonoGame source, you will find that the constructor depends on that (at least in OpenGL).This link could be helpful:
https://github.com/mono/MonoGame/issues/2586
Basically, you have two options:
Bringing a Game in (e.g. inheriting from Game) will set Game.Instance in the constructor
Customizing the MonoGame Source to use your Handle
By the way I am not 100% sure that this is what is causing your error message.
I know that this post is old and I am quite likely too late but this may be helpful for anybody else who is experiencing this error.

from VBS to WPF via COM

we have a nasty (or maybe a trivial?) issue.
There is a WPF control. It has 2 interfaces, the main and one for automated testing purpose. Defined this way:
[ComVisible(true)]
[Guid("xxx")]
public interface IXXXXXTest
{
[DispId(1)]
void Test1(int index);
}
[ComVisible(true)]
public interface IXXXXX
{
void Main1(index);
}
[ComVisible(true)]
[Guid("xxx")]
ClassInterface(ClassInterfaceType.None)]
public partial class XXXXX_WPF_CONTROL : UserControl,
IXXXXX,
IXXXXXTest
{
...
}
Now we are trying to reach it from VBS.
Try 1)
Set Ctrl = GetControl(...) <---- this is ok
Ctrl.Test1(0) <---- Object doesn't support this property or method: 'Ctrl.Test1'
Set Ctrl = GetControl(...) <---- this is ok
Ctrl.Main1(0) <---- this is ok
So it works fine for the "main" interface but for the test interface.
This seems ok(?), because as far as I know VBS reaches the "main" interface only via IDispatch if there is no IDispatchEx. So I added a property to the IXXXXX to get the test interface.
[ComVisible(true)]
public interface IXXXXX
{
void Main1(index);
IXXXXXTest Test { get;}
}
....
public IXXXXXTest Test
{
get { return this as IXXXXXTest; }
}
Great, so now I can reach this IXXXXTest interface via the "main" interface.
Try 2)
VBS:
Set Ctrl = GetControl(...) <---- this is ok
Set CtrlTest = Ctrl.Test <----- this is ok
CtrlTest.Test1(0) <---- Object doesn't support this property or method: 'CtrlTest.Test1'
:(
Note that, for an other .NET control of us the "Try1" works, without any trick!
So probably due to the WPF something different?
Also, changing the
ClassInterface(ClassInterfaceType.None)]
into anything else (AutoDispatch / AutoDual), or leaving it makes the WPF control unusable.
Besides that this is also how it should be by this article: Is it possible to package WPF window as COM Object
Do you have any idea what could be the problem?
Thank much in advance!
Scripting languages can only use the default interface on a class. You've got more than one so at least one of them will not be usable. And method names may be renamed if they conflict with other declarations. I'd assume you obfuscated the real names in your question so hard to diagnose such a renaming happening from what you posted.
Best thing to do is to temporarily apply the [InterfaceType(ComInterfaceType.InterfaceIsDual)] attribute on your interface types. Which allows you to generate a type library with Tlbexp.exe which you can then view with the OleView.exe utility, File + View Typelib command. You'll see the exact names of the methods and you'll see which interface is the [default] one on the coclass. From there you should have little trouble modifying your declarations so they'll work in a scripting language.

Why do I get error "ArgumentException was thrown on "ViewModelLocator": Cannot create an instance of "ViewModelLocator"

I have narrowed down to a simple method where I am attempting to fill an Observable collection from an entity model. I don't know if I'm doing it correctly.
Note: this appears to be a designer error. I can build and run the program...so it appears.
private ObservableCollection<LessonGroup> lessonGroups;
public ObservableCollection<LessonGroup> LessonGroups
{
get { return LessonGroups; }
set { lessonGroups = value; RaisePropertyChanged("LessonGroups"); }
}
private void GetLessonGroups()
{
//this using statement causes ArgumentException
using (MyEntities ae = new MyEntities())
{
foreach (LessonGroup lg in ae.LessonGroups)
{
LessonGroups.Add(lg);
}
}
}
Exception is as follows:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)
at System.Data.EntityClient.EntityConnection..ctor(String connectionString)
at System.Data.Objects.ObjectContext.CreateEntityConnection(String connectionString)
at System.Data.Objects.ObjectContext..ctor(String connectionString, String defaultContainerName)
at IMPACT.ARCTrainer.Model.ARCTrainerEntities..ctor() in C:\Users\Leland\Documents\Visual Studio 2010\Projects\ARCTrainer\Model\ARCTrainer.Designer.cs:line 56
at IMPACT.ARCTrainer.ViewModel.LessonsViewModel.GetLessonGroups() in C:\Users\Leland\Documents\Visual Studio 2010\Projects\ARCTrainer\ViewModel\LessonsViewModel.cs:line 171
at IMPACT.ARCTrainer.ViewModel.LessonsViewModel..ctor(ViewModelLocator viewModelLocator) in C:\Users\Leland\Documents\Visual Studio 2010\Projects\ARCTrainer\ViewModel\LessonsViewModel.cs:line 37
at IMPACT.ARCTrainer.ViewModel.ViewModelLocator..ctor() in C:\Users\Leland\Documents\Visual Studio 2010\Projects\ARCTrainer\ViewModel\ViewModelLocator.cs:line 46
GetLessonGroups seems to be called within the constructor of your class LessonsViewModel.
This method make a call to MyEntities and it looks like this Entity Framework context is not is the same project that the GUI project.
To resolve your issue, the best way you have is to check wether you are in Design mode or not. If you are using MVVM Light, you can check the IsInDesignMode property (and thus, call the GetLessonGroups method only if the property is false).

Why Would a Dependency-Property Implementation Crash My Application When I Provide a Default Value?

Why would a dependency-property implementation crash my application when I provide a default value?
This segment of code is in the class declaration for my UserControl object. Everything works fine - it compiles and runs perfectly.
public static System.Windows.DependencyProperty DepProp
= System.Windows.DependencyProperty.Register( "Rect",
typeof(System.Windows.Shapes.Rectangle),
typeof(FooControl));
public System.Windows.Shapes.Rectangle Rect
{
get
{ return ((System.Windows.Shapes.Rectangle)(GetValue(DepProp))); }
set
{ SetValue(DepProp, value); }
}
However, when I add the default value to the dependency property:
The code compiles, but crashes with a fatal exception when it tries to instantiate the UserControl.
For reference, my code now looks like this - with the PropertyMetaData line added:
public static System.Windows.DependencyProperty DepProp
= System.Windows.DependencyProperty.Register( "Rect",
typeof(System.Windows.Shapes.Rectangle),
typeof(FooControl),
new System.Windows.PropertyMetadata(new System.Windows.Shapes.Rectangle()));
public System.Windows.Shapes.Rectangle Rect
{
get
{ return ((System.Windows.Shapes.Rectangle)(GetValue(DepProp))); }
set
{ SetValue(DepProp, value); }
}
Removing the PropertyMetadata from the call to Register() causes the program to function perfectly, without any crashes or any other problems. But I need the default value for later code. How can I get it to accept the default value without crashing?
When it crashes, the following exceptions are shown in the output window:
A first chance exception of type 'System.ArgumentException' occurred in WindowsBase.dll
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
I need to get this working ASAP, so any advice would be awesome!
Short answer:
Dependency property default values need to be thread safe (e.g. inherit from System.Windows.Freezable) but System.Windows.Forms.Rectangle isn't.
Long answer:
http://social.msdn.microsoft.com/forums/en-US/wpf/thread/2cb12481-ef86-40b7-8333-443598d89933/
Hint:
If you are using Visual Studio it really helps to let the IDE break on every exception being thrown. Just go to "Debug" -> "Exceptions" and check "Common Language Runtime Exceptions" "Thrown".
Then you'll be prompted and get the exception message which in your case looks like this: "Additional information: Default value for the 'Rect' property cannot be bound to a specific thread."

Resources