I know that the way the declaration of the graphics device is suppose to look in the main Game1() constructor is:
GraphicsDeviceManager graphics;
graphics = new GraphicsDeviceManager(this);
then you can use stuff like:
graphics.PreferredBackBufferWidth = 1366;
But if I declare the same inside a separate class, what do I fill in for "this"?
GraphicsDeviceManager graphics;
graphics = new GraphicsDeviceManager(?);
EDIT:
After modifying everything as you said, I now get a error that sends me to this line of code:
/// <summary>
/// Event handler for when the Play Game menu entry is selected.
/// </summary>
void PlayGameMenuEntrySelected(object sender, PlayerIndexEventArgs e, Game game)
{
LoadingScreen.Load(ScreenManager, true, e.PlayerIndex,
new GameplayScreen(game));
}
This program is the menu sample you can get from Microsoft, heavily modified of course, this is the code that executes when you hit enter on the main menu screen with "Play Game" highlighted. I guess the problem is passing the variable.
Edit 2:
I fixed the code I think but now it sent me to this line and I don't know how to edit it.
playGameMenuEntry.Selected += PlayGameMenuEntrySelected;
You need a reference to your Game instance. I'd just pass it to your new class constructor.
For example, if you want to move the GraphicsDeviceManager instance into a separate class, Foo,
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
private Foo _foo;
public Game1()
{
_foo = new Foo(this);
}
protected override void Dispose(bool disposing)
{
if (_foo != null)
{
_foo.Dispose();
_foo = null;
}
base.Dispose(disposing);
}
}
public class Foo : IDisposable
{
private Game _game;
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;
public Foo(Game game)
{
_game = game;
_game.Content.RootDirectory = "Content";
_graphics = new GraphicsDeviceManager(_game);
_spriteBatch = new SpriteBatch(_game.GraphicsDevice);
}
public void Dispose()
{
if (!_spriteBatch.IsDisposed)
{
_spriteBatch.Dispose();
_spriteBatch = null;
}
}
}
Update
It's important to properly dispose of a lot of XNA objects (otherwise, you get memory leaks). See Foo.Dispose() and the Game1.Dispose() override above.
Related
How do I successfully call setPreferredSize in a method? I'm calling setPreferredSize twice. If I remove the call inside the constructor, the panel doesn't appear at all, whereas it had earlier appeared with the undesired size (500,300). This demonstrates that setPreferredSize is being executed in the constructor, but not in the method of the same class. Note that this is the only issue (as far as I have tested) with my code; there's no unexpected interference outside the code below.
...
public abstract class XYGrapher extends JPanel{
...
JFrame frame;
JPanel contentPane;
...
public XYGrapher() {
frame = new JFrame("Grapher");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setPreferredSize(new Dimension(500, 300));
contentPane.setLayout(new SpringLayout());
this.setPreferredSize(new Dimension(500, 300));
frame.setContentPane(contentPane);
frame.pack();
frame.setVisible(true);
contentPane.add(this);
}
//
public void drawGraph(int xPixelStart, int yPixelStart, int pixelsWide, int pixelsHigh) {
...
contentPane.setPreferredSize(new Dimension(pixelsWide, pixelsHigh));
this.setPreferredSize(new Dimension(pixelsWide, pixelsHigh));
...
}
//*/
}
For reference, this is how XYGrapher eventually gets used:
public class GrapherTester extends XYGrapher{
...
public static void main(String[] args) {
GrapherTester g = new GrapherTester();
g.drawGraph(0,0,100,100);
}
}
I have managed to fix the issue in the meantime. Simply add
frame.pack();
to the method.
I am having some issues with bindings using xamarin forms IOS.
I have bindings That display a loading label in the center of the screen when the first page appears.
After The listview loads the data the Loading label is hidden through bindings and the list view is displayed.
In the android project I have in this repo Xamarin forms IOS Android Test
It works fine. In the ios in the repro project the loading label is hidden when the application first loads and will display if you tap on the screen.
If you continue the loading label disappears and you see a blank screen but if you tap on the screen again the list data view appears.
I am thinking this is a bug with xamarin but I am hoping that my bindings are just incorrect. I work around for this issue would be appreciated.
I also two other problems. When you click on a list view item and the navigate back the data is not refreshed because onappearing is not triggered.
In android it is triggered without an issue. Sometimes onappearing does trigger after you tap on the screen like the steps mentioned above.
The last issue is that when switching between tabs IOS does not trigger on appearing. With android it does.
Any help on this issue would be greatly appreciated. I have done extensive searching on solutions for these problems and have yet to find and answer.
Thanks!
Here is some code snippets to help. This code is also in the GitHub repo if you want to test it out.
In XAML
<Label x:Name="xEmptyListView"
FontSize="16"
HorizontalOptions="CenterAndExpand"
HorizontalTextAlignment="Center"
VerticalOptions="CenterAndExpand"
Text="{Binding ListViewVisibleText, Mode=TwoWay}"
IsVisible="{Binding IsListViewLabelEmptyVisible, Mode=TwoWay }"/>
<ListView x:Name="ItemsListView"
ItemsSource="{Binding Items}"
VerticalOptions="FillAndExpand"
HasUnevenRows="true"
RefreshCommand="{Binding LoadItemsCommand}"
IsPullToRefreshEnabled="true"
IsRefreshing="{Binding IsBusy, Mode=OneWay}"
CachingStrategy="RecycleElement"
ItemSelected="OnItemSelected"
IsVisible="{Binding IsListViewVisible, Mode=TwoWay}"
IsEnabled="{Binding IsActivityRunning, Mode=TwoWay, Converter={StaticResource InverseBooleanConverter}}">
ViewModel
private bool activityRunning { get; set; }
public bool IsActivityRunning
{
get { return activityRunning; }
set
{
if (activityRunning == value)
return;
activityRunning = value;
OnPropertyChanged("IsActivityRunning");
}
}
private string listViewVisibleText { get; set; }
public string ListViewVisibleText
{
get { return listViewVisibleText; }
set
{
if (listViewVisibleText == value)
return;
listViewVisibleText = value;
OnPropertyChanged("ListViewVisibleText");
}
}
private bool listViewLabelEmptyVisible { get; set; }
public bool IsListViewLabelEmptyVisible
{
get
{
if (Items == null || Items.Count == 0)
{
if (IsBusy)
{
ListViewVisibleText = "Loading...";
}
else
{
ListViewVisibleText = "No Items found";
}
listViewLabelEmptyVisible = true;
}
else
{
ListViewVisibleText = string.Empty;
listViewLabelEmptyVisible = false;
}
OnPropertyChanged("IsListViewLabelEmptyVisible");
return listViewLabelEmptyVisible;
}
}
private bool listViewVisible { get; set; }
public bool IsListViewVisible
{
get
{
if (Items == null || Items.Count == 0)
{
listViewVisible = false;
}
else
{
listViewVisible = true;
}
OnPropertyChanged("IsListViewVisible");
return listViewVisible;
}
}
XAML.cs
protected override void OnAppearing()
{
base.OnAppearing();
viewModel.LoadItemsCommand.Execute(null);
}
I am using notify property changed. It is standard code
This is what my view model inherits for the notifyproperty changed
public class ItemsViewModel : BaseViewModel
which base viewmodel inherits from the observable object
public class BaseViewModel : ObservableObject
When you create a test xamarin project this is the way it looks.
public class ObservableObject : INotifyPropertyChanged
{
/// <summary>
/// Sets the property.
/// </summary>
/// <returns><c>true</c>, if property was set, <c>false</c> otherwise.</returns>
/// <param name="backingStore">Backing store.</param>
/// <param name="value">Value.</param>
/// <param name="propertyName">Property name.</param>
/// <param name="onChanged">On changed.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
protected bool SetProperty<T>(
ref T backingStore, T value,
[CallerMemberName]string propertyName = "",
Action onChanged = null)
{
if (EqualityComparer<T>.Default.Equals(backingStore, value))
return false;
backingStore = value;
onChanged?.Invoke();
OnPropertyChanged(propertyName);
return true;
}
/// <summary>
/// Occurs when property changed.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises the property changed event.
/// </summary>
/// <param name="propertyName">Property name.</param>
protected void OnPropertyChanged([CallerMemberName]string propertyName = "")
{
var changed = PropertyChanged;
if (changed == null)
return;
changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Activity running gets set when items are loading etc.
This all works on android. IOS it doesn't.
Sometimes the navigation behaviours are different from iOS and Android. If OnAppearing is not working, you can try to use MessageCenter https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/messaging-center/ to trigger data loading.
I figured this one out. The way I was handling the bindings with showing the label and hiding the list view and vice versa was interfering with the way that IOS handles requests. I removed the bindings and set the controls directly using a property changed handler on the list view. That fixed the on appearing problems for the tabs, the back button etc.
I have a class that I am applying multi-threading to. I would like to only allow 1 thread to 'startSpeaking()' at one time. Here is my attempt:
class VoiceEffect
{
SpeechSynthesizer reader = new SpeechSynthesizer();
static readonly object _locker = new object();
public void createVoiceThread(string str)
{
Thread voicethread = new Thread(() => startSpeaking(str)); // Lambda Process
voicethread.IsBackground = true;
voicethread.Start();
}
public void startSpeaking(string str)
{
lock (_locker)
{
reader.Rate = -2; // Voice effects.
reader.Volume = 100;
reader.Speak(str);
}
}
}
I am also calling createVoiceThread() method from another class. It is called by a similar convention in another class. E.g.
class Program
{
static void Main(string[] args)
{
VoiceEffect ve = new VoiceEffect();
string text = "Hello world, how are you today? I am super-duper!!";
for( int i=0 ; i < 10 ; i++ )
{
ve.createVoiceThread(text);
ve.startSpeaking(text);
Thread.Sleep(1000);
}
}
}
My question is how can I modify this program so that when startSpeaking() is called by any thread, that it only plays a single speech pattern at a time.
I know this question's old as hell, but if I'm understanding your question correctly (that you want all the speech done sequentially, as if it were done on a single thread) you can do something like this:
static class VoiceEffect
{
SpeechSynthesizer reader = new SpeechSynthesizer();
private volatile bool _isCurrentlySpeaking = false;
/// <summary>Event handler. Fired when the SpeechSynthesizer object starts speaking asynchronously.</summary>
private void StartedSpeaking(object sender, SpeakStartedEventArgs e)
{ _isCurrentlySpeaking = true; }
/// <summary>Event handler. Fired when the SpeechSynthesizer object finishes speaking asynchronously.</summary>
private void FinishedSpeaking(object sender, SpeakCompletedEventArgs e)
{ _isCurrentlySpeaking = false; }
private VoiceEffect _instance;
/// <summary>Gets the singleton instance of the VoiceEffect class.</summary>
/// <returns>A unique shared instance of the VoiceEffect class.</returns>
public VoiceEffect GetInstance()
{
if(_instance == null)
{ _instance = new VoiceEffect(); }
return _instance;
}
/// <summary>
/// Constructor. Initializes the class assigning event handlers for the
/// SpeechSynthesizer object.
/// </summary>
private VoiceEffect()
{
reader.SpeakStarted += new EventHandler<SpeakStartedEventArgs>(StartedSpeaking);
reader.SpeakCompleted += new EventHandler<SpeakCompletedEventArgs>(FinishedSpeaking);
}
/// <summary>Speaks stuff.</summary>
/// <param name="str">The stuff to speak.</param>
public void startSpeaking(string str)
{
reader.Rate = -2; // Voice effects.
reader.Volume = 100;
// if the reader's currently speaking anything,
// don't let any incoming prompts overlap
while(_isCurrentlySpeaking)
{ continue; }
reader.SpeakAsync(str);
}
/// <summary>Creates a new thread to speak stuff into.</summary>
/// <param name="str">The stuff to read.</param>
public void createVoiceThread(string str)
{
Thread voicethread = new Thread(() => startSpeaking(str)); // Lambda Process
voicethread.IsBackground = true;
voicethread.Start();
}
}
This gives you a singleton class that will manage all threads, and all threads will share the _isCurrentlySpeaking variable, which will mean that no speech prompts will ever overlap each other since they'll all have to wait until the variable is cleared before speaking. What I cannot guarantee is the order the prompts will be read (i.e., take control of the message-processing queue), if you submit multiple prompts to the queue while there's a prompt being spoken aloud already. Either way, this should pretty much work.
Your question isn't clear, but you have a single lock variable (_locker) which is static - that means only one thread can ever be executing startSpeaking at a time. It's not clear whether you're trying to make threads wait for each other, or whether your question is because you don't want them to wait for each other.
Either way, having a single static lock used like this is distinctly dubious, IMO. If you can really only effectively have one useful instance of this class, consider making it a singleton. (Generally not nice in terms of design.) If it's fine to have multiple independent instances, then make them independent by making the _locker variable an instance variable.
(I'd also strongly advise you to start following .NET naming conventions.)
I have a consistent, repeatable 120 second hang whenever the application calls
this.cacheProvider.Add(new CacheItem(cacheKey, data, this.regionName), cachePolicy);
at line 60 of the CachedDataSource.cs of the sample.. The .Add method is internal to Microsoft's DLL and I don't have code to it. Here are my parameters:
cacheKey = "listofCompanies"
data = // this is an EF 4.0 database first model class with 70 entries... result from IQueryable
this.regionName = "companies"
Reproducing the error:
I have a database-first EF4.0 project that I recently upgraded to 4.1 by adding the "EntityFramework" reference and a ContextGenerator to my DAL.
If I undo these changes, then my application is instantly performant.
My DAL and repository are stored in a separate DLL from my MVC application. Not sure if this is playing a part of the issue.
About my repository
/// Sample repository. Note that I return List<T> as IEnumerable,
/// and I use IDisposable
///
public class CompanyRepository : DisposableBase, ICompanyRepository
{
public IEnumerable<CompanyDetail> GetOneCompany(int? CompanyID)
{
var t = from c in _entities.CompanyDetail
where c.CompanyID == CompanyID.Value
select c;
return t.ToList();
}
}
/// <summary>
/// Disposable implementation based on advice from this link:
/// from Http://www.asp.net/entity-framework/tutorials/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
/// </summary>
public class DisposableBase : IDisposable
{
protected TLSAdminEntities1 _entities;
public DisposableBase()
{
_entities = new TLSAdminEntities1();
disposed = false;
}
private bool disposed ;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_entities.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
Question
Is this a bug, or am I using EF4.1, or the Caching layer incorrectly?
You mention that data is the result of IQueryable. Have you tried to perform .ToList() first on the data before sending it over to cache?
There is a program that I am working on and Im absolutly lost even at how to begin this. I am using Visual Studio C# Windows App Form.
What I need to do is allow the user to enter any path location they want and the program will return the Name of the file/folder; Path; date and size, and this will also be done for sub directories.
I found some code in the MSDN site and I am trying to use it and modify it for the first part of this project, but keep receiving error messages. Some of the messages indicate that there is more than one entry ie (static void Main() and using namespace Detailed).
This is what I have so far, a form with rich text box and the FolderBrowserDialog and it seems as I can't get beyond this point without so many errors.
This is under Form1.Designer.cs:
<i>namespace Detailed
{
partial class Form1
{
///
/// Required designer variable.
///
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.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.SuspendLayout();
//
// folderBrowserDialog1
//
this.folderBrowserDialog1.HelpRequest += new System.EventHandler(this.folderBrowserDialog1_HelpRequest);
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(12, 32);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(167, 23);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
//
// openFileDialog1
//
this.openFileDialog1.FileName = "openFileDialog1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.richTextBox1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
}
}
For the For1.cs this is what I have so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
public class FolderBrowserDialogExampleForm : System.Windows.Forms.Form
{
private FolderBrowserDialog folderBrowserDialog1;
private OpenFileDialog openFileDialog1;
private RichTextBox richTextBox1;
private MainMenu mainMenu1;
private MenuItem fileMenuItem, openMenuItem;
private MenuItem folderMenuItem, closeMenuItem;
private string openFileName, folderName;
private bool fileOpened = false;
public partial class Form1 : Form
{
public Form1()
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
{
}
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// FolderBrowserDialogExampleForm
//
this.ClientSize = new System.Drawing.Size(284, 262);
this.Name = "FolderBrowserDialogExampleForm";
this.ResumeLayout(false);
}
}
I'm still new to programing and hope I can get this figured out asap as I was requested to have this no later than Thursday morning est. I had the Rich TextBox in the Form, but removed it because of too many errors.
This is the code I found. I know this is just part of what I need to do, but when reading through the code I noticed that maybe I can apply what is needed to the form and then break up the code and put the pieces of code where I need them. This is the code I am following
Here is an error message I am receiving with Form1.Designer.cs - there are 14 of these same errors:
‘Detailed.form1’ does not contain a definition for ‘Form1_Load’ and no extension method ‘Form1_Load’ accepting a first argument of type ‘Detailed.Form1’ could be found (are you missing a using directive or an assembly reference?)
The first thing you want is a dialog prompting the user for a directory.
So get rid of all that code, start a new project win form and place a textbox in your form and a button in your form.
Simple enough one text box and one button. Now in the click event of your button "Browse", have you, you write code to open an instance of the FolderBrowserDialog class and you .ShowDialog().
To get this path:
Here is a sample screen output:
The code is fairly straightforward, look at my picture and how much code i have to do this.