fotg
fotg

Reputation: 639

Invocation of constructor on type MainWindow threw an exception

I am getting this exception when running my program on other peoples computers.

The invocation of the constructor on type TCPp2pTutorialWPF.MainWindow that matches the specified binding constraints threw an exception. Coming from the PresentationFramework, method: Void RewrapException(System.Exception, System.Xaml.IXamlLineInfo, System.Uri)

the inner exception is Object reference not set to an instance of an object coming from Finalize()

I cannot reproduce this on my own system, or on a virtual machine, or figure out what's causing it. I am confused because I haven't written Finalize()

C# code:

namespace TCPp2pTutorialWPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
    {
    p2pchat network = null;
    SelectUsername name = new SelectUsername ();


    public void MessageRecieved(string username, string message, bool isDisconnect)
        {
        ChatText.Dispatcher.Invoke((Action) ( () =>
            {
            ChatText.AppendText(username + ": " + message+"\r");


            try
                {
                if (isDisconnect)
                    {
                    Users.Dispatcher.Invoke((Action) ( () =>
                        {
                            Users.Items.Remove(username);
                        } ));

                    }
                }
            catch (NullReferenceException f)
                {
                MessageRecieved("ERROR", "We tried accessing the name list when it was null or something (??) "+f.Message + " " + f.Source, false);
                }
            } ));



        }


    public void NewUser(string user)
        {
        ChatText.Dispatcher.Invoke(new Action(() =>
            {
            Users.Items.Add(user);
            } ));
        }


    public MainWindow()
        {

        try
            {
            InitializeComponent();
            }
        catch (Exception e)
            {
            MessageBox.Show("Error initializing main chat window " + e.Message + " " + e.Source + " " + e.HelpLink.ToString() + " " + e.TargetSite);
            }

        if (string.IsNullOrEmpty(name.UserName))
            try
                {
                name.ShowDialog();
                }
            catch (Exception e)
                {
                MessageRecieved("ERROR", e.Message, false);
                }
        network = new p2pchat();
        ChatText.AppendText("port " + network.Port + " may need to be forwarded to accept incoming connections\r");

        //add the handlers
        network.ReceivedMessageHandler += MessageRecieved;
        network.NewUserHandler += NewUser;
        network.MyUserName = name.UserName;
        network.Start();

        }



    private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }



    private void Button_Click(object sender, RoutedEventArgs e)
        {
        Window1 getip = new Window1();
        try
            {
            getip.ShowDialog();
            }
        catch (Exception ee)
            {
            MessageRecieved("ERROR", ee.Message, false);
            }

        string Ip = getip.Ip;

        if (!string.IsNullOrEmpty(Ip))
            network.MakeConnection(Ip);
        }




    private void SendBox_KeyDown(object sender, KeyEventArgs e)
        {
        if (e.Key.Equals(Key.Enter))
            {
            network.SendMessage(new TextRange(SendBox.Document.ContentStart, SendBox.Document.ContentEnd).Text);
            SendBox.Document.Blocks.Clear();
            }
        }


    }
}

XAML:

<Window x:Class="TCPp2pTutorialWPF.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Chat" Height="379.439" Width="716.9" WindowStartupLocation="CenterScreen">
<Grid x:Name="Chat_Window">

    <RichTextBox x:Name="ChatText" HorizontalAlignment="Left" Height="280" Margin="0,23,0,0" VerticalAlignment="Top" Width="553" SpellCheck.IsEnabled="True" IsReadOnly="True" IsUndoEnabled="False" VerticalScrollBarVisibility="Auto" AcceptsReturn="False">
        <RichTextBox.Effect>
            <DropShadowEffect/>
        </RichTextBox.Effect>
        <FlowDocument AllowDrop="False"/>
    </RichTextBox>
    <ListBox x:Name="Users" HorizontalAlignment="Left" Height="280" Margin="558,23,0,0" VerticalAlignment="Top" Width="141" SelectionChanged="ListBox_SelectionChanged"/>
    <Menu x:Name="Menu" HorizontalAlignment="Left" Height="23" VerticalAlignment="Top" Width="699">
        <Button Content="User name"/>
        <Button x:Name="addip" Content="Add IP" Click="Button_Click"/>
    </Menu>
    <RichTextBox x:Name="SendBox" HorizontalAlignment="Left" Height="30" Margin="0,318,0,0" VerticalAlignment="Top" Width="699" SpellCheck.IsEnabled="True" KeyDown="SendBox_KeyDown" AcceptsReturn="False">
        <FlowDocument>
            <Paragraph>
                <Run Text=""/>
            </Paragraph>
        </FlowDocument>
    </RichTextBox>

</Grid>

EDIT: adding in screenshots of the stack traces, not going to type that. Will log it to a file for now on.

And adding in the upnp_helper code since it seems to reference it.

namespace TCPp2pTutorialWPF
{
class UPNP_Helper
    {
    UPnPNAT NatMgr;
    List<int> ports = new List<int>();

    public UPNP_Helper()
        {
        NatMgr = new UPnPNAT();
        }


    ~UPNP_Helper()
        {
        foreach (int i in ports)
            {
            try
                {
                NatMgr.StaticPortMappingCollection.Remove(i, "TCP");
                }
            catch
                {
                }
            }
        }





    public bool AddMappingToThisLocalIp(int port)
        {
        try
            {
            NatMgr.StaticPortMappingCollection.Add(port, "TCP", port, LocalIPAddress().ToString(), true, "p2pChat");
            ports.Add(port);
            return true;
            }
        catch
            {
            return false;
            }
        }




    private IPAddress LocalIPAddress()
        {
        if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
            return null;
            }

        IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
        return host
            .AddressList
            .FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
        }

    }
}

Upvotes: 0

Views: 3977

Answers (2)

fotg
fotg

Reputation: 639

WPF included in .NET 4.5 for windows 8.1 seems to be a slightly newer version than whats included in .NET 4.5 for windows 7, my test subjects claimed to have the latest version, but couldn't find the actual version installed. This problem was caused by app.Run(); and was solved by targeting an earlier version of .NET.

Upvotes: 1

Sheridan
Sheridan

Reputation: 69985

This is a common development scenario. Something in your code is null when run on another machine... but what? The easiest way to find out is to add a bunch of calls to MessageBox.Show:

public MainWindow()
{

try
    {
    InitializeComponent();
    }
catch (Exception e)
    {
    MessageBox.Show("Error initializing main chat window " + e.Message + " " + e.Source + " " + e.HelpLink.ToString() + " " + e.TargetSite);
    }

MessageBox.Show(string.Format("name: {0}, UserName: {1}", name, name.UserName));

if (string.IsNullOrEmpty(name.UserName))
    try
        {
        name.ShowDialog();
        }
    catch (Exception e)
        {
        MessageRecieved("ERROR", e.Message, false);
        }
network = new p2pchat();

MessageBox.Show(string.Format("ChatText: {0}, network: {1}", ChatText, network));

ChatText.AppendText("port " + network.Port + " may need to be forwarded to accept incoming connections\r");

//add the handlers
network.ReceivedMessageHandler += MessageRecieved;
network.NewUserHandler += NewUser;
network.MyUserName = name.UserName;
network.Start();

}

Now you should get a number of MessageBoxes popping up with relevant values in and one of them should be null. So that's half of the problem sorted out... next you just need to work out why that value was null and fix it.

Upvotes: 0

Related Questions