I'm not sure why this code won't work? - c#

I am trying to write some code, and I am trying to break it up in to different classes because of the way the code will eventually need to work, and I am also working with retrieving data from the internet, so I was trying to do two new things for myself and I can't figure out why this won't work, here is my code:
using System.Collections;
public class SomeClass {
SomeProjectClass_www Test = new SomeProjectClass_www();
Test.GetData();
}
public class SomeProjectClass_www : IEnumerator {
public IEnumerator GetData()
{
WWW www = new WWW("file://C:\\Users\\generic_user\Documents\\test.txt");
yield return url;
Debug.Log(www.text);
}
}
The code generates a CS1519 error, in Unity3d which is what I am using. That is where the Debug.Log comes from. Sorry, I didn't provide much useful information, I really don't know much of whats going on.

The problem is your SomeClass has logic defined in the class, not in a method:
public class SomeClass
{
// This logic needs to go into a method
void SomeMethod()
{
SomeProjectClass_www Test = new SomeProjectClass_www();
Test.GetData();
}
}

Related

How do I access an enum value in this class?

I am a fairly new programmer trying to make a pretty simple game by using MonoGame in C#. My problem is that I want to access an enum value (not sure if that's the right term) in this other class, but I don't know how. My guesses are that you could do something like: return Game1.State.EnterHighScore; or by making an object reference, but it has not worked for me, probably because I'm doing it incorrectly.
I would appreciate help!
I'm sorry I don't know how to format the code properly, but I tried to make it as clear as possible:
//File name: GameElements.cs
//...
//...
//...
//...
if (e.CheckCollision(player))
{
player.IsAlive = false;
return /*EnterHighScore*/; // I want to return the enum value EnterHighscore,
//..which is in the class Game1
}
//...
//...
//...
//...
//File name: Game1.cs
//...
public class Game1 : Game
{
enum State { PrintHighScore, EnterHighScore }; // I want to access EnterHighScore.
//...
}
//...
Keep your enum outside of any class. Then you can directly return from any method in any class in the same namespace.
eg:
public enum GameState
{
EnterHighScore,
EnterSomeOtherScore,
EnterLooserScore
};
public class SomeClass
{
public GameState CheckGame()
{
return GameState.EnterHighScore;
}
}
If you keep the enum inside any class, then the scope of enum will be only to that class.

NUnit cannot call properly method as Program can. How to Mock it properly?

In Nunit I try to test a method. I prepared the same input as in production code, but still method which do my work doesn't call properly. Tried to mock it, with no effect at this moment.
I was told that moq is the answer and it won't be easy, but send me a "Similar" question from this forum. below is try of all that I could. all found in that topic was implemented, but service is still not called properly. Checked if in normal case it would work (program.cs) and there function is called, and works as it should.
public class Helper
{
public string a;
public string b;
public Helper(string aa, string bb)
{
a = aa;
b = bb; //here is some transformation, but I checked it, and it's working properly
}
}
public class Service
{
public static string NotWorkingFunction(Helper o)
{
InternallService w = ThatPrivateFunctionWorks(o);
return ThatPrivateFunctionDont(w);
}
private InternallService ThatPrivateFunctionWorks(Helper o)
{
return DLL_external.SomeInternalService(o); //call was ok in both program, and in NUnit
}
ThatPrivateFunctionDont(InternallService w)
{
return DLL_external.CallingServiceFarAwayFromDLL(w); //this one works if is in part of program, but does not from NUnit. checks if have permission from Windows Credentials, then do a work. Error here from NUnit is that he cannot even call this function!
}
}
public class InternallService
{
public string smth;
public InternallService(Helper o)
{
smth = o.a;
}
}
public class DLL_external
{
public InternallService SomeInternalService(Helper o)
{
InternallService p = new InternallService(o);
return p; //prepare service for function. does not need to connect. output also is checked n another way, and is ok.
}
public InternallService CallingServiceFarAwayFromDLL(InternallService o)
{
return o; //here it connects to the service (don't know how, which protocol etc. works if run under program.cs)
}
}
in Nunit
public class Test
{
[Test]
public void Tester()
{
Mock<Helper> MockedObject = new Mock<Helper>("a", "B"); //Mocking an object
Mock<Service> MockedService = new Mock<Service>(MockBehavior.Strict);
var Helper = new Helper("a", "B");
Service.NotWorkingFunction(MockedObject.Object); //still does not work properly. cannot call service inside the function (But very similar thing Can, but in Program.cs)
MockedService.Object.NotWorkingFunction(MockedObject.Object);//service does not call
MockedService.Setup(p => p.NotWorkingFunction(MockedObject.Object)); //found at Stack overflow, but still function is not called
//of course all uncompiling things are commented in mine code
}
}
Expected to work. but still don't know how call it to test from NUnit. Maybe I am wrong with tool, which I use.
The idea of unit testing is that you test individual units of code rather than the whole system. Integration testing is where you test the whole system. You should test each public interface of each class individually. If that class has dependencies that you want to exclude from the test, you can create mocks of those dependencies: these are fake objects that are called instead of calling your actual code.
For example, to test the function that you say is not working you write a test that calls that function, not a test that goes through the rest of the code to hopefully call that function. You need to set up the data the function being tested needs, either directly or with mock objects. So tests for Dll_External might start like this:
[TestFixture]
public class Dll_External_Tests
{
[Test]
public void ShouldReturnAnInternalServiceFromCallingServiceFarAwayFromDLL()
{
// setup
Helper helper = new Helper("a", "B");
InternallService internalService = new InternallService(helper);
DLL_external dLL_external = new DLL_external();
// act
var result = dLL_external.CallingServiceFarAwayFromDLL(internalService);
// assert
Assert.IsNotNull(result);
Assert.IsTrue(result is InternallService);
// add more assertions for what you expect the result to be
}
}
You will see this test does not use Service at all - it is only testing DLL_External and only creates the objects it needs to be able to do that.
Incidentally, the code you have shown won't compile: you need an object to call a method on. You can only call static methods directly on the class like ClassName.StaticMethod(). Also, it can be a bit confusing if your objects have the same name as the class, convention is that class names start with a capital letter and instances (objects) start with a lower case letter.

Getting null errors even though Im using the variable

I'm trying to learn MonoGame and I'm trying to do basic stuff and I've figured most of it out on my own but I'm getting a null pointer and I'm not sure why. I'm trying to get MainMenuScene to just draw a texture but in SceneManager currentScene keeps giving me null pointers and I have no idea why. Ill post my SceneManager code but the rest will be on github. Its not much code so it shouldnt take long if you'd look over it. I'm super confused and I'm not sure what to google to try to figure it out myself.
https://github.com/eatmykhack/MonoGame.git
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tutorial.Scenes;
class SceneManager
{
private static SceneManager instance = new SceneManager();
Scene currentScene, newScene;
Dictionary<string, Scene> sceneDirectory =new Dictionary<string, Scene>();
public static SceneManager getInstance()
{
return instance;
}
public static Scene getCurrentScene()
{
return instance.currentScene;
}
public static void changeScene(Scene scene)
{
}
public static void addScene(string sceneName)
{
instance.newScene = instance.sceneDirectory[sceneName];
}
public void update() { currentScene.Update(); }
public void draw(SpriteBatch spriteBatch) { currentScene.Draw(spriteBatch); }
public void Initialize()
{
instance.sceneDirectory["MainMenuScene"] = new MainMenuScene();
instance.currentScene = instance.sceneDirectory["MainMenuScene"];
}
public void LoadContent(ContentManager content)
{
instance.currentScene.LoadContent(content);
}
public void UnloadContent()
{
instance.currentScene.UnloadContent();
}
}
you've declared Scene as an abstract class, so you can't just use it as you're doing: Scene currentScene, newScene. (See this reference for more details on abstract classes).
Either make scene a non-abstract class type or create another class that inherits from your abstract class, looking at your code it would be something like:
public class myScene : Scene
{
public override void Update()
{
//do something
}
// etc.
}
You are getting a NullReferenceException because you are mixing static and instance fields in your code:
There are several problems:
Your SceneManager has a public constructor, but its instance method all access the same static (singleton) instance.
Your SceneManager.Draw method does not access the static instance.
Your Game class instantiates a separate ScreenManager instance, meaning the singleton is initialized, but the Games instance isn't. This is allowed because of 1.
There are several ways of fixing this:
The Preferred way: remove the static stuff from SceneManager. Your game is going to have a single instance in the Game class anyway, and you can simply pass the instance along to any scenes. A no brainer.
However, if you want to keep this class a singleton, you need to change a couple of things. People usually want this because they are too lazy to pass the SceneManager along to each scene instance. So, singletons are bad, you won't be able to unit test anything, but I believe most indie game developers don't care too much about unit testing and would be happiest if everything was static and accessible from anywhere.
Make the constructor private, so that no other class (like Game) can instantiate it. If anyone wants to access the instance, they should do it through the getInstance() method. Which, btw, might better be a property instead:
public class SceneManager
{
// private constructor means other classes cannot instantiate this
private SceneManager() { }
private static readonly SceneManager _instance = new SceneManager();
public static SceneManager Instance
{
get { return _instance; }
}
}
If you now try to pull this off in your Game class:
var sceneManager = new SceneManager();
your compiler will tell you it's not going to work that way.
Your SceneManager should only have a single static method/property: getInstance() or the Instance property like shown above. All other methods should be instance methods of that one-and-only instance, and not access the instance field at all. They are accessing that instance anyway. It is a bad idea to have instance methods access static fields:
This is wrong:
public void Initialize()
{
var mainScene = = new MainMenuScene();
instance.sceneDirectory["MainMenuScene"] = mainScene;
instance.currentScene = mainScene;
}
But this is fine (and the this keyword is redundant, of course):
public void Initialize()
{
var mainScene = = new MainMenuScene();
this.sceneDirectory["MainMenuScene"] = mainScene;
this.currentScene = mainScene;
}
Because you're going to use it like this anyway:
// you're basically doing the same thing, but
// it's immediately clear what's going on, and there
// is no room for errors:
var manager = SceneManager.Instance;
manager.Initialize();
The simplest way to ensure you're doing it right it to remove all references to instance inside the SceneManager class.

Get instance of a class using generics

I'm working on a game that uses MVCS and has, so far, clearly separated the business logic from the view.
However, I've been having trouble with one particular piece of the puzzle.
In the game we have command classes (IPlayerCommand) that execute a specific business logic. Each command class returns a result class (PlayerCommandResult). For each PlayerCommand we have a respected visual command class (IVisualPlayerCommand) that takes the PlayerCommandResult and updates the view accordingly.
I'd like the IVisualPlayerCommand to use specific classes that inherit PlayerCommandResult in order to get the information it needs (as opposed to using object). I'd also like to make it compile-time safe (as opposed to casting it before using it). For these two reasons I made the classes use generics.
Here are the declaration of the classes:
public class PlayerCommandResult
{}
public interface IPlayerCommand<T> where T : PlayerCommandResult
{
T Execute(GameWorld world);
}
public interface IVisualPlayerComamnd<T> where T : PlayerCommandResult
{
void Play(T commandResult);
}
Here is the Move Unit command as an example:
public class MoveUnitPlayerCommand : IPlayerCommand<MoveUnitPlayerCommandResult>
{
private Unit unitToMove;
public MoveUnitPlayerCommand(Unit unit)
{
this.unitToMove = unit;
}
public MoveUnitPlayerCommandResult Execute(GameWorld world)
{
MoveUnitPlayerCommand result = new MoveUnitPlayerCommand();
// Do some changes to the world and store any information needed to the result
return result;
}
}
public class MoveUnitVisualPlayerCommand : IVisualPlayerCommand<MoveUnitPlayerCommandResult>
{
void Play(MoveUnitPlayerCommandResult commandResult)
{
// Do something visual
}
}
public class MoveUnitPlayerCommandResult : PlayerCommandResult
{
public Unit TargetUnit { get; private set; }
public Path MovePath { get; private set; }
}
So far, so good. However, I'm having a really hard time tying a IPlayerCommand to a IVisualPlayerCommand because of the use of generics:
public class CommandExecutorService
{
public void ExecuteCommand<T>(IPlayerCommand<T> command) where T : PlayerCommandResult
{
T result = command.Execute(world);
IVisualPlayerCommand<T> visualCommand = GetVisualPlayerCommand(command);
visualCommand.Play(result);
}
public IVisualPlayerCommand<T> GetVisualPlayerCommand<T>(IPlayerCommand<T> command) where T : PlayerCommandResult
{
// ?!?!?!?!?!??!?!?!??!?!
}
}
I have a feeling that what I'm trying to do is not even possible because of the way generics work in C# (as opposed to Java where I could say IVisualPlayerCommand<?>).
Could you help me figure out a way?
Any feedback for the design is welcome.
P.S. Sorry if the title doesn't reflect the question. I wasn't sure how to boil down the question in one line.
P.P.S. Which is why I also don't know if this question has been asked and answered before.
You two command classes, are served as service. To me, for this case, I would use the service locator pattern. As how to implement this pattern, you can check this link
The drawback of using template, is that, if something changes, you have to compiled it again.
Here's link which provides an example of the service locator pattern.
So for you code, you want find the corresponding instance of IVisualPlayerCommand to IPlayerCommand, so the concrete service can inherit from both interface, which it actually implements the IVisualPlayerCommand interface, while the IPlayerCommand just severs as a tag.
so the code will like this:
class MoveUnitVisualPlayerCommand: IVisualPlayerCommand, IPlayerCommand {}
services = new Dictionary<object, object>();
this.services.Add(typeof(IPlayerCommand ), new MoveUnitVisualPlayerCommand());
as how to get the service, you can refer the example.
Hope this helps.

MSScriptControl 'Specified cast is not valid' when exposing an object to VBScript

I'm trying to implement scripting capability to my application. I'm using the code below. Whenever I instantiate a new Api object, the application is supposed to quit (a little testing thing :p)
However, the application crashes at script.AddObject(...) with the error Specified cast is not valid. Is there a step I'm missing here?
public class ApiExposed
{
public string ModuleName;
public void Exit()
{
System.Environment.Exit(0);
}
}
public class Api
{
ScriptControlClass script;
ApiExposed ApiObj;
public Api()
{
ApiObj = new ApiExposed();
script = new ScriptControlClass();
script.Language = "VBScript";
script.AddObject("tbapi", (object)ApiObj, true);
script.Eval("tbapi.Exit()");
}
}
My guess is, the ApiExposed class is not COM visible - it will need to be in order for VBScript to interact with it.
I had similar problems to this.
Make sure you use [ComVisible(true)] on the class and methods.
Also, make your class PUBLIC!

Categories