.NET Remoting Part Three

We will host .net service into console application . Make sure you must add the reference from last class library project . Here is the code for run the service ..

namespace Server
{
    public class StudentRemotingService : MarshalByRefObject, IStudentRemotingService
    {
        public StudentRemotingService()
        {
        }

     public string Insert(string Name, string Address, string Email, string Mobile)
        {
            string messsage = null;
            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();
                    return messsage;


                }
            }
        }

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

        public void Update(int Student_Id, 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("UpdateStudent", con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Student_Id", Student_Id);
                    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();
                }
            }
        }


      public   DataTable GetRecord(int Student_Id)
        {
            string constr = ConfigurationManager.ConnectionStrings["StudentConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM Student where Student_Id=@Student_Id"))
                {
                    cmd.Parameters.AddWithValue("@Student_Id", Student_Id);
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        using (DataTable dt = new DataTable())
                        {
                            dt.TableName = "Student";
                            sda.Fill(dt);
                            return dt;
                        }
                    }
                }
            }
        }


        public DataTable Get()
        {
            string constr = ConfigurationManager.ConnectionStrings["StudentConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM Student"))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        using (DataTable dt = new DataTable())
                        {
                            dt.TableName = "Student";
                            sda.Fill(dt);
                            return dt;
                        }
                    }
                }
            }
        }

        public void Delete(int Student_Id)
        {
            string constr = ConfigurationManager.ConnectionStrings["StudentConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("DeleteStudent", con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.Parameters.AddWithValue("@Student_Id", Student_Id);
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }
    }

    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(StudentRemotingService),
                                                               "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);
        }
    }
}

Finally make sure you added the connection string into app.config file ..
  <connectionStrings>
        <add name="StudentConnectionString" connectionString="Data Source=.;Initial Catalog=3TierInWindowsApplication;Integrated Security=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>

No comments:

Post a Comment