13 Replies - 3081 Views - Last Post: 05 August 2012 - 08:13 AM Rate Topic: -----

#1 toyotajon93  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 04-August 12

Debug error - NULLReferenceException *Help*

Posted 04 August 2012 - 06:28 AM

Hello everyone I am new to this and fairly new to c#, helping a friend write and enhance a program we use for a game we love. I'm getting a debug error at this code section. Specifically the first HttpWEbrequest. The error is NUllReferenceException. I've tried numerous things to get it fixed. My program will compile but crashes when this process is requested. Any help/advice would be great. I know programming fairly well but new to c#. Thanks

public void LogOnToEmross()
        {
            try
            {
                HttpWebRequest requestEvents = WebRequest.Create(string.Concat(new object[] { server.server, "game/get_cdinfo_api.php?key=", this.userkey.key, "&city=", this.userinfo.user.city[0].id, "&_l=en" })) as HttpWebRequest;
                using (HttpWebResponse response = requestEvents.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    if (reader.ReadToEnd().Contains("code:0"))
                    {
                        HttpWebRequest requestEvents2 = WebRequest.Create(this.server.server + "game/get_userinfo_api.php?key=" + this.userkey.key + "&_l=en") as HttpWebRequest;
                        using (HttpWebResponse response2 = requestEvents2.GetResponse() as HttpWebResponse)
                        {
                            string responseText = new StreamReader(response2.GetResponseStream()).ReadToEnd();
                            string[] seperator2 = new string[] { "\"ret\":" };
                            string[] temp2 = responseText.Split(seperator2, StringSplitOptions.None);
                            UserInfo testResult = Json.Deserialize<UserInfo>(temp2[1].Substring(0, temp2[1].Length - 3).TrimEnd(this.trimmer).TrimStart(this.trimmer));
                            this.userinfo = testResult;
                        }
                        this.GetChestsAndKeys();
                    }
                    else
                    {
                        this.LogOn();
                        this.GetChestsAndKeys();
                    }
                }
            }
            catch
            {
                this.LogOn();
                this.GetChestsAndKeys();
            }
        }


Is This A Good Question/Topic? 0
  • +

Replies To: Debug error - NULLReferenceException *Help*

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5595
  • View blog
  • Posts: 11,970
  • Joined: 02-June 10

Re: Debug error - NULLReferenceException *Help*

Posted 04 August 2012 - 07:02 AM

First bug in my article:
What does this error mean?

toyotajon93: What this shows us is that you aren't familiar with breakpoints and how to debug your own code. Learning to debug one's own code is an essential skill. Sadly, one that apparently few college courses teach. Silly if you ask me.

Placing breakpoints and walking through the code line by line allows you to actually WATCH it execute.

Visualizing what your code does will let you see why it behaves the way it does.

It would be well worth your time to do the tutorials on FAQ 2. A couple hours learning this skill will save you hundreds of hours of confusion in one project alone.


See FAQ # 2. (Click the SHOW button below)



TOP most asked:
What does this error message mean?
FAQ 2: How do I debug
FAQ 3: How do I make Class1/Form1 talk to Class2/Form2


FAQ (Frequently Asked Questions - Updated July 2012
Spoiler



This post has been edited by tlhIn`toq: 04 August 2012 - 07:03 AM

Was This Post Helpful? 0
  • +
  • -

#3 toyotajon93  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 04-August 12

Re: Debug error - NULLReferenceException *Help*

Posted 04 August 2012 - 07:03 AM

I agree, I have not had a ton of experience debugging. I will read the faq as you mentioned. Thanks, any advice on the code itself?
Was This Post Helpful? 0
  • +
  • -

#4 MrShoes  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 313
  • View blog
  • Posts: 490
  • Joined: 13-June 12

Re: Debug error - NULLReferenceException *Help*

Posted 04 August 2012 - 08:22 AM

Is server instantiated before the method is called?

Which line are you getting the exception on (as highlighted in VS)?

Where is the method being called from?

There are too many unknown factors to resolve your problem. In the meantime, I recommend reading up on NullReferenceException - understanding what exceptions mean will help you resolve bugs.
Was This Post Helpful? 1
  • +
  • -

#5 toyotajon93  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 04-August 12

Re: Debug error - NULLReferenceException *Help*

Posted 04 August 2012 - 08:29 AM

Server is called here, I can send you the project if interested.

private void LogOn()
        {
            try
            {
                HttpWebRequest request = WebRequest.Create("http://m.emrosswar.com/info.php?user=" + activeUser.SelectSingleNode("username").InnerText + "&action=login&pvp=0") as HttpWebRequest;
                using (HttpWebResponse response2 = request.GetResponse() as HttpWebResponse)
                {
                    string responseText = new StreamReader(response2.GetResponseStream()).ReadToEnd();
                    string[] seperator2 = new[] { "\"ret\":" };
                    string[] temp2 = responseText.Split(seperator2, StringSplitOptions.None);
                    ServerInfo testResult = Json.Deserialize<ServerInfo>(temp2[1].Substring(0, temp2[1].Length - 3).TrimEnd(trimmer).TrimStart(trimmer));
                    server = testResult;
                }
                request = WebRequest.Create(server.server + "game/login_api.php?username=" + server.user + "&password=" + activeUser.SelectSingleNode("password").InnerText) as HttpWebRequest;
                using (HttpWebResponse response3 = request.GetResponse() as HttpWebResponse)
                {
                    string responseText = new StreamReader(response3.GetResponseStream()).ReadToEnd();
                    string[] seperator2 = new[] { "\"ret\":" };
                    string[] temp2 = responseText.Split(seperator2, StringSplitOptions.None);
                    Login testResult = Json.Deserialize<Login>(temp2[1].Substring(0, temp2[1].Length - 3).TrimEnd(trimmer).TrimStart(trimmer));
                    userkey = testResult;
                }
                request = WebRequest.Create(server.server + "game/get_userinfo_api.php?key=" + userkey.key) as HttpWebRequest;
                using (HttpWebResponse response4 = request.GetResponse() as HttpWebResponse)
                {
                    string responseText = new StreamReader(response4.GetResponseStream()).ReadToEnd();
                    string[] seperator2 = new[] { "\"ret\":" };
                    string[] temp2 = responseText.Split(seperator2, StringSplitOptions.None);
                    UserInfo testResult = Json.Deserialize<UserInfo>(temp2[1].Substring(0, temp2[1].Length - 3).TrimEnd(trimmer).TrimStart(trimmer));
                    userinfo = testResult;
                }
            }
            catch
            {
                MessageBox.Show("There was a problem login into account.\n Verify that username and password before continuing.");
            }
        }

This post has been edited by tlhIn`toq: 04 August 2012 - 08:30 AM
Reason for edit:: Please use code tags in replies as well as initial post

Was This Post Helpful? 0
  • +
  • -

#6 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5595
  • View blog
  • Posts: 11,970
  • Joined: 02-June 10

Re: Debug error - NULLReferenceException *Help*

Posted 04 August 2012 - 08:35 AM

I'm not certain, but this concerns me.

ServerInfo testResult = Json.Deserialize<ServerInfo>(temp2[1].Substring(0, temp2[1].Length - 3).TrimEnd(trimmer).TrimStart(trimmer));
                    server = testResult;


ServerInfo testResult is a method-level variable that will be destroyed at the end of the method.

server is then referenced to this object... that gets destroyed.

It wouldn't surprise me to find out that server becomes null once garbage collection takes place.

It might be wise to .Clone() the object rather than just use the = assignment which on objects is a reference to the existing object, not a duplication of the object.
Was This Post Helpful? 1
  • +
  • -

#7 toyotajon93  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 04-August 12

Re: Debug error - NULLReferenceException *Help*

Posted 04 August 2012 - 08:40 AM

I didnt write most of the code, just trying to help a friend make improvements. I may be in over my head for my knowledge...
Was This Post Helpful? 0
  • +
  • -

#8 toyotajon93  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 04-August 12

Re: Debug error - NULLReferenceException *Help*

Posted 04 August 2012 - 08:50 AM

here is my project file if interested.

Sorry I cant do anything right this morning, lol

Attached File(s)


Was This Post Helpful? 0
  • +
  • -

#9 CodingSup3rnatur@l-360  Icon User is online

  • D.I.C Addict
  • member icon

Reputation: 992
  • Posts: 972
  • Joined: 30-September 10

Re: Debug error - NULLReferenceException *Help*

Posted 04 August 2012 - 10:29 AM

MrShoes was spot on with the question regarding the server variable. The problem is that server is null when LogOnToEmross is called, meaning this line; server.server fails as you cannot access a property/field on a null object.

Yes, you instantiate server in the LogOn() method, but you don't call LogOn before you call LogOnToEmross.

I strongly suggest you read and learn from tlhIn`toq's What does this error mean? article. Using the techniques discussed in that article, and the articles about debugging linked from it, I was able to find the problem in under a minute. That's the power of the debugger for you :)

Also, just to clarify;

Quote

ServerInfo testResult is a method-level variable that will be destroyed at the end of the method.

server is then referenced to this object... that gets destroyed.

It wouldn't surprise me to find out that server becomes null once garbage collection takes place.


that won't be a problem in C#. If Json.Deserialize() returns an reference type, the reference stored in the server variable will keep the object alive on the heap, and only the reference that was stored on the stack or CPU register will be destroyed.

If it returns a value type, the structure will be copied into the server variable's storage location on the heap, and so will still be alive beyond the LogOn() method, and the original copy that would most commonly be on the stack or in CPU registers will be destroyed.

EDIT:

The garbage collector doesn't run at the end of every method, and when it does run, it will only collect objects that don't have any strong references to them :)

This post has been edited by CodingSup3rnatur@l-360: 04 August 2012 - 12:43 PM
Reason for edit:: I seem to have become confused about when to use quote tags vs code tags

Was This Post Helpful? 1
  • +
  • -

#10 toyotajon93  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 04-August 12

Re: Debug error - NULLReferenceException *Help*

Posted 04 August 2012 - 10:54 AM

I have it call Logon() in the LogontoEmross() method. Where should I add Logon() to LogonToEmross()? I have tried different locations with no luck.
Was This Post Helpful? 0
  • +
  • -

#11 CodingSup3rnatur@l-360  Icon User is online

  • D.I.C Addict
  • member icon

Reputation: 992
  • Posts: 972
  • Joined: 30-September 10

Re: Debug error - NULLReferenceException *Help*

Posted 04 August 2012 - 11:23 AM

View Posttoyotajon93, on 04 August 2012 - 05:54 PM, said:

I have it call Logon() in the LogontoEmross() method.


Yes, but not until after you have accessed server.server, which causes the NullReferenceException.

Quote

Where should I add Logon() to LogonToEmross()?


I have no idea. You (or your friend) have to evaluate what to do. I don't know your application well enough to comment with any accuracy. All I can tell you is that if you want to use server.server, you must give the variable server on the left hand side of the . a none null value first. How you manage that is down to you i'm affraid.

This post has been edited by CodingSup3rnatur@l-360: 04 August 2012 - 11:25 AM

Was This Post Helpful? 0
  • +
  • -

#12 toyotajon93  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 04-August 12

Re: Debug error - NULLReferenceException *Help*

Posted 04 August 2012 - 11:50 AM

Thank you, this is where I wish I knew c# better. I'll keep playing with it, has me pulling my hair out at the moment....
Was This Post Helpful? 0
  • +
  • -

#13 toyotajon93  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 04-August 12

Re: Debug error - NULLReferenceException *Help*

Posted 04 August 2012 - 04:55 PM

Thanks to everyone for the help, I have more of a feeling now that I was given decompiled source code. I'm seeing strings like, each like in the return causing a recursive call error.
public static Wolffsens_Utilities_for_Emross_War.Item bronzeKey
        {
            [CompilerGenerated]
            get
            {
                return bronzeKey;
            }
            [CompilerGenerated]
            set
            {
                bronzeKey = value;
            }
        }



In the code and I dont think this is part of the code. I'm not sure how much time I should waste trying to get this up and running since I'm no expert. If anyone has some free time and is bored would love their input. I'm sorry for wasting time thinking it was source.
Was This Post Helpful? 0
  • +
  • -

#14 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6081
  • View blog
  • Posts: 23,557
  • Joined: 23-August 08

Re: Debug error - NULLReferenceException *Help*

Posted 05 August 2012 - 08:13 AM

This looks like a violation of the game's TOS, so I'm nuking this.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1