Atomically increment a limited value in MySQL and PHP

Sometimes you need to acquire a limited resource in an atomically, concurrent way. This is what semaphores are for. But when this resource is in a MySQL row, apparently there is no straightforward way of doing it.

In my case, I had a row with two fields used to limit maximum resource usage: ‘used’ and ‘limit’, both integer fields. Let’s complete it with an ‘id’, and then all the remaining information you need. To give you a more concrete example, I used this to limit the number of times you could possibly use a discount coupon.

So, while investigating the best way to do it, I considered the following options:

  • Using table locking: the problem is that, if you use a MyISAM table, this locking is done at a table level. Also, you statement gets more complicated, because you have to lock, modify and unlock.
  • Using transactions: this is not supported by MyISAM engine, and in my case I was adding this to an already existing table (not created by me, BTW…).

Finally, I came with the following method, which I think is pretty clear, clean and compatible. First of all, the query uses an atomically UPDATE statement, like the one you can found in this Stack Overflow question: Is incrementing a field in MySQL atomic?

$query = "UPDATE coupon SET used = used + 1 WHERE ID_coupon='" . $this->id . "' AND used < limit";

Now, notice the WHERE clause. It selects the row by two criteria: row id (as usual) and the condition that the 'used' field is less than the 'limit' field. So, what does mean? If the number of used coupons is less than the limit, the condition will be fulfilled and the row will be found by the database engine and updated, but if it is not it won't be found, thus the update will not happen, effectively limiting the 'used' value.

Finally, the other reason of doing this way is that MySQL returns the number of rows affected by the query. Usually, this will be 1, but if we've already reached the limit the condition will not be fulfilled and the number of affected rows will be 0. So, in PHP we can check this condition with something like this (in my case I was using PEAR DB, but you can find the equivalent statement to "affectedRows()" for MySQLi or PDO):

$res=@$dbhm->query($query);
// Error handling omitted for brevity
$rows = $dbhm->affectedRows();
if ($rows > 0) {
  // We where able to use one coupon :D
  return true;
} else {
  // All the coupons have already been used :(
  return false;
}

Notice that probably this technique works on other DBs, and also can be applied to other languages than PHP.

Switching to Firefox again

The other day I stumbled upon the article Windows Timer Resolution: Megawatts Wasted and to make long story short, I ran powercfg -energy duration 5 on my system and found that Chrome, Spotify and Naver’s Line client for Windows were making my system to increase timer resolution to 1 ms, wasting energy and making my laptop run warmer than expected.

So I’ll be switching back to Firefox after quite a while using Chrome as my main browser, at least for regular browsing. Let’s hope Google fixes this soon.

Also, I’ve switched to Windows Store App version of Line client (my system runs Windows 8.1), and I’m considering what to do with Spotify.

UPDATE: maybe I’ve switched browsers too fast: now I’m seeing Firefox also increasing timer resolution to 1 ms! Possible causes:

  • Plugins (Flash, maybe?)
  • Google Mail
  • donno…

I’ll keep you posted.

Disabling right click and swipe on Windows Store Apps without using code-behind

A month ago I was working on a Windows Store project and I needed to disable right click and swipe for some grid controls. Of course, the property to disable/enable swipe is well known: IsSwipeEnabled. Just put a false there and you’re ready to go! But I could not find an equivalent property to disable right-click, and IsSwipeEnabled does exactly what it says: disable swipe touch gesture, but has no effect on right-click (which you may expect it will, because right-click is the equivalent manipulation using mouse).

Anyway, I found that the only way to disable right-click was to handle the right-click event, using code. So, my first thought was using code behind, and add an event handler and tell the remaining handlers that I handled the event already. So an event handler like this one should do it:

private static void RightClickEnabledProperty_RightTapped(object sender, Windows.UI.Xaml.Input.RightTappedRoutedEventArgs e)
{
    e.Handled = true;
}

But then, I thought I rather had a property implemented to be able to use it whenever I wanted without having to add more code behind to each XAML. So, here is the implementation for this property:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;

namespace App.Properties
{
    public class RightClickEnabledProperty
    {
        public static readonly DependencyProperty IsRightClickEnabledProperty =
            DependencyProperty.RegisterAttached("IsRightClickEnabled", typeof(bool), typeof(RightClickEnabledProperty),
                                                new PropertyMetadata(true, IsRightClickEnabledPropertyChanged));


        public static void SetIsRightClickEnabled(DependencyObject attached, bool value)
        {
            attached.SetValue(IsRightClickEnabledProperty, value);
        }


        public static bool GetIsRightClickEnabled(DependencyObject attached)
        {
            return (bool)attached.GetValue(IsRightClickEnabledProperty);
        }


        private static void IsRightClickEnabledPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            bool? value = e.NewValue as bool?;
            if (!value.HasValue || value.Value)
                (d as UIElement).RightTapped -= RightClickEnabledProperty_RightTapped;
            else
                (d as UIElement).RightTapped += RightClickEnabledProperty_RightTapped;
        }

        private static void RightClickEnabledProperty_RightTapped(object sender, Windows.UI.Xaml.Input.RightTappedRoutedEventArgs e)
        {
            UIElement control = sender as UIElement;
            if (control == null)
                return;

            if (!GetIsRightClickEnabled(control))
                e.Handled = true;
        }

    }
}

The downside of this is that the property must be defined in the item itself (usually in the top-level control or container inside the ItemTemplate), while the IsSwipeEnabled property is defined in the Grid or ListView itself.

See an example (remember to define the namespace in the root node of the XAML, like: xmlns:properties="using:App.Properties"):

<ListView
    ItemsSource="{Binding ElementList}"
    SelectedItem="{Binding SelectedElement, Mode=TwoWay}"
    IsSwipeEnabled="False"
    SelectionMode="Single">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextBlock
                Text="{Binding ElementName}"
                properties:RightClickEnabledProperty.IsRightClickEnabled="False"/>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Hope this helps to keep your XAML a little more clean, with less code-behind.

Showing a rotation-locked activity programatically in Android

Sometimes you need an activity showing in a locked orientation (i.e. no rotation allowed), but you need to decide which orientation should be the activity display dynamically by code. In my case, I had to implement a chroma-keyed camera app and the backgrounds where either landscape or portrait. When the user tapped the background to use I had to decide the orientation and lock the new camera activity to this orientation.

My first thought was using setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_x); on the onCreate() in the activity, but I found that was not reliable. In some cases the screen didn’t lock and rotated freely. I was doing my tests in a Honeycomb Galaxy Tab, so I’m not sure if in 4.x this method should work.

Finally, the method I used and that worked flawlessly was declaring two different activities in the manifest, using android:screenOrientation attribute:

<activity
 android:name="com.xrubio.retrats.activity.ActivityCameraLandscape"
 android:screenOrientation="landscape"
 android:theme="@style/AppTheme.NoActionBar" />
<activity
 android:name="com.xrubio.retrats.activity.ActivityCameraPortrait"
 android:screenOrientation="portrait"
 android:theme="@style/AppTheme.NoActionBar" />

The trick is not duplicate the whole class code, but to put all the logic in a base class ActivityCameraBase and derive two subclasses with the names ActivityCameraLandscape and ActivityCameraLandscape. Also, there will be a single layout file, for both orientations.

Activities detail

package com.xrubio.retrats.activity;

// imports here

// This class is used to be able to have two different orientations,
// locked at manifest level, so we're able to select which orientation
// we want the camera be locked at programatically, without having to
// reimplement everything again.
public class ActivityCameraBase extends Activity {

  @Override
  public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera);

    // remaining initialization stuff...
  }

  // remaining activity logic...
}
package com.xrubio.retrats.activity;

public class ActivityCameraLandscape extends ActivityCameraBase {
  // Look, ma, the class is empty!
}
package com.xrubio.retrats.activity;

public class ActivityCameraPortrait extends ActivityCameraBase {
  // Look, ma, the class is empty!
}

Notice, however, that you can have two different layouts if you need your layout to be different in landscape and portrait, but keep the logic the same. In this case you will put your portrait layout in the regular layout directory, and your landscape layout in the layout-land directory, using the same name.

Different layouts detail