Skip Navigation LinksHome > View Post

Filter this (Day 3)

One of my favorite hidden nuggets in Mobile Services is Service Filters. Service Filters allow you to place an interceptor between your client’s CRUD calls and the server. There are many useful applications for this, but one of my favorites is the ability to easily create a ‘busy’ or ‘activity’ indicator based on in-flight requests to the your Mobile Service. Here’s how in C#:

public class MyServiceFilter : IServiceFilter
{
    private int _callCount = 0;
    private Action<bool> _busyIndicator;

public MyServiceFilter(Action<bool> busyIndicator) { _busyIndicator = busyIndicator; }

public Windows.Foundation.IAsyncOperation<
IServiceFilterResponse> Handle( IServiceFilterRequest request, IServiceFilterContinuation continuation) { return HandleAsync(request, continuation).
AsAsyncOperation(); }

private async Task<IServiceFilterResponse> HandleAsync( IServiceFilterRequest request, IServiceFilterContinuation continuation) { // update the count by one in a single atomic operation. // If we get a 1 back, we know we just went 'busy' var outgoingCount = Interlocked.Increment(ref _callCount); if (outgoingCount == 1) { _busyIndicator(true); }

IServiceFilterResponse response = await continuation.Handle( request).AsTask();

// decrement the count by one in a single atomic operation. // If we get a 0 back, we know we just went 'idle' var incomingCount = Interlocked.Decrement(ref _callCount); if (incomingCount == 0) { _busyIndicator(false); }

return response; } }

The first step is to implement the IServiceFilter interface from the Microsoft.WindowsAzure.MobileServices namespace. There is just one method to implement called Handle. In the code above,  I simply delegate to HandleAsync to keep the code somewhat cleaner and allowing me to use .Net’s awesome Task framework. HandleAsync is where all the magic happens.

Inside HandleAsync, we know we have an outgoing call about to be started to increment the filter’s in-flight call count by one. If the call count is 1, we know we just went from no inflight calls to some, so we call the ‘busy’ delegate.

Next we actually invoke the server by calling Handle on the continuation parameter. Thanks to the awesome await keyword, we can keep our incoming response code right inline in the same method, and this is where we decrement the filter’s call count. If we have a new total of 0, we know we just went ‘idle’ and invoke the busy delegate with a value of false.

It really couldn’t be easier!

And now, to consume this filter we have to wrap our MobileServiceClient instance as follows:

var filter = new MyServiceFilter(busy =>
{
      // update the status of the busy indicator based on the status change
      progressControl.Visible = busy ? Visibility.Visible : Visibility.Collapsed;
}));

// use the newClient instance for all operations that should use busy tracking
var newClient = originalClient.WithFilter(filter);

You can also use filters in our WinJS client and the Objective C client for iOS. If you checkout the iOS quickstart you’ll notice that you get a sample implementation for free.

iOS (Objective C)

In iOS, using a service filter is as easy as implementing the MSFilter protocol, here’s an example:

- (void) handleRequest:(NSURLRequest *)request
                onNext:(MSFilterNextBlock)onNext
            onResponse:(MSFilterResponseBlock)onResponse
{
    // A wrapped response block that decrements the busy counter
    MSFilterResponseBlock wrappedResponse = ^(NSHTTPURLResponse *response, 
NSData *data,
NSError *error) { [self busy:NO]; onResponse(response, data, error); }; // Increment the busy counter before sending the request [self busy:YES]; onNext(request, wrappedResponse); }

And then in the same class, we have a busy method:

- (void) busy:(BOOL) busy
{
    // assumes always executes on UI thread
    if (busy) {
        if (self.busyCount == 0 && self.busyUpdate != nil) {
            self.busyUpdate(YES);
        }
        self.busyCount ++;
    }
    else
    {
        if (self.busyCount == 1 && self.busyUpdate != nil) {
            self.busyUpdate(FALSE);
        }
        self.busyCount--;
    }
}

To see this in action, just try the iOS quickstart

image

This was Day 3 in the series The twelve days of ZUMO. We’ll have more tomorrow.

 
Josh Post By Josh Twist
01:53
24 Dec 2012

» Next Post: Getting started with the CLI and backing up your scripts (Day 4)
« Previous Post: It&rsquo;s time for CRON (Day 2)

Comments:

Posted by chan luu bracelet @ 04 May 2013 04:21
Yes, you can make a super-dressy evening http://www.chanluustore.net/ work while the sun's still shining! Simply add a button-down tunic and a few easygoing accessories and voila-instant weekend outfit.Longoria's collection contains mostly functional, reasonably neutral bags, but the place where http://www.coachoutletvogue.com/ gets interesting is the products she chooses - Eva seems to be as big a fan of http://www.usitccoachpurses.net/ as she is prada, and not a lot of celebs can say that they take such an egalitarian http://www.marcjacobssale.co.uk/ approach to their wardrobes http://www.marcjacobsbagsstore.com/ .

Posted by Kelis @ 06 May 2013 05:06
<url>http://www.edpricelist.com/|viagra</url>; rsqr <url>http://www.tratamientodelaed.es/|tadalafil</url>; idt <url>http://www.autocoverageonline.net/|auto insurance</url> 167 <url>http://www.findcheapinsurproviders.com/|cheap car insurance</url> :-PP <url>http://www.comparecarquotesonline.com/|infinity auto insurance</url> itg <url>http://www.carinsurquote.com/|car insurance quotes</url> :D

Posted by Chyna @ 06 May 2013 21:36
<url>http://www.edpricelist.com/|genericviagra</url>; ntpq <url>http://www.findcheapinsurproviders.com/|cheap california auto insurance</url> :[ <url>http://www.carinsurcompanies.com/|car insurance</url> anczjk <url>http://www.carinsurproviders.com/|classic car insurance</url> 589617 <url>http://www.listofcarquotes.com/|cheap auto insurance</url> 290

Posted by Starr @ 08 May 2013 19:08
<url>http://www.findcheapinsurproviders.com/|cheap car insurance</url> gsb <url>http://www.locateinsurdeals.com/|carinsurance</url>; =-D <url>http://www.comparecarquotesonline.com/|car insurance quotes</url> 3932 <url>http://www.getyourquotesonline.com/|car insurance quotes</url> pqqs <url>http://www.carinsurproviders.com/|cheap car insurance</url> hnzrst <url>http://www.listofcarquotes.com/|cheap auto insurance</url> dek

Posted by Sugar @ 10 May 2013 18:40
<url>http://www.findcheapinsurproviders.com/|cheap car insurance</url> 444 <url>http://www.medspricechart.com/|buy viagra</url> =-P <url>http://www.compareinsuroffersonline.com/|auto insurance quotes</url> 155 <url>http://www.edmedsonline4you.com/|cialis</url>; 56461 <url>http://www.comparebestquotes.net/|car insurance quotes</url> =] <url>http://www.onlinecollegeseasily.com/|online colleges</url> zlixui <url>http://www.findbestinsurquotes.com/|auto insurance quotes</url> :-DD

Posted by reeti @ 15 May 2013 13:17
The morning walk is very essential for the human health. In fact, the morning walk is a source of active intake of oxygen and other essential factors. The people who have a routine of morning walk can absorb the sunlight. Sunlight of early morning contains the Vitamin D. <a href="http://www.getacneremedies.com/">www.getacneremedies.com</a>;

Posted by iuidtjfg http://paydayloansukcxa.co.uk/ payday loans online dzrtk http://paydayloansusacxa.com/ fast @ 16 May 2013 09:02
iuidtjfg http://paydayloansukcxa.co.uk/ payday loans online dzrtk http://paydayloansusacxa.com/ fast payday loan 7177 http://paydayloanscanadacxa.ca/ pay day loans rgdPPu http://paydayloansaustraliacxa.com/ payday loan 6877

Posted by zmqwtay http://paydayloansusacxd.com/ cash advance 2687 http://paydayloanscanadacxd.ca/ cash advance @ 17 May 2013 02:27
zmqwtay http://paydayloansusacxd.com/ cash advance 2687 http://paydayloanscanadacxd.ca/ cash advances 1125 http://paydayloansukcxd.co.uk/ payday cash 7246

Posted by Vicki @ 17 May 2013 10:48
<url>http://www.edpricelist.com/|viagra</url>; 9960 <url>http://www.youredmedsinfo.com/|cialis online</url> =] <url>http://www.comparecarquotesonline.com/|cheap car insurance</url> fjoyuf <url>http://www.insurcomparisonservice.com/|classic car insurance</url> gjoty <url>http://www.carinsurcompanies.net/|car insurance in florida</url> =O

Posted by xbewam http://paydayloansusacxg.com/ fast payday loan JTZbs http://paydayloanscanadacxg.ca/ no fax p @ 18 May 2013 01:42
xbewam http://paydayloansusacxg.com/ fast payday loan JTZbs http://paydayloanscanadacxg.ca/ no fax pay day loan AxRJl http://paydayloansukcxg.co.uk/ short term loan 7236

Posted by cqjljx http://paydayloansukcxi.co.uk/ Payday advance %-[[[ http://paydayloansusacxi.com/ payday adva @ 19 May 2013 05:04
cqjljx http://paydayloansukcxi.co.uk/ Payday advance %-[[[ http://paydayloansusacxi.com/ payday advance ajaqTM http://paydayloanscanadacxi.ca/ cash advance loans 8450

Posted by Buckie @ 19 May 2013 09:15
<url>http://edpricesonline.com/|viagra alternatives</url> 5528 <url>http://autoinsurshopping.com/|car insurance qoutes</url> %-]]] <url>http://www.accesstomedssavings.com/|prednisone</url>; :-O <url>http://www.autoprotectionoptions.com/|auto insurance quotes</url> %( <url>http://www.pricesforedmeds.com/|levitra</url>; lsgx <url>http://edsupertabs.com/|cialis</url>; 330200 <url>http://www.carinsurcompanies.net/|car insurance in florida</url> inrtsr

Post a comment:

Name  

E-mail (never shared)

URL

Comments  

Captcha ImageRefresh Image
What's this?
Enter code above

© 2005 - 2013 Josh Twist - All Rights Reserved.