Null Reference Exception(Tom Millers Book)

Started by
16 comments, last by TheNobleOne 18 years, 8 months ago
Well I am working through Tom's book: Managed DirectX 9 Graphics and Game Programming and I keep stumbling into these Null Reference Exceptions in his code. First one is in Chapert 2 when you are getting the device information.

textBox1.Text = e.Node.Text + " Capabilities: \r\n\r\n" + Manager.GetDeviceCaps
    (e.Node.Index, DeviceType.Hardware).ToString().Replace("\n", "\r\n");


The only thing that throws the Null Ref exception is the Replace method not shure what is going on with that line it is taken right out of the book and the source that comes with the book gets the same error. Another one is in chapter 3 where he is going on about how you must put the data back in the vertex buffer after the device is reset. I get the same error when doing that a Null Reference exception the line that throws it is the Event hook.

vb.Created += new EventHandler(this.OnVertexBufferCreate);


This is getting me very agervated because the syntax is right the code compiles but yet it is throwing these errors from nowhere. I am using .Net 2.0 framework and I thought that had something to do with it but I took the code and went to the 1.1 framework with it and compiled and am getting the same problem.
My JournalComputer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter. (Eric Raymond)"C makes it easy to shoot yourself in the foot. C++ makes itharder, but when you do, it blows away your whole leg."-- Bjarne Stroustrup
Advertisement
The first exception is probably thrown because ToString() returned null, and thus Replace was called on a null reference. Check whether ToString() returns an actual string or not.

Everything is fine till it gets to the ToString() Method. All the nodes are what they should be and everything. Any input on the 2nd one.

And again I say both of these can be reproduced by me by compiling the source code that comes with the book as well. Maybe it is a problem in the August SDK. Maybe some refrences are going null for some reason?

Ok here is the complete source for the first Null Reference problem.

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using Microsoft.DirectX;using Microsoft.DirectX.Direct3D;namespace Enumeration{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        public void LoadGraphics()        {            foreach (AdapterInformation ai in Manager.Adapters)            {                TreeNode root = new TreeNode(ai.Information.Description);                TreeNode driverInfo = new TreeNode(string.Format("Driver information: {0} - {1}",                    ai.Information.DriverName, ai.Information.DriverVersion));                root.Nodes.Add(driverInfo);                TreeNode displayMode = new TreeNode(string.Format("Current Display Mode: {0}x{1}x{2}",                    ai.CurrentDisplayMode.Width, ai.CurrentDisplayMode.Height, ai.CurrentDisplayMode.Format));                foreach (DisplayMode dm in ai.SupportedDisplayModes)                {                    TreeNode supportedNode = new TreeNode(string.Format("Supported: {0}x{1}x{2}",                        dm.Width, dm.Height, dm.Format));                    displayMode.Nodes.Add(supportedNode);                }                root.Nodes.Add(displayMode);                treeView1.Nodes.Add(root);            }        }        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)        {            if (e.Node.Parent == null)            {                textBox1.Text = e.Node.Text + " Capabilities: \r\n\r\n" + Manager.GetDeviceCaps                    (e.Node.Index, DeviceType.Hardware).ToString().Replace("\n", "\r\n"); // CAUSES THE NULL REF ERROR            }        }    }}


Here is the complete source for the seccond Null Reference problem.

using System;using System.Collections.Generic;using System.Drawing;using System.Windows.Forms;using Microsoft.DirectX;using Microsoft.DirectX.Direct3D;namespace MDXApp{    public partial class Form1 : Form    {        private Device device = null;        private VertexBuffer vb = null;        private float angle = 0.0f;        public Form1()        {            InitializeComponent();            this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);        }        /// <summary>        /// We will initialize our graphics device here        /// </summary>        public void InitializeGraphics()        {            // Set out presentation parameters            PresentParameters presentParams = new PresentParameters();            presentParams.Windowed = true;            presentParams.SwapEffect = SwapEffect.Discard;            // Create our device            device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams);            vb.Created += new EventHandler(this.OnVertexBufferCreate); // CAUSES NULL REF ERROR            OnVertexBufferCreate(vb, null);        }        private void Form1_Paint(object sender, PaintEventArgs e)        {            device.Clear(ClearFlags.Target, Color.CornflowerBlue, 1.0f, 0);            SetupCamera();            device.Lights[0].Type = LightType.Point;            device.Lights[0].Position = new Vector3();            device.Lights[0].Diffuse = Color.White;            device.Lights[0].Attenuation0 = 0.2f;            device.Lights[0].Range = 10000.0f;            device.Lights[0].Update();            device.Lights[0].Enabled = true;            device.BeginScene();            device.VertexFormat = CustomVertex.PositionNormalColored.Format;            device.SetStreamSource(0, vb, 0);            device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1);            device.EndScene();            device.Present();            this.Invalidate();        }        private void SetupCamera()        {            device.Transform.Projection = Matrix.PerspectiveFovLH((float)Math.PI / 4,                this.Width / this.Height, 1.0f, 100.0f);            device.Transform.View = Matrix.LookAtLH(new Vector3(0, 0, 5.0f), new Vector3(), new Vector3(0, 1, 0));            device.RenderState.Lighting = true;            device.RenderState.CullMode = Cull.None;            device.Transform.World = Matrix.RotationAxis(new Vector3(angle / ((float)Math.PI * 2.0f),                angle / ((float)Math.PI * 4.0f), angle / ((float)Math.PI * 6.0f)), angle / (float)Math.PI);            angle += 0.1f;        }        private void OnVertexBufferCreate(object sender, EventArgs e)        {            VertexBuffer buffer = (VertexBuffer)sender;            CustomVertex.PositionNormalColored[] verts = new CustomVertex.PositionNormalColored[3];            verts[0].Position = new Vector3(0.0f, 1.0f, 1.0f);            verts[0].Normal = new Vector3(0.0f, 0.0f, -1.0f);            verts[0].Color = Color.Aqua.ToArgb();            verts[1].Position = new Vector3(-1.0f, -1.0f, 1.0f);            verts[1].Normal = new Vector3(0.0f, 0.0f, -1.0f);            verts[1].Color = Color.Black.ToArgb();            verts[2].Position = new Vector3(1.0f, -1.0f, 1.0f);            verts[2].Normal = new Vector3(0.0f, 0.0f, -1.0f);            verts[2].Color = Color.Purple.ToArgb();            buffer.SetData(verts, 0, LockFlags.None);        }    }}


[Edited by - TheNobleOne on August 20, 2005 9:00:47 AM]
My JournalComputer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter. (Eric Raymond)"C makes it easy to shoot yourself in the foot. C++ makes itharder, but when you do, it blows away your whole leg."-- Bjarne Stroustrup
Second problem fixed turned out I never created the VertexBuffer for the event to hook to. Still having problems with the first one tho.
My JournalComputer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter. (Eric Raymond)"C makes it easy to shoot yourself in the foot. C++ makes itharder, but when you do, it blows away your whole leg."-- Bjarne Stroustrup
After tons of debugging I narrowed it down a little in the first Null Ref problem it turns out that Manager.GetDeviceCaps is becomming null due to exceptions that are hidden within it. And you can't call ToString on a object that does not exist. Not shure what is going on and I can't seem to fix it.
My JournalComputer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter. (Eric Raymond)"C makes it easy to shoot yourself in the foot. C++ makes itharder, but when you do, it blows away your whole leg."-- Bjarne Stroustrup
textBox1.Text = e.Node.Text + " Capabilities: \r\n\r\n" + Manager.GetDeviceCaps    (e.Node.Index, DeviceType.Hardware).ToString().Replace("\n", "\r\n");

The e.Node.Index thing looks to be the culprit. You add a root node for each adapter you have. However, each root also has its own nodes. So if you select any of these nodes, its index will probably be larger than the number of available adapters, and thus the function will return null (indicating failure, because no such adapter exists).

Associate the adapter number with a given node and all its children in another way.

The error comes before any node is selected because as the form loads in it is fireing that event, I am guessing by a default tree root selection. I can literally specify the node in the program to pull and it still shoots out the error. Not only this but the code in Tom Miller's sources off the cd causes the same problem. Which is why I am leaning to a problem in the DX API.

[Edit] Just tested without all of the node stuff just by passing in the default device param 0 for the primary adapter and same thing happens. [/Edit]

[Edited by - TheNobleOne on August 20, 2005 3:05:01 PM]
My JournalComputer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter. (Eric Raymond)"C makes it easy to shoot yourself in the foot. C++ makes itharder, but when you do, it blows away your whole leg."-- Bjarne Stroustrup
I just checked Manager.GetDeviceCaps with VStudio. It returns a structure, a value type. It can't return null. Add to that, it worked fine with me (June SDK).

Make sure textBox1, e, e.Node and e.Node.Text are not null.

I am using the August 2005 SDK. Note I checked and nothing is null. They are all fine. e.Node.Index comes out to 0 which is what it should be. e.Node.Text contains the name of the Video Card that is in my machine. The textbox is not null it is on my form ready for use and since I am getting null exception it contains no data just "". e can't be null as its members are giving me the right information.
My JournalComputer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter. (Eric Raymond)"C makes it easy to shoot yourself in the foot. C++ makes itharder, but when you do, it blows away your whole leg."-- Bjarne Stroustrup
Hmm..looks like ToString() does something wrong inside, then. You could use reflector or something and check its source code (thought it'd be rather huge). Or you could just upgrade to another SDK.

This topic is closed to new replies.

Advertisement