簡體   English   中英

Windows窗體應用程序因.NET Remoting Service失敗

[英]Windows Form Application failed with .NET Remoting Service

我正在嘗試使用application的Windows將數據插入數據庫。 我將其托管到控制台應用程序中。 我正在使用.net遠程處理來調用該方法。 我的主機正在運行,沒有任何問題,我也可以運行Windows窗體應用程序,沒有任何問題。 但是問題是當我單擊“提交”按鈕以插入數據時出現錯誤。我不知道為什么會收到此錯誤。

引發的異常:mscorlib.dll中的'System.NullReferenceException'其他信息:對象引用未設置為對象的實例。 發生了

這是接口。

namespace IHelloRemotingService
{
    public interface IHelloRemotingService
    {

        void Insert(string Name, string Address, string Email, string Mobile)
    }


}

這是接口的實現..

public class HelloRemotingService : MarshalByRefObject , IHelloRemotingService.IHelloRemotingService
{
    public void Insert(string Name, string Address, string Email, string Mobile)
        {
            string constr = ConfigurationManager.ConnectionStrings["StudentConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("AddNewStudent", con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Name", Name);
                    cmd.Parameters.AddWithValue("@Address", Address);
                    cmd.Parameters.AddWithValue("@EmailID", Email);
                    cmd.Parameters.AddWithValue("@Mobile", Mobile);
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();

                }
            }
        }
    }
    }

托管服務代碼....

 namespace RemotingServiceHost
{

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("          .NET Remoting Test Server");
            Console.WriteLine("          *************************");
            Console.WriteLine();

            try
            {
                StartServer();
                Console.WriteLine("Server started");
                Console.WriteLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Server.Main exception: " + ex);
            }

            Console.WriteLine("Press <ENTER> to exit.");
            Console.ReadLine();

            StopServer();

        }

        static void StartServer()
        {
            RegisterBinaryTCPServerChannel(500);

            RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;

            RemotingConfiguration.RegisterWellKnownServiceType(typeof(HelloRemotingService.HelloRemotingService),
                                                               "Insert.rem",
                                                               WellKnownObjectMode.Singleton);
        }

        static void StopServer()
        {
            foreach (IChannel channel in ChannelServices.RegisteredChannels)
            {
                try
                {
                    ChannelServices.UnregisterChannel(channel);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Server.StopServer exception: " + ex);
                }
            }
        }

        static void RegisterBinaryTCPServerChannel(int port, string name = "tcp srv")
        {
            IServerChannelSinkProvider firstServerProvider;
            IClientChannelSinkProvider firstClientProvider;

            var channelProperties = new Hashtable();
            channelProperties["typeFilterLevel"] = TypeFilterLevel.Full;
            channelProperties["machineName"] = Environment.MachineName;
            channelProperties["port"] = port;


            // create server format provider
            var serverFormatProvider = new BinaryServerFormatterSinkProvider(null, null); // binary formatter
            serverFormatProvider.TypeFilterLevel = TypeFilterLevel.Full;
            firstServerProvider = serverFormatProvider;

            // create client format provider
            var clientProperties = new Hashtable();
            clientProperties["typeFilterLevel"] = TypeFilterLevel.Full;
            var clientFormatProvider = new BinaryClientFormatterSinkProvider(clientProperties, null);
            firstClientProvider = clientFormatProvider;

            TcpChannel tcp = new TcpChannel(channelProperties, firstClientProvider, firstServerProvider);
            ChannelServices.RegisterChannel(tcp, false);
        }
    }
}

Windows窗體應用程序的代碼..

   namespace HelloRemotingServiceClient
{
    public partial class InsertStudentData : Form
    {


        public InsertStudentData()
        {
            InitializeComponent();
            RegisterBinaryTcpClientChannel();
        }



        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                var remService = (IHelloRemotingService.IHelloRemotingService)Activator.GetObject(typeof(IHelloRemotingService.IHelloRemotingService), "tcp://localhost:500/Insert.rem");
                remService.Insert(textName.Text, textAddress.Text, textEmail.Text, textBox1.Text);
                label5.Text = "Recored Inserted Successfully";
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        private void RegisterBinaryTcpClientChannel(string name = "tcp client")
        {
            IClientChannelSinkProvider firstClientProvider;
            IServerChannelSinkProvider firstServerProvider;

            var channelProperties = new Hashtable();
            channelProperties["name"] = name;
            channelProperties["typeFilterLevel"] = TypeFilterLevel.Full;
            channelProperties["machineName"] = Environment.MachineName;
            channelProperties["port"] = 0; // auto

            // create client format provider
            var clientProperties = new Hashtable();
            clientProperties["typeFilterLevel"] = TypeFilterLevel.Full;
            var clientFormatProvider = new BinaryClientFormatterSinkProvider(clientProperties, null);
            firstClientProvider = clientFormatProvider;

            // create server format provider
            var serverFormatProvider = new BinaryServerFormatterSinkProvider(null, null);
            serverFormatProvider.TypeFilterLevel = TypeFilterLevel.Full;
            firstServerProvider = serverFormatProvider;

            TcpChannel tcp = new TcpChannel(channelProperties, firstClientProvider, firstServerProvider);
            ChannelServices.RegisterChannel(tcp, false);
        }
    }
}

表格設計..

在此處輸入圖片說明

這是錯誤消息的屏幕截圖。

在此處輸入圖片說明 文本框能夠捕獲值,但為什么會引發此錯誤?

這是一個工作項目。 您沒有配置格式化程序。

SharedLib項目:

namespace IHelloRemotingService
{
  public interface IHelloRemotingService
  {
    void Insert(string Name, string Address, string Email, string Mobile);
  }
}

服務器控制台項目:

namespace Server
{
  public class HelloRemotingService : MarshalByRefObject, IHelloRemotingService.IHelloRemotingService
  {
    public HelloRemotingService()
    {
    }

    public void Insert(string Name, string Address, string Email, string Mobile)
    {
      Console.WriteLine("HelloRemotingService.Insert called");

    }

    public override object InitializeLifetimeService()
    {
      return null; // manage lifetime by myself
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("          .NET Remoting Test Server");
      Console.WriteLine("          *************************");
      Console.WriteLine();

      try
      {
        StartServer();
        Console.WriteLine("Server started");
        Console.WriteLine();
      }
      catch (Exception ex)
      {
        Console.WriteLine("Server.Main exception: " + ex);
      }

      Console.WriteLine("Press <ENTER> to exit.");
      Console.ReadLine();

      StopServer();

    }

    static void StartServer()
    {
      RegisterBinaryTCPServerChannel(500);

      RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;

      RemotingConfiguration.RegisterWellKnownServiceType(typeof(HelloRemotingService), 
                                                         "Insert.rem", 
                                                         WellKnownObjectMode.Singleton);
    }

    static void StopServer()
    {
      foreach (IChannel channel in ChannelServices.RegisteredChannels)
      {
        try
        {
          ChannelServices.UnregisterChannel(channel);
        }
        catch(Exception ex)
        {
          Console.WriteLine("Server.StopServer exception: " + ex);
        }
      }
    }

    static void RegisterBinaryTCPServerChannel(int port, string name = "tcp srv")
    {
      IServerChannelSinkProvider firstServerProvider;
      IClientChannelSinkProvider firstClientProvider;

      var channelProperties                = new Hashtable();
      channelProperties["typeFilterLevel"] = TypeFilterLevel.Full;
      channelProperties["machineName"]     = Environment.MachineName;
      channelProperties["port"]            = port;


      // create server format provider
      var serverFormatProvider             = new BinaryServerFormatterSinkProvider(null, null); // binary formatter
      serverFormatProvider.TypeFilterLevel = TypeFilterLevel.Full;
      firstServerProvider                  = serverFormatProvider;

      // create client format provider
      var clientProperties                = new Hashtable();
      clientProperties["typeFilterLevel"] = TypeFilterLevel.Full;
      var clientFormatProvider            = new BinaryClientFormatterSinkProvider(clientProperties, null);
      firstClientProvider                 = clientFormatProvider;

      TcpChannel tcp = new TcpChannel(channelProperties, firstClientProvider, firstServerProvider);
      ChannelServices.RegisterChannel(tcp, false);
    }
  }
}

客戶端WinForms項目:

namespace Client
{
  public partial class MainForm : Form
  {
    public MainForm()
    {
      InitializeComponent();

      RegisterBinaryTcpClientChannel();
    }

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);

      using (MainForm form = new MainForm())
      {
        Application.Run(form);
      }
    }

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>    
    protected override void Dispose(bool disposing)
    {
      if (disposing)
      {
        foreach (IChannel channel in ChannelServices.RegisteredChannels)
        {
          try
          {
            ChannelServices.UnregisterChannel(channel);
          }
          catch (Exception ex)
          {
            Debug.WriteLine("Client.Dispose exception: " + ex);
          }
        }

        if (components != null)
          components.Dispose();
      }
      base.Dispose(disposing);
    }

    private void _btnAccessServer_Click(object sender, EventArgs e)
    {
      try
      {
        var remService = (IHelloRemotingService.IHelloRemotingService)Activator.GetObject(typeof(IHelloRemotingService.IHelloRemotingService), "tcp://localhost:500/Insert.rem");
        remService.Insert("MyName", "MyAddress", "MyEmail", "MyMobile");
      }
      catch (Exception ex)
      {
        MessageBox.Show("Error: " + ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }

    private void RegisterBinaryTcpClientChannel(string name = "tcp client")
    {
      IClientChannelSinkProvider firstClientProvider;
      IServerChannelSinkProvider firstServerProvider;

      var channelProperties                = new Hashtable();
      channelProperties["name"]            = name;
      channelProperties["typeFilterLevel"] = TypeFilterLevel.Full;
      channelProperties["machineName"]     = Environment.MachineName;
      channelProperties["port"]            = 0; // auto

      // create client format provider
      var clientProperties                = new Hashtable();
      clientProperties["typeFilterLevel"] = TypeFilterLevel.Full;
      var clientFormatProvider            = new BinaryClientFormatterSinkProvider(clientProperties, null);
      firstClientProvider                 = clientFormatProvider;

      // create server format provider
      var serverFormatProvider             = new BinaryServerFormatterSinkProvider(null, null);
      serverFormatProvider.TypeFilterLevel = TypeFilterLevel.Full;
      firstServerProvider                  = serverFormatProvider;

      TcpChannel tcp = new TcpChannel(channelProperties, firstClientProvider, firstServerProvider);
      ChannelServices.RegisterChannel(tcp, false);
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM