Friday, May 27, 2011

Show timer with seconds using NSTimer on iPhone and Objective C

I am currently developing an iPhone App using X-Code and Objective-C. I had to show a simple timer showing the elapsed number of seconds and minutes. I don’t know much about Objective-C, but from my past experience I knew this task can be easily accomplished using a Timer. The timer should be called every second, and a simple int variable will hold the seconds. The variable is incremented on every call of the timer.
This is how I the timer is defined:
NSTimer *mainTimer = [NSTimer scheduledTimerWithTimeInterval:1 

Note that the timer is set to be activated every one second and the function that will be called every one second is named “timerController”.

In the “timerController” function I wrote the code that will increment the seconds variable as well as update a label on the screen. In order to update the label with the minutes and seconds I wrote a small function. The function gets seconds and returns a string of the format: “mm:ss” (for example, for input of 90 the function will return: “01:30”. Let’s see the function that returns the time:

- (NSString*)getTimeStr : (int) secondsElapsed {
  int seconds = secondsElapsed % 60;
  int minutes = secondsElapsed / 60;
  return [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];

And let’s have a look at the “timeController” function that use it:

- (void)timerController {
  [[self timeLabel] setText:[self getTimeStr]];

The “timeLable” is a UILabel control that is connected with a label that is show on the iPhone screen.

Thursday, May 26, 2011

Add Facebook Like Button to your (BlogSpot)

Facebook Like button is a great and easy way of sharing things that you like with your friends. If you have a blog on (BlogSpot) you can easily add a Facebook like button to any of your posts. Each post will have it's own Like button. This can help increasing the traffic of your blog.

Let's see how we can easily add Facebook like button:

Step 1: Editing out blog template as HTML:

  • press on: "Design" on your blog main menu.
  • Then press on "Edit HTML" on the upper sub menu.
  • Check "Expand Widget Templates" checkbox.
Step 2: Find the place in which Facebook Like button code should be entered:
Search for the String:
Facebook Like button should be placed before this code.

Step 3: Put the following code in your blog template:
<b:if cond='data:blog.pageType == &quot;item&quot;'>
<iframe allowTransparency='true' expr:src='&quot;; + data:post.url + &quot;&amp;layout=standard&amp;show_faces=false&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&quot;' frameborder='0' scrolling='no' style='border:none; overflow:hidden; width:450px; height:40px;'/>

After you save your template, go to one of your posts. You could see that a Facebook Like button was added right under the name of your post.

Monday, May 16, 2011

Log4j SMTPAppender and deadlocks - Adding Timeout support

On the post: Sending Email alerts with Log4j we saw how we can easily send mails whenever our system has an exception. But we have to remember that using Apache Log4j SMTPAppender, can be very risky if not used cautiously. In general, the Log4j SMTPAppender has 2 main problems:

  1. The part that send the mail, is synchronous. In fact, it is synchronous between all Log4j appenders. It means that when you log an error and a mail is being sent, all log commands are locked. This is quite risky. Especially when your system has many errors (for whatever reason). This may cause your whole system to get stuck. This issue can be easily handled by using: AsyncAppender. I may write about AsyncAppender in more detail in the future.
  2. The code responsible for sending the mail, which is written by Apache developers, doesn't has a Timeout. That mean, a mail being sent can be stuck forever and simply cause your entire system to go into a deadlock.
    In this post, we will improve the Apache SMTPAppender to include a Timeout property. The Timout property will make sure, that if a mail is being sent using SMTP connection for too long, it will be dropped. We may loose a report about an exception, but we will make sure our system won't be stuck indefinitely.

We will create a new class name: SMTPAppenderTimeout, that extends SMTPAppender. This new class will override the SMTPAppender method: createSession.
The new createSession method will make sure to add the following 2 properties to the mail session: 

  • mail.smtp.connectiontimeout
  • mail.smtp.timeout

These 2 properties instruct the Java mail framework to set a timeout on the SMTP connection.
Let's have a look on the SMTPAppenderTimeout class:

import javax.mail.Authenticator; 
import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 
import java.util.Properties; 
* @author Bashan 
public class SMTPAppenderTimeout extends SMTPAppender { 
  private int timeout; 
  public int getTimeout() { 
    return timeout; 
  public void setTimeout(int timeout) { 
    this.timeout = timeout; 
  protected Session createSession() { 
    Properties props; 
    try { 
      props = new Properties(System.getProperties()); 
    } catch (SecurityException ex) { 
      props = new Properties(); 
    if (timeout > 0) { 
      String timeoutStr = Integer.toString(timeout); 
      props.setProperty("mail.smtp.connectiontimeout", timeoutStr); 
      props.setProperty("mail.smtp.timeout", timeoutStr); 
    if (getSMTPHost() != null) { 
      props.put("", getSMTPHost()); 
    Authenticator auth = null; 
    if (getSMTPPassword() != null && getSMTPUsername() != null) { 
      props.put("mail.smtp.auth", "true"); 
      auth = new Authenticator() { 
        protected PasswordAuthentication getPasswordAuthentication() { 
          return new PasswordAuthentication(getSMTPUsername(), getSMTPPassword()); 
    Session session = Session.getInstance(props, auth); 
    if (getSMTPDebug()) { 
    return session; 

You can also download the SMTPAppenderTimeout.

Let's see an example of a log4j.xml file which use SMTPAppenderTimeout to allow timeout of 5 seconds (5000ms):       

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="">
	<appender name="RollFile" class="org.apache.log4j.RollingFileAppender">
		<param name="File" value="C:\\testlog.txt" />
		<param name="MaxFileSize" value="10MB" />
		<param name="MaxBackupIndex" value="1" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d{HH:mm:ss} %-5p [%c{1}]: %m%n" />
	<appender name="Email" class="">
		<param name="BufferSize" value="10" />
		<param name="SMTPHost" value="" />
		<param name="SMTPUsername" value="test_user" />
		<param name="SMTPPassword" value="test_password" />
		<param name="Timeout" value="5000" />
		<param name="From" value="" />
		<param name="To" value="" />
		<param name="Subject" value="System Error Notification" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d [%t] %-5p %c %x - %m%n" />
		<priority value="info" />
		<appender-ref ref="RollFile" />
		<appender-ref ref="Email" />

You can also download the log4j.xml.