Basic authentication of a .NET REST service

July 28th, 2009

One of the issues one can encounter when building a REST service with the .NET Framework 3.5 SP1 is the fact that when basic authentication is enabled, it defaults to authentication against Windows accounts in IIS. It’s not possible to specify your own handler/provider to authenticate against for instance a proprietary user database, nor is it possible to secure only a certain operation/service and leave the others unsecured.

Luckily there’s a open source project hosted on CodePlex called WCF REST Contrib which, besides adding a whole lot of other improvements, solves the aforementioned issues. The project provides a sample solution showcasing all the features, which might seem a bit overwhelming since it includes quite some configuration. I have attached a sample project with only the bare minimum configuration (using attributes) to enable per operation authentication.

Browse to CancerService.svc/request/skincancer to test the authentication, the browser should display a prompt asking for a username and password. The username is “tony” and password “clifton”. Don’t mind the rather questionable service and operation name, I had no inspiration at the time.

The original documentation failed to mention that the per operation/service authentication depended on the WebErrorHandler, which has been corrected.

Attachment: Authentication Tryout

The mutant iPhone

July 26th, 2009

A few months ago I received a first generation iPhone which had been in a car accident. The screen had been cracked and the aluminum case was in a bad shape, despite the horrible external imperfections it was actually working, well kind of. I was unable at the time to restore it to firmware 2.2.1 since it would hang at one specific point during the process. Luckily, with the advent of firmware 3.0, somehow I was able to restore it without the previous hang.

I used the device a few weeks as test device for my Emmer Inc related adventures, until I got my hands on Lemmy Van den Eede’s bricked iPhone which didn’t boot at all. In the end I combined the best parts of both iPhones to create one working mutant iPhone.

Disassembled

The internet is filled with movies and guides on how to disassemble an iPhone, but I thought I’d post a few lessons learned and give my own opinion on the process. Before I attempted the transplantation, I was unsure how doable it would be.

    Antenna cover removed

  • Removing the black antenna cover and the aluminum back casing is difficult. No matter how easy they make it look in the movies, it just isn’t. I used metal tools instead of the advertised plastic case openers, which I doubt will do the trick. I’ve read several comments stating that the plastic tools look good, but are useless at opening the case. Expect scratches and scuff marks on the case and slight bending of the aluminum casing! I highly doubt if anyone can open the casing for the first time without causing external damage.
  • Once the device is open, disassembling it is indeed straightforward, I was a bit scared that I might not be able to assemble it again. But as long as you don’t lose anything it is easier than one would think. Just take your time & you’ll be fine. The only “issue” I had when assembling it, was a latch which had to be connected to the motherboard, I thought it had to click, but you just have to slide it in the connector.
  • Removing the glass plate and the actual LCD from the inner case is rather difficult, removing the glass plate itself from the LCD is in my opinion nearly impossible without breaking your LCD. In the end I took the inner casing with the LCD and glass plate of the bricked iPhone and inserted the motherboard of the other iPhone.
  • Desoldered battery

  • While I was at it, I also desoldered the battery of the bricked iPhone and soldered it back in into the mutant iPhone. The battery is soldered to the motherboard with 3 wires, the wires are covered with glue which is a little tricky to remove. But it is doable, even with little to no experience soldering. Whatever you do, don’t let the red wire tough the white or black one, according to the disasembly guides. Put some tape over the red one.

Finished mutant iPhone

And that was kind of what I wanted to document. Just take your time, watch the disassembly videos a few times and you should be ok. If you came to terms with the fact that your beautiful iPhone will look a little less perfect afterwards, that is.

Multiline cells in iPhone SDK 3.0

June 21st, 2009

While surfing the web and browsing through development related forums, I encountered a lot of questions regarding multiline UITableViewCells. Prior to iPhone SDK 3.0 this was not an easy feat and although it is very common in UIs, the work that is related to creating multiline cells is not proportional to how common they are.

Apple definitely made it easier with new SDK, since we can interact directly with the UILabel. I know it’s pretty straightforward, but I’m always surprised by how many developers disregard the documentation & turn to forums/blogs for help.

Creating multiline cells is now as simple as setting the numberOfLines property to 0 (or a predefined number) of the textLabel, which is in turn a property of the cell. Given the height of the cell is sufficient, behold a multiline cell.

cell.textLabel.text = @"Some long text...";
cell.textLabel.numberOfLines = 0;

Change the height of the cell with the tableView:heightForRowAtIndexPath: delegate method of the UITableViewController, either by returning a fixed height or by calculating the height needed to show the desired text.

Note that the text property of a cell is being deprecated in favor of textLabel.text, more info on the new 3.0 predefined cell styles can be found here.

Be Tv version 1.2 available

June 18th, 2009

Almost 3 weeks after submitting the 1.2 update to Apple, it has finally been approved and can be downloaded in the Belgian AppStore as of yesterday June 17th. Apparently some minor event called WWDC & the release of a phone delayed the approval division of Apple. We weren’t the only victims, the UiTagenda update was approved after 3 weeks too & a new Facebook update addressing some specific 3.0 bugs is still in review after several weeks.

Picture 1The main improvements of version 1.2 have been mentioned before and can be found here. This new update is fully compatible with firmware 3.0, but isn’t built for 3.0 specifically. Users with 2.x firmwares are still able to install & use Be Tv.

In the mean time I can announce that Be Tv has been downloaded more than 20.000 times and has never left the top 50 since version 1.0 was released almost 3 months ago. It is currently at position 43 in the general top free applications and at position 9 in the entertainment ranking.

Unfortunately the new release was hindered today by a datacenter problem. And as with most things, it wasn’t something we could do much about ourselves. A firewall was misconfigured at the datacenter causing traffic directed at the Be Tv server to be rejected for a timespan of 6 hours, which is of course totally unacceptable. This downtime had nothing to do with the new Be Tv release, nor with firmware 3.0, there is and was no need to reinstall the application. We have started the quest to find a new hosting partner, since our current partner hasn’t proven to be reliable & responsible.

Update now and enjoy the new release!

Be Tv version 1.2 under review

June 6th, 2009

The new Be Tv version has now been under review for exactly 1 week. It will probably be approved and released somewhere at the beginning of next week. If WWDC doesn’t slow the process down, that is.

We aim at releasing an update once every month, which we would have made, if Apple didn’t take so long for reviewing the application.

The main improvements of version 1.2 are:

  • The ability to reorder channels.
  • Caching of the data.
  • An improved Now Playing screen, showing a progress bar of the current program & the name of the upcoming program.

Here’s a short video demonstrating these features, a full size video can be found on Vimeo.

Load view from nib improvement

May 11th, 2009

One of the constants in a developer’s life is seeing code and knowing you’re doing it wrong, but not really knowing how to fix it and get it right. Due to whatever reason: no time… My Facebook like loading indicator article was no exception, the way I loaded a specific view from a separate nib felt so bad. Yet I posted it since holding it back for another 4 weeks was no option either. A week ago I had a eureka moment and it all made sense at around 2am on a Saterday morning. Here’s the correct method to load a view from a separate nib file.

Instead of looping through the contents of the nib, the key are IBOutlets. Create a NSView IBOutlet in your controller class were you’ll want to use the view. Next step is to open your nib file which contains your external view and change the File Owner’s class identity to the controller class you’ve just extended with the IBOutlet for the view. Now just ctrl-drag from the File Owner to your view and select your desired IBOutlet from the list.

Now you’ve connected your controller and the external view, yet the IBOutlet will not be hooked up automatically when your controller’s created. This is a good thing because we can postpone loading the extra nib to when it’s really necessary saving resources for other, more important stuff. This is a practice Apple encourages, using multiple nib files and loading them dynamically when needed.

This is the code needed to load the nib, it’ll automaticall hook up your controller’s IBOutlet to your view.

[[NSBundle mainBundle] loadNibNamed:@"YourNibName" owner:self options:nil];

Simple? Indeed, yet it took me a while to realize using an external nib is basically just the same as putting all your views in a single nib container. It’s all based on hooking up IBOutlets.

Be Tv future

May 7th, 2009

With version 1.1 being available in the App Store for more than a week now, it’s time to look ahead. The update has received some very positive reviews mainly because it fixed some of the issues users had with Be Tv, like localization. By the way, as of today Be Tv has been downloaded more than 16.000 times, thanks everyone!

As for version 1.2 there are 3 main features which are in my opinion the most critical. Being: offline usage (caching), the ability to reorder channels (favorites) and the addition of program details. Although I can’t confirm if all three will make it in version 1.2.

While I have been working on these features secretly, there is something more important that needs to get done first. And that is finding a new partner to supply the information, enabling us to ensure the availability of the data. Currently Be Tv does not include program details, simply because our current partner does not provide this data. But this will hopefully be solved soon.

If you know someone who might be able to help Emmer Inc with this, be sure to leave a comment or send a mail using the in-app mail button.

Caching using WCF REST Starter Kit in Medium Trust

April 26th, 2009

Caching is one of the features provided by the WCF REST Starter Kit released by Microsoft at CodePlex. Jesus Rodriguez has written a walkthrough on how to get it running. The kit was designed to run under Medium Trust, but if you want to use caching in this trust level, you’ll have to configure it a bit differently.

System.Security.SecurityException: Request for the permission of type ‘System.Configuration.ConfigurationPermission, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’ failed.

Using Jesus’ approach you’ll be greated by a nice Security Exception, for some reason you can’t configure the caching in the Web.Config in Medium Trust. Luckily you can add all the caching configuration as attributes to your method. You’ll have to remove the <caching> block from the Web.Config, but leave the aspNetCompatibilityEnabled tag enabled! Here’s an example:

Instead of using this XML configuration:

<caching>
   <outputCacheSettings>
      <outputCacheProfiles>
         <clear/>
         <add name="SampleProfile" duration="30" enabled="true" location="Any" />
      </outputCacheProfiles>
   </outputCacheSettings>
</caching>

We add these attributes, unfortunately you’ll have to add these attributes to every method you’d like to cache. There are more attributes available, you can see them using the IntelliSense, but this configuration mimics the XML config.

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class SampleService : ISampleService
{
   [WebGet(UriTemplate= "/results")]
   [WebCache(Duration=30, Location=OutputCacheLocation.Any)]
   public Atom10FeedFormatter GetData()
   {
      ...
   }
}

Note: Tested in the ASP.NET Development Server provided by Visual Studio 2008 SP1. The OutputCacheLocation enum is located in the System.Web.UI namespace.

Facebook like loading indicator

April 25th, 2009

When performing an action that may take some time, it’s advised to show something to signal that the operation is being performed & the application is not crashing. Here’s an example on how to accomplish a loading indicator as used in the iPhone Facebook application.

Loading View

First we’ll create the actual loading view, let’s add an empty XIB to our Xcode project called LoadingView. Add a UIView to the nib and drag a UIImageView onto it. Use a vector program like Inkscape to create a black rectangle with rounded corners. Use a UILabel and a UIActivityIndicator to create something like the screenshot to the right. Be sure to check the animating property of the activity indicator and change the alpha of the root view to 0.8 for intance, since we want the view to be slightly transparant.

Once we’ve made the actual view, it’s time to show it.

- (UIView*)newLoadingView {
   NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"LoadingView" owner:self options:nil];
 
   NSEnumerator *enumerator = [nib objectEnumerator];
   id object;
 
   while ((object = [enumerator nextObject])) {
      if ([object isMemberOfClass:[UIView class]]) {
         return object;
      }
   }
 
   return nil;
}
 
- (void)doWork {
   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 
   // Add lenghty operation.
 
   [loadingView removeFromSuperview];
   [pool release];
}
 
- (void)someMethod {
   loadingView = [self newLoadingView];
   loadingView.center = CGPointMake(160, 350);
   [self.view addSubview:loadingView];
 
   [NSThread detachNewThreadSelector:@selector(doWork) toTarget:self withObject:nil ];
}

We’re using the newLoadingView: method to retrieve the view from the nib, the reason we’re looping through the contents of the nib is one cannot garantee the order in which items are retrieved will always be the same. For instance the index of the loading view will be different in firmware version 2.0 and 2.1. We retrieve a UIView item, in this case the loading view, since it’s the only UIView in the nib. I’m sure this code could be improved though, using your own derived UIView and checking for this derived class would be better. The center property of the loading view can be used to position the view, the top left corner has coordinates 0,0. (If anyone has a better method of getting a specific view from a nib, do tell)

The someMethod method is the one to call to start everything, this method will show the actual loading view and start the doWork method on a seperate thread. The reason we’re using a seperate thread is not to lock up the interface, otherwise the interface would freeze while the lenghty operation would be performed. The doWork method hides the loading view once everything is done.

Extension: The above code has one disadvantage, when using a tab controller the loading view will disappear once another tab is selected, returning to the original tab will show the loading view again though. In some cases this behaviour isn’t wanted, how do we solve this? Instead of showing the loading view on top of the content view displayed by the tab controller, we’ll show it on top of all the views, on top of the tab controller.

// Show loading view on top of everything
[[UIApplication sharedApplication].keyWindow addSubview:loadingView];

And that’s all there is to it.

Update: here’s the correct method to load a view from a separate nib file.

Localizing Localizable.strings woes

April 22nd, 2009

While localizing the Localizable.strings file of Be Tv I encountered a rather curious (mis)behaviour. I used the NSLocalizedString macro wherever I needed to get my localized text and used the genstring command to generate the Localizable.strings file. I made a dutch and french localization of this file and everything was working in the iPhone simulator. Nonetheless when deployed to my test device, the localization was not working. Localized nib files were though.

After fiddling with some Xcode settings, I gave up and resorted to Googling. Luckily I found this blog post, describing the exact same problem, giving an explanation why & providing a solution. Turns out the localized Localizable.strings file has the wrong encoding, UTF-8 instead of UTF-16. Change the encoding, do a clean rebuild and your localization is up & running.

To change the file’s encoding to UTF-16 from UTF-8, use ‘View’ –> ‘Text’ –> ‘File Encoding’ in XCode menu.

Credits go to Cagan Senturk.