Sunday, August 11, 2013

Objective C continued discussion
Properties encapsulate an object's values so you define the interface of type NSObject and add the properties. Properties values are accessed by Get or Set property values. Custom accessors can also be implemented. Properties are atomic by default means that the value is retrieved in its entirety even if accessed from different threads.  Objects can be allocated on the heap and their lifetime managed by reference counting. This is necessary because the scope of the pointer variable does not guarantee the lifetime of the object. Furthermore, the objects should not each be managed manually but through relationships between the objects. A strong reference is sufficient to keep the object alive. Avoid strong reference cycles though.
Use strong and weak declarations to manage ownership.
Blocks can be defined to represent a single task or a collection of methods. This is defined with the ^ syntax.  The braces indicate the start and the end of the methods. It can be assigned like a variable.
Blocks can take arguments and return values. Blocks can capture values from enclosing scope. You can pass blocks as arguments to methods or functions. Blocks can simplify concurrent tasks.
Errors are encountered in almost all applications. Some of them can be recoverable. There are some delegate methods that alert you to errors. Some methods pass errors by reference. If possible, display the error to the user. Errors can be generated as well and handled. Use the @try, @catch and @finally semantics. NSError can be used for most errors. Other than that, there may be some delegates that can alert on errors. Some methods pass errors by reference.
Some conventions to follow include the following:
Class names must be unique across an entire app. This means we cannot give general names that conflict with others such as with those in the frameworks. Some common prefixes used are NS for foundation framework and application kit, UI for UIKit, AB for address book, CA for core animation, CI for core image. If you are using classes, you could have three letter prefixes. Method names should be expressive and unique within the class. When you use the @property syntax, the compiler synthesizes the methods. Custom methods for these properties could use the dot syntax notation. Similarly, object creation method names must follow conventions.Class factory memthod should always start with the name of the class (without the prefix) that they create. In the case of NSArray class factory methods start with an array.
Categories add methods to existing classes. Categories are declared with the @interface ClassName (CategoryName) syntax. It can be added for any class, even if you don't have the original implementation source code. Any methods that you declare in a category will be available to all instances of that category.

Saturday, August 10, 2013

NSMutableURLRequest *request = 
        [[NSMutableURLRequest alloc] initWithURL:
            [NSURL URLWithString:@"http://openapi.starbucks.com/v1/token"]];
 
[request setHTTPMethod:@"POST"];
 
NSString *postString = @"grant_type=password&client_id=myclientid&client_secret=mysecret&username=XTest&password=aaaaaa&scope=test_scope";
 
[request setValue:[NSString 
        stringWithFormat:@"%d", [postString length]] 
        forHTTPHeaderField:@"Content-length"];
 
[request setHTTPBody:[postString 
        dataUsingEncoding:NSUTF8StringEncoding]];
 
[[NSURLConnection alloc] 
        initWithRequest:request delegate:self];

Much like the HTTP request above, Objective C is used to build the application as a network of objects. Some of which are provided by Cocoa and Cocoa Touch. The language also makes use of framework classes. When building applications, object sends and receives messages.  Interface of the classes are defined with the @interface keyword. A class interface declares the methods and properties associated with the user class. Protocols define messaging contracts. A protocol is used to declare methods and properties that are independent of any class and is declared with the @protocol.
Values and Collections are specifiable just as in C language. Scalar types are used in situations where you just don't need the benefits of using an object. Additional primitive types such as NSInteger, NSUInteger, and CGFloat  are available. Numbers are represented by Instances of the NSNumber class.
Most collections are objects. Arrays are ordered collections. Arrays can be created and queried.Sets are unordered collections while Dictionaries collect key value pairs. Collections can be used to persist the object graph. Fast enumeration makes it easy to enumerate a collection. Most collections also support enumerator objects.

Javascript is great to write cross platform client side scripts. With JQuery and Ajax, web requests are even more easier to write. Here is an example.
$.ajax({
 type: 'POST',
 url: 'http://openapi.starbucks.com',
data: { param1 : 'value1' },
beforeSend: function(){
 $('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
$('#ajax-panel').empty();
$(data).find('item').each(function (i) {
$('#ajax-panel').append('<h4>' + $(this).find('title').text()+ '</h4>');
});
},
error:function(){
$('#ajax-panel').html('<p class="error"> There was an error</p>');
}
});
or we could make an asynchronous request:
$.ajax({
   type: "POST",
   async: true,
   url: "http://<myserver>/<resource>",
   data: "{" + args + "}",
   contentType: "application/json"
   dataType: "json",
   success: function show(result) {
    data = result.d;
   },
   fail: function err(xhr) {
   data = "ERROR";
   }
});

re-sign

I wanted to publish a WPF application such that the application files don't appear under the nested 'Application Files\AppName_Major_Minor_Build_Revision' folder but published flat alongside the xbap file. The Xbap file had references to the files in the nested folder and it carried a digital signature.
Luckily the application (appname.exe.deploy) file and its manifest had no reference to this nested folder.
Since the xbap file is an xml file, I opened it in notepad and removed the reference to the nested folder.
But this invalidates the digital signature. The digital signature comes with the signing tab of the project properties. The publish tab of the same project properties also mentions which files to include and sign. The certificate associated with the project ( this is included as .pfx file in references ) was used to sign and publish. So I used sn.exe to re-sign the file and update its digital signature. The sn.exe is a dot net tool available with the Microsoft SDK. Incidentally, if you wanted to re-sign the manifest, you could edit and re-sign it in Mage.exe or MageUI.exe which also comes with the SDK. 

Friday, August 9, 2013

Fiddler installs a virtual machine on Mac to run. There is no http proxy like Fiddler running natively on Mac. 

Thursday, August 8, 2013

Objective C tutorial

It's a combination of object oriented programming, managed runtime and C programming language.

Methods are invoked like this
output = [object method];
output = [object methodWithInput:input];
Methods can return a value

id myObject = [NSString string];
id means anyType not known at compile time
All objective C object variables are pointer types so instead of id above we could have written NSString*

Nested messages are those where the output of one method or message call is the input to the other. It is written as
[NSString stringWithFormat:[prefs format]];

Method names can be split:
-(BOOL) writeToFile:(NSString*)path atomically:(BOOL)useAuxilaryFile;
and invoked as
BOOL result = [myData writeToFile:@"/tmp/log.txt" atomically:NO];
writeToFile:atomically is the method name

Code inside square brackets means you are sending a message to an object or a class.

property accessors are camel-cased for set as in setCaption and no mention of get as in caption

Instead of object and method notation in the square brackets, you can use object.method;

 Objects are created by assignment and allocation
NSNumber* value = [[NSNumber alloc] initWithFloat: 1.0];
NSString* string2 = [[NSString alloc] init];
[string2 release]

Interfaces are defined as :
@interface Photo:NSObject {
            NSString* caption;
            NSString* photographer;
}

@end symbols ends the class declaration.

Dealloc method is called to free up memory

Reference counting is done on objects. You manage local references. If you create an object with alloc or copy, send it to autorelease the old object and retain the new one. You can use keywords such as autorelease, release,  retain and super dealloc.

You only need to release that which you alloc.

Logging is done with syntax like this:
NSLog( @"The current date and time is: %@", [NSDate date] );

The nil object is the functional equivalent of NULL.

Categories are one of the most useful features of Objective-C. It lets you add methods to an existing class just like C# extensions.
For eg: to add a method to NSString to determine if the contents are URL, you could specify:
@interface NSString (Utilities)
- (BOOL) isURL;
@end;
Utilities is the name of the Categories.
In this post, I will be talking about web requests and responses in Objective C for an IPhone app. The framework provides NS APIs to make URL Requests such as NSMutableURLRequest and NSURLConnection. Both GET and POST methods can be made with these. However, CFNetwork library is even more easier  to use for this. The caveat with most helper methods is that their quirks have to be understood The approach to use NSURLConnection is quite straightforward. However, setting and detecting proxies with this framework isn't as convenient as say in the ASI framework. In fact, ASI framework can not only detect the proxy settings and configurations, it can also specify another or with a .pac script file.  ASI wraps the CFProxySupportTool. Unlike the WinInet in Windows, the way to retrieve the proxy settings from iOS is via the high level wrapper APIs.

Here's an example:

   NSMutableURLRequest *request =
    [[NSMutableURLRequest alloc] initWithURL:
     [NSURL URLWithString:@"https://test.openapi.starbucks.com/v1/oauth/token"]];
    
    [request setHTTPMethod:@"POST"];
    
    NSString *postString = @"grant_type=client_credentials&client_id=your_client_id&client_secret=your_client_secret&scope=test_scope&api_key=your_api_key";
    
    [request setValue:[NSString
                       stringWithFormat:@"%d", [postString length]]
   forHTTPHeaderField:@"Content-length"];
    
    [request setHTTPBody:[postString
                          dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[NSURLConnection alloc]
     initWithRequest:request delegate:self];
    
    
}