c # - Windows Form Application mislykkedes med .NET Remoting Service

Indlæg af Hanne Mølgaard Plasc

Problem



Jeg forsøger at indsætte data i database ved hjælp af windows fra applikationen. Jeg hostede det i konsol ansøgning. Jeg bruger .net fjernelse for at påberåbe metoden. Min vært kører uden problemer, og jeg kan også køre Windows-formularapplikationen uden noget problem. Men problemet er, når jeg klikker på Submit-knappen for at indsætte data, jeg fik fejl. Jeg ved ikke, hvorfor jeg får denne fejl.


Undtaget: 'System.NullReferenceException' i mscorlib.dll
Yderligere oplysninger: Objektreference er ikke angivet til en forekomst af et objekt. Der opstod



Her er grænsefladen.


namespace IHelloRemotingService
{
    public interface IHelloRemotingService
    {

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


}


Her er implementeringen af ​​grænsefladen ..


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

                }
            }
        }
    }
    }


Kode til hosting service ....


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


Kode til Windows formular ansøgning ..


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


Design af formularen ..


Indtast billedbeskrivelse her [8]


Her er skærmbilledet af fejlmeddelelser.


Indtast billedbeskrivelse her
Tekstfelterne kan fange værdierne, men hvorfor kaster den denne fejl? [9]

Bedste reference


Her er et arbejdsprojekt. Du har ikke konfigureret formateringen.


SharedLib Project:


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


Server Console Project:


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


Client WinForms Project:


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