Hacking Bangkok Blog

Tech and Living in Thailand's City of Angels

The Hacking Bangkok blog covers I.T. and technology in general, and my experiences working and living in the Kingdom of Thailand. Bangkok has a very long Thai name, which starts with Krung thep - City of Angels.
Bangkok sunset from my bedroom balcony

Saturday, April 4, 2009

Maybe There Is A God - Terminator 4 Is Almost Here

This is a (somewhat blurry) pic of a 'Terminator 4: Salvation' display in front of the entrance to a theater I go to near my condo. I was really doubtful about another installment of the Terminator franchise after the mess of 'Rise of the Machines', but when I heard Christian Bale was playing John Connor, I suspended my doubts.

I'm sending this blog post out from my trusty Touch Diamond, which has served pretty well over the past 10 months. Still, I'm betting this will be a big year for android (and possibly the first viable x86 smartphone, given that "Moorestown"-based LG prototype Intel has been showing around).

Tuesday, March 31, 2009

Adventures With Linq-to-SQL: The Update Dilemma


I haven't written a post that goes into much (any?) detail on what I am working on over here, so this is that post. Since December, I've been working on a set of applications for a recruiting company, to replace the apps that they're using now (which I also wrote, about three years ago mostly). The old version, while it works, has some design flaws (some of which I inherited by way of using the database that held the previous never-finished attempt to create the app, built by some local programmers), some of which were inherent in using Windows .Net forms, and some of which resulted in my (over-) reliance on DataSets for storing object data.

So the new version of the app is an almost-complete rewrite; it uses SQL 2008 (or SQL 2005) rather than SQL 2000, but the bigger changes are that I'm using WPF for the UI, and Linq-to-SQL for almost 100% of the data access layer. Linq is beguilingly easy to use. Instead of writing code along the lines of, "If Not IsDBNull(ContactDataSet.Tables(i).Rows(j).Item("Name"))", I can just write, "myContact.Name" and get a string value. Linq objects are strongly-typed (granted, you can create strongly-typed datasets as well), and once you lean the very simple to use Linq query syntax, you can fetch objects out of the database with very little code, and no t-sql at all. Inserting new objects into the database is equally easy, and I love that columns with default values in the database can be set to automatically-sync their values back to the object on inserts or updates.

It's only when you go to update an existing object that you start finding out why people have so much trouble with Linq: because if you fetched an object with one "DataContext", which you shoud promptly discard (the typical pattern of usage is, "Using myDC as New MyDataContextClassname() ... CRUD... End Using), and then update it, and then create a new instance of your DataContext, trying to save it becomes annoying. By default, for the new DataContext instance to save changes to your item, you need to attach it, with a call to the context's .Attach() method. And there the fun starts!

Trying to attach an object you loaded from a different context will, unless you do some extra work, throw an exception. You'll get an error along the likes of "Attempt to attach an object that is not new, or loaded by a different context." Now, my app uses a lot the "deferred loading" in Linq, which means that a linq object has properties that represent other linq objects, or collections of those objects, which aren't loaded until they're requested by something. So, a contact object like MyContact (an instance of Contact, which is pulled from a Contacts table, for example) might have properties called "Company_Id" (from FK column of the same name), and another property called "Company". The "Company" property is actually of type EntityRef(Of Company). Or, if the relationship from Contacts -> Companies in your database is one-to-many, then MyContact probably has a property called "Companies", which returns (natch!) a collection of the Company objects to which it's related via the PK-FK relationship. The "Companies" property of MyContact is actually of type EntitySet(Of Company) in this case. If you reference MyContact.Company, you will get a Company object if there is one, and so on, so you probably don't even see the EntityRef stuff until later. When you try to update your contact!

Either way, either in using WPF databinding or in code-behind, this design makes it really easy to get to related objects and collections of them. So in WPF, if I have a bunch of elements bound to MyContact, I might have an element whose content property (or whatever property) is set to "{Binding Path=Company.CompanyName}", or even "{Binding Path=Company.Country.CountryName}". During binding, the "Company" property is called automatically, which then loads (if it's not already loaded) the Company object, or for the second example there, it will actually fetch a Country object that's linked to the Company object that is in turn linked to MyContact. All with no code! See ma, no hands!!

The problem is that now, MyContact has its "Company" property set. If you dig a little, you'll see that in the .dbml file (the Linq-to-sql class and mapping file), that the Company property is, as I mentioned, of type EntityRef(Of Company), and that it's just a public property wrapper for the private member _Company. And variables of type EntityRef have a property called .HasLoadedOrAssignedValue, which is boolean, and .Entity, which essentially refers to some object (of type Company, for this example) in the same DataContext. You see, DataContext has one "object" for each table that you've added to your .dbml file, which represents a table of those objects. When my XAML (or code-behind) calls the .Company propert of MyContact, the DataContext that MyContact belongs to duly loads that company object into it's Companies table, and points the private member MyContact._Company.Entity so that it refers to that company.

Now - after binding is done, and I've disposed of my datacontext like a good boy - I still have access to that Company object, via MyContact. I can even create a new object, "MyCompany", and set it equal to MyContact.Company, and then have my way with it. But when I update MyContact, instantiate a new datacontext (again, "Using NewDc as New MyDataContextName().."), and call NewDc.Attach(MyContact), it will fail. MyContact has those EntityRefs that refer to objects (like Company) that are in a datacontext I already disposed of. Even though the object is there, and accessible. I'm going to confess that I'm not sure why, fundamentally, the Linq team couldn't have come up with a built-in solution, something like "MyContact.Detach" (to clear out it's entity-refs and entity-sets). But anyway.

There are multiple ways around the dilemma. First, keep in mind that, in order to perform concurrency checks (that is, to ensure one user isn't overwriting another user's changes), Linq will either check the old values against the current ones, or (if you're using a rowversion/timestamp column), it will just check that. For simplicity, I added rowversion columns to all my tables containing editable records.

Okay, I said there were ways to save your data.

(1) You can pass the .Attach method both the current state of your object, plus it's original state. Of course, that original state is only available from the already-disposed datacontext you used to load it (if it wasn't disposed, you could call, "myDC.Contacts.GetOriginalEntityState(MyContact)" which returns the Contact object with all the properties set to their original values, when you pulled it from the database). You could also just keep a copy of every object that you plan to change, so you have the old copy to pass to .Attach() - I did play around with this, and didn't have much success. Also, it's annoying (to me) to have to manually keep an extra copy of objects I'm about to change, just to update them.

(2) You could turn off DeferredLoading on your datacontext, thus killing one of the great benefits (in my opinion) using linq in the first place. I never really considered mucking with changing the deferred loading on the fly, but that might be viable for some people. You can also set ObjectTrackingEnabled to False, but you can read on Rick Strahl's blog why this is usually pointless (in short, you can't get to linked objects at all).

(3) You could do what I did when prototyping this project, which was to keep a single DataContext in an object, and open, insert and update every object using that datacontext (this turns out to be the opposite of what the MSDN documentation recommends, maybe because it's keeping a database connection open, I'm not sure). Anyway - the datacontext objects are meant to be used then disposed.

(4) You could use some elegant feature or method in Linq that I don't know of yet - and if you do know of it, please leave me a comment below!!!

Or (5), you can write you own .Detach methods, which is what I did.

This might not be an ideal solution for many people (possibly even for me!), but it has the advantage that (a) it works, and (b) I already did it. Linq's classes are all generated as partial classes, so you can extend them willy-nilly in another partial class (normally in the file that's created if you right-click the .dbml file in VS solution explorer, and choose "View Code"). I created a new public method, "Save()", for each of the types of objects that users will edit (i.e., Contact, Company, Appointment, and so on). I also wrote two private methods for each, "Detach()" and "RestoreContext()".

If the property is not an EntitySet, but just an singular EntityRef (so, one company, not a collection), you can just assign null/nothing to property's .Entity propety, like so: Me._Company.Entity = Nothing. Now, in a few places in my app, I might want to get at that object again without having to load it (again) from the database. In fact, if I call my .Save() method, which first calls my .Detach() , then any WPF fields that were bound to properties of the company (like in the binding examples I gave above) will suddenly go blank after the save. You could set the binding mode to one-time, but maybe I want the user to be able to actually see more properties of the company in a pop-up box or something. So my solution was pretty straight-forward: I added private variable declarations in my partial classes. I declare two kinds of things, depending on my object:

Private CompanyEntity As Company
Private HobbyEntitySet As EntitySet(Of Hobby)

Note that I don't really have a list of hobbies, just using it as an example. So anyway, in my Detach() method, I put:
If Me._Company.HasLoadedOrAssignedValue() Then CompanyEntity = Me._Company.Entity

And finally, the public .RestoreContext() method I wrote just reverses the process - it sets Me._Company = CompanyEntity, then sets CompanyEntity back to nothing/null. I don't always need to restore the context - if the user clicked, "Save & Close", for example, I just call the .Save method on my object. If I'm saving some changes, but keeping the object (MyContact) around, I just call .Save, and then .RestoreContext().

If the property IS an EntitySet, I use the same principle.
The auto-generated linq classes do already have (private) methods for these EntitySet(Of T) properties. These methods are in the main .rbml file, and are called "detach_xxxxx" and "attach_xxxxx" which are called whenever you do something like, "MyContact.Companies.Remove(SomeCompany)" or "MyContact.Companies.Add(SomeCompany)" (assuming a one-to-many with Companies, obviously). When you instantiate a new Company - which happens whenever you load one from the DB, or attach it to a context, or declare one (eg., "Dim c As New Contact) - the generated linq code assigns attach_xxxxx and detach_xxxxx as the functions called whenever you add or remove a Company, say, to or from the .Companies list. And so I've seen posts on the web where people wrote .Detach() methods in a partial class (which is where I got the idea!), and they loop through each attached object, calling .Remove on each, like so: "For each c As Company in Me.Companies.... Me.Remove(c)... Next", or the equivalent in C#. Maybe that's what I should have done, but....

Being a bit lazy, I went for the rather quicker and dirtier one-line solution:
Me._Hobbies = New EntitySet(Of Hobby)

You can optionally specify those attach_xxxxx and detach_xxxxx functions, like this:
Me._Hobbies = New EntitySet(Of Hobby)(AddressOf Me.attach_Hobbies, AddressOf Me.detach_Hobbies)

If you know you're about to dispose of the object, or if you know you won't be calling "MyContact.Hobbies.Add(SomeNewHobby)", then you don't really need to worry about specifying the callbacks. I only needed to do that for one object, the rest never have things added/removed like that.

And again, because I sometimes want to keep those collections of objects in the EntitySets around (maybe I have a ComboBox bound to it or something), I use private vars to hold the original values, and assign them back again in .RestoreContext.

So, for the Company and Hobbies example, the total code in the partial "Contact" class might look like this:

Private CompanyEntity As Company
Private HobbyEntitySet As EntitySet(Of Hobby)

Private Sub Detach()
If Me._Company.HasLoadedOrAssignedValue() Then CompanyEntity = Me._Company.Entity
Me._Company.Entity = Nothing
HobbyEntitySet = Me._Hobbies
Me._Hobbies = New EntitySet(Of Hobby)
End Sub

Public Sub Save(ByVal User As String)
Using db As New MyDataContext
Me.Detach()
If Me.ContactID = 0 Then
Me.CreatedBy = User
db.Contacts.InsertOnSubmit(Me)
Else
db.Contacts.Attach(Me, True)
Me.recmodifiedBy = User
Me.recmodifiedDate = Date.Now
End If Try
db.SubmitChanges()
Catch e As ChangeConflictException
'handle concurrency conflict here, and use .Refresh and .SubmitChanges() as needed.
End Try
End Using
End Sub

Public Sub RestoreContext()
Me._Hobbies = HobbyEntitySet
Me._Company.Entity = CompanyEntity
HobbyEntitySet = Nothing
CompanyEntity = Nothing
End Sub

For now, this is working for me, although if I run into any wierdness, I'll post about that later. Many thanks to all the great Linq-to-SQL blogs I've read, which led me to ultimately implement this hack-like solution. Like I said - if you know of a more elegent solution, let me know, thanks! Also, apologies for any typos in the code above that I've missed...

So hopefully most of my posts won't be this techie, unless I get a lot of positive feedback (which seems unlikely!!). Do people prefer the pictures of cows maybe?

Sunday, March 22, 2009

Visiting the Chokchai Ranch & Farm

This isn't exactly (or, say, remotely) tech-related unless you count "lack of". I'm sending this from my phone, at the Chokchai Farm, a sizeable dairy and beef cattle farm 90 minuyes outside Bangkok. Watching a sort of mini-rodeo right now, and the photo is Yui milking her first cow.

I'll write a real post - on WPF and linq-to-sql in a day or so, plus some updates on x86 smartphone developments (hint: LG is building one based on "Moorestown").

Until then, enjoy the cow photo!

Monday, January 5, 2009

True Move Taking iPhone Reservations: Delivery January 16

Yes, the jesus-phone is finally, at long last, almost here.
True Move (a subsidiary of the behemoth that announced they were in talks w/Apple last November) is running TV ads on local Thai channels advertising the imminent arrival of the iPhone 3G.

Granted, as I've written a few posts about the sad state of 3G in the Kingdom - and what pitiful little 3G that AIS has going on is still more than True Move has. Either way - check out their page at: www.truemove.com/iphone for details. The model in the TV ad makes the iPhone 3G look even more beautiful and desirable than it already is. Or maybe that's just the model, ha ha.

Better Late Than Never Part 1: Christmas in Bangkok


Merry Christmas Bangkok!


Okay, so this is definitely a late blog entry, considering Christmas was two weeks ago. But hey, quality takes time, right?


With minimal commentary, here are some images I snapped with my ever-trusty HTC Diamond's cam. Phone cams are getting ever better, but the shutter speed is still a bit slow -hence the blurriness in some of the shots (and no flash either, doh!) To the left is the decorated Christmas tree in front of Central World Mall.



Inside the mall, some of Santa's elves were milling around looking bored!

Actually, there were a bunch of different school groups and choirs that were singing assorted holiday songs and carols. The mall had a baby-grand piano, which was also used by the four-piece orchestra (not kidding) playing music during the holidays on the ground floor.




The faux-snow-globe with two actual people (dressed as a rather-skinny Santa and his rather-cute elf!) inside was at another mall, "Esplanade", in an area called Ratchada. See the next photo for the elf in close-up!






And now you know why Santa is so jolly, ha ha ha (or ho! ho! ho!). I have so many holiday-season photos that I don't have room for here, that I'll eventually post them on the main Hacking Bangkok website.

Friday, December 12, 2008

HTC Touch HD Fondled In Bangkok!


Using her Jedi powers to make me want it...

HTC's new iPhone-sized phone, the Touch HD (for "High Definition") has finally shown up in stores in Bangkok. While not actually HD in the television-sense, it does boast a resolution of 800 x 480 on its monster 3.8" screen. That's both slightly larger than the iPhone's 3.5" screen, and 2.5 times the resolution! Yowza! While not quite as "pixel dense" as the Touch Diamond (which is 640 x 480 but only 2.8"), the Touch HD will let you watch a DVD rip in its full glory, with some horizontal space left over. It also uses the same 528 MHz ARM-based processor as the Touch Diamond and Touch Pro.

The camera (on the back) is 5 megapixels, a nice bump from the 3.2 MP of my Touch Diamond. On the other hand, I end up chopping the size of most of my cam-shots by 50% for the web anyway.


At this particular store, called "Touch", in Central World mall, the Touch HD is selling for the full retail price of 37,400 baht. Then again, they've got the Touch Diamond selling for 27,000 baht, and I only paid 25,500 baht for mine last June (and you can pick one up for 20,000 baht if you wander around MBK for a bit). And, just for comparison, they've got unlocked iPhone 3Gs for 37,000 baht - a premium of 4,000 baht over the haggling-shops of MBK. This store is in a high-end mall, so everything is more expensive than elsewhere.

Speaking of the Touch Diamond - this store also has the new white-backed Touch Diamond version, which looks a lot cooler than I thought it would. But it's only the back that's white - the front is still black (??). I don't get that - but maybe they'll sell just the white back cover for it, so I can fashionably accessorize my phone (NOT!).

Thursday, December 11, 2008

I Have 3G On My Diamond in Bangkok. Inside the Mall. Which Has WiFi Anway. Nevermind.


I'm not sure what it was that lured convinced me to buy a pre-paid AIS 3G SIM card, but much like the old guy on the right in this photo, I couldn't seem to help myself. In any case, after the leather-clad sales-girls let me use a "demo" sim card in my phone to make sure it worked - including a video-call made to another booth-girl on a different floor - I plunked down my 110 baht, plus 300 baht for 1.5 GB of data (over either EDGE or HSPA) for a pre-paid sim. AIS's 3G service runs on their 900 MHz spectrum, so definitely check with them to make sure your handset will work before signing up (I can confirm that HTC Diamonds do work!).


AIS's prepaid brand is 1-2-call, and the sim-package was sporting a very happy-looking frog wearing a crown. No, I have no idea. Based on the frog's smile, he never leaves Central World though (more on that in a sec). After slipping the sim into my Touch Diamond, and booting up, WinMo helpfully told me that it needed to configure my phone for AIS (I normally use DTAC), after which (this IS Windows) it had to reboot. I had to manually change the "band" selection from "auto" to "WCDMA" for some reason - according to the AIS guy, their mini-cell-tower's software needs to be upgraded.



In keeping with the green animal motif, the plastic card has a picture of a green mouse riding a cheese-mobile. The so-called "Freedom sim" works on AIS's regular GSM network, with all its EDGE mediocrity, wherever 3G isn't up and running yet. That would be practically everywhere. The only 3G coverage is provided by some sort of pico-cells, or mini-cells, in Central World Mall, Siam Paragon (another giant mall), and MBK (the grand-daddy of Bangkok malls), in addition to their original test network in Chiang Mai.

Oh - and the new airport (Suvarnabhumi), which is once again running after recently being the subject of a sit-in by protestors.

The stupid thing about the current state of AIS's mini-cell locations is that all of them have WiFi coverage anyway - True Move offers WiFi (not free) in all of these places, which cost me 250 baht/month on a promotion. I wrote about True recently when checking out a new store/cafe they opened. An AIS employee assured me, though, that the first "real" cell-towers will be upgraded to 3G starting next month, so I'll post back when there's any new info. Until then, though, if your phone has WiFi, you're better off with that.

The low-down on pricing is this: Video calls are 1 baht/minute. Not that therei s anybody to call, except the AIS demo-booth girls. Whether you sign up for a normal post-paid account, or get a pre-paid sim, you need to pick a data plan (since it's a baht per MB if you don't!). All the below are for monthly usage:
  • 100 baht for 500 MB
  • 300 baht for 1.5 GB
  • 500 baht for 2.5 GB
  • 900 baht for 15 GB
  • 1,500 baht for 30 GB
If you're sucking down 30 GB per month, you clearly have a bittorrent problem and should be running that on your DSL at home, but otherwise the prices are not bad! 500 baht (about $14) for 2.5 GB of data is enough for a lot of web-surfing, youtubing, emails and general syncing to Exchange/Zimbra/Gmail or whatever. Google maps is fabulous over 3G, as I discovered in Korea in September. I did a couple of speed-tests using DslReport's "iPhone browser Speed and Latency Test". Given that I'm in Thailand, and the server is likely in the U.S., I was pretty happy with the 491 Kbps and 467 Kbps results in my two tries. It's no 4G WiMax, but it beats EDGE.

So. I don't really want to change phone numbers (no mobile-number-portability-act here!), so sometime in February or March, I'll see what DTAC is up to - if there's less than a 90-day lag before they roll out their service, I'll wait. Otherwise, I'll be back to see the AIS girls!*

*Note - the girl who helped me with the demo admitted she was just hired part-time for this promotion. I asked her if she uses AIS, and she sheepishly admitted that no, she's using DTAC too. LOL.

Friday, December 5, 2008

Bangkok's 7-Story Spiral Stairs Using Escalators (take THAT Gizmodo!)


I read Gizmodo pretty often obsessively, and about a week ago they had a brief story (with photos) of a building in Taipei. The 10-story faux "spiral" escalators in Taiwan apparently impressed the Gizmodo editors, so I thought I'd invite them to come check out Central World Plaza shopping mall in Bangkok.

The same basic effect - albeit seven stories instead of 10 - is at the heart of the Bangkok mall's architecture also, and has been for... um... I'm gonna say three years about. Ever since the mega-refurbishment that tripled the size of the already large shopping mecca. So, these are all some shots (taken with my phone-cam, again, sorry!) of my local architecural wonder.

Since it's Christmas time, and even Thailand is not immune from the ever-present Christmas trees, mind-numbing songs about Santa and snow, you can see a gi-normous (fake) tree in the center of the circular (tubular?) space in the middle of the spiral.

I'll post some pics in my next entry of more of Bangkok's wonderfully tacky holiday decorations. Even though I have to enter the mall to do it >>shudder<<.

View from the top - and yes, I should use a real camera for these shots. But a shout-out to Gizmodo for giving me an idea of how to show off some of Thailand's architectural/technological prowess!

Island Wedding - Koh Samui


The weekend before the PAD protestors shut down the two major airports in Bangkok (which are now re-opened, yeah!!!), I flew down to a friend's wedding in Koh Samui. Me being me, I forgot to take a camera along, but luckily the cam in my phone (Touch Diamond) is not too bad in daylight - a "touch" blurry (okay, that was horrible) is all. The ceremony was partly inside, and partly outside (the rain miraculously stopped for the duration of the wedding!)

My friend (Rie) is actually not Thai, she's Japanese/Chinese, and lives in London with her new husband, Tim. So they and their families flew from all over the globe to have the wedding in Samui. Here's a photo of them at the reception, along with Rie's friend Xian (or Chien?), who must be the world's cutest bridesmaid):

And like every good reception, after the newlyweds ride off in a decorated... um.... elephant. Ha! You don't see this at your average wedding:

One of the things that I really love about Thailand is that you can go from being in your high-rise condo watching "Heroes" one day, to watching your newly-married friends trying to ride an elephant on the beach the next. Seriously, this is a great place to live!