Round up a number to highest 10s place


Download Source Code

Recently we faced a problem that we need to round-up a number to greatest 10s place.
For ex: we needed to round-up a number as follows
1023 -> 2000
37911 -> 40000
912345 –> 1000000

First we checked Math.Round(). However, it did not solve our problem.  Math.Round() supports only rounds a value to the nearest integer or the specified number of fractional digits. Further checking we come up a solution by using Math.Ceiling() method.

Math.Ceiling()returns the smallest integral value that is greater than or equal to the specified double-precision floating point number.
For ex:
Math.Ceiling(7.3)     -> 8
Math.Ceiling(7.64)     -> 8
Math.Ceiling(0.12)     -> 1

Below is the solution we came up

decimal[] values = { 1023, 37911, 23000, 1234, 912345 };
foreach (var value in values) {
//// get the lenght of the 10s places;
var length = (int)Math.Log10((double)value);
//// using Math.Pow() calculate the power of 10s
var power = Math.Pow(10, length);
//// var roundadValue = Math.Ceiling(1023 / 1000) * 1000;
var roundadValue = Math.Ceiling(value / (decimal)power) * (decimal)power;

Console.WriteLine("Value:{0} Rounded Value:{1}", value, roundadValue); 


Math.Ceiling() Results

The Logic

Math.Ceiling(value / (decimal)power) * (decimal)power;
var roundadValue = Math.Ceiling(1023 / 1000) * 1000;

So, for any number, fist compute power of 10s and then it use for the above calculation to get the results.

Automate PNG & JPG Image Optimization


Download Source Code


If you are a web developer, you already know how important to reduce the image size by compressing the image. When you are checking the page speed using the tool like “Google PageSpeed Insight” or “Yahoo YSlow”, you can see how many bytes we can save by compressing the image.

Google:Page Speed

Images saved from programs like Fireworks can contain kilobytes of extra comments, and use too many colors, even though a reduction in the color palette may not perceptibly reduce image quality. Improperly optimized images can take up more space than they need to; for users on slow connections, it is especially important to keep image sizes to a minimum.

You should perform both basic and advanced optimization on all images. Basic optimization includes cropping unnecessary space, reducing the color depth to the lowest acceptable level, removing image comments, and saving the image to an appropriate format. You can perform basic optimization with any image editing program, such as GIMP.  Advanced optimization involves further (lossless) compression of JPEG and PNG files. You should see a benefit for any image file that can reduced by 25 bytes or more (less than this may not result in any appreciable performance gain). Optimize images >

There are some online tools like “Yahoo” use lossless compression techniques and reduce file size by removing the unnecessary bytes from the image. However, if you want to make it automate, how do you do that? Several standalone tools are available that perform lossless compression on JPEG and PNG files.

For JPG Google recommended using,

  • Jpegtran – available for both Windows and Linux and Mac
  • Jpegoptim – available only on Linux

For PNG Google recommended using,

Using the code

Here I wrote a windows batch file that recursively search the given folder and optimized the JPEG and PNG files.

  1. Download jpegtran, OptPNG and PNGOUT executable files. (Or download attached zip file all the necessary files already included)
  2. Create a folder “ImageOptimization” in your C:\ Drive. (You can change those name and folder location by editing the batch file content) and put above downloaded utility files there.
  3. Create a batch file “optimize.bat” within the folder and copy following code into it
    @echo none
    REM Optimizing JPEG with jpegtran
    forfiles /p %1 /s /m "*.jpg" /c "cmd /c  echo processing @path && D:\ImageOptimization\jpegtran.exe -optimize -progressive -copy none -outfile @path @path"
    REM Optimizing PNG with pngout
    forfiles /p %1 /s /m "*.png" /c "cmd /c  echo processing @path && D:\ImageOptimization\pngout.exe @path"
    REM Optimizing PNG with optipng
    rem forfiles /p %1 /s /m "*.png" /c "cmd /c  echo processing @path && D:\ImageOptimization\optipng.exe -force -o7 @path"

    Although I included both PNGOUT and OPTPNG in the script you no need to use both.

  4. Finally, you can execute the bat file by passing the image folder you wish to optimize
    optimize.bat “D:\image”

How it works

  • forfiles command – Select a file (or set of files) and execute a command on each file (Batch processing) Refer:
  • %1 – accept the folder as a parameter. In above example, this equals to “D:\Image”

forfiles command find all the images in the given directory (recursively) and execute the optimizing executable by passing the image as a parameter to them (@path).


  1. You can further improve by adding this batch command as a context menu command
  2. Alternatively, even you can use a scheduler (e.g. Windows scheduler) to find the daily updated file and optimize them by slightly modifying the forfiles command with “/d” option.

How to transfer ownership of your android application


Suppose you have developed an Android game and publish that on the Google play. Many users downloaded your app, and you have released few versions also. What if a company wants to acquire your app game? You need to transfer your app to the new business account, and it should display as their registered app. Google makes it quicker and easier way to transfer the ownership of application from one account to another account.

  1. First you have to login to the Google play publish account using the original app owner’s credentials.
  2. Then click Help & Feedback -> Contact Support
    Google Play: Contact Support
  3. Select “I would like to have my apps transferred to a new account. Once you select that it asks to fill the form to resolve the issue.
    Google Play: Contact Support
    Google Play: App Transfer Form
  4. Follow the provided guidelines. It contains several checklist to make sure you are ready to submit the transfer request
    Google Play: App Transfer Checklist
    Make sure,
    You’ll need to prepare both developer account tosubmit your app transfer.

    Original Account – This is the account where your app is currently published.
    Target Account – This is the account you want to transfer your app to.

    Google Play: App Transfer Checklist
    Google Play: Checklist step

  5. Finally, Fill the “Application Transfer Request” and submit the form. Normally Google responds to your request within a day, and if all the details are correct they transfer the app to new account
    Google Play: App Transfer Final Step
    Google Play: Application Transfer Request Form

Google Play: Submit Success

Emoji and web application


Download SQL query

I am back after few months or so of not blogging. Have you heard something called “Emoji”?

iPad Emoji Keyboard

Emoji; is the Japanese term for the ideograms or smileys used mostly in Japanese electronic messages and webpages. These small images are starting to appear more and more outside Japan. Originally meaning pictograph, the word emoji literally means “picture” (e) + “letter” (moji).

If you want to know what the emoji meanings check the following cheat sheet

Although originally only available in Japan, some emoji character sets have been incorporated into Unicode (Unicode 6.0 in 2010), allowing them to be used elsewhere as well. The core emoji are as of Unicode 6.0 consists of 722 characters.

More recent iOS, Android, Windows 8 and OS X (Mountain Lion +) display Emoji natively, regardless of the typeface. However, how we display that on the all other desktop and the web application? When you are viewing Emoji with unsupported device or browser, Emoji shows up as squares or foreign text. You can convert them to a viewable format just by pasting it in the box above then viewing it in the preview.

I have found that several open source JavaScript libraries and the projects support for this. The most comprehensive seems to be Github’s Gemoji project.

Following are some of other good projects and scripts

For more info about Emoji Unicode table, please check below URL

Emoji and Database

Emojis are UTF-8 encoded symbols. Therefore, to save the Emoji in the database, your database column should support for the UTF-8 encoding.

Emoji and MySQL

To store the Emoji in the MySQL, you have to modify the table character set to support UTF-8.  Please keep in mind starting from iOS5, Emoji represents as 4-byte characters.  That means your MySQL table charset should set as utf8mb4. (Earlier version of iOS Emoji worked well with utf8 charset). utf8mb4 support is dependent on the MySQL version that you use. MySQL 5.5+ works fine with 4-byte characters when properly configured.

create table MyEmoji (emojicolumn VARCHAR(255) CHARACTER SET utf8mb4) default character set utf8mb4;

Make Sure Followings,

  1. Your database table character set is: utf8mb4
  2. Your PHP application character set is: UTF-8
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
     header('Content-type: text/html; charset=utf-8');
  3. In the application database, connection character set is: utf8mb4

For more information:

Emoji and MS SQL

SQL Server does not support UTF-8 by default. However, it supports UCS2 to store Unicode characters. (UCS2 is typically UTF-16).  SQL server handles the UTF-8 conversion automatically. However, keep in mind, MS SQL VARCHAR column type does not support for this. Instead of that you have to use NVARCHAR column type. Then you must precede all Unicode strings with a prefix N when you deal with Unicode string constants in SQL Server

For more information:

CREATE TABLE [dbo].[MyEmoji](
    [EmojiColumn] [nvarchar](255) NULL
INSERT INTO MyEmoji (EmojiColumn) VALUES (N'EncodedString')

Make sure followings,

  1. Your database table column is: nvarchar
  2. You are sending in Unicode data by adding an N in front of the encoded string

How to enable Emoji keyboard in iOS and Android

iPhone –
Android –

EmoJi for PHP

Generate insert statements from the specific table data using SQL Server


When you are deploying your application, sometimes you may want to generate SQL script with the insert statement of the specific database table. The following article shows two easiest ways to do this with SQL Server and SQL Server tools.

  1. Using Database Publishing Wizard (“SqlPubWiz.exe”)

If you install Visual Studio 2008 / Visual Studio 2008 Express full version, it automatically installs the Microsoft SQL Server Data Publishing Wizard in the following location.
[SQL Server Installation Location]\90\Tools\Publishing[version]\ SqlPubWiz.exe

If it is not there, you can download it from the following URL

SQLPubWiz location

SQLPubWiz location

When you run the “SqlPubWiz.exe”, it opens the database publishing wizard

Database Publishing Wizard

Database Publishing Wizard

Click next and enter the database server connection information accordingly.

Database Publishing Wizard - Database Server Connection

Database Publishing Wizard – Database Server Connection

Click next, and it asks you to select the database, which you want to generate the data from

Database Publishing Wizard - Select Database

Database Publishing Wizard – Select Database

Next screen asks to select the Object type. You can use this database publishing wizard to generate data and schema both. In here I consider only for the data generation part. Now choose “Tables” as an option and click next. (Make sure to uncheck “Script all objects in the selected database”)

Database Publishing Wizard - Choose Object Type

Database Publishing Wizard – Choose Object Type

Then, the next ask to select the table that you want to generate the data from. Select whatever the table you want and click next.

Database Publishing Wizard - Choose Tables

Database Publishing Wizard – Choose Tables

Next step asks to specify the output location. You can enter the file name and the location there.

Database Publishing Wizard - Select an Output Location

Database Publishing Wizard – Select an Output Location

By clicking Next, It shows to choose the publishing options. There are three publishing types, Schema only, Data only, or Schema and data. Here you have to select “Data only”.

Database Publishing Wizard - Select Publishing Option

Database Publishing Wizard – Select Publishing Option

Click next and it generates the insert data script for you.

Database Publishing Wizard - Publishing Progress

Database Publishing Wizard – Publishing Progress

Database Publishing Wizard - Generated Script

Database Publishing Wizard – Generated Script

  1. Using SQL Server Generate Script wizard
SQL Server Generate Script

SQL Server Generate Script

When you select “Generate Script” menu item, it opens the Generate SQL Server Scripts Wizard dialog.

SQL Server Generate Script - Wizard Dialog

SQL Server Generate Script – Wizard Dialog

By clicking next, it asks to select the database that you want to generate the script.

SQL Server Generate Script Wizard - Select Database

SQL Server Generate Script Wizard – Select Database

By clicking Next, It shows to select the script options dialog box. In here, you change the “Script Data” as “True” and click the next button

SQL Server Generate Script Wizard - Choose Script Option

SQL Server Generate Script Wizard – Choose Script Option

Next screen asks to select the Object type. Now choose “Tables” as an option and click next.

SQL Server Generate Script Wizard - Choose Object Type

SQL Server Generate Script Wizard – Choose Object Type

Next screen asks you to select the tables that you want to generate the data from. Select whatever the tables and click next

SQL Server Generate Script Wizard - Choose Tables

SQL Server Generate Script Wizard – Choose Tables

Next step asks to specify the output options. If you select “Script to file” as an option, then you can enter the file name and the location there.

SQL Server Generate Script Wizard - Output Option

SQL Server Generate Script Wizard – Output Option

Next two steps are very straight forward. It shows the script generation summary, and by clicking next it generates the script with insert statements for the selected tables.

SQL Server Generate Script Wizard - Script Summary

SQL Server Generate Script Wizard – Script Summary

SQL Server Generate Script Wizard - Script Progress

SQL Server Generate Script Wizard – Script Progress

SQL Server Generate Script Wizard - Generated Script

SQL Server Generate Script Wizard – Generated Script

How to Fix Orphaned SQL Users


Recently I had to involve in a database migration task. I backed up the database and restored successfully in the new server. However when I access the database through the web site, database login didn’t work. The problem was even though the database user is included in the restored database; the login information was not there. So I re-created the login in the server, but it also didn’t work.

This phenomenon is called “orphaned users“.

Database with orphaned users

Details of the Problem:

User logon information is stored in the syslogins table in the master database. By changing servers, or by altering this information by rebuilding or restoring an old version of the master database, the information may be different from when the user database dump was created. If logons do not exist for the users, they will receive an error indicating “Login failed” while attempting to log on to the server. If the user logons do exist, but the SID (secure identifier) in master..syslogins and the sysusers table in the user database differ, the users may have different permissions than expected in the user database. (Microsoft

User login information in syslogins table in the master database

User login information in syslogins table in the master database

User information in the sysusers table in the user database

User information in the sysusers table in the user database

See above example, both tables contain the different SID for the username “eyepax”

How to fix:

1. The easiest way to fix this is delete the user from the restored database and then create and setup the user & corresponding permission to the database.

2. If the user owns a schema in the database, you won’t be able to delete the user. Then you can use the special stored procedure “sp_change_users_login”.


sp_change_users_login [ @Action = ] action
[ , [ @UserNamePattern = ] user]
[ , [ @LoginName = ] login]
[ , [ @Password = ] password]


[@Action =] action

Following are the list of actions can be performed by the procedure.

Value Description
Auto_Fix Links a user entry in the sysusers table in the current database to a login of the same name in sysxlogins. You should check the result from theAuto_Fix statement to confirm that the correct link is in fact made. Avoid using Auto_Fix in security-sensitive situations.
When using Auto_Fix, you must specify user and password; login must be NULL. user must be a valid user in the current database.
Report Lists the users and corresponding security identifiers (SID) in the current database that are not linked to any login.
user, login, and password must be NULL or not specified.
Update_One Links the specified user in the current database to login. login must already exist. user and login must be specified. password must be NULL or not specified.

To perform the operations, first you have to select the database which contained the issues. Here are some of the operations you can perform.

  • Lists the orphaned users
EXEC sp_change_users_login 'Report'
Lists the orphaned users

Lists the orphaned users

  • If you already create a SQL server with same login information and if you want to map that with the database user
EXEC sp_change_users_login 'Auto_Fix', 'user'
Auto fix orphaned user

Auto fix orphaned user

3. MSDN says, maps an existing database user to a SQL Server login. sp_change_users_login feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Use ALTER USER instead.


WITH <set_item> [ ,…n ]

<set_item> ::=
NAME = newUserName
| DEFAULT_SCHEMA = schemaName
| LOGIN = loginName


userName -Specifies the name by which the user is identified inside this database.
LOGIN =loginName, Re-maps a user to another login by changing the user’s Security Identifier (SID) to match the login’s SID.
NAME =newUserName, Specifies the new name for this user. newUserName must not already occur in the current database.
DEFAULT_SCHEMA =schemaName, Specifies the first schema that will be searched by the server when it resolves the names of objects for this user.

Alter user

Alter user

For more information



Troubleshoot Orphaned Users (SQL Server)

JavaScript Frameworks and Resources



Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.


AngularJS is an open-source JavaScript framework, maintained by Google, that assists with running what are known as single-page applications. Its goal is to augment browser-based applications with model–view–controller (MVC) capability, in an effort to make both development and testing easier. The library reads in HTML that contains additional custom tag attributes; it then obeys the directives in those custom attributes, and binds input or output parts of the page to a model represented by standard JavaScript variables. The values of those JavaScript variables can be manually set, or retrieved from static or dynamic JSON resources.


Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.


Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.


Modernizr is a small JavaScript library that detects the availability of native implementations for next-generation web technologies, i.e. features that stem from the HTML5 and CSS3 specifications. Many of these features are already implemented in at least one major browser (most of them in two or more), and what Modernizr does is, very simply, tell you whether the current browser has this feature natively implemented or not.


RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.


LESS extends CSS with dynamic behavior such as variables, mixins, operations and functions.LESS runs on both the server-side (with Node.js and Rhino) or client-side (modern browsers only).


Sass is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin.