I have been trying to build the following Text Adventure and have reached an error that I cannot figure out how to resolve. The error is:
Assets/My_Scripts/MH_Script.cs(19,23): error CS1501: No overload for method Add' takes 2' arguments
Here is the beginning code for MH_Script.cs, the list is rather long since this is a Text Adventure.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MH_Script {
public static List<MH_ScriptManager> sList = new List<MH_ScriptManager>();
public MH_Script(){
sList.Add("start", "You awaken in a sweltering room....
There are more strings added to sList in the same manner followed by:
public string SendScript(string state){
string returnthis = "";
foreach(MH_ScriptManager sm in sList){
if(sm.getState() == state){
returnthis = sm.getStory();
}
}
return returnthis;
}
}
and here is MH_ScriptManager:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MH_ScriptManager{
public Helpers.STATE gState;
public string gScript;
public string getCurrentState(){
return gState;
}
public MH_ScriptManager (string state, string script){
gState = Helpers.ParseEnum<Helpers.STATE>(state);
gScript = script;
}
public string getStory(){
return gScript;
}
public string getState(){
return gState.ToString();
}
public void setStory(string script){
gScript = script;
}
public void setState(string state){
gState = Helpers.ParseEnum<Helpers.STATE>(state);
}
public bool compareStatetoString(string compare){
if (gState == Helpers.ParseEnum<Helpers.STATE> (compare))
return true;
else
return false;
}
}
Can somebody please explain to me what I am doing wrong, and how I can go about resolving this error in the future?
List.Add takes single argument, but in this case you are passing two arguments, which is causing an exception.
Also sList is of type MH_ScriptManager , so what you need is
sList.Add(new MH_ScriptManager("start", "You awaken in a sweltering room..."));
Because Add method should have one argument but you give it two arguments, so
sList.Add("start", "You awaken in a sweltering room);
change to:
sList.Add("You awaken in a sweltering room)
Related
G'day,
I am currently working on a Unity3d project and get this error while working on the ItemDatabase.cs file. The code looks fine to me but I get the error for some reason. Could I please get some help with fixing the error.
Thanks,
https://i.stack.imgur.com/xUETY.png
ItemDatabase.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
[System.Serializable]
public struct Item
{
public int ID;
public string Name;
public bool Stackable;
public string Slug;
public Item(int id, string name, bool stackable, string slug){
ID = id;
Name = name;
Stackable = stackable;
Slug = slug;
}
}
public class ItemDatabase : MonoBehaviour {
public List<Item> itemDatabase = new List<Item>();
// Use this for initialization
void Start () {
GetDatabase("Assets/Resources/ItemData.txt");
}
// Update is called once per frame
void Update () {
}
void GetDatabase(string path)
{
StreamReader sr = new StreamReader(path);
AddItem:
itemDatabase.Add(new Item(
int.Parse(sr.ReadLine().Replace("id", "")),
sr.ReadLine().Replace("name: ",""),
bool.Parse(sr.ReadLine().Replace("stackable: ","")),
sr.ReadLine().Replace("slug: ","")
));
string c = sr.ReadLine();
if(c == ",")
{
goto AddItem;
}
else if(c == ";")
{
sr.Close();
}
}
}
The error message here is quite explicit in what it's telling you - you're calling int.Parse() on a string that it can't recognise as an integer value here:
itemDatabase.Add(new Item(
int.Parse(sr.ReadLine().Replace("id", "")),
sr.ReadLine().Replace("name: ",""),
bool.Parse(sr.ReadLine().Replace("stackable: ","")),
sr.ReadLine().Replace("slug: ","")
));
You're going to need to double-check what input you are passing to GetDatabase and go from there.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am trying to attempt mocking on some reflection (code below). I have been advised to use NSubstitue but I am struggling on how to implement this and to get it started.
At the moment my test stubs are simply like the one below, however on the build server these obviously fail as the DLLs are not present.
[TestMethod]
public void CanGetStudentXml()
{
var student = new ReadStudent();
var results = student.GetStudentXml();
Assert.AreNotEqual(string.Empty, results);
}
Can anyone give me any pointers on how I should go about doing this? Do I need to create mock assemblies? If so, based on the one below, how would I achieve that?
Also is Nsubsitute the best for the job, or would moq be better suited? Which would be the best mocking framework to use?
Sample code:
namespace MokPoc
{
using System.Reflection;
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var students = new ReadStudent();
var results = students.GetStudentXml();
var contacts = students.GetTelephoneXml();
}
}
public enum ReflectedAssembyType
{
SimsProcessesTpPersonStudent,
SimsProcessesTpPersonContact
}
internal class ReflectedAssemblyFactory
{
public static ReflectedAssemblyBase GetReflectedAssembly(ReflectedAssembyType reflectedAssembyType)
{
ReflectedAssemblyBase value = null;
switch (reflectedAssembyType)
{
case ReflectedAssembyType.SimsProcessesTpPersonStudent:
value = new SimsProcessesTpPersonStudent("ThirdPartyProcesses.dll");
break;
case ReflectedAssembyType.SimsProcessesTpPersonContact:
value = new SimsProcessesTpPersonContact("PersonContacts.dll");
break;
}
return value;
}
}
internal abstract class ReflectedAssemblyBase
{
private string path = string.Empty;
private string type = string.Empty;
public string Path
{
get { return this.path; }
set { this.path = value; }
}
public string Type
{
get { return this.type; }
set { this.type = value; }
}
public object InvokeFunction(string name, object[] args)
{
var assemblyToLoad = Assembly.LoadFrom(this.path);
var typeToLoad = assemblyToLoad.GetType(this.type);
var methodToInvoke = typeToLoad.GetMethod(name, args.Select(o => o.GetType()).ToArray());
object obj = Activator.CreateInstance(typeToLoad);
return methodToInvoke.Invoke(obj, args);
}
}
internal sealed class SimsProcessesTpPersonStudent : ReflectedAssemblyBase
{
public SimsProcessesTpPersonStudent(string assembly)
{
this.Path = System.IO.Path.Combine(#"C:\Program Files\Zoosk", assembly);
this.Type = "SIMS.Processes.TPPersonStudent";
}
}
public class ReadStudent
{
public string GetStudentXml()
{
var contacts = ReflectedAssemblyFactory.GetReflectedAssembly(ReflectedAssembyType.SimsProcessesTpPersonStudent);
return (string)contacts.InvokeFunction("GetXmlStudents", new object[] { DateTime.Today });
}
public string GetTelephoneXml()
{
var contacts = ReflectedAssemblyFactory.GetReflectedAssembly(ReflectedAssembyType.SimsProcessesTpPersonContact);
return (string)contacts.InvokeFunction("GetXmlTelephone", new object[] { DateTime.Today });
}
}
}
I have refactored you code to understand what you are trying to test, it seems like you had a lot of classes to do something that seems could be the responsibility of one class, the heart of what you are trying to do is in GetStudentAttributes, I would create a test.dll with a class and public method that returns some strings and then run an actual method to test, in that case you are not using a stub or mock but it is a valid test to ensure your code works. You should also test GetTelephoneXml and GetStudentXML but the only thing you are really testing there is that GetStudentAttributes is inkoved with the appropriate parameters, so when GetStudentXML is called you invokeGetStudentAttributes with "ThirdpartyProcesses.dll" and "GetXmlStudents".
Depending on the framework you use the solution to testing will be different, with Rhynomocks you will have to make the methods virtual to allow the proxy to inherit and invoke your methods, but you can certainly test that the method was called and that the parameters are what you expect, I haven't used nSubstitute, so not sure how to do it there but if the framework is decent you should be able to test those calls and the parameters.
One of the first things that you should do when using driven development is to start by writing the tests first, making sure it fails, making it pass and refactor, usually when you try and retrofit tests to existing code it could get really hard, there are some good resources out there about unit testing, this is a great book about it http://www.amazon.com/Test-Driven-Development-By-Example/dp/0321146530, but in my experience when something is hard to test it usually tells you that your code is too complex or something can be improved, once the code is simplified or fixed testing is usually not a problem.
Good luck and hope this helped a bit!
using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace MokPoc
{
internal class Program
{
private static void Main(string[] args)
{
var students = new ReadStudentsService();
string results = students.GetStudentXml();
string contacts = students.GetTelephoneXml();
}
}
public class ReadStudentsService
{
private const string ProgramFilesZooskDirectory = #"C:\Program Files\Zoosk";
private const string SimsProcessesTppersonstudent = "SIMS.Processes.TPPersonStudent";
public string GetStudentXml()
{
return GetStudentAttributes("ThirdPartyProcesses.dll", "GetXmlStudents");
}
public string GetTelephoneXml()
{
return GetStudentAttributes("ThirdPartyContacts.dll", "GetXmlTelephone");
}
public string GetStudentAttributes(string dllToUse, string methodToExecute)
{
var fullpath = Path.Combine(ProgramFilesZooskDirectory, dllToUse);
var args = new object[] {DateTime.Today};
var assemblyToLoad = Assembly.LoadFrom(fullpath);
var typeToLoad = assemblyToLoad.GetType(SimsProcessesTppersonstudent);
var methodToInvoke = typeToLoad.GetMethod(methodToExecute, args.Select(o => o.GetType()).ToArray());
var obj = Activator.CreateInstance(typeToLoad);
return (string) methodToInvoke.Invoke(obj, args);
}
}
}
Sorry for asking such a simple question but I lost really long time trying to solve this. At the end, I decide to ask you.
Let's start with the code base :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Navigation.Helpers
{
public static class NavigationBarSE
{
public static MvcHtmlString RenderNavigationBarSE(this HtmlHelper helper, String[] includes)
{
return new MvcHtmlString("Y U no Work??");
//NavTypeSE res = new NavTypeSE(includes);
//String ress = res.toString();
//return new MvcHtmlString(ress);
}
}
}
In the original form, this helper needs to return a String that produced by the NavTypeSE class. But in the end, to get a result, I only want it to return a String for me... But it didn't do that...
Before you ask, I can say that,
<add namespace="Navigation.Helpers"/>
exists in my Web.config file in Views folder.
For detailed information, my NavTypeSE class as below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Navigation.Helpers
{
//Creates a Navigation Menu Type which includes Previous, Next and Validate Buttons
public class NavTypeSE
{
Boolean pr, nt, vld;
Boolean Previous { get; set; }
Boolean Next { get; set; }
Boolean Validate { get; set; }
public NavTypeSE(Boolean Previous, Boolean Next, Boolean Validate)
{
this.pr = Previous;
this.nt = Next;
this.vld = Validate;
}
public NavTypeSE() { }
public NavTypeSE(String[] inc)
{
for(int i=0; i<inc.Length; i++)//foreach (String s in inc)
{
String s = inc[i]; // Don't need for foreach method.
if (s.Equals("previous")||s.Equals("Previous"))
{
this.pr = true;
}
else if (s.Equals("next") || s.Equals("Next"))
{
this.nt = true;
}
else if (s.Equals("validate") || s.Equals("Validate"))
{
this.vld = true;
}
else
{
this.pr = false; this.nt = false; this.vld = false;
}
}
public String toString()
{
return "Previous: " + this.pr + ", Next: " + this.nt + ", Validate: " + this.vld;
}
}
}
Also, in my View, I call this Helper like below :
#{
String[] str = new String[] { "Previous", "next", "Validate" };
Html.RenderNavigationBarSE(str);
}
This is just a base for a project. And I'm starter level in both C# and ASP.NET MVC Platform. Sorry for spending your time.
Your RenderNavigationBarSE writes nothing into the Response just returns a MvcHtmlString.
So you need to put an # before the method call to tell Razor engine that you want to write the returned MvcHtmlString into the response (otherwise inside a code block it just executes your method and throws away the returned value)
#{
String[] str = new String[] { "Previous", "next", "Validate" };
}
#Html.RenderNavigationBarSE(str);
You can read more about the Razor syntax:
Introduction to ASP.NET Web Programming Using the Razor Syntax (C#)
There is also a C# Razor Syntax Quick Reference
I am evaluating Winnovative's PdfToText library and have run into something that concerns me.
Everything runs fine and I am able to extract the text content from a small 20k or less pdf immediately if I am running a console application. However, if I call the same code from the NUnit gui running it takes 15-25 seconds (I've verified it's PdfToText by putting a breakpoint on the line that extracts the text and hitting F10 to see how long it takes to advance to the next line).
This concerns me because I'm not sure where to lay blame since I don't know the cause. Is there a problem with NUnit or PdfToText? All I want to do is extract the text from a pdf, but 20 seconds is completely unreasonable if I'm going to see this behavior under certain conditions. If it's just when running NUnit, that's acceptable, but otherwise I'll have to look elsewhere.
It's easier to demonstrate the problem using a complete VS Solution (2010), so here's the link to make it easier to setup and run (no need to download NUnit or PdfToText or even a sample pdf):
http://dl.dropbox.com/u/273037/PdfToTextProblem.zip (You may have to change the reference to PdfToText to use the x86 dll if you're running on a 32-bit machine).
Just hit F5 and the NUnit Gui runner will load.
I'm not tied to this library, if you have suggestions, I've tried iTextSharp (way too expensive for 2 lines of code), and looked at Aspose (I didn't try it, but the SaaS license is $11k). But they either lack the required functionality or are way too expensive.
(comment turned into answer)
How complex are your PDFs? The 4.1.6 version of iText allows for a closed sourced solution. Although 4.1.6 doesn't directly have a text extractor it isn't too terribly hard to write one using the PdfReader and GetPageContent().
Below is the code I used to extract the text from the PDF using iTextSharp v4.1.6. If it seems overly verbose, it's related to how I'm using it and the flexibility required.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
namespace ClassLibrary1
{
public class PdfToken
{
private PdfToken(int type, string value)
{
Type = type;
Value = value;
}
public static PdfToken Create(PRTokeniser tokenizer)
{
return new PdfToken(tokenizer.TokenType, tokenizer.StringValue);
}
public int Type { get; private set; }
public string Value { get; private set; }
public bool IsOperand
{
get
{
return Type == PRTokeniser.TK_OTHER;
}
}
}
public class PdfOperation
{
public PdfOperation(PdfToken operationToken, IEnumerable<PdfToken> arguments)
{
Name = operationToken.Value;
Arguments = arguments;
}
public string Name { get; private set; }
public IEnumerable<PdfToken> Arguments { get; private set; }
}
public interface IPdfParsingStrategy
{
void Execute(PdfOperation op);
}
public class PlainTextParsingStrategy : IPdfParsingStrategy
{
StringBuilder text = new StringBuilder();
public PlainTextParsingStrategy()
{
}
public String GetText()
{
return text.ToString();
}
#region IPdfParsingStrategy Members
public void Execute(PdfOperation op)
{
// see Adobe PDF specs for additional operations
switch (op.Name)
{
case "TJ":
PrintText(op);
break;
case "Tm":
SetMatrix(op);
break;
case "Tf":
SetFont(op);
break;
case "S":
PrintSection(op);
break;
case "G":
case "g":
case "rg":
SetColor(op);
break;
}
}
#endregion
bool newSection = false;
private void PrintSection(PdfOperation op)
{
text.AppendLine("------------------------------------------------------------");
newSection = true;
}
private void PrintNewline(PdfOperation op)
{
text.AppendLine();
}
private void PrintText(PdfOperation op)
{
if (newSection)
{
newSection = false;
StringBuilder header = new StringBuilder();
PrintText(op, header);
}
PrintText(op, text);
}
private static void PrintText(PdfOperation op, StringBuilder text)
{
foreach (PdfToken t in op.Arguments)
{
switch (t.Type)
{
case PRTokeniser.TK_STRING:
text.Append(t.Value);
break;
case PRTokeniser.TK_NUMBER:
text.Append(" ");
break;
}
}
}
String lastFont = String.Empty;
String lastFontSize = String.Empty;
private void SetFont(PdfOperation op)
{
var args = op.Arguments.ToList();
string font = args[0].Value;
string size = args[1].Value;
//if (font != lastFont || size != lastFontSize)
// text.AppendLine();
lastFont = font;
lastFontSize = size;
}
String lastX = String.Empty;
String lastY = String.Empty;
private void SetMatrix(PdfOperation op)
{
var args = op.Arguments.ToList();
string x = args[4].Value;
string y = args[5].Value;
if (lastY != y)
text.AppendLine();
else if (lastX != x)
text.Append(" ");
lastX = x;
lastY = y;
}
String lastColor = String.Empty;
private void SetColor(PdfOperation op)
{
lastColor = PrintCommand(op).Replace(" ", "_");
}
private static string PrintCommand(PdfOperation op)
{
StringBuilder text = new StringBuilder();
foreach (PdfToken t in op.Arguments)
text.AppendFormat("{0} ", t.Value);
text.Append(op.Name);
return text.ToString();
}
}
}
And here's how I call it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using iTextSharp.text.pdf;
namespace ClassLibrary1
{
public class PdfExtractor
{
public static string GetText(byte[] pdfBuffer)
{
PlainTextParsingStrategy strategy = new PlainTextParsingStrategy();
ParsePdf(pdfBuffer, strategy);
return strategy.GetText();
}
private static void ParsePdf(byte[] pdf, IPdfParsingStrategy strategy)
{
PdfReader reader = new PdfReader(pdf);
for (int i = 1; i <= reader.NumberOfPages; i++)
{
byte[] page = reader.GetPageContent(i);
if (page != null)
{
PRTokeniser tokenizer = new PRTokeniser(page);
List<PdfToken> parameters = new List<PdfToken>();
while (tokenizer.NextToken())
{
var token = PdfToken.Create(tokenizer);
if (token.IsOperand)
{
strategy.Execute(new PdfOperation(token, parameters));
parameters.Clear();
}
else
{
parameters.Add(token);
}
}
}
}
}
}
}
My aim is to "Sanitize a string".
The class should do:
trim an input
make the first letter upper case.
Could you please tell me:
Is there a way to better code it?
Would it make sense to use a PARAMETER for a method like: CapitalizeFirstLetterTrim(string x)
when I initiate an object I need write a lot of code like below, any other way to make it shorter?
UserInputSanitizer myInput = new UserInputSanitizer();
myInput.Input = " ciao world";
string ouput = myInput.CapitalizeFirstLetterTrim();
Useful resource http://msdn.microsoft.com/en-us/library/bb311042.aspx
----------- CLASS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebProject.Core.Utilities
{
public class UserInputSanitizer
{
// Backing variables
private string _input;
// Properties
public string Input
{
set { _input = value; }
}
private string _output;
// Backing variables
// Properties
public string Output
{
get { return _output; }
}
public string CapitalizeFirstLetterTrim()
{
// Trim
_input.Trim();
// Make First letter UpperCase and the rest levae lower case
_output = _input.Substring(0, 1).ToUpper() + _input.Substring(1);
return Output;
}
}
}
I think I would create an extension method on string instead:
public static class MyStringExtensions{
public static string Sanitize(this string input)
{
if(input == null) throw new ArgumentNullException("input");
var trimmed = input.Trim();
return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(trimmed);
}
}
You would call the method like this:
var s = " Unsanitized ";
var sanitized = s.Sanitize();
You can use Extension Method to support your requirement
With extension methods , you can use method as if they are part of System.String class.
See Here
I would use an extension method for the string class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WebProject.Core.Utilities
{
public static class StringExtensions
{
public static string Sanitize(this string s)
{
//your code to sanitize your string, for example
if(s == null) throw new ArgumentNullException("s");
var trimmed = input.Trim();
return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(trimmed);
}
}
}
Then you can use:
string s = " UnsanitizedString";
s = s.Sanitize();
I would make the class and methods static
namespace WebProject.Core.Utilities
{
public static class UserInputSanitizer
{
public static string CapitalizeFirstLetterTrim(string input)
{
// Trim
input.Trim();
// Make First letter UpperCase and the rest levae lower case
return input.Substring(0, 1).ToUpper() + input.Substring(1);
}
}
}
and then you would call it like this:
string ouput = UserInputSanitizer.CapitalizeFirstLetterTrim(" ciao world");
Rather than a utility class, it may make more intuitive sense to write this as an extension method for string so you can just call it directly from the literal. Much less overhead.