Life & Technology

Handful lessons in different areas of technology and life in general.

Category Archives: Development

QuickFix: Server Committed a Protocol Violation Error in .NET

While testing the Hacker News website, I encountered a WebException error which is my first time encountering this kind of message:

The server committed a protocol violation. Section=ResponseStatusLine

I thought this is caused by HAP but I was wrong, a quick MSDN search says that this error occurred because the server response is not a valid HTTP response and has a WebExceptionStatus of ServerProtocolViolation.

If you don’t own the server, chances are you never get to fix the problem on the server itself but Microsoft provided a HttpWebRequestElement property that will ignore validation errors that will occur during parsing:

  1. <>
  2. <settings>
  3. <httpWebRequest useUnsafeHeaderParsing=”true”/>
  4. </settings>
  5. </>

With this setting in place inside your web.config file, the error disappear and HTTP response will be displayed.


GCNetworkKit: Download with progress via UIAlertView

For the past few months, I’ve been using this simple to use yet powerful HTTP set of classes called GCNetworkKit to communicate to your server with ease. For a brief description from the github page:

GCNetworkKit is a helpful set of classes for interacting with a http server. All classes make use of ARC. In order to use it you need to drag the folder into your xcode project. You also need to add the MobileCoreServices and the SystemConfiguration framework to your project.

And with this, I’ve come up with a simple example that demonstrate the ease of use of this library.

UIAlertView + UIProgressView

For this demo, we want to have a file download functionality that we need to display via UIAlertView with additional UIProgressView to view the progress and a UILabel to determine the total percentage completion. These two subviews will be attached to our UIAlertView and will be used during the file downloading. If you downloaded the app called CityMaps2Go, the way they present their maps download is exactly what we’ll be creating.

Our initial screen will look like this:

Next, we will hook our UIButton to trigger the display of UIAlertView on the screen and immediately start the process.

  1. -(IBAction)download:(id)sender
  2. {
  3.     NSURL *fileURL = [NSURL URLWithString:@”http://YOUR_URL_HERE/PATH/TO/FILE.pdf”%5D;
  4.     downloadAlertView = [[UIAlertView alloc] initWithTitle:@”Downloading…”
  5.                                                     message:@”             “
  6.                                                    delegate:self
  7.                                           cancelButtonTitle:@”Cancel”
  8.                                           otherButtonTitles:nil];
  9.     [progressView setProgress:0];
  10.     [downloadAlertView addSubview:progressView];
  11.     [downloadAlertView addSubview:progressLabel];
  12.     [progressView setProgressViewStyle: UIProgressViewStyleBar];
  13.     [downloadAlertView show];
  14.     [self downloadDataAtURL:fileURL];
  15. }

After adding the UIProgressView and UILabel on our UIAlertView, we will call our method that will actually perform the file downloading. Line 16 will start to call GCNetworkKit’s block-based methods as follows:

  1. – (void)downloadDataAtURL:(NSURL *)url {
  2.     __GC_weak ViewController *weakReference = self;
  3.     weakReference.progressLabel.text = @”Preparing …”;
  4.     [self performSelectorOnMainThread:@selector(updateStatusLabel:) withObject:@”> Status: Download Starting” waitUntilDone:NO];
  5.     GCNetworkDownloadRequest *request = [GCNetworkDownloadRequest requestWithURL:url];
  6.     request.autoDeleteTMPFile = YES;
  7.     request.loadWhileScrolling = YES;
  8.     request.continueInBackground = YES;
  9.     request.progressHandler = ^(CGFloat progress){
  10.         NSLog(@”Progress on downloading data: %f.”, progress);
  11.         [weakReference updateProgress:progress];
  12.     };
  13.     request.downloadCompletionHandler = ^(NSString *filePath){
  14.         self.requestHash = nil;
  15.         [self performSelectorOnMainThread:@selector(updateStatusLabel:) withObject:@”> Status: Download Completed.” waitUntilDone:NO];
  16.         [downloadAlertView dismissWithClickedButtonIndex:0 animated:YES];
  17.         NSLog(@”Downlaoded data and saved at: %@.”, filePath);
  18.         UIAlertView *success = [[UIAlertView alloc] initWithTitle:@”Download Status” message:@”File successfully downloaded!” delegate:nil cancelButtonTitle:@”Great!” otherButtonTitles: nil];
  19.         [success show];
  20.     };
  21.     self.requestHash = [[GCNetworkRequestQueue sharedQueue] addRequest:request];
  22. }

You see on Line 11, we don’t have to worry getting the current progress status of the file being downloaded, GCNetworkKit already has this functionality built-in. And on Line 15 is the completionHandler callback that we can use to process the file being downloaded or even display another UIAlertView that will popup the completion alert message.

And if we like to cancel the download process, we only need to call cancelRequestWithHash: method to immediately halt the current operation. This is possible because every request that is put in the queue automatically has a unique id in the form of hash.

  1. – (void) cancelDownload
  2. {
  3.     [[GCNetworkRequestQueue sharedQueue] cancelRequestWithHash:self.requestHash];
  4.     self.requestHash = nil;
  5. }

Using GCNetworkKit library, we achieved our task with minimal effort in coding and the result is exactly what we expected!

Screenshots for our demo project

The XCode project is compiled under ARC and available for download here.

NSString Category Function: isIn()

Usually when we’re trying to check if two strings are equal, we often used this code:

 NSString *isoView = @"Isometric View";
 if([isoView isEqualToString:@"Parallel View"]) // do something

Which is fine but if you’re testing against multiple values for equality, you might end up writing code like this:

 NSString *isoView = @"Isometric View";
 if([isoView isEqualToString:@"Parallel View"] || [isoView isEqualToString:@"Dynamic View"]
    || [isoView isEqualToString:@"Inverted View"] || [isoView isEqualToString:@"Range View"])
     // Do somethng here

And you’re code will contain bunch of ORs ( || ) just to test if your string matches to your qualifiers.

With this problem, I have created a simple NSString Category that basically solves this kind of situation and improves your code a little bit. I created a boolean function that accepts multiple string values terminated by nil that will be used for equality check of string.

Our interface header looks like this:

// NSString+Additions.h
#import <Foundation/Foundation.h>

@interface NSString (Additions)
- (BOOL) isIn: (NSString *) strings, ... NS_REQUIRES_NIL_TERMINATION;

And the implementation code is a simple for .. loop to achieve our goal:

// NSString+Additions.m
#import "NSString+Additions.h"

@implementation NSString (Additions)

- (BOOL) isIn: (NSString *) strings, ...
    BOOL isFound = NO;

    va_list args;
    va_start(args, strings);
    for (NSString *arg = strings; arg != nil; arg = va_arg(args, NSString*))
        if ([self caseInsensitiveCompare:arg] == NSOrderedSame) {
            isFound = YES;

    return isFound;

If we’re going back to our sample snippets above, we would then write the conditional checking as follows:

NSString *isoView = @"Isometric View";
if ([isoView isIn:@"Parallel View", @"Dynamic View", @"Inverted View", @"Range View", nil])
   // Do Something

Simple and not cluttering with OR ( || ) statements!

The basic principle on the above Category is based on Objective C feature called Variable Argument Lists which is explained clearly by Matt on his blog post.

The category is easy to override to include checking against NSArray or NSDictionary.

Easy RSS Syndication in .NET

My office colleague just asked me about the easy way to read and retrieve an RSS feed for a specific or multiple sites. And I say that Microsoft did indeed has a class called Syndication that resides under System.ServiceModel namespace that handles not only RSS but also Atom format too!

Below is a console application that I created to show how easy it is to read RSS via .NET:

Declare the import:

   1: using System.ServiceModel.Syndication;

Make sure you add the ServiceModel and ServiceModel.Web on your Reference.


Basically, the main logic for reading RSS is to call the Url via the WebClient class and create an XmlReader object to hold/read the XML results being fetched on the WebClient request. And then, finally, just pass the XmlReader object to the Syndication object and it will parse all results into a feed collection.


and the Main() call would just be:


And when I run the project, the output will look similar on the screenshot below:


Simple as that!

The RSSConsole Project File for this snippet is available for download here.