Saturday, May 29, 2010

Code Syntax Highlighting

notesI have a blog posting on this issue last year. I have really enjoyed to practice those steps to highlight my codes in blog. There are two issues I still don't feel good: first, the HTML codes generated from VIM are not-CSS. The embedded color styles make my blog HTML hard to read and edit. The size of my blog is much bigger even it is not a big deal.

The second issue is that I like change my code background color to black so that it is easy and comfortable for eyes. The white background color is too bright and contrast. It consumes more energy, I think, for the terminal as well. So I think it is time to make change to my code syntax highlighting HTML codes.

Fortunately, I found that VIM has an option for TOhtml command to convert to HTML with CSS classes. The command is very simple:

:let html_use_css=1

The result of TOhtml will be HTML with style css classes defined in header part and all the syntax highlight HTML codes are based on span with class.



The next step is that I have to update my style css classes in my blogger. Two groups of css classes I have to include in my blog header section. It is easy to do since Blogger provides Edit HTML in blog settings. The first group is css classes in my div section as a box for codes. Based on the previous div, I added additional divs with additional background color and text color settings:

...
color: #cccccc;
background-color: #000000;
...

The second group of css files are those generated by VIM in HTML header section. I think VIM use generic css class names for codes. For example, the following are some generated by TOhtml command for Objective-C code:

<style type="text/css">
<!--
.Comment { color: #80a0ff; }
.Statement { color: #fbf204; }
.Special { color: #fb8000; }
.Identifier { color: #40ffff; }
.Type { color: #60ff60; }


For C#, SQL or other languages, the syntax color scheme may be different, but the class names are almost the same. That's the advantage of css.

With above changes, now my codes are and will be in new syntax highlighted colors, and my blog will be much easy to read and maintain.

Read More...

Sunday, May 23, 2010

MyLogger Class in Objective-C (1)

Objective-C is new for me. In the past weeks, I have been working on my first iPhone application. This has been quite interesting and rewarding experience. Since I have been doing development in in .Net for many years, I always compare Objective-C to .Net, or try to find out something similar in Objective-C like ones I have used in .Net. Recently, I found some classes in System.Diagnostics namespace are quite useful, especially Debug class. I can use it to print debug information in my classes and I can use indent feature to net messages in a nice indented structure. All the debug strings are displayed in Visual Studio's output panel. I don't not need to worry about all those debug print codes since in the released mode, they will not work.

In Xcode, there is similar feature available. It is NSLog(), which is a Cocoa foundation function.


This function can be used to print out debug messages in the same way as Debug.Print() in .Net. However, NSLog() is only a C-like function, therefore, there is no other features you can alter the behaviour of its output, as far I know about it. Therefore, I need a wrapper class for NSLog().

I found a very nice blog by Objectuser: A Single Class Logger in Objective C. This is very close to what I want, except for indention. Based on the class, I created my logger class: MyLogger. Here is the header of the class:

#define kLogLevelDebug 1
#define kLogLevelWarning 2
#define kLogLevelError 3
#define kLogLevelInfo 4
#define kLogLevelNone 100

@interface MyLogger : NSObject {
  int mLevel;
  NSString* mContext;
}

@property (nonatomic, assign) int level;
@property (nonatomic, retain) NSString* context;

+ (char) indentChar;
+ (void) setIndentChar:(char)aChar;
+ (NSString*) format;
+ (void) setFormat:(NSString*)aFormat;
+ (int) defaultLoggingLevel;
+ (void) setDefaultLoggingLevel:(int)defaultLevel;

- (id) initWithContext:(NSString*)loggingContext;
- (id) initWithContext:(NSString*)loggingContext logLevel:(int)intentLoggingLevel;
- (BOOL) levelEnabled:(int) intentLevel;
- (BOOL) debugEnabled;
- (BOOL) warningEnabled;
- (BOOL) errorEnabled;
- (BOOL) infoEnabled;
- (MyLogger*) indent:(BOOL)indent;
- (MyLogger*) debug:(NSString*)messageFormat, ...;
- (MyLogger*) warning:(NSString*)messageFormat, ...;
- (MyLogger*) error:(NSString*)messageFormat, ...;
- (MyLogger*) info:(NSString*)messageFormat, ...;
@end

The header file describes all the class members, properties, and methods.

Usage

The main purpose of this class is for easy to use. Typically, you need to create an instance of MyLogger in a class's init(). Then the instance is ready to use. For example, here is a view controller class .h:

@class MyLogger;

@interface MyViewController : UITableViewController
  ...
  @private
    MyLogger* mLogger;
}
...
@end

Notice that the class level mLogger is a private variable. There is no reason for outside to access to this mLogger instance. The following is an exmaple how this mLogger is used in the .m class:

#import "MyViewController.h"
#import "MyLogger.h"
...
@implementation MyViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
   if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
     // create logger with class name as context
     logger = [[MyLogger alloc] initWithContext:@"MyViewController"];
     // log a message and then indent
     [[logger info:@"initWithNibName:bundle:"] indent:YES];
     ...
     [logger info:@"object: %@", obj];

     ...
     // off indent and print msg
     [[logger indent:NO] info:@"initWithNibName:bundle: DONE"];
   }
}
...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [[mLogger debug:@"tableView:cellForRowAtIndexPath:"] indent:YES];
    [mLogger debug:@"indexPath: %@", indexPath];

    ...
    [[mLogger indent:NO] @"tableView:cellForRowAtIndexPath: DONE"];
}
...
- (void)dealloc {
  if ([logger retainCount] > 0 ) {
    [logger release];
  }
  ...
}
@end

I think it is very straightforward: creating logger in init and retain it, using it anywhere in the class, and releasing it at end of the class. I declare logger in the .m file to keep it as private data members in the class. Three is no need to let outside to access or set this instance.

Here is an example output:

[INFO] MyController - viewDidLoad
--[INFO] MyViewController - fetchedResultsController
----[INFO] MyViewController - managedObjectContext
------[INFO] MyViewController - creating new managedObjectContext
----[INFO] MyViewController - managedObjectContext DONE
----[INFO] MyViewController - getFetchRequestWithEntity:inContext:inContext:
----[INFO] MyViewController - getFetchRequestWithEntity:inContext:inContext: DONE
----[INFO] MyViewController - managedObjectContext
----[INFO] MyViewController - managedObjectContext DONE
--[INFO] MyViewController - fetchedResultsController DONE
[INFO] MyViewController - viewDidLoad DONE

My next blog will discuss some key points in MyLogger class.

Reference


Read More...

Tuesday, May 11, 2010

Customize Xcode like MSVS

After month time coding in Xcode, I think I should spend some time to learn Xcode and configurations so that I will be familiar with Xcode short-cut keys. Furthermore, I'll be able to configure my Xcode like Microsoft Visual Studio since I have done more than ten years .Net programming; at least, find out similar ways I use VS.

Key Bindings

This blog provides very useful information about how to customize key bindings. The basic idea is to create a customized .dict file:

/Users/USERNAME/Library/KeyBindings/DefaultKeyBinding.dict

The content of this file is JSON like:

/* ~/Library/KeyBindings/DefaultKeyBinding.dict */
{
"KEY1" = "ACTION1"; /* Bind KEY1 to ACTION1 */
"KEY2" = "ACTION2"; /* Bind KEY2 to ACTION2 */
...
}

The blog list all the modification keys and actions.

This blog has a MSVC key bindings. I gave it a try, but I think I still like to use Xcode default kyes. I like VS smart list or code completion by Control+Space the most. In Mac, I found out that the default Xcode key is "Control+,", F5 or Option+esc. Mac Developer Tips >> Xcode code completion has detail description about this my favorite feature and more.

In the Xcode preference->Key Bindings, a list of actions and keys are defined there. I think the above default keys may fill the blanks when I create a new one as its instructions.

Copy and Paste

The basic copy and paste in Mac is very similar to Windows. For example, Command+C, X, and V for copy, cut and paste, and +Z for undo. I think Control+Y is for redo, but Command+Shift+Z is for redo(I think it make sense in Mac).

In Windows, you can select a text and drag it anywhere, or hold Control key to make a copy. In Mac, the copy is by holding Option key.

Selection Indent

This tip explains how to do selection indent and un-indent. The keys are Command+] or [ for block indent or un-indent.

Block Comment/Un-comment

To comment or uncomment a block of codes, use key Command+/. Repeat to uncomment. This tip (one out of 10) is from the tip by John Muchow.

Refactor

VS provides great set of Rectoring tools, renaming variable is a great one. Xcode also provide this feature. Select a variable and press Shift+Comman+J, a dialog window is displayed. Rename is in a selection on the top left. This article has detail description and picture to show what Refactor is.

Overall, all above pretty much codes most part of features and functions I have used in VS. Xcode is a very competitive development tool for Mac and iPhone application development. I think with my continuing exploring and efforts, I'll be able to find out more powerful features to increase my productivity.

Read More...

Sunday, May 09, 2010

Ouch! iPhone Memory Management

Here is my story about iPhone development update. I thought I had very good understanding of iPhone memory management. For each object created by alloc and init, a corresponding release should be made to balance its life cycle. It is simple, right? When I put my hands on my first application codes, I got hurt! But it was a good experience. Here is the story.

In my codes, one of view controller uses core data as data source. In the header file, a fetchedResultController is defined:

@interface MyViewController : UITableViewController <NSFetchedResultsControllerDelegate, UITableViewDelegate>
{
  // ...
  NSFetchedResultsController *fetchedResultsController;
  // ...
}

// ...
@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;
// ...
@end


In my .m file, the implementation of my customized getter is like this:

@synthatic fetchedResultsController;
// ...
- (NSFetchedResultsController *)fetchedResultsController {
  if (fetchedResultsController != nil) {
    return fetchedResultsController;
  }
....
  NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc]
  initWithFetchRequest:fetchRequest
  managedObjectContext:managedObjectContext
  sectionNameKeyPath:nil cacheName:@"Root"];
  aFetchedResultsController.delegate = self;
  fetchedResultsController = aFetchedResultsController;
  // [fetchedResultsController retain]; I missed this line to contain the object
  // ...
  return fetchedResultsController;}


My intension to implement getter is for this view controller class to have its own fetched result controller with the class own managed context object and fetch request. However, I did not retain the controller. The result is unexpected with the alloc and init object.

Here is a simplified example:

  instance = aInstance;
  self.instance = aInstance;



The first line is directly reference or pointer assignment. The result is that both variables are pointing to the same memory address, and both variables have the same reference count; while the second line actually calls to the setter property of instance, and the reference of right side variable is passed to the setter method. It will be up to the setter class to retain, copy or do assignment.

In my customized property getter, in order to retain my alloc and init object, there are two options. First option is to do the direct assignment and then to retain it so that object reference count is increased to 1. The second and simple option is call the setter to do it [self instance] = ... The synthetic property definition guards the "retain" feature.

I had spent almost one week of evenings and one week end time to figure the issue out. The exception I got was "EXC_BAD_ACCESS". The following is my NSLog message in the getter method with system crash messages:

2010-04-12 07:15:23.347 MyApplication[8030:207] ... 
2010-04-12 07:15:23.348 MyApplication[8030:207] MyViewController->fetchedResultsController
Program received signal: "EXC_BAD_ACCESS".

The exception happened at the end of the property getter. Now I understand the meaning of "EXC_BAD_ACCESS", at least this is one of many cases. It does say what it means: access to the memory which was released and not accessible.

Actually, I found the clue when I tried to google the issue. When I read some answers about one StackOverflow question (http://stackoverflow.com/questions/327082/exc-bad-access-signal-received). I immediately realized it was memory issue and then realized the object I tried to return was actually released.

It is a really good lesson. iPhone development is new for me, and I really en joy it when I figure out something. This is a way to gain knowledge and to make progress. After I corrected my codes, my application was back to alive and the view was displayed!

Read More...

Saturday, May 01, 2010

Web Tool: EverNote

toolsI think I knew EverNote for a quite while. I heard about it from Stanford University's iPhone training program. EverNote staff gave a special presentation about its free iPhone program and their experience with iPhone application development.

EverNote basically provides a web service to people to make notes about anything, simple text notes, html formatted notes with formatted text, links, pictures, movies. The basic service allows 100 notebooks and 40MB monthly uploading. Nootbooks and tags are great feature to organize notes.

Recently I decided to create my basic account at EverNote. The main reason I like to use this web service to take my personal notes. I can use it anywhere: write, edit and view your notes. To write a blog, normally it takes much longer time than just writing a note. I do my blog most time at weekends. With EverNotes, I can create my notes quickly, anywhere and anytime. It is a great place to record my ideas and findings.

Another great feature is that EverNotes provides RSS feeds for public shared notebooks. For example, here is my .Net notebook RSS feed. This provides a way to share my ideas with my friends and other developers.

Just found that EverNote Mac application has Import and Export features. I just exported all my notes to my Mac. The exported file is an XML file(enex). This provides a back way to import and export notes.

Another similar web service is UberNote, which was created by a group of university students. It was created by the idea to share student's notes. Now it is a public project and it is free. However, it does not support multiple notebooks.

Read More...

Tuesday, April 20, 2010

Web Page Rank Check Tool

toolsI found one web page rank checking tool: Google PageRank Checker. It is very easy to use. Just type in a URL and then verification code, you will see the rank for the web page. Here is the detail explanation about PageRank at WikiPedia with the formula how a rank value is calculated.

Here are results of my blogs. All are either 0 or N/A. Here is only one with 0:

This blog:
Free PageRank Checker

Read More...

Sunday, April 18, 2010

Add Custom Managed Object Class

I use Core Data in my first iPhone application. During the development, I have many occasions to change/update my entity objects in my managed data model. For each change, I have to update the custom managed object class. XCode provides a template to create custom managed object class I generated before. However, it is very tricky to use this template. The key point is that you have select an Entity in Data Model first. Here are the steps to that.

Managed object classes are by default located in Resource group. The first step is to remove the old managed object class. For example, I added a new property "note" to entity "paymentType". Therefore, the first step is to remove the paymentType.m and .h files from Resource group.


Next, select the entity in .xcdatamodel, "paymentType". Then from the menu File, select "New File...".

Choose the template Managed Object Class in Cocoa Class:


All the next steps are very straightforward. Continue next to finish.

Apple's developer's web page provides similar information about this issue.

Another very critical thing to do is to remove the application in both device (iTouch or iPhone) and simulator. Since the managed data model has been changed, the updated .sqlite database most likely may not be compatible with the previous version. Therefore, the sqlite file has to be removed.

Read More...

Monday, April 12, 2010

MEF and IoC/DI (6)

Let's look my third API class - MEFWrapper.

MEFWrapper Class


The above two classes not only make the DI mappings easy, but they also try to expose MEF rich infrastructure as minimum as possible. How to load this DI information to MEF? This comes to the third class, MEFWrapper. The same applies to the MEFWrapper class. This class encapsulates the logic of how to create MEF's container and how add composable parts to the container.

Steps to Load DI Information


With this class, there are three steps to load DI information to MEF. The first step is get an instance of MEFWrapper through the static method CreateInstance(). This follows singleton pattern, to create a single MEF container instance per application.

The second step is to add DICatalog instances through Add() or AddRange() interfaces.

After all the DI information are added to MEFWrapper, the third step is to call the method of InitialzeDIMappings(), which encapsulates the logic of loading DI parts and catalogs to MEF container.

Get Mapped Instance


Now your MEF framework is ready for use. You can use MEF's Import attribute to let MEF to inject instances for your usage. MEFWrapper also provides static methods of GetInstance() and GetInstance(key) to explicitly retrieve a mapped instance from MEF.

Dispose MEFWrapper Instance


After your usage or your application is going to be terminated, you should call the method of dispose() (IDisposable implementation) of the MEFWrapper instance.

Here is an example of using this wrapper class in a DIRootCatalog class:
public class DIRootCatalog : DICatalogBase {
  private static MEFWrapper _instance = null;

  # region CTOR
  private DIRootCatalog() :
    base (Assembly.GetExecutingAssembly())
  { }
  # endregion

  public static void LoadDIMappings(){
    // Create instance and load DIs only once
    if (_instance == null) {
      _instance = MEFWrapper.GetIntance(new DIRootCatalog());
      // Exampels to add DIs to instance
      // Assume DIs are based on DICatalogBase
      _instance.Add(new DIDataReader());
      _instance.Add(new DIProcessorController());
      _instance.AddRange(
        new DICatalogBase[]{
          new DILog(), new DIDBService() }
        );
      _instance.Add(new DICatalogBase("DIExtensions"));
      // Initialze MEF Container with DI parts through catalogs
      _instance.InitializeDIMappings();
    }
  }

  public static void UnLoadDIMappings() {
    if (_instance != null) {
      _instance.Dispose();
      _instance = null;
    }
  }
}

...
internal class DIResolver : DIResolverBase {
    // Define Import and Export properties
  ...
}


And there is an example of a console application where the above DIRootCataLog is used:
class Program {
  static void Main(string[] args) {
    // Load MEF framework with DI mappings
    DIRootCatalog.LoadDIMappings();
    // Get process controler instance from MEF
    var mainProcess = MEFWrapper.GetInstance<IProcessController>();
    // Start process
    mainProcess.Start();
    // Unload MEF framework
    DIRootCatalog.UnLoadDIMappings();
  }
}



Here is the library of DICommonLibrary project.

Note: the project depends on two library files: one is MEF library and another is a related open source library for MEF. Both are available from CodePlex:

System.ComponentModel.Composition.dll
Microsoft.Practices.ServiceLocation.dll

Read More...

Saturday, April 10, 2010

MEF and IoC/DI (5)

Let's look my second API class - DICatalogBase.

DICatalogBase Class


The second class I use in my practice of DI library is the DICatalog class. The main purpose of this class is to provide APIs load DIs as parts to MEF and to pass information to customize Export instances. DICatalog is a customized API class for public usage. Therefore, it is an optional class if the customization is required.

Add Parts


To facilitate loading DI parts to MEF, a base class of DICatalogBase with several CTORs (constructors) is provided, which correspond to load one or a list of libraries as assembly catalog, directory catalog, type catalog and aggregate catalogs.

Here are some examples. First one is to load DI by an executing assembly. In the base class the assembly is converted to assembly catalog instance to MEF:
public class DICatalog : DICatalogBase {
  public DICatalog():
    base(Assembly.GetExecutingAssembly())))
  {...}
}

internal class DIResolver : DIResolverBase {
    // Define Import and Export properties
  ...
}


The following is another example to use a base CTOR with a collection of two DICatalogBase instances. The first one is load the executing assembly as DI part and the second to load all the DI parts in a directory ("DIExtensions" under the executing assembly location).
public class DICatalog : DICatalogBase {
  private const string DIExtensions = "DIExtensions";
  public DICatalog()
    : base(new DICatalogBase[] {
      new DICatalogBase(Assembly.GetExecutingAssembly()),
      new DICatalogBase(DIExtensions)
      })
  {...}
}

internal class DIResolver : DIResolverBase {
    // Define Import and Export properties
  ...
}

Since the inherited instances based on DICatalogBase are created by clients and then loaded to MEF; therefore, the inherited classes have to be public.

Pass Customized Information


The customized information is passed through a customized CTOR of DICatalog class. For example, if some exported instances have to be created based on a configuration file, a customized CTOR can be used to input the configuration information.

Here is an example of DICatalog class with a Configuration class as CTOR's parameter:
public class DICatalog : DICatalogBase {
  [Export]
  private static LogConfig _logConfig { get; set; }

  internal static DataReaderConfig _readerConfig { get; private set; }

  public DICatalog(Configuration config)
    : base(Assembly.GetExecutingAssembly()) {
    _logConfig = config.LogConfig;
    _readerConfig = config.ReaderConfig;
    ...}
}

internal class DIResolver : DIResolverBase {
    // Define Import and Export properties
  ...
}

The configuration is passed as CTOR's parameter to the DICatalog class. How is this information passed to MEF's parts? Here I use two ways to achieve it.

The first one is by using Export attribute for a private property value, i.e., to export LogConfig. The DICatalog class has a customized CTOR, therefore MEF cannot create an instance of it. Even MEF could create an instance of the class if the default CTOR were defined; we would not be able to set the property value for the instance. In order to set the Export property value, the property has to be static and it can be set in CTOR. Fortunately, MEF does pick up the exported value from a static property. Here LogConfig is an exported property known to MEF.

The advantage of using Export attribute is that the exported value can be injected to anywhere in other DI libraries, components, or application through MEF Import attribute. If a piece of information is only used within a library, by using static property may be good enough. Here the second property of DataReaderConfig may be used within the DIResolver class, to customize a DataReader class instance as Export.

Read More...

Sunday, March 28, 2010

MEF and IoC/DI (4)

Let's look my first API class - DIResolverBase.

DIResolverBase Class


First, I need to create a class or a library project to define DI mapping relationships which will be used in my application. For example, DIResolver class is a class where I define MEF Import and Export properties. When the class is loaded as an assembly catalog or directory catalog to MEF, the parts or Import and Export mapping relationships are then loaded to MEF framework.

DIResolverBase class is a base class for DIResolver. The class is very simple. It implements IDisposable interface and contains a protected Add() method for holding disposable items.

When I started to use MEF, I was confused by the concept of disposing instances I retrieved from MEF or injected by MEF. At the start, I thought that an instance being requested from MEF was created by MEF and hence MEF should dispose them on application termination. However, it did not happen. In some cases, I had to explicitly dispose the instances retrieved from or injected by MEF in my application; otherwise, some resources such as files or connections would be left unclosed when my application is terminated.

Finally, I figured it out. It is wrong that I thought MEF created requested/injected instances, even MEF does create some instances in my DI library. It'll be much easier to explain it in an example: a console application and a DI library with a DIResolver class. The application only knows IProcessControler interface. The mapped instance is retrieved from the DI library. Here is a picture how the application and MEF work:


and here are some DI codes:

internal class DIResolver : DIResolverBase
{
  [Export]
  private IProcessController _exportController {
  get {
    var instance = new MyController( _log, _reader );
    // Add disposable obj to base created by this class
    // so it will be cleaned up when app terminates
    base.Add(instance);
    return instance;
  }

  [Import]
  private IDataReader _reader { get; set; }

  [Import]
  private ILog _log { get; set; }

}

At the start, the DI library is loaded to MEF as an assembly catalog. Then an instance of IProcessController is requested by the application (1). On the request, MEF resolves the mapping instance by creating an instance of DIResolver class because it found the Export for this type there (2). Hence the Import properties are initialized (3) with the injected instances (Export properties are defined in other DI libraries). Finally, a new the instance is created in the Export property getter (4). In this sense, MEF does create the instance of DIResolver class but not the instance of IProcessController. It is the DIResolver class that creates or news the instance. Therefore the clean up job should be done in this class.

Fortunately, MEF does the nice and cleaning up job when the application is terminated or the MEF container is disposed. MEF will call the dispose() method on all the composable parts, including DIResolver which is based on DIResolverBase. The base class provides the change of disposable.

The protected Add() API in the base class provide a way for the driving class to add any created and to-be-disposed instance to the base. The base class will do the cleaning up job on termination. In above example, you can see the customized DIResolver class is very simple and clean. In case of some instances which do not implement IDisposable interface but do have some resources to be released by other interfaces such as Close() or Disconnect(), the DIResolver class should override Dispose() method, do the customized cleaning job there, and call the base Dispose() method if any disposable instances were added.

One interesting feature of DIResolver class is that it can be an internal type class and the Import and Export properties can be private. This class is mainly used for MEF and rarely used as a public API. So I define it as a none-accessible class from the DI library. It is amazing that MEF can figure it out, i.e., to create DIResolver instances and to access to the private properties.

Read More...

Saturday, March 27, 2010

GitHub Repository as Source Code Repository

toolsWhile I was doing programming with XCode last night, one thing came to my mind: I need a repository to keep track of my source codes. It is not only a good way to save and track my changes, but it also provides a remote repository on Cloud to safely keep my project source codes. So I started to investigate options.

I have done some projects by using Google Code. I use it as a host for my public shared projects. I have not really used it as my source code repository. At work, I also use Subversion(SVN) as a alternative repository. Here is a list of SVN listing. For personal use, I heard many developers recommending GitHub as an alternative. So I gave it a try.

I created an account at GitHub. The basic account is free with .3GB space and no private repository. It provides update to fee-based private repositories. The following is what I have done.

First I need to install git. There is Mac version at Google. The installation is straightforward by running the installation pkg. A reboot is required to access to git in Terminal. I think the installation may add git to the terminal PATH.

The second step is to generate a SSH key. GitHub provides detail step-by-step information about this on Mac. I think this key is used to identify my Mac to a remote SVN repository.

The third step is to add the key to my GitHub account. The key is in my ~/.ssh folder. The generated SSH key is rsa type and the public key is in the file of id_rsa.pub. After adding my public key to my GitHub account, there is one file is created in my ~/.ssh folder as know_hosts.

That's all I have done so far. I have not reached the point to save my source codes in XCode to a repository yet.

Read More...

Friday, March 26, 2010

My New Web Site: Expense Log

By chance, I watched several YouTube videos about Google Site. I think I saw it long time ago and did not have any desire to create one. There are many web site provides and many of them are free. One interesting feature of Google's Sites is that is a Wiki based web site. People can leave comments there.

That's the feature I like. At present, I have been working on my first application. It will be released soon. So it is better to register a web site first. When the product is released, I'll update the site: Expense Log.

Read More...

Saturday, March 20, 2010

MEF and IoC/DI (3)

Here is the way how MEF interacts with the class. When there is a request to get an instance of IProcessController from MEF, MEF will create an instance of DIResolver since MEF knows the Export is defined in this DIResolver class. At the time when the instance is created, the two Import properties are injected with instances of IDataReader and ILog. Finally, the property getter marked as the Export type of IProcessController type is called with the result instance from MEF and then to the request.


You could place many or all Imports and Exports in one DIResolver class, but I prefer to define DIXXXResolver in a logical way so that it contains only the related mapping relationships, for example, DIContollerResolver for resolving the export of IProcessController, DIDataReaderResolver for the export of IDataReader, and DILogResolver for the export of ILog.

OK. I think is very clear about the concept of Export and Import as Parts in MEF in terms of DI. How are the parts (Import and Export) loaded to MEF so that the expected instances can be retrieved from the framework?

In MEF, all the parts are loaded to a DI container, which is called as CompositionContainer class. The container class interacts with Parts actually through another layer called as Cataglog. This is a very interesting and powerful structure. MEF currently supports four types of Catalog classes and they all inherited from ComposablePartCatalog class:


Those catalogs are straightforward by their names. For example, AssemblyCatalog is used for loading parts within an assembly; DirectoryCatalog for loading parts by specifying a folder or file pattern; TypeCatalog for loading a list of specific set of types; and AggregateCataglog for loading a list of catalogs. The first three are most commonly used ones. With this design of structure, Catalog class provides a wild range of strategies to load parts to a MEF container.

For example, I use the AssemblyCatalog to load a list of assemblies or DI libraries where DIXXXResolver classes are defined. I can also put some DI library and related library files in one folder, such as "DIExtensions". Then the folder is loaded by DirectoryCatalog. This makes it possible to dynamically add new extensions or update extensions without rebuilding or compiling my application source codes.

Although it is very easy to load Catalogs to MEF, you still need to understand and follow MEF pattern to do that. As you will find out, MEF contains a wild range of types, classes, interfaces and attributes. It may be very confusing or intimidating for beginners. I'll stop here about further explain MEF; instead, I'll show you three help classes I have created. Those classes provide very simple APIs to define DI mappings, to load DI catalogs, to retrieve instances, as well as other benefits you can get from them.

Still I think it will be very helpful to visit MEF class library and documentations when you see some MEF terms in my classes.

Read More...

Sunday, March 14, 2010

MEF and IoC/DI (2)

Let's explore how to use MEF as a DI framework.

Define Object Mapping Relationships


The documentation at CodePlex MEF project provides excellent information about its MEF structure, how to use it and examples. The information over there may be overwhelming, or more than you need if terms of DI. Here I'll explain MEF briefly just in the area of how to use MEF as a DI framework.

In MEF, the basic units are called as Composable Parts. A part can be either Export or Import. In the case of DI, this can be used to describe mapping relationships.


An Export is used to describe a composable part as a mapping relationship, for example, a class to a class type or interface type. In other words, it tells MEF how to get or create an instance for a class or an interface type.

An Import part, one the other hand, provides a gate way for a client get an instance as a class type or an interface type from MEF. For an import, MEF will inject an instance for a property or field variable if MEF has the knowledge of the corresponding Export part.

In MEF framework, Export and Import are used as attributes. Export attribute can be used to mark a class, a property or a method, while Import attribute can be used to a property, a field value or a constructor parameter.

In my DI practice, I use Export to define mapping relationships, and use Import in codes to let MEF to inject instances based on Export mappings. I mostly use Export/Import for property or field values, rarely for classes, methods or CROR parameters. One reason is that in most cases, I use third part components or reuse components I created before I knew MEF, therefore I cannot add Export/Import attributes to those classes or properties. Another reason is that those attributes actually have less relationship with their logic implementations. I would reluctant to impose other users to use my libraries with MEF binary files.

The advance of applying Export/Import to property or field values is that I can create one or a list of libraries, where only DI logic is described, nothing else. In addition to that, those libraries may have interfaces to get objects injected from MEF. Those libraries are the only places where I use MEF to define DI mappings and to provide a few of simple interfaces to retrieve objects for clients or applications.

As enough as I have said, I'll show you some examples how to use Export and Import attributes for DI mappings. Let's look at following example. Here are some interface definitions and a controller class definition:

public interface ILog {
  ...
}
...
public interface IDataReader {
  ...
}
...
public class MyController : IProcessController, IDisposable {
  // My implementation class
  ...
  // CTOR
  public MyControler(ILog log, IDataReader reader) {
     ...
  }
  ...
}


Then in a DI mapping library, I define a DIResolver class with some property variables marked as Export or Import:

internal class DIResolver {
  [Export]
  private IProcessController _exportController {
  get {
    return new MyController( _log, _reader );
  }

  [Import]
  private IDataReader _reader { get; set; }

  [Import]
  private ILog _log { get; set; }

}


There are some very interesting points in above codes. First, the class DIResolver can be internal, only visible within the project but not to the outside. It makes sense because I don't need to use this class as an API for any public uses. In addition to that, I can also hide Import and Export properties as private ones if I don't have intension to use them outside the class. MEF can access them.

I define the property _exportController as a mapping relationship between the interface of IProcessController and the implementation class MyContoller. The CTOR of MyController has two parametes: ILog and IDataReader. There are many ways to get instances for those parameters. Here I define two properties as the type of IDataReader and that of ILog, and they are accessible to the CTOR since they are local getters. The key point is that those two properties are also defined as setters and marked by Import attribute. As a result, MEF will be able to inject instances to them. Of course, the Exports for IDataReader and ILog have to be defined some other places such as DI libraries, where I define them in a similar way.

Read More...

Saturday, March 06, 2010

MEF and IoC/DI (1)

Inverse of Control (IoC) and Dependency Injection (DI) are widely used patterns in software development. Here I call DI in short for IoC/DI afterwards. I have used StructureMap in .Net as a framework to inject instances to my application, a nice way to decouple interfaces and implementations(see my previous blog posts). MEF(Managed Extensibility Framework) is another very hot topic in .Net recently. Now it is a part of new libraries in .Net Framework 4.0, and it is also available for .Net Framework 3.5. Actually, MEF started as an Open Source project at CodePlex by a group of Microsoft developers. It is claimed with more features than DI.

In the past weeks, I have tried MEF as an alternative way to StructureMap to provide DI. It works out very great. MEF may have much rich features than StructureMap since the later is mainly focused on DI while the former is on the extensibility and discovery ability. Since I am more familiar with DI, therefore, in the view of ID, in this and following posts, I’ll explain in detail how I use MEF as a DI framework.

Overview


Let's stand back a few of steps to get a big picture of implementation of DIs in an application. From my past experience of using StructureMap, I treat it as a library to hold a DI container in cloud.

First, I provide it with information about mapping relations of class to class or interface to class to the container. Then either I fetch instances by interfaces or class from the container directly whenever I need them, or I mark my codes with some kinds of indicators such as attribute so that the cloud will be able to inject appropriate instances automatically. As a result, I would not need to know how instances are created, nor need I to have any knowledge of what actual instances are mapped. This will let me to concentrate on my business logic or working on components individually.



The above is the picture I perceive. With this picture in mind, I found that MEF works in a similar way. I don’t need to change my interface library and components (3), nor my business implementation or application (4). What I need to do is to understand the structure and the way of how to add/load my mapping relationships through the block (2) to the new container (1), and understand how to request instances from the DI framework to my application (4), or to construct my application so that instances will be able to inject to "magically".

In the above picture, there are two doted arrows, which mean that there are two ways to call or reference to each other. One is direct call or request. For example, you can write codes to let the container to know what the mappings are, and you can make a call to the container to get an instance by type. In other words, you have direct access to the container. Another way is that you don't need to write codes to do any direct call at all. Most DI frameworks provide some ways to mark dependencies and injects so that DI framework will be able to detect or load mappings and inject instances automatically. For example, you may construct a mapping configuration file, or add some special attributes to your classes, property variables, constructors or method parameters. Both MEF and StrcutreMap support these two ways; however, they provide different strategies and implementations in terms of how to describe the mappings and to provide injections.

In this and following posts, I'll discuss how to use MEF to describe mappings and injections. My practice only exposes the tip of iceberg, as MEF has much rich infrastructure and features. Even though, I think my DI exercise may help you better to understand MEF. During my exploration, I have done several times of refactory of my codes, which were quite rewarding learning experience.

Read More...

Sunday, February 14, 2010

iPhone SDK 3.1.3

toolsAnother new iPhone SDK 3.1.3 is available. This one is very similar as the previous one on Feb 1 I got. The size is very big, about 3.05GB. Here is what Apple says about the SDK:

What’s New in this Version
- SDK support for targeting non-Mac OS X platforms, including iPhone OS SDK.
- GCC 4.2 & LLVM GCC 4.2 optional compilers for use with Mac OS X 10.5 SDK
- Updated assistants to create new projects, targets, and source files
- Toolbar uses a single popup to choose platform, target, and debug/release
- Integrated SCM support now works with Subversion 1.5

Company:Apple Inc.
Version:3.1.3
Post Date:February 2, 2010
License:Freeware
File Size:3.05GB
URL Type:Form
Download ID:17946




Here is what actually in the installation:

iPhone SDK 3.1
Installs the iPhone SDK 3.1.

iPhone SDK 3.1.2
Installs the iPhone SDK 3.1.2.

iPhone SDK 3.0
Installs the iPhone SDK 3.0.

iPhone SDK 2.2.1
Installs the iPhone SDK 2.2.1. NOTE: this will install the iPhone SDK 2.2.1 to work only on a device; the iPhone Simulator requires iPhone SDK 3.0 or later on Mac OS X 10.6 Snow Leopard.

Sytem Tools
Installs system-wide tools such as Shark (part of the CHUD performance tools), DTrace components used by Instruments, and distributed build processes.

There can be only one, newest set of System Tools per Mac OS X installation at a time, and are always installed into /Developer on the boot volume.

UNIX Development Support
Optional content to allow command-line development from the boot volume. Installs a duplicate of the GCC compiler and command line tools included with the core Xcode developer tools package into the boot volume. It also installs header files, libraries, and other resources for developing software using Mac OS X into the boot volume.

This package is provided for compatibility with shell scripts and makefiles that require access to the developer tools in specific system locations. This content is not relocatable and will only be installed onto the boot volume.
Documentation
Xcode will download developer documentation to disk at first launch, and automatically keep it updated. Deselecting this option requires a network connection while viewing documentation. You can change this at any time in the Xcode Documentation preferences.


Finally, here is the space difference between before and after the update:
Command: df -lakUsed(Kilobytes in 1024-blocks)
Before ...4,408,568
After...2,729,796
Difference (A-B)-1,678,772

Read More...

Monday, February 08, 2010

iPhone Development Update

In the past week evenings and weekend, I spent most of my watching iPhone development related videos. I got those video information when I accessed to Apple’s iPhone developer web site. I remember that I watched a serials of iPhone development classes by Stanford University last Spring. Since then there are more training materials from Apple and other institutions.

Here is a snap-shot of videos I have in my iTunes:



It is great to watch those on my Mac iTunes. However, they are not directly available from Web, or from browsers. I tried to install iTunes at my work PC and I was planning to watch them after work so that I would have quite time there. Unfortunately, I could not get those videos from iTunes in Windows. It looks like that the download URLs or iTunes protocols are blocked at the work. There is no way to get them from browsers, at least I don’t know. In this sense, those videos are not widely opened.

For videos I watched last week, I understand most contents very well. I think that this is the benefit of my past year reading iPhone OS Reference Library and other materials at Apple’s Dev Center. Still those excellent videos greatly help me to understand some concepts such as memory management, MVC, KVC, KVO, and delegates.

By the way, I tried to optimize the size of my snap picture by using Yahoo’s Smuit.com. It is very interesting that Smushit could not find any savings in my pictures. Mac’s png picture is quite good if it is true. I am not sure if the recent update enhances this or not.

Read More...

Saturday, February 06, 2010

Retry Component

Last Friday, I finished a project of reading data from a service and saving the data to a network drive. The project is a console application based on a framework of DI. that is, dependency injection. The whole process is divided into several small tasks, and each task is corresponding to a component, or a library in .Net. Each one does one job and does it well. Together, the components are plugged in to a main controller, where a work flow of components is laid out in a logic as expected. In addition to this clear and well defined structure, there are many other advantages as well, for example, easy maintenance and reusability.

The application will run on daily base to prepare data for one department. I demoed the application to my project team leader. He was very happy to see how the demo run. After the demo, he asked me a question: how about retry? Is there a way to run this application on a retry style if the required data are failed to deliver to the network drive? I have worked on several cases to read required data from SQL servers. All those application have the retry feature. For example, one applications gets the required data first, if the returned data is empty, then the application will quit immediately. If the required data are not empty, the application then gets the data and saves them to the server.

However, for this case, the data source and destination are not at the same place. Therefore, the application will always get the data from source when it runs. I have to work out a way for the retry. In other words, I have to define or create some key references to check if the retry is needed.

Since the job will run on daily base, I come out two keys to check: date and status. For the date, there is one as expected date, and another as actual last date; same for the status, one as expected status and another actual last status. The actual value has to match to the expected value. For example, a user can set up the expected date today and the expected status as a string of "ProcessOK". When those conditions are true or the actual values match the expected values, the application will not read data from source; otherwise, it will read data and continue the remaining steps. After all is done, the actual values will be updated.

All those expected and actual information are defined and saved in an XML configuration file. The expected date can be a script of C# code like "DateTime.Parse(DateTime.Now.ToShortString())", which will always to get today's date. The expected status is static as well. Therefore, only two actual values have to be updated by the application when a complete run is finished.

Here are the pseudo codes of the retry logic:

   bool retry = method call to an instance of Retry with the logic:
!(actual_last_date is set) ||
!(actual_last_status is set) ||
(expected_date != actual_last_date) ||
(expected_status != actual_last_status);
if (retry)
{
run_application
...
save actual_last_date
save actual_last_status
}

The Retry class is a component in a library project. The Retry class implements an interface of ICommuncationChannel in a framework library:
  interface ICommunicationChannel<TData, TValue>
  {
    TData Request(TValue value);
  }

so that it can be requested to return a result of retry. A configuration class is also defined in the Retry component library. The config class is simple class with property definitions corresponding to the expected values and the actual values. An instance of the config is wired to the XML configuration.

After one day hard-thinking and coding, I got the component completed, added the DI mapping and XML mapping for Retry's config, and almost finished the main controller with Retry component in the logic.

The reason that I decided to save the actual last results the XML configuration file is that those values can be easily parsed out by another PowerShell script project to get the job status. I have done a monitor process based on PS and Growl for sending notification messages. With the retry feature, I can bring an additional benefit: adding these actual values to the monitor process so that the notification message will include the information.

Read More...

Monday, February 01, 2010

iPhone SDK 3.1.2

After about one year reading of iPhone development reference documentations and training materials, I am going to start my new adventure of iPhone application development. I downloaded the iPhone SDK long time ago. I think I need to get the newest version of DSK 3.1.2 first. The total package is about 2.5GB, which takes long time to get it. I just started about a few minutes ago, now the remaining time is about 37 minutes.

At the same time, I found there are some iTune video materials available from ADC, I am going to get them as well. My first application will be in the category of Productivity area for managing personal expense information. The datastore will be based on SQLight which is recommended by Apple for iPhone app. I have created several tables for raw data. In order to management raw data, I am going to use Tags to let user to tag those information. The main interface will be based on tableview controls for displaying data with editing features. The edit view will be a view with text and date time controls. I am going to draw those views and workflow structure of views.

The application will be MVC based application. To my surprise, Apple developers has implemented this pattern for quite long time, even long before the current Microsoft MVC model in Windows and ASP applications.

Even the iPhone development and Objective-C are new for me, I think I have very good knowledge of C/C++, as well as extensive experience in OO. I have explored some iPhone applications and had my hands on some examples. I really like the framework of Cocoa. It will take time get used to the new framework for sure. I think the most achievement is to develop my own applications and test them out on the Apple Store.

I have a line of ideas to develop iPhone applications. iPad will be available in less than 60 days and iPad 3G in less than 90 days. If I can get some out for iPhone, it will be fun to see how they are in iPad. I may move to iPad application development as well.

The following are snap-shots of the installation steps:







Detail descriptions for items:

iPhone SDK 3.1
iPhoneSDK.3.1.2Install1
iPhone SDK 3.0
Installs the iPhone SDK 3.0.
iPhone SDK 2.2.1
Installs the iPhone SDK 2.2.1. NOTE: this will install the iPhone SDK 2.2.1 to work only on a device; the iPhone Simulator requires iPhone SDK 3.0 or later on Mac OS X 10.6 Snow Leopard.
System Tools Support
Installs system-wide tools such as Shark (part of the CHUD performance tools), DTrace components used by Instruments, and distributed build processes.


There can be only one, newest set of System Tools per Mac OS X installation at a time, and are always installed into /Developer on the boot volume.
Documentation
Xcode will download developer documentation to disk at first launch, and automatically keep it updated. Deselecting this option requires a network connection while viewing documentation. You can change this at any time in the Xcode Documentation preferences.
Mac OS X 10.4 Support
Support for developing applications that target Mac OS X 10.4 APIs.

I checked the "Mac OS X 10.4 Support" (even it is still Zero KB).

Read More...

Saturday, January 23, 2010

.Net Reflector

.Net Reflector is a must-have tool for .Net developers. Last year I updated my Visual Studio at work to 2008. However, I forgot to add this tool. When I started to work on a project based on MEF(Managed Extensibility Framework) as DI (dependency injection), this reminded me about the tool. I need this tool to browse the class structure of Microsoft.ComponentModel.Composition.dll.

The tool was developed by Lutz Roeder. In his blog, he said that now it is transfered to Red Gate Software. I think I used the SQL Compare application from this company. Anyway, .Net Reflector is a Windows based application, and it is very easy to install as a tool in VS 2008. From the menu Tools->External Tools..., it can be added there. Here is a snapshot of the installation:



There are also many Add-Ins for this tool.

Read More...