Friday, August 10, 2012

In C#, how to check if a TCP port is available?

When hosting wcf service which is use net tcp binding and without port sharing in a windows service , we should make sure the availability of our wcf port number. Other wise service doesn't start.

There fore as a best practice its is better to have code which will check the availability of the port when starting the service.This code should included to the service startup event. 

   1: protected override void OnStart(string[] args)
   2:        {
   3:            try
   4:            {
   5:                if (serviceHost != null)
   6:                {
   7:                    serviceHost.Close();
   8:                }
   9:  
  10:                PortChecker pc = new PortChecker();
  11:  
  12:                if (pc.IsPortAvailable())
  13:                {
  14:                    serviceHost = new ServiceHost(typeof(M3ISPlusService));
  15:                    serviceHost.Open();
  16:                }
  17:            }


ANd this is the port checker class



   1: public bool IsPortAvailable()
   2:         {
   3:             bool isAvailable = false;
   4:             TcpListener tcpListner = new TcpListener(GetServerIp(), GetPort());
   5:             Logger logger = Logger.GetLogger();
   6:  
   7:             try
   8:             {
   9:                 tcpListner.Start();
  10:                 isAvailable = true;
  11:             }
  12:             catch (Exception ex)
  13:             {
  14:                 logger.Log(ex.Message);
  15:             }
  16:  
  17:             finally
  18:             {
  19:                 try
  20:                 {
  21:                     tcpListner.Stop();
  22:                     tcpListner = null;
  23:                 }
  24:                 catch (Exception)
  25:                 {
  26:                     tcpListner = null;
  27:                 }
  28:             }
  29:  
  30:             return isAvailable;
  31:         }

To get port in code please refer my previous post :- Read End point address programmatically


Happy Coding :)

Friday, August 3, 2012

Programmatically reading endpoint address from web.config file?

 

There are some instances where we have to read wcf endpoint url from the code.As following you can accomplish that task.

once we add a service to the code it will get added to web.config under <system.serviceModel> section.

so we can access web config like this.

ServicesSection servicesSection = (ServicesSection)ConfigurationManager.GetSection(BASE_ADDRESS_PATH);

var item = servicesSection.Services[0].Host.BaseAddresses[0].BaseAddress;
Uri baseAddress = new Uri(item);