How to pass boolean parameters to a restful service? - wcf

What is the best way to pass boolean parameters to a WCF RESTful service?
Using trueor false like this:
api/resource?hasProperty=true
or using 0 or 1 like this:
api/resource?hasProperty=1

I like the
api/resource?hasProperty=true
approach because it is more user-friendly.
It tells the API consumer indirectly that it is a boolean parameter. 0 or 1 does not imply that.

They both are ok! It depends on your underlying logic.
[OperationContract]
[WebGet(UriTemplate="api/resource?hasProperty={hasProperty}")]
bool propertyCheck(bool hasProperty);
Or you can use otherwise!
OperationContract]
[WebGet(UriTemplate="api/resource?hasProperty={hasProperty}")]
bool propertyCheck(int hasProperty);
And in its implementation! Just check whether it is "true" or contain "0/1".

Related

General advice on returning success messages in WCF WebMethods

I'm just looking for some general advice with this one please. My WCF WebMethod needs to work across applications using different software, e.g. ASP.NET --> Java, for example.
I know that in the event of a method failing, I can utilize FaultException(Of MyError) to generate a SOAP Fault, however, what is generally the best way to send a success message?
Take for example the following interface that defines functionality for saving a user into a database:
<ServiceContract()>
Public Interface IService1
<OperationContract()>
Sub SaveUserIntoDataBase(ByVal u As MyAppUser)
End Interface
<DataContract()>
Public Class MyAppUser
<DataMember()>
Public Property FirstName() As String
<DataMember()>
Public Property Surname() As String
End Class
If I needed to send feedback that the user was saved successfully, how would this be generally done? Is there a 'success' equivalent of a FaultException, or is it recommended to just return Boolean or a String?
I suppose a value should always be returned?
There isn't any equivalent success result to exception if execution of service call doesn't fail.
One option is to create some customzed types such as enums and return those based upon different results from underlying source.
The return types of every call may be different or customized to user needs. Returning a boolean value is better than some string value in your case. Also you are using a "Sub", so if its a function then this could be one case.
You can follow some discussion here as well:
Whats the best practice for returning a Boolean and string value
There is no need for a success message. If the operation did not fail, then it was a success.
Use a FaultException to indicate failure.

Passing Objects Between WCFs

I have an ASP application, which calls an HTTP WCF service, which calls a TCP WCF service (all on different servers). I'm ultimately trying to pass one class object between the three.
I've discovered that I can't do this directly in the HTTP WCF, even though my class object is defined identically in BOTH WCFs. Like this:
Public Function CallOtherFunction(ByVal ThisClass as MyClass)
Dim RetVal as Boolean
RetVal = CallMyOtherWCFFunction(ThisClass)
End Function
Instead I have to:
Public Function CallOtherFunction(ByVal ThisClass as MyClass)
Dim RetVal as Boolean
Dim MyOutgoingClass as MyOtherWCF.MyClass
MyOutgoingClass.MyString = ThisClass.MyString
RetVal = CallMyOtherWCFFunction(MyOutgoingClass)
End Function
My objects are rather large, to say they have a lot of properties. Any way to not have to declare a new variable in my calling function, so my code can be a little easier (like the first example)?
Thanks,
Jason
You can't pass it directly because those are two diffrent types. You can, however, declare your data contracts in a shared assembly (used by the three projects, or at least by the HTTP and the TCP services), an when adding the service reference to create the proxy in the HTTP service, you specify that you want to "reuse types in referenced assemblies". This way it should use the same type in all projects.

How to access properties dynamically / late-bound?

I'd like to implement a method which allows me to access a property of an unknown/anonymous object (-graph) in a late-bound / dynamic way (I don't even know how to correctly call it).
Here's an example of what I'd like to achieve:
// setup an anonymous object
var a = new { B = new { C = new { I = 33 } } };
// now get the value of a.B.C.I in a late-bound way
var i = Get(a, "B.C.I");
And here's a simple implementation using "classic" reflection:
public static object Get(object obj, string expression)
{
foreach (var name in expression.Split('.'))
{
var property = obj.GetType().GetProperty(name);
obj = property.GetValue(obj, null);
}
return obj;
}
What other options do I have with C# / .NET 4 to implement something similar as shown above, but maybe simpler, more performant, etc.?
Maybe there are ways to achieve the same thing, which would allow me to specify expression using a lambda expression instead of a string? Would expression trees be helpful in any way (e.g. as shown in this question)?
Update: the object and the expression are passed into my code via a web service call. That's why I used object and string in my Get() method.
Do you actually only have the expression as a string? Is it known at compile-time, just that the types themselves aren't known (or are hard to express)? If so:
dynamic d = a;
int i = d.B.C.I;
If you really only have it as a string (e.g. as user-entered data) that makes life a lot harder, and none of the C# 4 features really help you. You could potentially evaluate it as an IronPython script or something like that...
EDIT: Okay, after the update it sounds like you're in the latter situation - in which case, I don't know of a nicer way than using reflection. Some of the built-in property binding built for UIs may help, but I don't know of a clean way of accessing it.
If you want to use C# style, you could use the Mono compiler as a service from your application. I describe how to do this here:
Mono Compiler as a Service (MCS)
As an alternative approach, you could use reflection to put all of your object's properties into an ExpandoObject then use it like a dictionary (because ExpandoObject implements IDictionary). Alternatively, you could use JSON.NET and call JObject.FromObject, which will turn a regular object into a JObject which is accessible in a dictionary-like style (and as an added benefit has recursive graph support). Lastly, you could use the same approach to dump your object into a dictionary of dictionaries.

best practice for return value in WCF services

I have a WCF service sitting in the cloud.
And my application makes several calls to this WCF service.
Is it a best practise:
1] to always use return value as bool which indicates if the operation was sucessful or not.
2] returning the values you meant to return as the OUT parameters
I would:
return an atomic value (bool, string, int) if appropriate
return a complex type (a class instance) if I need to return more than one value - make sure to mark that class with [DataContract] and its properties with [DataMember]
a SOAP fault FaultException<T> when an error occurs; the <T> part allows you to define your own custom error classes, and again - don't forget to mark them with [DataContract] / [DataMember] and declare them as FaultContract on your operations
1] to always use return value as bool which indicates if the operation was sucessful or not
Yes, if the operation isnĀ“t time consuming AND the return status is always relevant:
Waiting on a return value can affect both client and service host(server) performance/scalability. Ex. in a Request-Responsecall, Requests can keep connections open for a long preriod of time waiting for operation completion. You could implement in a way similar to "HTTP 202 Accepted" status code usage(i.e operation received arguments and has started(patially), but does wait for the completion)
No, if the operation logic only makes sense if synchronous.
No, if you are keen on refactorability/maintainability ex. when you want to return include an error message/code in the return.
2] returning the values you meant to return as the OUT parameters
Yes, this makes the service operation more wsdl compliant and easy to read.

Recommended naming conventions for same method with different signatures?

been creating a few wcf methods and i have a method called IsValidLogin ... there various versions, 1 takes 2 strings, 1 takes an object etc.
Of course in WCF you can't overload methods can anyone suggest the best way to name these methods..
I was thinking of IsValidLogin1, IsValidLogin2??
But I am open to any suggestions.
When you start adding index numbers to your identifiers, you're usually doing it wrong.
One way I've seen is adding "With" and the parameter names to the name, i.e. IsValidLoginWithUsernamePassword, and IsValidLoginWithToken (assuming your object is some kind of authentication token). These are kind of long though.
I'd just call the methods IsValidUsernamePassword and IsValidToken.
First of all, you should stick with message/contract first methodology when working with wcf services, passing in a request and returning a response. This will save you a lot of headache down the road.
That being said, you should create two methods like so:
public LoginValidResponse IsLoginValid(UserObjectRequest userRequest)
and
public LoginValidResponse IsLoginValid(UsernamePasswordRequest usernameRequest)
There are probably better names for these, but you get the idea. If you provided more information about what you were passing in and back, I could help out with naming a bit more.
Notice these two methods return the same response LoginValidResponse.
Put your two strings in the UsernamePasswordRequest (I'm assuming the strings are username and password). Put the User Object in the UserObjectRequest.
You can also reuse these requests / responses in later methods, e.g, GetUserInfo(UserObjectRequest request).
The LoginValidResponse will contain your bool (and any other information you want to pass back in your response).
*Note - I only named the methods IsLoginValid b/c that was your question. On top of the request / response pattern, I might also rename the methods to something like ValidateLoginByUser and ValidateLoginByUsername (or something like that).
Of course in WCF you can't overload methods can anyone suggest the best way to name these methods..
You can overload methods in WCF by adding unique OperationContract behaviours. OperationContract has the Name property that exposes the WCF methods to WSDL Schemas. Your service-side (WCF) code would remain clean. But you would still have to call the methods by signature you defined in the Name property of the OperationContract behaviour.
[OperationContract(Name="IsValidLoginWithUsernameAndPassword")]
void IsValidLogin(string username,string password);
[OperationContract(Name="IsValidLoginWithToken")]
void IsValidLogin(AuthToken token);
Usage......
TestClient client = new TestClient();
string callMethod1 = client.IsValidLoginWithUsernameAndPassword("user","pass");
string callMethod2 = client.IsValidLoginWithToken(authToken);
You can read more here
http://www.codeproject.com/Tips/656042/Method-Overloading-in-WCF
I don't think that IsValidLogin1,2, etc. is clear enough. When you overload methods normally, you don't have to worry about names because it's the same name with different parameters, however in this case you have to remember the parameters for each method, and numbers could get confusting.
I might suggest IsValidLoginNumStr etc, which is to say, maybe list key parameters in the method name to help remind you which method you're referring to. Either that or if one takes a password, then IsValidLoginPass, or something of the like. I say this because I'm a fan of long, descriptive method names. If you want to keep the name short as possible, and you can think of a letter that would help, like P for password, or O for object, then tack on a helpful letter at the end. Something more than a number will help you in the long run