Tuesday 8 December 2015

Read Service End points , Method Details in client Side using Reflection

 [HttpPost]
        [AllowAnonymous]
        public JsonResult ListServiceEndPoints()
        {
            ClientSection clientSection = (ClientSection)ConfigurationManager.GetSection("system.serviceModel/client");

            List<WcfServiceEndPointDetails> endPointDetails = new List<WcfServiceEndPointDetails>();

            for(int i = 0; i < clientSection.Endpoints.Count; i++)
            {
                var endPoint = clientSection.Endpoints[i];
                List<EndPointContractOperations> operationDetails = GetContractOperationDetails(endPoint);
                endPointDetails.Add(new WcfServiceEndPointDetails()
                {
                    EndPointName = endPoint.Name,
                    EndPointAddress = endPoint.Address.ToString(),
                    ContractName = endPoint.Contract,
                    ContractOperations = operationDetails
                });
            }
            return Json(new { Success = true, Data = endPointDetails });
        }

        /// <summary>
        /// Get Operations Details
        /// </summary>
        /// <param name="endPoint">endPoint</param>
        /// <returns>EndPoint Contract Operations</returns>
        private List<EndPointContractOperations> GetContractOperationDetails(ChannelEndpointElement endPoint)
        {
            List<EndPointContractOperations> endPointContractOperations = new EditableList<EndPointContractOperations>();

            try
            {
                ContractDescription contractDescription =
                    ContractDescription.GetContract(
                        typeof (IAuthenticationSessionApi));
                foreach (OperationDescription operation in contractDescription.Operations)
                {
                    endPointContractOperations.Add(new EndPointContractOperations()
                    {
                        OperationName = operation.Name,
                        Signature = MethodSignature(operation.SyncMethod),
                        OperationDescription = string.Empty
                    });
                }
            }
                //// Empty Catch -  If any Contract throw error then it will continue to read other Contract Operations
            catch (Exception)
            {
            }

            return endPointContractOperations;
        }

        public static string MethodSignature(MethodInfo mi)
        {
            String[] param = mi.GetParameters()
                .Select(p => String.Format("{0} {1}", p.ParameterType.Name, p.Name))
                .ToArray();


            string signature = String.Format("{0} {1}({2})", mi.ReturnType.Name, mi.Name, String.Join(",", param));

            return signature;
        }