I keep getting a null object reference error when im running one of my unit test.
Unit Test:
[Test]
public void EnumeratedData_ValidInputType_NoErrorAdded()
{
List<String> errorMessageList = new List<string>();
UserInputEntity myEntity = new UserInputEntity();
myEntity.DataTypes = new List<string>();
myEntity.DataTypes.Add("DateTime");
myEntity.DataTypes.Add("datetime");
myEntity.DataTypes.Add("decimal");
myEntity.DataTypes.Add("decIMAL");
myEntity.DataTypes.Add("DOUble");
myEntity.DataTypes.Add("double");
myEntity.DataTypes.Add("FLOat");
myEntity.DataTypes.Add("float");
myEntity.DataTypes.Add("INT");
myEntity.DataTypes.Add("int");
PathReader reader = new PathReader();
IOManager manager = new IOManager(reader);
VerificationManager testObject = new VerificationManager(manager);
testObject.EnumeratedDataTypes(myEntity, errorMessageList);
Assert.AreEqual(errorMessageList.Count, 0);
}
Method Code:
public void EnumeratedDataTypes(UserInputEntity inputs, List<String> errorMessageList)
{
inputs.EnumeratedDataTypes = new int[inputs.DataTypes.Count];
try
{
for (int i = 0; i < inputs.DataTypes.Count; i++)
{
inputs.EnumeratedDataTypes[i] = (int)Enum.Parse(typeof(Enumerations.ColumnDataTypes), inputs.DataTypes[i].ToUpper());
}
}
catch (Exception ex)
{
errorMessageList.Add(ex.Message);
}
}
Enum:
class Enumerations
{
public enum ColumnDataTypes
{
DATETIME = 0,
DECIMAL = 1,
DOUBLE = 2,
FLOAT = 3,
INT = 4
}
}
ErrorMessage:
FrazerMann.CsvImporter.Entity.Test.EntityVerificationTests.EnumeratedData_ValidInputType_NoErrorAdded:
System.NullReferenceException : Object reference not set to an instance of an object.
Im assumin im overlooking something stupidly simple but i cant see it. id appreciate it if someone could put me out of my misery.
In your EnumeratedDataTypes method, you first set the length of the inputs.EnumeratedDataTypes property to inputs.ColumnNames.Count, which is equal to 0 since it has not been filled with data yet (it is only the List capacity that has been set to 9).
Next, when filling this array property with data you loop from 0 to index (including) inputs.DataTypes.Count:
for (int i = 0; i <= inputs.DataTypes.Count; i++)
I count the size of the input.DataTypes list to 10. Thus, you will try to write data to an empty array.
I propose the following changes:
First, initialize the inputs.EnumeratedDataTypes array as follows:
inputs.EnumeratedDataTypes = new int[inputs.DataTypes.Count];
Second, use < instead of <= in the for loop:
for (int i = 0; i < inputs.DataTypes.Count; i++)
Related
Currently I have a class called Field:
public class Field
{
public int Id { get; set; }
}
var listOfListOfFields = new List<List<Field>>();
var listOfFields = new List<Field>(){ new Field {id = 1}}; // in reality, data comes here.
for (int i = 0; i <= 2; i++)
{
var copyFirstList = listOfFields.ToList(); // to avoid reference thing, I still get same value
for(int j =0; j < copyFirstList.Count; j++)
{
copyFirstList[j].Id = i;
}
listOfListOfFields.Add(copyFirstList);
}
The output in the listOfListOfFields contains 2 for all the lists in id. Please suggest.
Copying a list of references types gives you the same references to those reference types (nothing changed). For instance, if someone gave you a bucket of post-it-notes with phone numbers on them, and you tip them in to another bucket, you still have the same post-it-notes!
There are many ways to solve this problem. However, one way is to project using Select and recreating the objects
copyFirstList = listOfFields.Select(x => new Field() {Id = x.Id}).ToList():
Please check the code below. I am trying to set value to a random property of a int list. Problem is that even after i set 5 to a random list this value getting inserted to that property. What am I doing wrong here?
var TransactionList = new List<int>();
for (int i = 0; i < 59; i++)
{
TransactionList.Add(0);
}
var randTransaction = TransactionList.OrderBy(x => Guid.NewGuid()).FirstOrDefault();
//here i am trying to set 5 value to a random TrnasactionList but this not being set
randTransaction = 5;
Try like below. new Random().Next(0, 59); will return value between 0 and 59. Or you can better set it like new Random().Next(0, TransactionList.Count); for it to be dynamic with list.
new Random().Next(minValue, maxValue); The maxValue for the upper-bound in the Next() method is exclusive—the range includes minValue, maxValue-1, and all numbers in between.
var TransactionList = new List<int>();
for (int i = 0; i < 59; i++)
{
TransactionList.Add(0);
}
// var index = new Random().Next(0, 59);
// Below will work for dynamic length of list.
var index = new Random().Next(0, TransactionList.Count);
TransactionList[index] = 5;
If you don't mind the original list getting sorted you could do this:
class Program
{
static void Main(string[] args)
{
var transactionList = new List<int>();
for (int i = 0; i < 59; i++)
{
//I initialized the list with i instead of 0 to better see sorting in place
transactionList.Add(i);
}
transactionList.Sort(new RandomComparer());
//changed it to 99 to spot it more easily
transactionList[0] = 99;
foreach (var i in transactionList)
Console.WriteLine(i);
}
}
public class RandomComparer : IComparer<int>
{
private Random _random = new Random();
public int Compare(int x, int y)
{
return _random.Next(-1, 2);
}
}
See it in action:
https://dotnetfiddle.net/NKuPdx
randTransaction is "int" data type, which is primitive data type.
if you want to set randTransaction that reflect to it's object, just set the object it self
WCF generates 6 random lottery numbers, it returns them in an array on the wcf service, however I can't get it to print to a label on the form.
if I try to print it to a message box I get "Value cannot be parsed as type int32"
I tried creating a new array on the form the logic being like, form array = service array, since its returning an array the service should be an array shouldnt it? with that I get Cannot implicitly convert type int to int[]
here's where im at:
IService
public interface ILottoService
{
[OperationContract]
int[] GenerateLottoDrawNums();
[OperationContract]
int[] GenerateIrishLottoNums();
}
Service
public int[] GenerateLottoDrawNums()
{
int min = 1;
int max = 59;
int[] randomNums = new int[6];
Random rand = new Random();
for (int i = 0; i < randomNums.Length; i++)
{
int tempNum = rand.Next(min, max);
while (IsDuplicate(tempNum, randomNums))
{
tempNum = rand.Next(7);
}
randomNums[i] = tempNum;
}
return randomNums;
}
public Boolean IsDuplicate(int tempNum, int[]randomNums)
{
foreach (var item in randomNums)
{
if (item == tempNum)
{
return true;
}
}
return false;
}
}
}
Form
public partial class FrontEnd : Form
{
LottoServiceReference.LottoServiceClient ws = null;
public FrontEnd()
{
InitializeComponent();
}
private void FrontEnd_Load(object sender, EventArgs e)
{
ws = new LottoServiceReference.LottoServiceClient();
}
private void btnLottoDraw_Click(object sender, EventArgs e)
{
try
{
int[] LottoDrawNums = new int[6];
for (int i = 0; i < LottoDrawNums.Length; i++)
{
LottoDrawNums[i] = ws.GenerateLottoDrawNums();
lblNum1.Text = String.Join(",", LottoDrawNums.ToString());
MessageBox.Show(String.Join(",", ws.GenerateLottoDrawNums()));
Console.WriteLine(String.Join(",", ws.GenerateLottoDrawNums()));
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
}
Guessing I'm missing some [] or int[]?
My college tutor could not help, she referred me to you guys. Saying "It thinks its an int and it isn't. Try converting to String or List then printing that. She Googled and found a Stack Overflow question about converting but I didn't save it and can't find it at home.
Thank you.
this code
for(int i = 0; i < LottoDrawNums.Length; i++)
{
lblNum1.Text = LottoDrawNums[0].ToString();
}
Set's only the first position of the array to the label.
Try String.Join
https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=netframework-4.7.2
LblNum1.Text = String.Join(" , ", LottoDrawNums);
This will return somethingh like "3 , 45 , 6 , 54 , 56 , 7, 45 "
Also use it in MessageBox.Show(String.Join(" , ", ws.GenerateLottoDrawNums()));
The GenerateLottoDrawNums and IsDuplicate methods work fine!
Try using StringBuilder, something like this:
StringBuilder sb = new StringBuilder ();
For each element in array:
sb.Append($"{element} ,")
String arrayAsString = sb.ToStirng(0, sb.Length-2);
LblNum1.Text = arrayAsString;
MessageBox.Show(arrayAsString);
Also, I think that you are missing Service Contract attribute above IService definition
See https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.operationcontractattribute?view=netframework-4.7.2
It seems that there is no problem with your project. I copy the code snippets and test it locally, works well. Maybe like the brother upstairs said, you may have lost something. I suggest you post more details about your project.
You could add the breakpoint to the server end and run the WCF service in debugging mode and check the return value. Or you add another method to test whether the service works well.
It should be noted that I host the WCF in a console application and use the basic binding.
Cbooks has an atribute "CTeam[] Teams" and it is of fixed size (8). If I want to add objects to it using this in the Main:
CBook A1 = new CBook("Title1", "Author1");
CBook A2 = new CBook("Title1", "Author2");
CBooks ArrayOfBooks = new CBooks(8);
ArrayOfBooks.Add(A1);
ArrayOfBooks.Add(A2);
then position 0 and 1 are ocuppied, and the positions from 2 to 7 are null. What I want to do is, using a variable "int aux=0", count the ocupied positions like this:
for (int k = 0; k < NumberOfTeams; k++)
{
if (Teams[k].Name=="")
Aux += 1;
}
So, Aux in this case would be 2, then I want to do "Teams[Aux] = A" so that A would be in the position 2 and now I should have three objects in my array. But I'm getting "Index out of bound"
Your implementation then should look similar to this:
public class Program
{
public static void Main(string[] args)
{
Element a = new Element("A");
Element b = new Element("B");
MyArray array = new MyArray(8);
array.Add(a);
array.Add(b);
Console.WriteLine(array.Count()); //2 Elements are in the array
}
}
//Sample element class.
public class Element{
public readonly String MyString;
public Element(String myString){
MyString = myString;
}
}
//Sample array class.
public class MyArray{
private readonly Element[] myArray;
private int count; //Use a property here
public MyArray(int size){
//Be careful -> check if size is >= 0.
myArray = new Element[size];
}
public bool Add(Element element){
if(myArray.Length == count) // return false if no more elements fit.
return false;
myArray[count] = element;
count++;
return true;
}
public int Count(){
return count;
}
}
So there is no need for creating an extra count loop. Your "count" variable in "MyArray" class holds always the correct value.
Anyway the implementation or use case of this code is a little bit clunky.
Why are you cant use directly a more safe list or something. That would be a better solution.
What do you need CBooks for? From what I understand, it's just an array of 8 CBook objects so why not use CBook[]?
CBook A1 = new CBook("Title1", "Author1");
CBook A2 = new CBook("Title1", "Author2");
CBooks[] ArrayOfBooks = new CBook[8];
ArrayOfBooks[0] = A1;
ArrayOfBooks[1] = A2;
int aux = 0;
for (int k = 0; k < ArrayOfBooks.Length; k++)
{
//break the loop because we know there are no more books
if (ArrayOfBooks[k] == null)
break;
aux++;
}
The question doesn't cover what the variables NumberOfTeams and Teams are for but could those be added to the implementation of CBook?
I have the following piece of code:
Chromosome[] pop = new Chromosome[popSize];
int[] initialGenes = new int[i];
for (int m = 0; m < i; m++)
initialGenes[m] = -1;
for (int j = 0; j < popSize; j++)
{
pop[j] = new Chromosome(graph, initialGenes);
}
Chromosome is my class and has a property
public int[] Genes { get; set; }
As you can see I initialize an array of Chromosome objects. The problem is when I try to change the value of pop[i].Genes[k] (e.g. pop[1].Genes[2] = 123) all Genes[k] of pop are changed (i.e.
pop[0].Genes[2] == 123
pop[2].Genes[2] == 123
etc.)
Could anyone explain what the problem is?
Thanks.
Change your constructor of Chromosome to make a copy of the array that is passed in.
I assume, your constructor looks like this:
public Chromosome(int[] initialGenes)
{
Genes = initialGenes;
}
But it should look like this:
public Chromosome(int[] initialGenes)
{
Genes = new int[initialGenes.Length];
Array.Copy(initialGenes, Genes, Genes.Length);
}
This happens because you pass same object to all Chromosome clases. You should create new copy of initialGenes for each Chromosome class