Skip to content

Instantly share code, notes, and snippets.

@amitapl
Created September 4, 2012 22:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitapl/3627234 to your computer and use it in GitHub Desktop.
Save amitapl/3627234 to your computer and use it in GitHub Desktop.
Custom parameters for azure mobile services
/// <summary>
/// Add custom parameters to each request when applying this filter to a mobile service client.
/// </summary>
public class CustomParametersServiceFilter : IServiceFilter
{
private IDictionary<string, object> parameters;
public CustomParametersServiceFilter(IDictionary<string, object> parameters)
{
this.parameters = parameters;
}
public IAsyncOperation<IServiceFilterResponse> Handle(IServiceFilterRequest request, IServiceFilterContinuation continuation)
{
// Get previous uri query
var uriBuilder = new UriBuilder(request.Uri);
var oldQuery = (uriBuilder.Query ?? string.Empty).Trim('?');
// Build new query starting with our custom parameters before old query
var stringBuilder = new StringBuilder();
foreach (var parameter in parameters)
{
// Currently using ToString on the value, an improvement will be to serialize the object properly
stringBuilder.AppendFormat("{0}={1}&", parameter.Key, parameter.Value);
}
stringBuilder.Append(oldQuery);
// Apply new query to request uri
uriBuilder.Query = stringBuilder.ToString().Trim('&');
request.Uri = uriBuilder.Uri;
return continuation.Handle(request);
}
}
public static class ServiceFilterHelpers
{
public static IMobileServiceTable<T> GetTable<T>(this MobileServiceClient mobileService, object parametersObject)
{
if (parametersObject != null)
{
// Extract parameters to a dictionary
Dictionary<string, object> parameters = new Dictionary<string, object>();
foreach (var property in IntrospectionExtensions.GetTypeInfo(parametersObject.GetType()).DeclaredProperties)
{
string name = property.Name;
object value = property.GetValue(parametersObject);
parameters[name] = value;
}
// Apply custom parameters filter and get the requested table
return mobileService.WithFilter(new CustomParametersServiceFilter(parameters)).GetTable<T>();
}
return mobileService.GetTable<T>();
}
}
List<User> allUsers = await App.MobileService.GetTable<User>(new { allUsers = true }).ToListAsync();
function read(query, user, request) {
// Check for the allUsers custom parameter
if (request.parameters != null && request.parameters.allUsers == "true")
{
// With this custom parameter only return the names of the users
query.select('name');
}
else
{
// Without it return the current authenticated user only
query.where({serviceUserId: user.userId});
}
request.execute();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment