Raveesh
Raveesh

Reputation: 70

get all service contract method names

Am consuming the WCF service from WPF and I want to list all the method names from service.

I have tried with two solutions, 1.

MethodInfo[] methods = typeof(TypeOfTheService).GetMethods();
foreach (var method in methods)
{
    string methodName = method.Name;
}

It lists all functions but it include some other functions also like "to string","open","abort" etc.


2.

MethodInfo[] methods = typeof(ITimeService).GetMethods();

            foreach (var method in methods)
            {
                if (((System.Attribute)(method.GetCustomAttributes(true)[0])).TypeId.ToString() == "System.ServiceModel.OperationContractAttribute")
                {                 
                    string methodName = method.Name;
                }
            }

it ends up in an error showing "Index out of bound".

Upvotes: 2

Views: 1254

Answers (2)

Yacoub Massad
Yacoub Massad

Reputation: 27871

The problem with the second approach is that not all methods seem to have the OperationContract attribute. Thus for these methods, GetCustomAttributes returns an empty array. Now, when you try to access the first element of the array, you get this exception.

You can simply do something like this:

var attribute = method.GetCustomAttribute(typeof (OperationContractAttribute));

if(attribute != null)
{
    //...
}

to see if the method has the OperationContract attribute.

If what you got is the type of the service itself, you could get all of the interfaces it implements, get all of their methods, and then check if such methods have the OperationContract attribute like this:

var methods =
    typeof (TimeService).GetInterfaces()
    .SelectMany(x => x.GetMethods())
    .ToList();

foreach (var method in methods)
{
    var attribute = method.GetCustomAttribute(typeof(OperationContractAttribute));

    if (attribute != null)
    {
        //...
    }
}

Upvotes: 1

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34234

You can search for methods within service contract, i.e. interface, it will not contain any methods like ToString():

var contractMethods = typeof(ITimeService).GetMethods(); // not TimeService

Upvotes: 1

Related Questions