This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I'm trying to build an array of valid id's by checking the last time they were active. I am right at the finish line and I'm getting a null exception error when I find an active device. "thestream" variable has the JSON in it and contains this:
{"domain":"d50fb707f9317","stuff":"comm","thing":"000780000001","m2m_raw":"{\"command\":100,\"current-flow\":25,\"cap-max\":1200,\"cap-remain\":339}","m2m_nestedkey":["System
Characteristics","Diagnostic Information","Diagnostic
Information2","System Settings","Valve
Settings"],"clock":0,"attributes":{"current-flow:clock":"1401480786291382","weight":"150","cap-max":"1200","myname":"valve12","current-flow":"25","command":"100","hello:clock":"1401201915442520","myname:clock":"1401276113497347","cap-remain:clock":"1401480786291382","hello":"there","cap-max:clock":"1401480786291382","command:clock":"1401480786291382","cap-remain":"339","weight:clock":"1401275692557475"}}
My Model has this declaration in it:
public class ListofDevices
{
public long[] Devices { get; set; }
}
It is declared in the controller like this:
var TheList = new ListofDevices();
activeCount is declared and set to zero:
byte activeCount = 0; //(the highest number in here is 36)
All of the code below is in the controller.
JObject CheckIt = JObject.Parse(thestream); // parse the Json as best as we can, given the json we are getting back
string ClockNumString = (string)(((Newtonsoft.Json.Linq.JValue)((((((Newtonsoft.Json.Linq.JContainer)(CheckIt)).Last).First).First).First)).Value);
long ClockNum = Convert.ToInt64(ClockNumString); // convert the string into a number
ClockNum = ClockNum / 1000000; // convert to seconds
TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1); // get the current epoch time
long secondsSinceEpoch = (long)t.TotalSeconds; // convert to seconds for comparison
if ((secondsSinceEpoch - ClockNum) < 60000) {
TheList.Devices[activeCount] = Convert.ToInt64(uniqueitems[i]); // ERROR IS HERE
activeCount++;
}
My crazy Newtonsoft.Json.Linq command is due to the fact that the JSON that is coming back can't be handled any other way. The data I'm getting into ClockNumString is correct. But I'm getting the NullRefenceException error when I try to store the item into the active array, that passes the if statement. It appears to be a type error(?), but I've scoured stackoverflow for assistance and have been working on this all day, but no luck. Any help greatly appreciated.
Devices from TheList as not been initialized, and/or uniqueitems as not been initialized, use new to initialize an object or an array, ie:
TheList.Devices = new long[N];
Related
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 1 year ago.
(Starred out sensitive details for obvious reasons)
The problem line of code is :
int val = (int)user.Properties["userAccountControl"].Value;
I tried instantiating int val before the try catch, but that doesn't seem to do it. I am guessing that I am incorrectly converting the userAccountControl value to an int that's why it is outputting it as a null value. I have tried moving the (int) function around the line.
I also tried adding parenthesis around the whole thing :
((int)user.Properties["userAccountControl"].Value);
The disable function :
public void Disable(string userDn)
{
try
{
DirectoryEntry user = new DirectoryEntry(userDn);
user.Path = "LDAP://******";
user.Username = #"********";
user.Password = "*******";
int val = (int)user.Properties["userAccountControl"].Value;
user.Properties["userAccountControl"].Value = val | 0x2;
user.CommitChanges();
user.Close();
}
catch (System.DirectoryServices.DirectoryServicesCOMException E)
{
MessageBox.Show(E.Message.ToString());
}
}
This is the userDn string and how I run the Disable function:
Disable("CN=Bob Ross,OU=***,DC=***,DC=***");
Debug error message :
Any help would be much appreciated
Thank you
Without more data, best guess - something is not where it supposed to be or cast failed.
A - string userDn was null and constructor of DirectoryEntry throw
B - constructor did not fail, but something in the (int)user.Properties["userAccountControl"].Value; chain was null.
I would say for start check those 2 options. For 'B', maybe try some checks, like var value = Int.TryParse(user.Properties["userAccountControl"]?.Value , out var result) ? result : throw new... / return -1 / handle error etc
Posted by mobile, sorry for formatting.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 1 year ago.
I am trying to convert integers (I got the integers from converting characters to their ascii codes) into an array of integers but when I run the program I get an error that says "Object Reference Not Set to an Instance of an Object" and it is referring to the last line in the code. What am I doing wrong here?
Thank you for any input, I am relatively new.
foreach (char letter in arReverse)
{
int count = -1;
count = count + 1;
int num = (System.Convert.ToInt32(letter + 5));
Console.Write(System.Convert.ToInt32(letter + 5));
Console.Write(" ");
arNum[count] = num;
}
I get an error that says "Object Reference Not Set to an Instance of an Object" and it is referring to the last line in the code.
...
What am I doing wrong here?
arNum[count] = num; may not be initialized.
Make sure the array/list arNum is initialized. This is done with the new keyword such as
var arNum = new List<int>();
var arNum = new int[arReverse.Length];
This question already has answers here:
Print out object elements from list [duplicate]
(2 answers)
Print List of objects to Console
(3 answers)
print list<object> in console c# [duplicate]
(2 answers)
Closed 2 years ago.
I'm learning to code. I have started a little project where I design a text-based RPG.
I am struggling with storing and retrieving objects in and from an array.
Please have a look at my progress so far and tell me what I am doing wrong.
If I am using a wrong approach please also let me know how to do the whole thing smarter :)
First I define some properties of the player:
static class Globals
{
public static string playername;
...
public static object[] playerInventory = new object[4];
}
Then I create the weapon class:
public class Weapon
{
public string weaponName;
public int weaponBaseDamage;
public Weapon(string name, int baseDamage)
{
weaponName = name;
weaponBaseDamage = baseDamage;
}
Then I create the first basic weapon and try to store it in an array.
public class Program
{
public static void Main()
{
Weapon StartSword = new Weapon("My first Sword", 1);
Globals.playerInventory[0] = StartSword;
Console.WriteLine(StartSword.weaponName); // This works
Console.WriteLine(Globals.playerInventory[0]); // This prints "CSharp_Shell.Weapon", but I expected "StartSword"
Console.WriteLine(Globals.playerInventory[0].weaponName); // This results in an Error
The unexpected result of the second WriteLine command tells me that something must be quite wrong, but I don't know what it is and how to fix it. Any advice is welcome! (And please keep in mind that I am new to Coding).
It's required Typecasting. Please try like below:
Console.WriteLine(((Weapon)Globals.playerInventory[0]).weaponName)
Ok, lets look at what your code does:
Weapon StartSword = new Weapon("My first Sword", 1);
Globals.playerInventory[0] = StartSword;
Console.WriteLine(StartSword.weaponName); // This works
Above you create an object of the type Weapon with the name "My first Sword". And then print the name of that public property that is populated in the constructor.
Console.WriteLine(Globals.playerInventory[0]); // This prints "CSharp_Shell.Weapon", but I expected "StartSword"
Here you try to write an object. But an object is not a string so c# will automatically try to convert that to a string and will look at the type. So it is expected that it will not write the properties but a representation of the type.
Console.WriteLine(Globals.playerInventory[0].weaponName); // This results in an Error
Globals.playerInventory is defined as object[] playerInventory, so even if we know that you have entered an object of type weapon there, we need to specify that. Either by letting playerInventory be of the type Weapon[] playerInventory, or by type casting your object before using its properties, like this:
Console.WriteLine(((Weapon)Globals.playerInventory[0]).weaponName);
This question already has answers here:
Cannot assign null to an implicitly-typed variable
(4 answers)
Closed 3 years ago.
I have an else block containing two for loops.
With the second for loop I am trying to create a set of objectYouCreate instances from a clean slate, as in if a set of instances was previously made, it was already successfully destroyed via the first for loop. So each time this code runs (in the Update method), it is creating an entirely new set of instances after wiping the previous set.
This is the (could be flawed) logic I came up with to do that, but I'm getting this error:
Error: "Cannot assign <null> to implicitly typed variable"
Can I receive help with how to best restructure this code logically and without errors. Thank you.
else{
var objectYouCreate = null; //gives the error
for (int i = 0; i < mesh.vertexCount; i++)
{
Destroy(objectYouCreate);
}
for (int i = 0; i < mesh.vertexCount; i++)
{
Vector3 position = mesh.vertices[i];
objectYouCreate = Instantiate(CubePrefab, position, transform.rotation);
}
}
__
edit:
By introducing usage of tags to my code... I was able to change the code so that the only var declaration happens inside a single for loop and is not null.
I'm also trying to utilize the tags for the Destroy portion, so that it does not just focus the same object but instead focuses all objects with the given tag upon instantiate. But this new code crashes Unity! If anyone has suggestions for optimization or a different method please let me know.
else
{
while (GameObject.FindWithTag("CubePFInst") != null) Destroy(GameObject.FindWithTag("CubePFInst"));
for (int i = 0; i < mesh.vertexCount; i++)
{
Vector3 position = mesh.vertices[i];
var cubeClone = Instantiate(CubePrefab, position, transform.rotation);
cubeClone.tag = "CubePFInst";
}
}
var was introduced for compile-time type-binding for anonymous types yet we can use var for primitive and custom types that are already known at design time. At runtime there's nothing like var, it is replaced by an actual type that is either a reference type or value type.
References:
var (C# Reference)
https://www.itorian.com/2015/04/initialize-var-with-null-or-empty-in-c.html
This question already has answers here:
How to pass a List<int> to a service reference (C#, VS2008)
(5 answers)
Closed 2 years ago.
I'm attempting to pass a generic list of integers from a client application to a web service using the the SOAP protocol.
When I attempt to pass the list as a parameter to the web method declared in the web service, I get the error "cannot convert from generic.list to ArrayOfInt".
How do I go about resolving this?
// web service method
[WebMethod(CacheDuration = 30, Description = "Returns the calculated sum value of all numbers supplied in the list")]
public int CalculateListSum(int[] list)
{
int _sum = 0;
foreach (int _val in list)
{
_sum += _val;
}
return _sum;
}
// client app buton click event
private void btnRun_Click(object sender, EventArgs e)
{
string str = this.tbValues.Text;
// clear the list
ClearIntList();
// take the textbox input, format and add to the List
PopulateIntList(str);
WSCalculate.CalculateSoapClient client = new WSCalculate.CalculateSoapClient();
int[] _int_array = this._int_list.ToArray();
// the line below is generating the error
int _result = client.CalculateListSum(_int_array);
this.tbResult.Text = _result.ToString();
}
Error 1 The best overloaded method
match for
'WFCalculate.WSCalculate.CalculateSoapClient.CalculateListSum(WFCalculate.WSCalculate.ArrayOfInt)'
has some invalid
arguments WFCalculate\Form1.cs 58 27 WFCalculate
Error 2 Argument '1': cannot convert
from 'int[]' to
'WFCalculate.WSCalculate.ArrayOfInt' WFCalculate\Form1.cs 58 51 WFCalculate
SOAP doesn't know about Lists and collections, but understands Arrays.
Convert your list of integers to an array of integers:
int[] intArr = myList.ToArray();
And pass this through instead.
Update:
Looks like the webservice is expecting WFCalculate.WSCalculate.ArrayOfInt, so you need to convert you list to that and pass that through.
Not tested:
WFCalculate.WSCalculate.ArrayOfInt myClientArray = (WFCalculate.WSCalculate.ArrayOfInt)myList.ToArray();
int _result = client.CalculateListSum(myClientArray);