Current Context error - c#

I am having trouble calling out Method Globals.Global.InstantiateBlowerObj(); in public frmMain(). I am getting the error "The name 'Globals.Global.InstantiateBlowerObj' does not exist in the current context." I have all the classes and methods as public and I cant figure this out.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WetVacClient;
using Globals;
using Globals.Global;
namespace Globals
{
public class Global
{
public Blower[] _Blower = new Blower[4];
public void InstantiateBlowerObj()
{
for (int i = 1; i < 4; i++)
_Blower[i] = new Blower(i);
}
}
}
namespace WetVacClient
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
Globals.Global.InstantiateBlowerObj();
}
}
}

You need to make both the method and _Blower Property Static
public static Blower[] _Blower = new Blower[4];
public static void InstantiateBlowerObj()
{
for (int i = 1; i < 4; i++)
_Blower[i] = new Blower(i);
}
Otherwise create an intance of Global and call it's instance method (but that's not what you want I think).
Globals.Global g=new Globals.Global();
g.InstantiateBlowerObj();

Make it static.
You are trying to access a non-static member in an static context.
public static void InstantiateBlowerObj()
{
for (int i = 1; i < 4; i++)
_Blower[i] = new Blower(i);
}

Related

Run method from another class to scroll listbox to bottom

I want to autoscroll WPF ListBox to bottom automatically. I have two classes - one is Timer.cs and another one is MainWindow.xaml.cs
Here is Timer.cs:
using System;
using System.Configuration;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Importer_WPF
{
class Timer
{
public static readonly string MinutesExecution = ConfigurationManager.AppSettings["MinutesExecution"];
static System.Threading.Timer timer;
public static void StartTimer()
{
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(Convert.ToDouble(MinutesExecution));
timer = new System.Threading.Timer((e) =>
{
Task.Delay(100).ContinueWith(_ => App.Current.Dispatcher.Invoke(() => MainWindow.Names.Add(DateTime.Now.ToString())));
MainWindow.AutoScroll(); // Problem is here
}, null, startTimeSpan, periodTimeSpan);
}
public static void StopTimer()
{
timer.Change(Timeout.Infinite, Timeout.Infinite);
}
}
}
MainWindow.xaml.cs:
using System;
using System.Collections.ObjectModel;
using System.Configuration;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Input;
namespace Importer_WPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public static ObservableCollection<string> Names { get; set; }
public static bool IsCheckedYes { get; set; }
[Obsolete]
public MainWindow()
{
InitializeComponent();
}
public void AutoScroll()
{
int itemCount = ConsoleOutput.Items.Count - 1;
if (itemCount > -1)
ConsoleOutput.ScrollIntoView(ConsoleOutput.Items[itemCount]);
}
}
}
Debugger is giving this message:
Severity Code Description Project File Line Suppression State
Error CS0120 An object reference is required for the non-static field,
method, or property 'MainWindow.AutoScroll()'
Any hints how to edit code structure so it will not produce errors?
You need to get a reference to the instance of mainwindow class which is in memory.
((MainWindow)Application.Current.MainWindow).AutoScroll();

Change button background image using method in Winforms

My code for Form
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;
namespace YAHTZEE
{
public partial class GameMainWindow : Form
{
public GameMainWindow()
{
InitializeComponent();
}
private void buttonRollDice_Click(object sender, EventArgs e)
{
DiceManager dm = new DiceManager();
dm.intDice_1_Roll();
dm.intDice_2_Roll();
dm.intDice_3_Roll();
dm.intDice_4_Roll();
dm.intDice_5_Roll();
Class1 c1 = new Class1();
c1.buttonDice_1Manager();
}
}
}
My class for generating random number for all the dice.
This works perfectly fine.
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;
namespace YAHTZEE
{
public class DiceManager
{
Random rnd = new Random();
public int intDice_1_Roll()
{
int intDice_1 = rnd.Next(1, 7);
return intDice_1;
}
public int intDice_2_Roll()
{
int intDice_2 = rnd.Next(1, 7);
return intDice_2;
}
public int intDice_3_Roll()
{
int intDice_3 = rnd.Next(1, 7);
return intDice_3;
}
public int intDice_4_Roll()
{
int intDice_4 = rnd.Next(1, 7);
return intDice_4;
}
public int intDice_5_Roll()
{
int intDice_5 = rnd.Next(1, 7);
return intDice_5;
}
}
}
Class to change button background image.
This is where my problem is, the code works if I put it on my form but it does nothing when I make it a method on another class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YAHTZEE.Properties;
namespace YAHTZEE
{
class Class1 : GameMainWindow
{
public void buttonDice_1Manager()
{
DiceManager dm = new DiceManager();
if (dm.intDice_1_Roll() == 1)
{
buttonDice_1.BackgroundImage = Properties.Resources.Dice1;
}
}
}
}
Am I missing something?
P.S. I want them to be separated because there are a lot of things to consider making my code very long.
In class1, try changing your method to:
public System.Drawing.Bitmap dice1Manager(int diceRoll)
{
if(diceRoll == 1)
return Properties.Resources.Dice1;
}
In your main class, change what you have to:
private void buttonRollDice_Click(object sender, EventArgs e)
{
DiceManager dm = new DiceManager();
Class1 c1 = new Class1();
button_dice1.BackgroundImage = c1.dice1Manager(dm.intDice_1_Roll());
dm.intDice_2_Roll();
dm.intDice_3_Roll();
dm.intDice_4_Roll();
dm.intDice_5_Roll();
}

C# Ninject: How to inject dependency depending on field?

A class named Round is a level design in a adventure game.Its filed number indicate which level the player is in. Different level will have different figures to guess. The figures are produced by field FigureFactory.
The question is: using Ninject for dependency injection, how can I set the cooresponding FigureFactory to the variable round, according to the field number? For instance, when field number==1, the cooresponding factory is FigureFactory1, when field number==2, the cooresponding factory is FigureFactory2?
using GuessFigure.Model.Factory;
using Ninject;
using Ninject.Modules;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ninject.Planning.Bindings;
namespace GuessFigure.Model
{
class Round
{
private int number=1;
private FigureFactory figureFactory;
[Inject]
internal void SetFigureFactory(FigureFactory figureFactory)
{
this.figureFactory = figureFactory;
}
public int[] GetCurrentRoundFigures()
{
return figureFactory.Produce(number);
}
}
//this not work, help please
class RoundModule : NinjectModule
{
public override void Load()
{
Bind<FigureFactory>().To<FigureFactoryRound1>().When(request=>request.ParentRequest.Target.Type.GetField("number").Equals(1));
Bind<FigureFactory>().To<FigureFactoryRound2>().When(request => request.Target.Type.GetField("number").Equals(2));
Bind<FigureFactory>().To<FigureFactoryRound3>().When(request => request.Target.Type.GetField("number").Equals(3));
Bind<FigureFactory>().To<FigureFactoryRound4>().When(request => request.Target.Type.GetField("number").Equals(4));
Bind<FigureFactory>().To<FigureFactoryRound5>().When(request => request.Target.Type.GetField("number").Equals(5));
}
}
}
Factory Method Pattern implementation:
using System;
namespace GuessFigure.Model
{
abstract class FigureFactory
{
protected int figureNumber;
public FigureFactory(int figureNumber)
{
this.figureNumber = figureNumber;
}
internal int[] Produce()
{
int[] figureArray = new int[figureNumber];
for (int i = 0; i < figureNumber; i++)
{
figureArray[i] = Algorithm(i + 1);
}
return figureArray;
}
abstract protected int Algorithm(int inputNumber);
}
}
Concrete Factory(there are still some like this);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GuessFigure.Model
{
class FigureFactoryRound1 : FigureFactory
{
public FigureFactoryRound1(int figureNumber) : base(figureNumber)
{
}
protected override int Algorithm(int inputNumber)
{
return inputNumber;
}
}
}
class FigureFactoryRound3 :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GuessFigure.Model.Factory
{
class FigureFactoryRound3 : FigureFactory
{
public FigureFactoryRound3(int figureNumber) : base(figureNumber)
{
}
protected override int Algorithm(int inputNumber)
{
return (int) Math.Pow( inputNumber,2) ;
}
}
}
class FigureFactoryRound4 :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GuessFigure.Model.Factory
{
class FigureFactoryRound4 : FigureFactory
{
public FigureFactoryRound4(int figureNumber) : base(figureNumber)
{
}
protected override int Algorithm(int inputNumber)
{
return (int)Math.Pow(inputNumber, 3);
}
}
}
Usage:
IKernel kernel = new StandardKernel(new RoundModule());
Round round = new Model.Round();
round.SetFigureFactory(kernel.Get<FigureFactory>());
int[] array=round.GetCurrentRoundFigures();

NSubstitute Checking received calls don't work

Hey guys im new with the NSubstitute framework. I'm trying to test some of my classes, but when i use NSubstitute to check received calls it says received no matching calls.
I'm trying to test if the method Tick() is receiving update() from track class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ATM_System.Event;
using ATM_System.EventDetection;
using ATM_System.Region;
using ATM_System.Track;
namespace ATM_System
{
public class ATM
{
private List<ITrack> _tracks;
private IRegion _region;
private List<IEventDetection> _eventdetects;
private List<IEvent> _events;
public ATM()
{
_tracks = new List<ITrack>();
_region = new Region.Region(100000,100000); //could be changed by user
_events = new List<IEvent>();
_eventdetects = new List<IEventDetection>();
}
public void Tick()
{
// update track positions
foreach (var track1 in _tracks)
{
track1.update();
}
//check for events
foreach (var detector in _eventdetects)
{
_events.AddRange(detector.DetectEvent(_tracks));
}
//handle events and output
foreach (var event1 in _events)
{
event1.HandleEvent();
event1.LogEvent();
}
}
public void IncomingTrack(ITrack track)
{
//add incoming track
_tracks.Add(track);
}
}
}
TEST FILE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ATM_System.Event;
using ATM_System.EventDetection;
using ATM_System.Track;
using NUnit.Framework;
using NSubstitute;
namespace ATM_System.Tests.Unit
{
[TestFixture]
class ATMUnitTests
{
private ATM _uut;
private ITrack _track;
private IEvent _event;
private IEventDetection _eventDetection;
[SetUp]
public void Setup()
{
_track = Substitute.For<ITrack>();
_event = Substitute.For<IEvent>();
_eventDetection = Substitute.For<IEventDetection>();
_uut = new ATM();
}
[Test]
public void Tick_UpdateTracks_TracksUpdated()
{
_uut.Tick();
_track.Received().update();
}
}
}
You forgot to include _track in notification receivers. It simply hasn't subscribed to event and as a result is not notified. To fix simply call your IncomingTrack method:
[Test]
public void Tick_UpdateTracks_TracksUpdated()
{
_uut.IncomingTrack(_track);
_uut.Tick();
_track.Received().update();
}

how can I add items to my ListView

I keep getting this error and I know why but I need help figuring out how I can solve it. The only way I have been able to add my items it to make a new form but that seems silly.
It wont work if I make all my methods static =(
I keep getting,
"An object reference is required for the non-static field, method, or
property 'Handicap_Calculator.FormMain.listViewLog'
\Form1.cs 74 13 Handicap Calculator"
Here´s my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Handicap_Calculator
{
public partial class FormMain : Form
{
//FormAddScore FormAddNewScore = new FormAddScore();
public static bool addScoreIsShown = false;
public static FormAddScore _FormAddScore;
public static ListViewItem Item;
//public static List<string> ScoreInfo = new List<string>();
public FormMain()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
try
{
if (_FormAddScore == null || _FormAddScore.IsDisposed)
{
_FormAddScore = new FormAddScore();
}
_FormAddScore.Show();
if (_FormAddScore.WindowState == FormWindowState.Minimized)
{
_FormAddScore.WindowState = FormWindowState.Normal;
}
_FormAddScore.BringToFront();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public static void AddScore()
{
int Round = 1;
DateTime date = _FormAddScore.date;
string course = _FormAddScore.course;
int holes = _FormAddScore.holes;
int score = _FormAddScore.score;
float courseRating = _FormAddScore.courseRating;
float slopeRating = _FormAddScore.slopeRating;
string[] ScoreInfo = new string[7];
ScoreInfo[0] = Round.ToString();
ScoreInfo[1] = date.ToString();
ScoreInfo[2] = course;
ScoreInfo[3] = holes.ToString();
ScoreInfo[4] = score.ToString();
ScoreInfo[5] = courseRating.ToString();
ScoreInfo[6] = slopeRating.ToString();
AddToList(ScoreInfo);
}
public static void AddToList(string[] ScoreInfo)
{
Item = new ListViewItem(ScoreInfo);
//listViewLog.Items.Add(Item);
}
}
}
Edit...
Here is the class im calling it from:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Handicap_Calculator
{
public partial class FormAddScore : Form
{
public DateTime date;
public string course;
public int holes;
public int score;
public float courseRating;
public float slopeRating;
public FormAddScore()
{
InitializeComponent();
}
private void FormAddScore_FormClosing(object sender, FormClosingEventArgs e)
{
FormMain.addScoreIsShown = false;
}
public void getscore()
{
try
{
date = dateTimePicker1.Value;
course = textBoxCourse.Text;
holes = Convert.ToInt16(textBoxHoles.Text);
score = Convert.ToInt16(textBoxScore.Text);
courseRating = Convert.ToSingle(textBoxCourseRating.Text);
slopeRating = Convert.ToSingle(textBoxSlopeRating.Text);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
getscore();
FormMain.AddScore();
}
}
}
The simple solution is to define your methods AddScore and AddToList as non-static.
public void AddScore()
{
//your code
}
public void AddToList(string[] ScoreInfo)
{
// your code
}
If you want to use static methods you should pass the instance of your Form to the method, on which you want to add items to the ListView.
public static void AddScore(FormMain mainForm)
{
//your code
AddToList(mainForm, ScoreInfo);
}
public static void AddToList(FormMain mainForm, string[] ScoreInfo)
{
// your code
}
Update:
According to your updated code the solution is to pass the instance of your FormMain to your FormAddScore when you create it. In FormAddScore you store the reference to the FormMain instance to call the methods on.
public partial class FormAddScore : Form
{
// your code
private FormMain _mainForm;
public FormAddScore(){
InitializeComponent();
}
public FormAddScore(FormMain mainForm) : this(){
_mainForm = mainForm;
}
In your FormMain when you create the instance of FormAddScore you should use the constructor that expects an instance of FormMain
_FormAddScore = new FormAddScore(this);
With this setup you can change your methods to non-static and you can call the methods of FormMain in your FormAddScore, by using the stored reference in variable _mainForm.
_mainForm.AddScore();

Categories

Resources