Reduce the XML WCF response size

March 23rd, 2009

I recently received a request for a post on how to reduce the XML response size of a WCF service easily. When developing for mobile devices (like the iPhone), it’s crucial to keep loading times as small as possible. Reducing the size of the XML response can be done in two ways: either the actual data or the encapsulating XML elements is/are treated. Changing the actual data probably has a severe impact on you’re applications inner workings, that’s why we’ll focus on the latter. Here’s how:

[DataContract(Name = "p")]
public class Product
{
   [DataMember(Name = "n")]
   public string Name { get; set; }
 
   [DataMember(Name = "a")]
   public int Amount { get; set; }
}

By adding the name attribute we can specify how the XML element will be called, by default it uses the name of the class or property. The original response is 64 characters long, while the tweaked is only 35 characters, a reduction in size of more than 40%. This also works when the response is or contains a list or products.

// Original response
<Product>
   <Name>MacBook</Name>
   <Amount>123</Amount>
</Product>
 
// Response after tweaking
<p>
   <n>MacBook</n>
   <a>123</a>
<p>

In the end it’s a trade-off between overall readability and performance, if you’re consuming the service in .NET with WCF, then you won’t even know that the response has been tampered with, since it’s all done in the background. If you’re calling the WCF service from for instance Objective-C and are parsing the result, you’ll have to adjust the parsing to use the new XML element names.

In the case of an application for a mobile device, the benefits (faster loading) outweigh the disadvantages. You even get an added bonus: less bandwidth consumption on the server.

Break on exception in Xcode

March 19th, 2009

One of the issues I encountered switching to Xcode, coming from Visual Studio, was related to exceptions. When an exception occurs in Visual Studio it breaks and shows the exact line that caused the exception, but by default Xcode has a different behaviour. When an exception occurs, some kind of general message is shown like “_objc_error”, “EXC_BAD_ACCESS” or “___TERMINATING_DUE_TO_UNCAUGHT_EXCEPTION___” and no real indication is given where it happened. Stepping through your code to find the faulty line is time consuming and plain stupid.

Luckily you can configure Xcode to break on exception and here’s how. Let me first give you a little bit of background, when the compiler compiles your application in debug-mode, it adds extra information (called symbols) to the executable enabling Xcode to map the running statements to lines of code. This adds some overhead and is the reason (or one of the) why you shouldn’t deploy your application in debug-mode, but rather in release-mode (without the symbols).

That being said, let’s get to the interesting part, Xcode supports 2 kinds of breakpoints: (normal) breakpoints which are placed on a certain line and symbolic breakpoints. Chances are that you’ve worked with normal breakpoints hundreds of times, without knowing there was another type.

Symbolic breakpoints are breakpoints based on the method name instead of the line number of a file, the advantage of this is that the exact location of the method does not have to be known. Open the breakpoints window (Run – Show – Breakpoints) and add two symbolic breakpoints called “objc_exception_throw” and “[NSException raise]“. If you choose to make them in the Global group, they are available in all your projects while the Project group applies to the current project.

Symbolic Breakpoints

These two methods are used to throw an exception, the first one being the most recent style and the latter being the “old & traditional” style, for simplicity’s sake. If you run your code and a exception is raised your code will stop, just like it used to do without the extra symbolic breakpoints. But if you open the debugger (Run – Debugger) and browse the callstack, you should be able to locate the faulty line, which is displayed with a black font color, while the others are light gray. Click on it and your source code will be shown with the “exception throwing line” highlighted. While it’s not as fast/easy like Visual Studio which shows the baddie immediately, looking it up in the debugger works too, right?

Debugger

Important: while I’ve had great success with this, there have been times when the symbolic breakpoints did not work. The debugger would show the raw statements in the callstack when an exception occured, which is the behaviour without the symbolic breakpoints. I have been able to “fix” this by adding a normal breakpoint (I’ve put it in the method where the exception occured, but I think you can put the breakpoint anywhere) and running the code again, afterward the normal breakpoint could be deleted and the symbolic breakpoints would continue to work. I think it might have something to do with the normal breakpoint causing Xcode to load and/or process all the breakpoints or it’s just me doing something wrong. If anyone knows more about this issue, let me know in the comments.

Multiple async NSURLConnections example

March 15th, 2009

After posting the custom NSURLConnection subclass blog post, I thought I might post an example of how it would be used, since quite a lot of visitors came to the blog searching for the keywords: “multiple asynchronous NSURLConnection”. The code itself is pretty straightforward, but might prove handy for those developers setting their first steps in Cocoa Touch.

The basic idea is to use a dictionary which stores the received data per tag, remember that the actual connection cannot be used as the key of a dictionary. Each NSURLConnection methods retrieve the NSMutableData object from the dictionary based on the tag and does it magic with it.

If you don’t know how to use the NSURLConnection class, take a look at the documentation. That should get you going in no time.

First of all add a mutable dictionary to the header file:

NSMutableDictionary *receivedData;

Here’s the actual code. The load method starts the actual asynchronous calls. The startAsyncLoad:tag and dataForConnection methods are convenience methods to keep the code tidy & readable.

- (void)startAsyncLoad:(NSURL*)url tag:(NSString*)tag {
   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
   CustomURLConnection *connection = [[CustomURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES tag:tag];
 
   if (connection) {
      [receivedData setObject:[[NSMutableData data] retain] forKey:connection.tag];
   }
}
 
- (NSMutableData*)dataForConnection:(CustomURLConnection*)connection {
   NSMutableData *data = [receivedData objectForKey:connection.tag];
   return data;
}
 
- (void)load {
   receivedData = [[NSMutableDictionary alloc] init];
 
   NSURL *url1 = [NSURL URLWithString:@"http://blog.emmerinc.be"];
   NSURL *url2 = [NSURL URLWithString:@"http://www.emmerinc.be"];
   NSURL *url3 = [NSURL URLWithString:@"http://twitter.com/emmerinc"]; 
 
   [self startAsyncLoad:url1 tag:@"tag1"];
   [self startAsyncLoad:url2 tag:@"tag2"];
   [self startAsyncLoad:url3 tag:@"tag3"];
}
 
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
   NSMutableData *dataForConnection = [self dataForConnection:(CustomURLConnection*)connection];
   [dataForConnection setLength:0];
}
 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
   NSMutableData *dataForConnection = [self dataForConnection:(CustomURLConnection*)connection];
   [dataForConnection appendData:data];
}
 
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
   NSMutableData *dataForConnection = [self dataForConnection:(CustomURLConnection*)connection];
   [connection release];
 
   // Do something with the dataForConnection.
}

In the connectionDidFinishLoading: method the tag of the connection should be used to determine what to do with the actual received data. And that is about it!

Don’t forget to release the dictionary in the deconstructor or after all the asynchronous calls have been completed though.

One line initialization of a Dictionary

March 7th, 2009

The .NET 3.5 Framework not only brought us the Windows Communication & Presentation Foundation, it also contained an update of C# to version 3.0. With the celebrated lambda and var functionality.

One of the most useful features it introduced is/was one line initialization. A list of strings can be declared and initialized using the following line:

var list = new List<string>() { "String1", "String2", "String3" };

Luckily this feature is not limited to simple lists. A dictionary can be declared and initialized using the same approach:

var dictionary = new Dictionary<string, string>() { { "Key1", "Value1" }, { "Key2", "Value2" }, { "Key3", "Value3" } };

I have used this extensively with lists, but only recently discovered this was possible with dictionaries.

iPhone (game) development links

March 5th, 2009

A collection of links/blogs I gathered in the course of the last month regarding iPhone (game) development and some other useful things. Probably of the most value to beginning iPhone developers.

Blog: Cocoa with Love
Includes an asteriods style game in CoreAnimation how to.

Blog: CrystalMinds
Includes a Duck Hunt game with regular UIViews how to.

Documentation: Create a singleton instance
Apple documentation on how to create a singleton instance.

Code snippets: iPhone SDK Examples
Some simple but useful examples.

Blog: iPhone Development
Decent blog with some good articles.

Forum: iPhone Dev SDK
One of the largest forums regarding iPhone (and Mac) development, contains an interesting business sub-forum.

Blog: iPhone Developer Tips
Another active and useful blog.

Blog: iPhone Development Bits
Has some nice links to other articles including a little game.

That’ll be it for now.

Network activity indicator hidden in simulator

March 3rd, 2009

Yesterday I encountered this little nuisance, using Xcode 3.1.2 and firmware version 2.2.1. The following code snippet can be used to show and hide the network activity indicator in the status bar, yet when being run in the simulator it doesn’t work. When deployed to a device, the indicator is shown (and hidden afterwards).

Can’t really think of a valid reason why the indicator wouldn’t work on the simulator except that it is a bug, since I’ve made no changes to the code. I’ll have to see if it is a specific firmware 2.2.1 issue.

// Show network activity indicator
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
 
// Hide network activity indicator
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

Custom NSURLConnection class with tag

March 2nd, 2009

A caveat one quickly encounters when using multiple asynchronous NSURLConnections with the same target delegate is that there is no easy way to distinguish one connection from the other, in for instance the connection:didReceiveData: method.

Since using multiple asynchronous connections implies handling the received data chunks yourself, one is likely to create a dictionary which contains a NSMutableData object for each NSURLConnection key. Unfortunately does a NSDictionary copy its keys and this is not something a NSURLConnection supports. A quick solution to avoid this is to make a subclass with a tag to distinguish each connection. This tag can be used as key in the dictionary.

Interface:

@interface CustomURLConnection : NSURLConnection {
   NSString *tag;
}
 
@property (nonatomic, retain) NSString *tag;
 
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately tag:(NSString*)tag;
 
@end

Implementation:

@implementation CustomURLConnection
 
@synthesize tag;
 
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately tag:(NSString*)tag {
   self = [super initWithRequest:request delegate:delegate startImmediately:startImmediately];
 
   if (self) {
      self.tag = tag;
   }
   return self;
}
 
- (void)dealloc {
   [tag release];
   [super dealloc];
}
 
@end

As you can see, creating a subclass with a tag property is rather easy and solves the dictionary issue.

Control reaches end of non-void function

March 1st, 2009

Lately I’ve been getting a “control reaches end of non-void function” warning when compiling. Although it didn’t make any sense since I was not returning any value and the function had a return type of void, the code ran fine too. A few days later it hit me, I had made a typo in the return type.

- (void*)load {
}

Lesson of the day: a return type of (void*) does the job, but (void) does it better.