9 February 2012

Add a Facebook "like" and Google "+1" button to Magento and integrate them with Google Analytics

Let's start with adding the Facebook like button. On this page: https://developers.facebook.com/docs/reference/plugins/like/, you can create the button as you would like it to appear on your site. When you press "Get Code", you'll get 2 pieces of code.

First we have to add the JavaScript code. To do this, open your head.phtml page, which can be found here:
app/design/frontend/<your template>/<theme>/template/page/html/head.phtml

In this file, add the script, like so:

<script type="text/javascript">
  (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/nl_NL/all.js#xfbml=1";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
</script>

After that, you can add the other part of the Facebook code in any of your pages, where you would like to have the button. If you want to have it in a CMS page, you can create a Custom Variable, by opening the admin part of your Magento shop and navigating to System -> Custom Variables. In there, create a new variable and insert the code in the Variable HTML Value.

29 November 2011

Error during serialization or deserialization using the JSON JavaScriptSerializer

Today one of the internal web applications that we have wouldn't run properly on my development machine (it works fine on the production server). When opened it would produce the following exception:

Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

It seems that the production server has a higher maxJsonLength value in its machine.config than my development machine. To solve this problem, add the following in your web.config.

22 November 2011

The Null coalescing operator

It seems that a lot of people do not know of the existence of this handy little operator, so I decided to put it up here, so it may help somebody clean up their code.

Have you ever had a Nullable<...> type which you needed to read to a regular value type, but needed a "default" value for when it was NULL, as the regular value type cannot handle it?
Chances are, you've written it in one of the following ways:

int? i = null; // please note that Nullable<int> is the same as int?
int a;
if(i.HasValue) // equal to: if(i != null)
  a = i.Value;
else
  a = -1;

or

int a = i.HasValue ? i.Value : -1; // This is already a bit shorter!

But using the NULL coalescing operator, you can simply write: