在MainWindow类型上调用构造函数引发了异常

时间:2014-01-27 08:10:39

标签: c# wpf exception

我在其他人的计算机上运行我的程序时遇到此异常。

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

内部异常Object reference not set to an instance of an object来自Finalize()

我无法在我自己的系统或虚拟机上重现这一点,或找出导致它的原因。我很困惑,因为我没有写过Finalize()

C#代码:

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>

编辑:添加堆栈跟踪的屏幕截图,而不是输入。现在将它记录到文件中。

并添加upnp_helper代码,因为它似乎引用它。

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);
        }

    }
}

2 个答案:

答案 0 :(得分:0)

这是一种常见的开发方案。在另一台机器上运行时,代码中的某些内容为null ...但是什么?最简单的方法是向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();

}

现在,您应该获得一些MessageBox es弹出相关值,其中一个应该是null。所以问题的一半已经解决了......下一步只需要解决为什么这个值是null并修复它。

答案 1 :(得分:0)

Windows 4.5 for Windows 8.1中包含的WPF似乎比.NET 4.5 for Windows 7中包含的版本略微更新,我的测试对象声称拥有最新版本,但找不到安装的实际版本。此问题是由app.Run();引起的,并通过定位早期版本的.NET来解决。