Round up a number to highest 10s place

0

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(). But it didn’t solve our problem.  Math.Round() supports only rounds a value to the nearest integer or to 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 above calculation to get the results.

Automate PNG & JPG Image Optimization

0

Download Source Code

Introduction

If you are a web developer you already know how important to reduce the image size by compressing the image. When you checking the page speed using the tool like “Google PageSpeed Insight” or “Yahoo YSlow”, you can see how much 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 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 be reduced by 25 bytes or more (less than this will not result in any appreciable performance gain). <Google Inc., 2012. Optimize images  https://developers.google.com/speed/docs/best-practices/payload#CompressImages >

There are some online tools like “Yahoo Smush.it” use lossless compression techniques and reduce file size by removing the unnecessary bytes form the image. But 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 which 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"
    pause
    

    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: http://ss64.com/nt/forfiles.html
  • %1 – accept the folder as a parameter. In above example this will equal 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).

Try

  1. You can further improve by adding this batch command as a context menu command
    http://msdn.microsoft.com/en-us/library/windows/desktop/cc144169(v=vs.85).aspx
  2. Or 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

0

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 company account and it should display as their registered app. Google makes it quicken and easier way to transfer the owner ship 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 new account. Once you select that it ask 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 check list 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 accountstosubmit 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 will respond to your request within a day and if all the details are correct they will 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

4

Download SQL query

I’m 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).
Refer: http://en.wikipedia.org/wiki/Emoji

If you want to know what the emoji meanings check the following cheat sheet
http://www.emoji-cheat-sheet.com/

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 set as of Unicode 6.0 consists of 722 characters.

http://www.unicode.org/charts/PDF/U1F300.pdf
http://www.unicode.org/charts/PDF/U1F600.pdf
http://www.unicode.org/charts/PDF/U1F680.pdf
http://www.unicode.org/charts/PDF/U2600.pdf

More recent iOS, Android, Windows 8 and OS X (Mountain Lion +) display Emoji natively, regardless of typeface. But 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.

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

https://github.com/fengmk2/emoji
https://github.com/iamcal/js-emoji

For more info about Emoji Unicode table please check below URL
http://apps.timwhitlock.info/emoji/tables/unicode

Emoji and Database

Emojis are UTF-8 encoded symbols. Therefore, to save the Emoji on the database, your database column should supports 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 is represented as 4 byte characters.  That’s mean your MySQL table charset should be 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" />
    
    <?php
     header('Content-type: text/html; charset=utf-8');
    ?>
    
  3. In the application database connection character set is: utf8mb4

For more information: http://mathiasbynens.be/notes/mysql-utf8mb4#utf8-to-utf8mb4

Emoji and MS SQL

SQL server doesn’t support UTF-8 by default. But it supports UCS2 to store Unicode characters. (UCS2 is typically UTF-16).  SQL server handles the UTF-8 conversion automatically. But keep in mind, MS SQL VARCHAR column type doesn’t 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: http://support.microsoft.com/kb/239530

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 – http://support.apple.com/kb/ht4976
Android – http://anewdomain.net/2013/09/25/enable-emoji-keyboard-in-android-4-1-higher/

EmoJi for PHP

http://code.iamcal.com/php/emoji/

Generate insert statements from the specific table data using SQL Server

0

When you are deploying your application, sometimes you may want to generate SQL script with the insert statement of the specific database table. In this article I will show you 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 will automatically install the Microsoft SQL Server Data Publishing Wizard on 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
http://go.microsoft.com/fwlink/?LinkId=119368

SQLPubWiz location

SQLPubWiz location

When you run the “SqlPubWiz.exe”, it will open 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 will ask 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 will ask 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 which 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 ask 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 select 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 will generate 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

2. Using SQL Server Generate Script wizard

SQL Server Generate Script

SQL Server Generate Script

When you select “Generate Script” menu item, it will open 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 which 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 will ask 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 ask you to select the tables which 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 ask 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 strait forward. It shows the script generation summary, and by clicking next it will generate 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

8

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 et.al)

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”.

Syntax

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

Arguments

[@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.

Syntax

ALTER USER userName
WITH <set_item> [ ,...n ]

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

Argument

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 UserName WITH LOGIN = UserName
Alter user

Alter user

For more information

sp_change_users_login
http://msdn.microsoft.com/en-us/library/ms174378(v=sql.110).aspx

ALTER USER
http://msdn.microsoft.com/en-us/library/ms176060.aspx

Troubleshoot Orphaned Users (SQL Server)
http://msdn.microsoft.com/en-us/library/ms175475.aspx