How can I initialize my WPF Monogame ContentManager? - wpf

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.

Related

Upgrade From WinForms to Telerik

I am trying to upgrade WinForms to Telerik Controls and when I am upgrading this
this.treeAccounting.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.TreeAccountingAfterSelect);
To this new RadControl Statement:
this.treeAccounting.SelectedNode += new Telerik.WinControls.UI.RadTreeViewEventArgs(this.TreeAccountingAfterSelect);
I get an error about best overloaded method match having invalid arguments for the TreeAccountingAfterSelect. Also it says cannot convert from 'method group' to 'Telerik.WinControls.UI.RadTreeNode'. Here is the function event for TreeAccountingAfterSelect.
private void TreeAccountingAfterSelect(object sender, Telerik.WinControls.UI.RadTreeViewEventArgs e)
{
string strSelectedNode = treeAccounting.SelectedNode.Text;
// Since the user can select any node (root, branch, leaf) of a tree in any order -
// cannot presume that they will select a root, then a leaf - so handle accordingly.
if (treeRootNames[(int)TreeNodes.TrialBalance] == strSelectedNode)
{
// Configure the Generator for doing a Trial Balance (detail) report
CrntReport = ReportTypes.TrialBalance;
CrntLocation = Locations.UNKNOWN;
// Based on default settings in the Report Property dialog (from App.Config) initialize
// screen controls.
lblCurrency.Visible = rptProperties.TBShowCurrencyCodes;
cboxCurrencyCode.Visible = rptProperties.TBShowCurrencyCodes;
this.Refresh();
// Setup the selections for the various parameters in the TrialBalance
// Parameters group.
SetupTBControls();
}
return;
}
I'm new to Telerik and I have tried different events and tried changing the parameter passed through the function and for some reason it isn't letting me use it like the WinForms. Can someone tell me where I am not understanding the change in WinForms to Telerik.
Looking at their documentation it seems that there is no SelectedNode event for a RadTreeView.
Instead you have
SelectedNodeChanged Occurs when selected node has been changed.
SelectedNodeChanging Occurs when the selected node is changing
And you don't use the RadTreeViewEventArgs to bind the event handler but a RadTreeViewEventHandler
So perhaps you need to write
this.treeAccounting.SelectedNodeChanged +=
new RadTreeViewEventHandler(this.TreeAccountingAfterSelect);
The syntax for delegate will allow also
this.treeAccounting.SelectedNodeChanged += this.TreeAccountingAfterSelect;

Expression obviously does not return the right value

my application uses MarkupExtensions in order to accomplish automatic translation of the user interface. This works insanely great at runtime but it does not at design-time. Normally this wouldn't be much of a problem but once you have about 40 controls which are bound to translation, you see 40 erros which say "Object not set to an instance." because the Translator is not instanced. Moreover would it be really nice to see how it actually looks when there's translated text instead of "!keyname!". This helps desinging the UI significantly.
Unfortunately my application is very abstract and modular and because I don't want to reference the Localization assembly I had to do some nasty tricks to enable design-time translation.
One class is always in use and safe for use at design-time. It's the Core which gives access to everything (including the Localization assembly, but that one is not instanced at design-time). So I added some code to the static constructor of the Core which looks up for the assembly and creates the Translator through Reflection/Expressions. This obviously works as I got an exception which occured in the Translator's constructor.
But when I try to assign the instance of the Translator to the property in the Core, which will later be used to create design-time translation bindings, I have to notice that there is no instance set. When the MarkupExtensions are created I get an exception which tells me that there's no DesignTimeTranslator set.
I can't figure out why this happens and because of this running at design-time, I can't debug well. I'm not that much into Expressions so I don't know what happens when they fail to execute nor what should be the actual output (but I guess it should be ITranslator).
if (!DesignerProperties.GetIsInDesignMode(new DependencyObject())) return;
try
{
Assembly locA = Assembly.Load(
AssemblyName.GetAssemblyName(Path.Combine(Environment.CurrentDirectory,
"Localization.dll")));
if (locA == null) throw new Exception("No DesignTimeTranslator assembly found.");
Type locT = locA.GetType("Localization.Translator");
if (locT == null) throw new Exception("DesignTimeTranslator type not found.");
ConstructorInfo constructorInfo = locT.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance,
null, Type.EmptyTypes, null);
if (constructorInfo == null) throw new Exception("No constructor found for DesignTimeTranslator.");
NewExpression constrExp = Expression.New(constructorInfo);
Func<object> constructor = Expression.Lambda<Func<object>>(constrExp, null).Compile();
DesignTimeTranslator = (ITranslator)constructor();
MessageBox.Show(DesignTimeTranslator != null ? DesignTimeTranslator.GetType().FullName : "No Translator :(");
}
catch (Exception ex)
{
MessageBox.Show("[DESIGNTIME] Exception occured: {0}{1}".FormatWith(ex.Message, ex.StackTrace));
MessageBox.Show(Path.Combine(Environment.CurrentDirectory,
"Localization.dll"));
}
Here's the translator's constructor:
internal Translator()
{
bool designTime = DesignerProperties.GetIsInDesignMode(new DependencyObject());
if (_instance != null) throw new InvalidOperationException("CanĀ“t create another Translator instance!");
_instance = this;
this._languagePacks = new Dictionary<CultureInfo, LangFormat>();
}
Thanks :)

How can I get my WinForm back after it claims a class is named "?"?

I selected a control on my form and hit the Delete key. It wouldn't delete. I then selected another control, right-clicked, and selected Properties. The Properties pane displayed, but blank. I then got:
If I gave a class the name "?", it certainly was not intentional. How can I unmangle this mangled mess?
UPDATE
The compiler is completely confused, because it tells me, "A namespace cannot directly contain members such as fields or methods" on this line of code:
else if (cmbxSel.Equals("CHECKBOX"))
...and this is just one of 39 errors that all-of-a-sudden "popped up."
UPDATE 2
There is nothing weird looking, AFAICT, in the Designer.cs file. It is just stuff like:
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.ckbxUseScrollViewer = new System.Windows.Forms.CheckBox();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPageRow0 = new System.Windows.Forms.TabPage();
this.lblRow0Element5 = new System.Windows.Forms.Label();
this.lblRow0Element4 = new System.Windows.Forms.Label();
this.lblRow0Element3 = new System.Windows.Forms.Label();
this.lblRow0Element2 = new System.Windows.Forms.Label();
this.lblRow0Element1 = new System.Windows.Forms.Label();
this.lblRow0Element0 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.cmbxRow0Element5 = new System.Windows.Forms.ComboBox();
this.label4 = new System.Windows.Forms.Label();
this.cmbxRow0Element4 = new System.Windows.Forms.ComboBox();
. . .
...and searching for the purported "?" turns up nothing.
UPDATE 3
And there are many other "crazy" error messages in the related code/.cs file, such as:
"Identifier expected" here:
safeText = replaceIllegalCharsWithUnderscore(btnText);
..."Invalid token '!=' in class, struct, or interface member declaration" here:
if (string.Empty != cmbxSel)
..."Method must have a return type" here:
safeText = replaceIllegalCharsWithUnderscore(btnText);
..."Type expected" here:
stringXMLEntry = string.Format("<string name=\"{0}\">{1}</string>\"", btnStringId, btnText);
...and "Type or namespace definition, or end-of-file expected" on the "}" line here:
sb.Append(Environment.NewLine);
}
else if (cmbxSel.Equals("RADIOGROUP"))
IOW, it's as if the compiler has a severe case of vertigo/disorientation.
UPDATE 4
Problem solved; It was all because somehow this:
// and, even before that (if ckbxUseScrollViewer is checked), add the <ScrollView>
private string getXMLForElement(ComboBox cmbxCtrl, Label lblCtrl)
...had become this:
// and, even before that (if ckbxUseScrollViewer is checked), add the <ScrollView> private string getXMLForElement(ComboBox cmbxCtrl, Label lblCtrl)
Once I inserted a crlf (positioned the cursor (I had been the curser prior to that) before the "private") and mashed the Enter button), all was well again. I went from 39 errors and 504 warnings (yes, 504) to 0 and 0.
How that happened when selecting a control in the designer and masching the Delete key, I'll probably never understand, but that must have been what happened...
How I found the source (no pun intended) of the problem was by looking at the first of those warnings:
CSharp.CsParser : A syntax error has been discovered in file C:\DroidLayoutBuilder\DroidLayoutBuilder\Form1.cs on line 389.
...which took me right to that spot.
Isn't it bizarre that such a thing would cause that many errors and warnings, and for the designer to complain so bitterly?!?
UPDATE 5
Oddly enough, I got the err msg in the designer again, but the project runs fine. Perhaps related (???) is I keep getting, in the code-behind file, "You have mixed tabs and spaces. Fix this?" The first couple of times, I selected "Tabify" not knowing how the code got untabbified, but I finally grew tired of the nagging, and selected "Don't show again" - yet, the implied promise to quit the nagging was a bald (or is it bold)-faced lie.

WinForms Designer Exception

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?

Start and Back Button pressed in rapid succession WP7

I asked this question in a similar post but there have been significant updates since then, but still no results so I will try to re-ask the question with the updated information.
Basically I have a pivot view with 4 pivot items. If I create the scenario where I hit the windows key then rapidly press the back key my application will reopen without reconstructing (this is the expected outcome). The functionality of the application is there. I can press application bar buttons etc.
What doesn't work is the pivot items are frozen. If I was on Pivot item A and I press the start and back button quickly I come back to Pivot Item A. If I try to switch Pivot Items, the screen does not update, its "frozen" on Pivot Item A BUT the functionality of Pivot Item B is there. (I know this because the application bar Icons for Pivot Item B are now showing).
I have read many articles on proper tombstoning scenarios and how to approach this problem. My data IS being tombstoned correctly, and upon reactivation the tombstoned data works. No objects are null so I don't have any exceptions being thrown at me.
I check to see if I need to reload the Main ViewModel (I don't need to in this case so the UI elements being created initially are not being re created).
What does fix the problem however is if the application is reconstructed. Lets say I go to the marketplace from my app, let it finish loading and press back, My application will be refreshed and working fine since it properly deactivated and reconstructed istelf. I don't rely on constructors doing all the work so I am not missing any key elements not being set when they aren't fired in the windows/back button scenario.
Does anyone have any idea why my screen would not be updating?
constructor/loaded event/on navigated to event
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if (App.firstTimeLoading == true)
{
App.firstTimeLoading = false;
}
BuildApplicationBar();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
this.DataContext = App.ViewModel;
App.viewIdentifier = StringResource.MainPageView;
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
String bookTitle;
App.Parser.appBookInfoDict.TryGetValue(CPlayerInventoryKeys.kInventoryKeyTitleShortTitle, out bookTitle);
PivotBackground.Title = bookTitle.ToUpper();
CreatePivotItems();
}
if (App.playerController.chapterPlayer.Source == null)
App.restoreStateClass.RestoreState();
//applies the proper background image
if (App.isDarkTheme)
{
BitmapImage bitmapImage = new BitmapImage(new Uri(StringResource.PanoramaBlackImage, UriKind.Relative));
BackgroundImage.ImageSource = bitmapImage;
BackgroundImage.Opacity = .85;
}
else
{
BitmapImage bitmapImage = new BitmapImage(new Uri(StringResource.PanoramaWhiteImage, UriKind.Relative));
BackgroundImage.ImageSource = bitmapImage;
BackgroundImage.Opacity = .5;
}
if (App.firstTimeLoading == false && PivotBackground.SelectedItem != SuggestedPivotItem)
BuildApplicationBar();
else if (PivotBackground.SelectedItem == SuggestedPivotItem)
{
BuildMarketPlaceApplicationBar();
}
base.OnNavigatedTo(e);
}
I found the answer. Since I had a media element open (play/paused) and I was implementing the "non tombstoned" method of hitting windows key and back button very quickly, the media element source was corrupt. Even though I reset this source, apparently it can be ignored and not function properly. All I had to do was add a line of code to the Application Deactivated handler.
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
App.MainAudioPlayer.Source = null; //(only showing line added)
}
The behavior you are describing seems to be solely related to the way you are manipulating data internally and constructing your layout. I tested this both in the emulator and on a couple of physical devices, both producing normal output (even when bound to a view model).
Try creating a new Pivot-based application (without all your data - just using the default template) and see if the problem persists. Also worth mentioning - are you testing on a device or in the emulator?
Are you using transitions from the toolkit?
Are they defined in XAML?
If so that could be the issue. There's a bug which is fixed in the next version.
The solution for now is to remove the transitions or define them in code.

Resources