Archive for 2010

Reading IMEI on Windows Phone 7 Devices (Samsung Only)

This is a short post showing how to read IMEI (and other stuff if you want to walk alone over the code) on Samsung devices running Windows Phone 7.

This simple code uses the Samsung native DLLs for Windows Phone 7, so they (surely?) won’t work on LG or HTC devices.


If you are new to WP7 hacking, you may need some research on how to get started executing native code calls on Windows Phone 7, here are the requirements in a quick recap:

  • <Capability Name="ID_CAP_INTEROPSERVICES" /> inside the <Capabilities> tag in the WMAppManifest.xml file.
  • a WPInteropManifest.xml file in the root of your solution containing:
       1: <?xml version="1.0" encoding="UTF-8"?>
       2: <Interop>
       3: </Interop>

  • The Samsung native DLLs, a hint for where to find them? Hack the Marketplace, or just download them from here :D
  • A reference to Microsoft.Phone.InteropServices.dll, you can grab it from here and then add it to the Windows Phone 7 SDK.
  • In case you forgot to strong name the DLL above, here’s the last step you need (the Visual Studio command prompt must be started with admin rights)

       1: SN -Vr "PATH-TO-DLL\Microsoft.Phone.InteropServices.dll"

Code :

After setting up everything, you can read the IMEI as following:

   1: public partial class MainPage : PhoneApplicationPage
   2: {
   3:     // Constructor
   4:     public MainPage()
   5:     {
   6:         InitializeComponent();
   7:         this.Loaded += new RoutedEventHandler(MainPage_Loaded);
   8:     }
  10:     void MainPage_Loaded(object sender, RoutedEventArgs e)
  11:     {
  13:         ComBridge.RegisterComDll("COMRilClient.dll", new Guid("A18F6B1A-924E-4787-AA82-19F98B49CF5D"));
  14:         COSecRilControl cls = new COSecRilControl();
  15:         ISecRilControl intrfc = (ISecRilControl)cls;
  18:         //READING THE IMEI
  19:         string imei;
  20:         intrfc.GetIMEI(out imei);
  21:     }
  22: }
  24: [ComImport, Guid("A18F6B1A-924E-4787-AA82-19F98B49CF5D"), ClassInterface(ClassInterfaceType.None)]
  25: public class COSecRilControl
  26: {
  27: }
  29: [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("A5857C17-04C2-49c5-A460-05A21660588F")]
  30: public interface ISecRilControl
  31: {
  32:     void Init();
  33:     void Deinit();
  34:     void Run(int mode);
  35:     void End();
  36:     void SetInput(int type);
  37:     void Back();
  38:     void GetDispInfo(out uint svcMode, [MarshalAs(UnmanagedType.SafeArray)] out byte[] info);
  39:     void GetEvent(int type, out int pEvent);
  40:     void SetEventCOM(string name);
  41:     void LaunchExe(string exe, string arg);
  42:     void DoHiddenKey(int hashcode);
  43:     void GetLockingStatus(out uint m_dwLockFacility, [MarshalAs(UnmanagedType.SafeArray)] out byte[] pPasswd);
  44:     void SetLockingStatus(out uint m_dwLockFacility, string data, out uint m_dwStatus, [MarshalAs(UnmanagedType.SafeArray)] out byte[] result);
  45:     void GetIMSI(out string IMSI);
  46:     void GetIMEI(out string IMEI);
  47:     void DoHiddenKeyWithResult(int hashcode, out string jobName);
  48:     void WaitNamedEvent(int timeout, string name);
  49:     void RegSetDWORD(uint HKEY, string pwszPath, string valueName, uint value);
  50:     void RegGetDWORD(uint HKEY, string pwszPath, string valueName, out uint value);
  51:     void RegSetString(uint HKEY, string pwszPath, string valueName, string value);
  52:     void RegGetString(uint HKEY, string pwszPath, string valueName, out string value);
  53:     void ReadTextFile(string path, out string result);
  54: }

This is a great read about Windows Phone 7 hacking [link].

Posted in , , |

Windows Phone 7 hacks, all the diagnosis codes you need, Part 2

As promised in part 1, here is the rest of the Samsung diagnosis codes for Windows Phone 7. If you don’t know how to use them, refer to part 1 for more information.

*#05# Main tests : Camera, sensors, proximity, battery, acceleration, light …
*#9908# GPRS manager/Gumi test Bed/ Suwon2G / Suwon3G
*#9909# -
*#9911# Debug mode for chg/bat
*#9920# -
*#32489# Ciphering control
*#32589# Camera FW update
*#94765# Disable AutoSim settings
*#99732# The (Java) Build script
*#99785# PVK Key
*#232331# Bluetooth RF Test Mode
*#232332# Bluetooth Audio
*#232333# Bluetooth Search Test
*#232337# Bluetooth Mac
*#232338# WLAN Mac
*#232339# WLAN Test – Change channel – Datarange etc..
*#737425# -
*#914789# Apps launcher / List of EXE files
*#997856# PVK File name
*#1472365# Black Swan GPS location services
*#4238378# GCF / GSM
*#7465625# Lock status/ network lock / Subset, SP lock/ CPLOCK
20652609 Disable Bluetooth log
20652619 Enable Bluetooth log (you can copy the file use wpget.exe)
20652629 SSP debug on
20652639 SSP debug off
*#22558463# Call time logs
35190718 Erasing IMEI (seriously?)
35190728 Bluetooth stuff
61709124 =
61709134 Bluetooth log
61709144 SSP
61709154 SSP
71671835 Factory Reset (careful while testing this one)
76247233 Factory Reset
76247243 Factory Reset
*#99867247# -

Posted in , |

Windows Phone 7 hacks, all the diagnosis codes you need, Part 1

Lately I have been working on some hacks for the Windows Phone 7, and was interested especially in the Samsung diagnosis app that uses different codes to debug their devices.
I’ve succeeded to extract more than 60 codes that I will show in this post and the next one, and their basic functionality/use in the diagnosis app.
The following codes were tested on a real Samsung Omnia 7, I’ll be happy if you can confirm their use on other devices as well.
To enter the diagnosis app, type ##634# and press call, the application should now be placed on the list of apps.

*#80# Touch Debug stuff
*#526# Wifi factory test
*#745# -
*#780# SR test
*#1111# FTA SW version
*#1234# WIFI / Bluetooth mac
*#1575# Gps test mode
*#1793# Micro usb / sync / modem / tethering
*#2222# FTA HW version
*#2263# WCDMA, GSM band
*#2470# Camera FWUpdate
*#2580# Integrity control
*#2663# Touch Screen Version
*#7284# Micro USB Test
*#7298# GPRS settings, auto pwr on/off
*#7353# Self Diagnosis tool
*#7450# Error report Off
*#7451# Error report on
*#9090# USB Diag / DBG msg on/off
*#9900# Debug Dump
*#9906# Debug Dump + Ril log
*#770# Vphone tests 0
*#771# =
*#772# =
*#773# =
*#774# =
*#775# =
*#776# =
*#777# =
*#778# =
*#779# Vphone tests 9

Posted in |

Windows Phone 7: why you should obfuscate your code

A while back Microsoft sent some warning emails to the registered Windows Phone 7 developers about the threats their apps might face once published on the Marketplace. The apps on the Marketplace are available for download without any authentication required. What you need to get an app is simply the direct link to the .xap file, something of the form, which contains the DLL that can be disassembled very easily with Reflector for example. More info here.

Here’s an excerpt from the email :

It is important to note that because of the leak containment steps Microsoft takes applications obtained outside of Marketplace will not run on consumer retail devices. Modified files would only run on a limited number of “unlocked” phones, such as those that have been registered by Marketplace developers on App Hub….

One powerful tool for protecting your apps and games is code obfuscation, which is a long standing best practice for managed code. Obfuscation is available tools like the Dotfuscator product recently announced for Windows Phone 7 applications. Microsoft has partnered with PreEmptive Solutions to make this tool, as well as a robust application analytics solution, available to Windows Phone developers for free through March 31st, 2011.

Right now, it seems that the only option to protect your app, is to use a code obfuscator, since anyone is allowed to download it from Microsoft servers without any restriction, whether they are using a real Windows Phone 7 or they are sniffing the traffic made by the Zune software (yes, I’m not going to tell you how to do it! you need to figure it out yourself).

For demonstration purposes, here is what Reflector shows when applied on an obfuscated DLL and on a non obfuscated one:


1. Obfuscated


2. Clear

As you can see, on the obfuscated version, Reflector shows either a message saying that the code was obfuscated and it cannot be disassembled, or a bunch of unreadable variable names with a lot of “goto” instructions.

On the other hand, the non obfuscated version is disassembled to (almost) the original source code, only the comments are missing.

Last word, if you are developing anything for Windows Phone 7, do not forget to obfuscate your code before publishing your app on the market.

Posted in , , |

Windows Phone 7 Hacks : the start…

So Windows Phone 7 haven’t been out for a long time and we have already started to see some hacks from around the web. In this post series, I’ll list the hacks and tips that I test myself on my Samsung Omnia 7. As a result I won’t be held responsible for you screwing anything up with your machine.

Diagnosis mode:

Diagnosis mode on Windows Phone 7 seems to be a way WP7 creators used to test the devices, fortunately, it is also used to enable and disable features on the phone, here is how to activate it:

  • type ##634# and press call, the diagnosis app should now be added to your applications
  • there are a lot of diagnosis codes that you can try, for instance :
    • *#03# will get you to the SMDInfo
    • *#05# will give you a very rich interface for testing capabilities, including Vibration, keys, Camera, TSP, Acceleration, Battery, Proximity, Loopback and Light
    • *#1234# will show a lot of information including the Wifi Mac address and the Bluetooth Mac address
    • *#06# shows the IMEI number
    • *#2222# some debugging stuff that I couldn’t figure out.


Enable tethering mode :

By going to the Diagnosis mode showed in the previous section, and typing *#7284# you will get the choice to change the connection to the PC from Zune sync, to Modem Tethered Call or Modem Usb Diag, more coverage about tethering here.

You need to note that using the device as a modem will enable you to connect your PC to internet using the phone’s network, I couldn’t reach this in France, since the dial-p numbers for SFR don’t seem to work for me (*#9# or *#9***1#).

Also, on Windows 7 x64, the phone won’t be detected, I suspect that the drivers are not signed and Windows reject them, hence you need to try the above method on a 32bit Windows.

Here is a screenshot for Samsung Omnia 7 installed as a modem on a Vista x86.



SD-Cards, are they seriously dead once put on a WP7 phone?

There have been a lot of talking about this one, and how magically Windows Phone 7 locks sd-cards so they become unreadable and cannot be formatted on any other machine.

It turns out that Symbian devices can actually format WP7 sd-cards, so if you got a nokia, you are clear, all your sd-cards are useful again, more on the topic here.


WP7 already rooted, jailbreaked?

It seems it will happen soon, some developers out there are claiming access to the wp7 filesystem, let’s hope it will happen soon, more here.

Windows Phone 7 filesystem access


Source code of apps on the Marketplace:

A very strange but true fact about wp7 and the Zune software, is that, when you use Zune to download apps from the Marketplace, you can sniff the traffic sent and returned to Zune to intercept the url of the application xap (a zip file containing binaries and resources of the app).

Once, this xap is downloaded (yeah, MS servers just give you the app happily without any authentication or anything), the DLLs could be disassembled to retrieve the original source code, using a tool such as .NET Reflector for example.

This is a sample of a url of an app from the Marketplace****id-here****/CurrentBinary.xap

More details will be discussed about this specific topic, from how to sniff packets till full disassembly (it is legal isn’t it?)


Mount a wp7 device as a USB drive:

Today, a small hack showed that wp7 can be mounted as a normal usb drive, but unfortunately, you can only copy files *from* wp7, I tried to copy files to wp7 including music and pictures, but it didn’t work, you can’t also create new directories neither.

Well, now it seems I am able to copy files into the phone :D. No, no, it is back, I cannot copy files into the phone, need more investigation it seems.

For how to make wp7 behaves as a USB drive, here is how

  • Open regedit, and locate HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB then search for ZuneDriver
  • Change ShowInShell from 0 to 1
  • Change PortableDeviceNameSpaceExcludeFromShell from 1 to 0
  • Change EnableLegacySupport from 0 to 1

Voila! just close that cursed Zune thing and the phone will show up as a USB driver as showed in the following pictures.

If you need assistance with pictures (!!) here’s a detailed post about it.


Posted in , |

Windows Phone 7 : hands on (Samsung Omnia 7)

It has been almost a week I am trying a new device, the Samsung Omnia 7, which runs the new Microsoft’s OS Windows Phone 7. It took me a lot of time to get one after the very chaotic launch of the new OS in France, but well, finally I’ve got one.


In this post, and the ones that will follow, I’ll describe my experience with the new OS (the device too), so if you are looking for a technical review of the OS, here’s an exhaustive review from ars technica.

The OS

Talking about the OS itself, there are things I love about it, things I like, and stuff I hated already. The look ‘n’ feel of the Windows Phone 7 UI is great, I like so much the minimalistic design, no round boxes, no shadows etc, just different sizes of text to differentiate the title of a page from its content for example.

DSC00520          DSC00522

What I also like about Windows Phone 7 is the fact that you can use several services other than Windows Live for syncing contacts, calendars and emails. Gmail integrate pretty well, and if you have been an Android user like me, all your contacts can be imported just as easy as your Live ID contacts.

The camera is awesome, when taking a picture, you just slide on the left side and you get the last pic you took, no menus to go through, very intuitive and simple.

Animations also are pleasant, they don’t disturb your work, and are as fast as they should be to give a great user experience.

Internet explorer is really fast and smooth with Bing search and voice commands, it is a pretty enjoyable experiment.

Today, I had the chance to try the gps on the device and how fast and accurate it is, I was completely surprise, it is perfect, pretty fast, so responsive and accurate while used with Bing Maps.

What I don’t like about Windows Phone 7 is mainly the features that lacks the OS and which have been discussed in (almost) every website reviewed the OS.

You cannot change the ringtone (what a big deal right ;D ).

More seriously, there is no copy past!! I totally hate the way Microsoft is playing Apple with its customers! The whole world knows that copy/paste is not that hard to implement on any OS, and hence MS has made the choice not to include it and not because it is a feature that they will *work* on on the future!

While they have already promised for some updates by early 2011, playing Apple with Windows Phone 7 is “disgusting”, Windows Phone users are not iPhone users, and even if MS wants to play the game, does that mean it has to copy the iPhone 1 and let its users 4 years late compared to the other Mobile Operating Systems??

There is no way to take screenshots on the device!! how I am supposed to do reviews on the OS and apps then?

Also, there is no sharing option for webpages, videos or even pictures and photos on social networks! you take a pic, you close the Photos app, you open Twitter app, then join a pic to share it! For a webpage it is simply impossible to share its URL, since there is no freaking copy/paste.

The Filesystem is completely unknown for users (developers), there is an Adobe Acrobat reader app, but guess how you open pdf files?? whether you download them from the web and they get saved somewhere, or you download them from your email! there is no way to just put your pdfs on the phone to read them later.

Multitasking, please don’t get me to start on this one!

You have no control over the browsers settings, you can’t disable Javascript for example. You can’t install arbitrary certificates on the device and you can’t setup proxies, if you have come from the Android world, that will be a hell for you.

The Device

Samsung Omnia 7 rocks, with its 4inch AMOLED screen that puts the iPhone’s to shame (according to my biased opinion ^_^), the touch is just another great part of the device as well. With a 5 MP camera, HD video recording and 1GHz processor, I simply adore it.


For a complete review about the device, take a look here.

However, I find the search’s button (if it can be called so) position a little irritating, while holding the device in landscape mode, usually, your finger just press it unwillingly, since it is almost at the edge of the corner, but with time, you get used to it.

But! the earbuds are a complete failure, the quality of sound is just good, but the way they have to be used is really irritating, first, when you put them you can hear nothing around you, literally nothing, you can get hit by a car without even noticing (hearing) it approaching.

If you try to lower the volume on the earbuds to try to hear any extern voices, you will get an annoying sounds of the earbuds themselves when they touch your clothes, which makes them useless in the two cases.

DSC00501           DSC00506

Posted in , |

Encode Javascript with a Japanese style emoticons (^_^)

Remember that JJencode method that inserts $ everywhere and makes the code absolutely unreadable from the last post? well, if you liked it, then this one is going to be a real surprise for you.

The same guy who created the JJencode methode, has created also some weird method to encode Javascript, a Japenese emoticons encoded Javascript (^_^), no seriously, here is how your code will look like after encoding (enjoy :D imagine that in a real webpage):

((o^_^o) +(o^_^o))+ ((o^_^o) +(o^_^o))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (゚ー゚)+ (゚Θ゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) - (゚Θ゚))+ (o^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (゚ー゚)+ (o^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ ((o^_^o) - (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ (゚Θ゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ (c^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ (゚ー゚)+ (゚Д゚)[゚ε゚]+(゚ー゚)+ ((o^_^o) - (゚Θ゚))+ (゚Д゚)[゚ε゚]+((゚ー゚) + (゚Θ゚))+ (゚Θ゚)+ (゚Д゚)[゚o゚]) (゚Θ゚)) ('_');

Pretty convincing right, especially the ('_')  and (゚ー゚) emoticons, and yeah, that's real javascript there.

To get your scripts encoded, just head to Yosuke HASEGAW's webpage here, and as usual, to know what is going on behind an encoded script like that, here's the magical part :
document.write("<textarea>"+ encoded_code +"</textarea>");

This guy absolutely rocks, I mean, do you see how this Javascript looks like (^_^).

Posted in |

jjencode, a new way to obfuscate Javascript

Extraexploit blog reported lately a new wave of infected websites (using joomla CMS) with Javascript code that looks like this :

$._$+", \\"+$.__$+$.__$+$._$_+$.$_$_+"\\"+$.__$+$.$$_+$.$$_+$.$_$_

It turns out that this new method of obfuscation is actually not totally new, the method is called jjencode and it is available on

If you ever run onto an obfuscated code like that one, you can use the above website to decode it, (careful with the eval part though), and if you wanted the plain Javascript code you can wrap the encoded code within the following call:
document.write("<textarea>"+ encoded_code +"</textarea>");

Posted in , |

Ajax Calls on ASP.NET UserControls

You cannot make Ajax calls on ASP.NET user controls can you? So what’s the solution? give up? absolutely not.

While believing arrogantly that I am a genius or that C# is the most beautiful piece of software ever created (and will be), ideas had been floating in my head non-stop, and most of the problems I faced just got solved, of course with nasty non advised tricks :-), keep reading.

I needed to call a web method on a usercontrol, and all I wanted was the result of the processing returned by this method, so I tried the ASP.NET AJAX PageMethods but the result was PageMethods is not defined!

Cool, if we need the result of the web method in our JavaScript, we can profit of the ASP.NET server controls and the UpdatePanel for Ajax calls, here are the steps:

1. Inserting an UpdatePanel on you usercontrol, and within it, inserting a Label and a button or a timer (or whatever way you want to callback you usercontrol)

  1. <asp:UpdatePanel ID="UpdatePanel1" runat="server">
  2.     <ContentTemplate>
  3.         <asp:Timer ID="Timer1" runat="server" Interval="4000" ontick="Timer1_Tick">
  4.         </asp:Timer>
  5.         <br />
  6.         <asp:Label ID="Label1" runat="server" Text="Label" CssClass="ResultPlaceHolder"></asp:Label>
  7.     </ContentTemplate>
  8. </asp:UpdatePanel>

The label above will be a placeholder of our Ajax call result, it has a class name ResultPlaceHolder so that it will be found easier using jQuery, as you should know, ids and names on server controls get messed up in client side with ASP.NET.

2. Setting up the result from within the Timer tick method (or the click method of your button)

  1. protected void Timer1_Tick(object sender, EventArgs e)
  2. {
  3.     Label1.Text += "a: ";
  4.     return;
  5. }

3. Exploiting these fresh results in your JavaScript, the best way would be by setting an interval for a function that checks the results in the placeholder every given moments.

  1. <script src="http://my-super-slow-uncool-laptop/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>
  3. <script>
  4.     $(document).ready(function () {
  5.         $("#button1").click(function () {
  6.                 alert($(".ResultPlaceHolder").text());
  7.         });
  8.     });
  10.    var i = 1;
  11.    function updateResult() {
  13.        i++;
  14.        if (i < 10)
  15.            $("#show").html($("#show").html() + "<br/>" + $(".ResultPlaceHolder").text());
  16.        else {
  17.            $("#show").html($(".ResultPlaceHolder").text());
  18.            i = 1;
  19.        }
  20.    }
  22.    setInterval(updateResult, 1000);
  23. </script>
  24. <p>
  25.     <input type="button" value="Ajax it" id="button1"/>
  26.     <div id="show"/>
  27. </p>

And voila, this is a nasty nonadviced method to do Ajax calls to webcontrols’ methods, a la “vite fait”. Enjoy.

How to select distinct values based on a specific predicate using Linq Disctinct method

Selecting distinct values in a Linq query while working on non trivial data need more than a simple call to the extension method Distinct().

Say I have the following xml data, and I want to select only distinct data elements based on their date attribute.

  2.     <HISTORY>
  3.         <data date="19/01/10 14:34:00" >1963</data>
  4.         <data date="19/01/10 13:34:00" >1960</data>
  5.         <data date="19/01/10 14:34:00" >1960</data>
  6.         <data date="17/01/10 21:34:00" >1911</data>
  7.         <data date="17/01/10 21:34:00" >1911</data>
  8.         <data date="17/01/10 11:34:00" >1911</data>
  9.         <data date="17/01/10 18:34:00" >1911</data>
  10.         <data date="17/01/10 17:34:00" >1911</data>
  11.     </HISTORY>
  12. </SOMETING>

As you can see there are some duplicates regarding the date attribute, the following Linq query will return all the data elements as an IEnumerable of HistoryDataElement.

  1. class HistoryDataElement
  2. {
  3.     public string Date { get; set; }
  4.     public int Value { get; set; }
  5. }
  7. XDocument doc = XDocument.Parse(xml);
  9. var dataElements = (from data in doc.Descendants("data")
  10.                                 select new HistoryDataElement
  11.                                 {
  12.                                     Date = data.Attribute("date").Value,
  13.                                     Value = int.Parse(data.Value)
  14.                                 });

If we want distinct results based on the date attribute for example, we have to create a comparison class that implements the interface IEqualityComparer<T>.

Here is a very simple implementation:

  1. class DataExtractorElementComparer : IEqualityComparer<HistoryDataElement>
  2. {
  4.     public bool Equals(HistoryDataElement x, HistoryDataElement y)
  5.     {
  6.         return x.Date == y.Date;
  7.     }
  9.     public int GetHashCode(HistoryDataElement obj)
  10.     {
  11.         return obj.Date.GetHashCode();
  12.     }
  13. }

With this class in place, we can just pass a new instance of this class to the Distinct method to get the desired results :

  1. var dataElements = (from data in doc.Descendants("data")
  2.                                 select new HistoryDataElement
  3.                                 {
  4.                                     Date = data.Attribute("date").Value,
  5.                                     Value = int.Parse(data.Value)
  6.                                 }).Distinct(new DataExtractorElementComparer());

Notice that this way, you are eliminating all the duplicates that have the same property date, so only the first element of the matching elements is retrieved even If the other properties differ, this is cited by code in the Equals method of the IEqualityComparer<T>.

Multilingual Website Interface on the Fly With jQuery

Applying a multilingual interface on your webpages and allowing the change at the client side without the need for a server postback has never been easier using the technique I’ll describe in this post.
While developing Bloginto, I came across the situation of implementing an English-Arabic-French interface with the possibility to change the language on the fly (on the client side), so I used a trick so close to culture resource files in the .NET.
My first priority was to write the minimum of code using jQuery, and as you will see, it is *really* minimal.

1. Preparing the resources for the language

We will encapsulate the language resources with Javascript arrays, here is an example:
  1. function getLanguageResources() {
  2.     var fr = new Array(); var en = new Array();
  4.     fr['settings'] = "paramètres"; en['settings'] = "settings";
  5.     fr['default_feed'] = "Flux par défaut"; en['default_feed'] = "Default feed";
  6.     fr['hidden'] = "Masquer"; en['hidden'] = " Hidden";
  7.     fr['save_settings'] = "Enregistrer les paramètres"; en['save_settings'] = "Save settings";
  9.     var resources = new Array();
  10.     resources['fr'] = fr;
  11.     resources['en'] = en;
  13.     return resources;
  14. }
The getLanguageResources function returns an array that contains an associative key/value arrays of the desirable languages, notice how the same key is used for the different translations.

2. Preparing the HTML markup

We need to put placeholders for the multilingual text to show in the markup, I choose a <span> tag here, but obviously you can use whatever elements fits best. The trick is to have all these multilingual spans use the same name attribute (this is not a necessity neither, you can use whatever attribute you wish), and have them use another attribute, for example caption which value is the key of the text to show in the resource arrays.
We will also add two buttons to test the language change, here is the final markup :
  1. <input type="radio" id="radioEnglish" name="radio-language" value="en"/><label for="radioEnglish">English</label>
  2. <input type="radio" id="radioFrench" name="radio-language" value="fr"/><label for="radioFrench">Français</label><br/>
  4. Text for : settings : <b><span name="lbl" caption="settings"></span></b><br/>
  5. Text for : default_feed : <b><span name="lbl" caption="default_feed"></span></b><br/>
  6. Text for : hidden : <b><span name="lbl" caption="hidden"></span></b><br/>
  7. Text for : save_settings : <b><span name="lbl" caption="save_settings"></span></b><br/>
Notice how the radio buttons for changing the language have values which are the keys of the resource language (the arrays).

3. jQuery magic

Now we will apply some jQuery code to associate the spans with their corresponding text from the language selected by the radio buttons
  1. function changeLanguage(lang) {
  2.     var langResources = getLanguageResources()[lang];
  4.     $("span[name='lbl']").each(function (i, elt) {
  5.         $(elt).text(langResources[$(elt).attr("caption")]);
  6.     });
  7. }
  9. $(document).ready(function () {
  10.     $("input[name='radio-language']").click(function () {
  11.         changeLanguage($(this).val());
  12.     });
  13. });
Here we attach a click event to the radio buttons, and we simply call the function changeLanguage whenever a button is clicked, we pass the value of the “value” attribute of that button to the function which represents the specified language (‘fr’ or ‘en’)
The changeLanguage function loads the corresponding array of the languages from the getLanguageResources function, then iterate through every element that has the attribute namelbl”, and change its text to the value in the resource language array which key is the caption of that specified element (span), pretty simple!
As you can see, all the magic is done with 2 lines of jQuery, if you guessed that the “.attr()” method will do the same instead of “.each()” then you’ve guessed wrong, attr() applies only to the first element in the selection set. See .attr() specification here.

4. Demo

Her is a working demo

Posted in , |

Swedish Greys - a WordPress theme from Nordic Themepark. Converted by