Core Data Gotcha: Objects in Child Contexts Don’t Receive Permanent IDs From a Save

With the introduction of child contexts since iOS 5, a typical Core Data stack is to create a parent NSManagedObjectContext with a concurrency type of NSPrivateQueueConcurrencyType, and also create a child context from it with a concurrency type of NSMainQueueConcurrencyType. The UI thread would use the child context whenever it needs to work with Core Data objects, while data persistence will happen in the parent context. This setup allows the application to persist data to disk without blocking the UI thread.

Now, I’m questioning whether this is the proper setup. It seems that child contexts are probably not intended to be used like that, and as a result, I ran into a issue of keeping the child and parent fully synchronized. In one of the iOS apps I’m developing, I discovered NSManagedObjects in the child context do not receive a permanent NSManagedObjectID upon a save that propagates all the way to the parent. In other words, if you do the following:

  1. Create a new object in the child context
  2. Save the child context
  3. Save the parent context (to persist to disk)

The newly created object in the child context will not update its temporary ID to the permanent one assigned by the persistence store when the parent is saved. Only the object in the parent context will be updated to reflect the new ID. The object in the child context will remain with a stale temporary ID. The reason why this is an issue is that the UI thread may continue working with the child context and if it happens to pass along the object’s ID to other components, the object will not be found.

It seems that this behavior is by design, though in my opinion, it’s not intuitive. I see three solutions to this issue:

  1. Call obtainPermenantIDForObjects:error before saving the child and parent contexts.
  2. Discard the child context after a save to parent. I believe this is the intended use of parent-child contexts.
  3. Listen to NSManagedObjectContextObjectsDidChangeNotification & NSManagedObjectContextDidSaveNotification notifications from the parent and refresh & merge objects respectively into the child context.

Since it seems like the intended use of child contexts is to only use them temporarily, I’ve actually went back to using the traditional model of having two independent contexts (one for the background thread and one for the main thread), each using the same persistence store. Creating a new child for each screen and managing change notification objects didn’t seem worthwhile. However, I still use a child context for create/update screens, where changes made by the user can be cancelled. This is where the advantages of child contexts truly shine.

NexusDialog: Dynamic Form Builder for Android

Writing repetitive UI code can be tedious sometimes. Whenever you observe a repetitive pattern in how code is built, it’s usually a good sign that it can be refactored out to its own module, or even its own library. It’s also likely that other developers will run into similar needs. This is exactly why I just released an open-source project for Android I called NexusDialog. It provides an easy and simple way to build a form-based UI. This was motivated by a recent app I developed that required displaying many form-based screens. As most developers do, I initially looked around to see if there were existing libraries that provided such functionality. On iOS, there are plenty, so I expected to similarly find many options for Android. Surprisingly, I was not able to find an active one. This is perhaps because UI design is significantly easier and more flexible on Android than iOS. Nevertheless, there is merit to having a framework that simplifies the development of a certain class of UIs, like forms. Thus, NexusDialog was born.

Here’s a simple example of how to create the following form:

Here’s the code to generate the form:

import java.util.Arrays;
import com.github.dkharrat.nexusdialog.FormActivity;
import com.github.dkharrat.nexusdialog.controllers.*;

public class SimpleExample extends FormActivity {

    @Override protected void initForm() {
        FormSectionController section = new FormSectionController(this, "Personal Info");
        section.addElement(new EditTextController(this, "firstName", "First name"));
        section.addElement(new EditTextController(this, "lastName", "Last name"));
        section.addElement(new SelectionController(this, "gender", "Gender", true, "Select", Arrays.asList("Male", "Female"), true));

        addSection(section);
        setTitle("Simple Example");
    }
}

It doesn’t get any simpler than that. Read more details about the library at https://github.com/dkharrat/NexusDialog. Feedback, suggestions, and contributions are very welcome!

My list of 7 must-have Chrome Extensions

I sometimes get inquires from friends and colleagues of what extensions I use for Chrome. Rather than sending out links or explaining what they are, I thought of documenting my favorite list of Chrome Extensions that I can’t work without:

  1. Session Buddy: Manage your browser sessions
  2. Google Dictionary: Double-click on any word on the page to view its definition.
  3. JSONView: View pretty-formated JSON content
  4. LastPass: Save and generate passwords for a site
  5. Pocket: Save current page to read later anywhere
  6. Postman – REST Client: Nice tool to debug HTTP requests
  7. Tape: Dynamically create a ruler on the page to measure distance. Useful for front-end development.

Suggestions to other useful extensions are welcome!

Continuously Rebooting System and BSOD in Windows Logon Process STOP:0xc000021a

Today, I accomplished something that I thought was quite challenging. I solved a very cryptic and frustrating STOP message. I wake up one morning, and discover that my WinXP computer was completely hung. I restart it and wait for it to boot up, but a couple of seconds in the boot up process (in the “Windows XP” boot logo) , it rebooted. Thinking it was a one-time glitch, I waited for my computer to start up again. But it rebooted yet again. It kept rebooting each time. I then remembered that this might be because of a STOP error occurring that is triggering the reboot. I pressed F8 right before boot up and chose the “Disable Automatic Restart on System Failure” option. As I expected, I got the “Blue Screen of Death” (BSOD) error message:

STOP: c000021a {Fatal System Error}

The windows Logon Process system process terminated unexpectedly with a status of 0xc0000139 (0×00000000 0×00000000). The system has been shut down.

Luckily, I had a laptop around so I was able to search about the problem on the Internet. However, I wasn’t able to find anything related. I found an Microsoft support article about troubleshooting this kind of error, but it was unrelated. It talked about the STOP error occurring during normal operations of the system.

I knew the “Windows Logon Process” corresponds to winlogon.exe, so I wanted to find out what the status 0xc0000139 meant. I searched in the XP Windows DDK files and found this:

// The procedure entry point %hs could not be located in the dynamic link library %hs.
#define STATUS_ENTRYPOINT_NOT_FOUND      ((NTSTATUS)0xC0000139L)

Hmm; interesting. So, what I understood from this status code was that winlogon.exe isn’t able to load because some entry point wasn’t found in one of it’s dependent DLLs. In order to find out the details, I needed a way to get access to my harddisk and run some tools. Eventually, I found out about this really useful tool: BartPE which creates a bootable Windows system on a CD. What’s really cool about this tool is that you can boot into Windows from the CD and have a complete functioning Windows environment, where you can perform maintenance tasks, run applications, access the NTFS/FAT hard disk, and more.

With BartPE, I was able to boot into a working Windows system and have complete access to my hard disk. Then, I used the “depends” tool to get the DLL dependencies of winlogon.exe. I then compared that to the dependencies of a working XP installation (I used the system32 windows files in BartPE itself as reference, since it’s technically a “working XP installation”. Eventually, I found out that the difference was in the following two files:

oleaut32.dll
olepro32.dll

Those files were using an entry point in msvcrt.dll called “strcat_s” that doesn’t exist. It looked like oleaut32.dll and olepro32.dll failing to load caused winlogon.exe to fail to load. It looked like they were for Vista since their version number matched the versioning scheme on Vista. I have no clue how those files got replaced. Maybe a bad update?

Anyways, after replacing those files with the ones from my WinXP installation CD and rebooted, my system started successfully! After wasting around 6 hours trying to solve this, at the end it’s quite relieving to know that the time spent didn’t end up being wasted for nothing.

Wrong Flowers

A joke that I found hilarious. I wonder what the reaction was at the funeral part :D

On opening his new store, a man received a bouquet of flowers. He became dismayed on reading the enclosed card, that it expressed “Deepest Sympathy”. While puzzling over the message, his telephone rang. It was the florist, apologizing for having sent the wrong card. “Oh, it’s alright.” said the storekeeper. “I’m a businessman and I understand how these things can happen.” “But,” added the florist, “I accidentally sent your card to a funeral party.” “Well, what did it say?” ask the storekeeper. “‘Congratulations on your new location’.” was the reply.

A New Look

It’s been ages since I updated my site, and just recently, my site has been apparently hacked and some of my previous posts were overwritten with some random messages. They even took over my admin account and I couldn’t log-in to my own site! So, I had to restore everything directly from the database. Good job hackers; you wasted a couple of minutes of my valuable time.

I’ve updated the blogging software to the latest in order to take advantage of the latest security updates of the blogging software. Also, I’ve changed the site’s theme to a completely new one. I hope everyone likes it.

Things going smoothly…and enjoying my time

Apologies for the long update. Life has been hectic here and you really don’t get much time to do much stuff. It’s been around 4 months since I moved to San Jose and things are going pretty well. Overall, I’ve been enjoying my time here and having lots of fun. A friend of mine, Salman, lived with me for around two months and we had a great time together. We got to play with an 34″ HDTV, Xbox 360, and 5.1 surround sound system! Watching movies on 34″ high-definition screen with the awesome sound system is a totally different experience!

A couple of weeks ago, my friend and I went to San Francisco, which was extremely fun. We visited Pier 39 in Fishermen’s Wharf, a very famous port on the bay with lots of attractions. We also got on a boat tour to see the San Francisco Golden Gate Bridge and the Alcatraz prison located in an island (an abandoned ~100-year old military prison that eventually turned into a historic landmark). Moreover, we visited a wax museum, which reconstructs the bodies of most of the popular figures throughout history in wax. Everything in the museum is made of wax; pretty cool. Right beside the wax museum was the Ripley’s Believe it or Not Museum, which contains hundreds of interactive displays and illusions off the popular TV show. We also got to see many really cool street performers. All this was in just Fishermen’s Wharf alone, which took the whole day – much longer than anticipated. San Francisco, obviously requires more than one day.

One of the other places we visited was Lake Tahoe, which was fabulous. The scenic route to the lake was just breathtaking – with all the trees, mountains, curvy roads, rivers, some snow, …. At the lake, we tried Jet Skiing, which was the first time I ever do it in my life – finally, at last, I managed to get to personally experience it.

There are many other places we went to, but I think that’s enough to mention for now ;)

Working at NVIDIA!

I have recently accepted a full-time position at NVIDIA as a Software Engineer, which means I will be moving to Santa Clara, California very soon. I’m expected to start work on May 1st. I’m pretty excited about this new job and for the opportunity to live in Silicon Valley. I’ve never thought in my wildest dreams that one day, I will be living and working there; in fact, I used to dismiss that thought as being virtually impossible given the highly competitive job market and my personal misconceptions regarding cost of living, safety, etc. But now, against all odds, I will be starting my professional career there!

I’m hoping to enjoy my time there as much as possible. I’m hearing from lots of people that the city is gorgeous and fun, especially around San Francisco. I have no idea at the moment how my work load at NVIDIA will allow me to enjoy life, but we’ll see. One of the first things I need to do is find an apartment and buy/lease a car.

Basically, can’t wait…

Developing a 3D Motion Capture System

These days I have been busy working with a friend on a hardware project, called 3D Motion Capture System. This has been the biggest hardware project I’ve been involved in. Most (if not all) my personal projects that I’ve worked on in the past were basically software related. For this reason, I’m pretty excited about this new project, as it provides me an opportunity to work on a slightly different domain than what I’m used to. After all, I have a Computer Engineering degree, and I ought to be relatively good with this stuff. Thankfully, since the one-month that I’ve been working on this project, I have to admit that I have gained tremendous experience with hardware. I’ve also come to a conclusion: hardware isn’t really my thing :)

Now, to explain more about this project, it is basically a system that allows a user to capture 3D positions. The system is composed of at least three “stations” and a couple of “markers”. The markers are mobile devices, which have a position in space. The position of these markers is what’s captured by the system. The markers can be installed on the human body for example, which will allow the user to capture human motion. The stations are stationary and are responsible for calculating the distances between themselves and each marker.

Determining the position of these markers in space is the bread-and-butter of our system. This is done via ultrasonic transducers. Basically, each station starts a timer and then sequentially “ping” the markers via RF signals to inform them to start emitting ultrasonic waves. The sound wave (at 40kHz) is then emitted from the markers. Once the stations receive this ultrasonic wave, the delay between the time of the ping request and the time the sound wave was received in the station is calculated (each station performs this). This delay will provide distances between each marker and each station. Using three stations, the 3D position of each marker can be determined. The stations connect to the PC via USB cables.
Our system essentially provides the 3D positions of the markers through a driver. The application can do whatever it wants with this data. The number of applications are of course limitless. We are thinking of developing a simple prototype system of a “3D pen”. Using one marker, the user can draw in 3D space anything s/he desires. Sounds pretty exciting, eh?

Right now, we are about 95% done with the hardware! What is left is basically programming the microcontrollers to perform what they are supposed to do, and to eventually send the 3D position of each marker. After that is done, we can actually start making that 3D Pen application.

Hopefully what I said made sense. I’ll post more updates as the project progresses along.