Ivan Uzunov Blog: Web Development Tips & Tricks


 Ivan Uzunov, a blogger since 2007, is still active posting free code for all those techies out there who would prefer to do it themselves… with a little help from Ivan, of course.

In 2006 & 2007 Ivan posted lots of code for his visitors and followers. At some point the domain expired and the site saw several different owners with content that had nothing to do with Ivan’s blog post. The site has now been revived with a number of his blog posts about Web Development Tips & Tricks gathered from 2006-2007 archived pages. Read, enjoy, and perhaps you will learn something useful.

I first heard about Ivan Uzunov around the early winter in 2007 during my weekly poker night with friends at our favorite online US casino site. I remember the night well because I had just received a new North Face 660 jacket from an online site I had recently been recommended. I am a huge fan of North Face jackets in general, but this style is really exceptional. The 660 stands for the weight of the jacket or so I thought, but then my wife said it had to do with the fabric. I don't really care since the jacket was/is just amazing. This wasn't a typical North Face high loft goose down jacket. Instead it's made with streamlined baffles that are contoured to fit your body. It has an ultra-light, highly compressible synthetic insulation to keep you warmer in cold, wet weather which is typical of our winters here in the northwest. Supposedly it has the warmth equivalent of 600 fill goose down jacket. I don't really know. But I still am wearing the jacket five years later, if you can believe it. But the first time I wore it was to our "online" poker night. The same night when I heard about Ivan. Here's the real story.... Instead of playing at home with real poker chips and cards, we all gather at a designated house with our laptops and sign in to our favorite casino site to play Caribbean Stud Poker, Caribbean Draw Poker or Caribbean Hold'Em Poker. Sometimes we throw caution to the winds and settle in for a slots night. And if we are really feeling good, we'll all enter a virtual poker tournament. There's the usual snack foods and craft beer available as well. Anyway, we were discussing various issues with JavaScript and someone mentioned that Ivan Uzunov had numerous posts on the subject. I looked up his site and started following his posts. You can imagine my dismay when in the posts stopped. I don't know what the reasons were, but the domain must have expired. I discovered its availability recently and bought the domain with the intent of rebuilding at least as many of the blog posts as I could find, using archived pages from the original site. Consider this an historical document of Ivan Uzunov's post from between 2006-2007. Enjoy, perhaps you will learn something.

***

Posts by Ivan Uzunov:

17 Sep 2007JavaScript web Development Top 10 Sites
13 Aug 2007Top 5 Front-End Developer Online Manuals
10 Jul 2007Top 10 JavaScript String.prototype Extensions
29 Jun 2007How to get the last day of the week
07 Jun 2007How to Create a Random Password in MySQLv 01 May 2007How to open PostBackURL in new window
24 Apr 2007Redirect all HTTP requests to HTTPS with ISAPI Rewrite
23 Apr 2007Using JavaScript confirm() in ASP.NET control OnClientClick property
19 Apr 2007Prevent postback in FF invoked by textarea enter click (ASP.NET 2.0)
12 Mar 2007Create High Quality Thumbnails with .NET
23 Apr 2007Using JavaScript confirm() in ASP.NET control OnClientClick property
19 Apr 2007Prevent postback in FF invoked by textarea enter click (ASP.NET 2.0)
12 Mar 2007Create High Quality Thumbnails with .NET
17 Jan 2007Web Client Software Factory Released
16 Jan 2007Prevent Spammers email collecting with JavaScript
25 Dec 2006del.icio.us Play Tagger WP Plugin
22 Dec 2006del.icio.us Tagometer Badge WP Plugin
19 Dec 2006Setting the next ID in MSSQL Table
16 Dec 2006Microformats
25 Nov 2006Adding contains(t) function to JavaScript String.prototype

Ivan Uzunov Blog Posts 2006 - 2007

del.icio.us Play Tagger WP Plugin
December 25th, 2006 by Ivan Uzunov

This Word Press Plugin adds del.icio.us Play Tagger into your blog. Play Tagger is a neat little tool that allows you to easily play mp3 files on your website or blog. It will add a player tool to all the mp3 links on the page.

listenExample mp3 link

Installation Instructions

Just drop the delicious-play-tagger.php file into your wp-content/plugins folder and activate the plugin in the admin. The plugin will then add the necessary code at the right position in the HTML of your blog’s pages.

***

del.icio.us Tagometer Badge WP Plugin
December 22nd, 2006 by Ivan Uzunov

This Word Press Plugin adds del.icio.us Tagometer Badge into your blog. The badge can be added in the home page, in the side bar or after each post or page.

Installation Instructions

Just drop the delicious-tagometer-badge.php file into your wp-content/plugins folder and activate the plugin in the admin. Go to the “del.icio.us Tagometer” options page under “Options” and set the type of Tagometer  Badge that you want to use.

The plugin will then add the necessary code at the right position in the HTML of your blog’s pages

Upgrading

Just replace delicious-tagometer-badge.php file into your wp-content/plugins folder and change the Options of the plug-in.

***

Setting the next ID in MSSQL Table
December 19th, 2006 by Ivan Uzunov

Have you ever been in a situation when you want to set the next value of the identity column? This is s simple task that can be done with DBCC CHECKIDENT statement. This example deleted all records with ID greater than 135 from the table Products. Than it sets the current identity value to 135. Thus when the next record is added it will have ID with value 136.

DELETE  FROM [Products] WHERE id>135

GO

DBCC CHECKIDENT (Products, RESEED, 135)

GO

DBCC CHECKIDENT, identity, MS SQL Server, RESEED

***

Microformats
December 16th, 2006 by Ivan Uzunov

“Designed for humans first and machines second, microformats are a set of simple, open data formats built upon existing and widely adopted standards. Instead of throwing away what works today, microformats intend to solve simpler problems first by adapting to current behaviors and usage patterns (e.g. XHTML, blogging).” Source: http://microformats.org/about/

I really like microformats because they allow machines to export data like contacts in vCard format with a simple change of existing code. With a few simple CSS class additions I’ve created a web site that supports microformats.

More information how to use microformats can be found on the official web page: http://microformats.org/. The site includes hCard, hCalendar and hReview creators that will show you how the microformats are embedded in XHTML for example.

This is a simple example of HTML with added microformats hCard:

 

 

     Ivan Uzunov

    

Uzunov Ltd.

 

    myemail@uzunov.com

 

 

To take advantage from microformats as a simple website user you will need a tool that extracts the data from the web site page and allows you to do something with it. For example it can import contacts data into your email client. I’m using these two Firefox extensions:

Tails Export (https://addons.mozilla.org/firefox/2240/)

I prefer this one but is not supported in Firefox 2.0 yet.

Operator (https://addons.mozilla.org/firefox/4106/)

Of course the microformats could be dangerous because of spammers. They could easily collect email addresses.

***

Prevent Spammers email collecting with JavaScript
January 16th, 2007 by Ivan Uzunov

Using JavaScript to prevent email addresses harvesting by spammers if an effective method against the standard harvesting programs. Nevertheless the spammers could modify their harvesting programs to read the email addresses from the JavaScript. That is why this is not a bulletproof solution but is really effective and could easily be customized for any web site.

The idea is to create a JavaScript function that will print the email address:

function printEmail(theName, theExtras, theLink, theDomain) {
var theEmail = theName + "@" + theDomain;

    if (theName == "") {
        theName = "ERROR";
        theLink = "ERROR";
        myEmail = theName;
        myLink = theLink;
       
    } else {
   
        if ((theExtras == "") && (theLink =="")){
            myEmail = theEmail;
            myLink = theEmail;
        }
       
        if ((theLink == "") && (theExtras != "")){
            myLink = theEmail;
            myEmail = theEmail+theExtras;
        }
       
        if ((theLink != "") && (theExtras != "")){
            myLink = theLink;
            myEmail = theEmail+theExtras;
        }
       
        if ((theLink != "") && (theExtras == "")){
            myLink = theLink;
            myEmail = theEmail;
        }
    }
   
    document.write(’’ + myLink + ‘’);
}

You can call the function using this line of code:

***

Web Client Software Factory Released
January 17th, 2007 by Ivan Uzunov

Overview

The Web Client Software Factory provides an integrated set of guidance that assists architects and developers in creating composite Web client applications. The application blocks, software factory includes reference implementation, how tos, patterns, and Visual Studio .NET extensions.

System Requirements

Supported Operating Systems: Windows Server 2003; Windows XP

Microsoft .NET Framework 2.0

Microsoft .NET Framework 3.0

Visual Studio 2005 extensions for .NET Framework 3.0 (Windows Workflow Foundation)

In the Box

  • Application Blocks and Libraries
  • Visual Studio 2005 extensions for automating common tasks. Guidance Automation Overview
  • How-to topics and QuickStarts
  • Architecture guidance and Patterns for Web Client Applications
  • Reference Implementation (a sample applications using the Factory)
  • Training content (Hands-On-Labs, demos, etc) (under development

***

Create High Quality Thumbnails with .NET
March 12th, 2007 by Ivan Uzunov

Creating thumbnails with .NET is really simple task. You have to call only one method Image.GetThumbnailImage(). The problem is that the quality of the created image is really poor. So I’ve started googling around and the result is this GenerateImageThumbnail() function:

    public static void GenerateImageThumbnail(Stream streamImage, string sThumbnailImagePath, int nMaxWidth, int nMaxHeight)

    {

        Image oImage = Image.FromStream(streamImage);

        GenerateImageThumbnail(oImage, sThumbnailImagePath, nMaxWidth, nMaxHeight);

    }

    public static void GenerateImageThumbnail(string sImagePath, string sThumbnailImagePath, int nMaxWidth, int nMaxHeight)

    {

        Image oImage = Image.FromFile(sImagePath, true);

        GenerateImageThumbnail(oImage, sThumbnailImagePath, nMaxWidth, nMaxHeight);

    }

    public static void GenerateImageThumbnail(Image oImage, string sThumbnailImagePath, int nMaxWidth, int nMaxHeight)

    {

        float fRatio = 1;

        int nWidth = oImage.Width;

        int nHeight = oImage.Height;

       

        //calculate the thumb image size if needed

        if (oImage.Width > nMaxWidth || oImage.Height > nMaxHeight)

        {

            if (oImage.Width >= oImage.Height)

            {

                fRatio = ((float)oImage.Height) / ((float)oImage.Width);

                nWidth = nMaxWidth;

                nHeight = Convert.ToInt32(nMaxHeight * fRatio);

            }

            else

            {

                fRatio = ((float)oImage.Width) / ((float)oImage.Height);

                nWidth = Convert.ToInt32(nMaxWidth * fRatio);

                nHeight = nMaxHeight;

            }

        }     

         //create the thumbnail ans set it’s settings

        Image oThumbnail = new Bitmap(nWidth, nHeight);

        Graphics oGraphic = Graphics.FromImage(oThumbnail);

        oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

        oGraphic.SmoothingMode = SmoothingMode.HighQuality;

        oGraphic.PixelOffsetMode = PixelOffsetMode.HighQuality;

        oGraphic.CompositingQuality = CompositingQuality.HighQuality;

        oGraphic.DrawImage(oImage, 0, 0, nWidth, nHeight);

        //save the thumbnail

        if (DefineImageType(sThumbnailImagePath) == ImageFormat.Gif)

        {

            using (oThumbnail)

            {

                ImageManipulation.OctreeQuantizer quantizer = new ImageManipulation.OctreeQuantizer(255, 8 );

               

                using (Bitmap bmpQuantized = quantizer.Quantize(oThumbnail))

                {

                    bmpQuantized.Save(sThumbnailImagePath, ImageFormat.Gif);

                }

            }

        }

        else

        {           

            ImageCodecInfo[] iciInfo = ImageCodecInfo.GetImageEncoders();

            EncoderParameters encoderParameters;

            encoderParameters = new EncoderParameters(1);

            encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);

            oThumbnail.Save(sThumbnailImagePath, iciInfo[1], encoderParameters);

        }

        if (oThumbnail != null) { oThumbnail.Dispose(); }

    }

public static ImageFormat DefineImageType(string sFileName)

    {

        string sFileExtention = Path.GetExtension(sFileName);

        ImageFormat oImageFormatToReturn;

        switch (sFileExtention)

{

            case ".gif":

                oImageFormatToReturn = ImageFormat.Gif;

                break;

            case ".png":

                oImageFormatToReturn = ImageFormat.Png;

                break;

            case ".bmp":

                //oImageFormatToReturn = ImageFormat.Bmp;

                //break;

            case ".jpg":

            case ".jpeg":

            case ".jpe":

            default:

                oImageFormatToReturn = ImageFormat.Jpeg;

                break;

        }

        return oImageFormatToReturn;

    }

Since there is a problem with creating thumbnails from GIF images the function uses a class ImageManipulation.OctreeQuantizer. You can get the source code for this class from this MSDN article “Optimizing Color Quantization for ASP.NET Images” written by Morgan Skinner. You can download the project DotNET_Color_Quantization_Code.msi, build it and use the ImageManipulation.dll in your project. Of course the animated GIFs will not be animated anymore, but at least the transparency is preserved.

You can use the function with this sample code:

GenerateImageThumbnail(filePhoto.PostedFile.InputStream,"c:your_thumbnaill_file_name.jpg", 400, 400);

***

Prevent postback in FF invoked by textarea enter click (ASP.NET 2.0)
April 19th, 2007 by Ivan Uzunov

Recently I found new bug in MS WebResource.axd javascript. The problem is that when a multiline textbox is put inside panel with DefaultButton set, pressing the enter button while editing text in the textbox submits the form instead of going to new line.

The fix that I’ve found is this JavaScript function that accepts the textbox client id as parameter:

function PreventSubmitOnKeyPress(sObjectID) {

    try {

        if (!document.all) {

            var oObject = $id(sObjectID);

           

            if (oObject.addEventListener) { 

                oObject.parentNode.addEventListener("keypress",

                    function(e) {

                        if (e && e.keyCode && e.keyCode==13) {

                            e.stopPropagation();

                        }

                    }, false); 

            } 

        }

    } catch (e) {}

}

To call the function you can use something like that:

var sMyTextBoxID = ‘<%=txtMyTextbox.ClientID %>’;

PreventSubmitOnKeyPress(sMyTextBoxID);

***

How to open PostBackURL in new window

May 1st, 2007 by Ivan Uzunov

 

To open a page in new window with ASP.NET 2.0 button PostBackURL property you have to set the FROM’s target to "_blank".

Page.Form.Target = "_blank";

Or to use the following JavaScript code:

    var sFormID = ‘<%=Page.Form.ClientID%>’;

    var oForm = document.getElementById(sFormID);

    oForm.target = ‘_blank’;

ASP.NET, PostBackURL

***

Redirect all HTTP requests to HTTPS with ISAPI Rewrite
April 24th, 2007 by Ivan Uzunov

To redirect all HTTP requests to HTTPS with ISAPI Rewrite you can use the following rewriting rules in your httpd.ini file:

# redirect all http requests  to https

RewriteCond  %HTTPS (?!on).*

RewriteCond Host: (.*)

RewriteRule (.*) https://$1$2 [I,RP]

ISAPI Rewrite, URL Rewriting

***

How to Create a Random Password in MySQL
June 7th, 2007 by Ivan Uzunov

It is quite simple:

SELECT LEFT(md5(UUID()), 10)

The UUID() function returns a Universal Unique Identifier (UUID). The rest is obvious :)

;

 

If you are looking for the same functionality in MS SQL click here.

>

MySQL, Random Password, T SQL

p>

***

4 Responses to “How to Create a Random Password in MySQL”

on 08 Jun 2007 at 9:43 am   Josh Storz

>

There are many ways to accomplish this, yours is one. May I suggest doing md5(md5()) for only a bit more code little more security.

on 09 Jun 2007 at 9:37 am   Peter Cooper

Since we’re dealing with a UUID, MD5ing it twice isn’t really giving any advantage over once. I do spy one possible flaw though?

 

You surely don’t want people to have to type in (yes, some people don’t seem to know about cut and paste :( ) a 32 character password? Just move the LEFT to the outside:

 

SELECT LEFT(MD5(UUID()), 8) ;

 

I must admit I don’t see any compelling reason to trim the UUID down to the left 8, because it’ll hash the whole thing anyway.. although admittedly SHA1 would be nicer..

 

SELECT LEFT(SHA1(UUID()), 8) ;

 

Didn’t know there was SHA1 as well, but it seems to just work :)

 

on 11 Jun 2007 at 4:05 am   Q4

32-char passwords are fine if you’re doing your actual connections with public/private keys.

 

Agree on the LEFT() being a Bad Thing, though - you’re reducing the entropy of the password to the point where it’s within the range of a rainbow table.

 

on 11 Jun 2007 at 8:37 am   Ivan Uzunov

Yep, you are right - it should be like this:

 

SELECT LEFT(md5(UUID()), 10)

 

I’ve changed it in the post.

***

How to get the last day of the week
June 29th, 2007 by Ivan Uzunov

 

This sample shows how to get the last day of the current week. It easily could be reconfigured to get any day of the week of any date.

DateTime dtWET = DateTime.Today;

//get the last day of the week. If you need another day change the 6 to a number between 0 and 6. Please note that depending on you regional settings the week 0 day could be Sunday or Monday.

dtWET = dtWET.AddDays((-(Convert.ToInt32(dtWET.DayOfWeek))) + 6);

dtWET = new DateTime(dtWET.Year, dtWET.Month, dtWET.Day, 22, 00, 0);

.NET

***

Top 10 JavaScript String.prototype Extensions
July 10th, 2007 by Ivan Uzunov

 

This is the list of mine top 10 JavaScript String.prototype extensions. If you want to you can post yours bellow.

This extension adds trim() function:

String.prototype.trim = function(){ return this.replace(/^s+|s+$/g,'’); }

//test trim

test = ‘ testing trim ‘;

document.write (’"’ + test.trim() + ‘"’);

This extension splits the string by given separator and returns an array with trimmed  items. It uses the trim() extension above:

String.prototype.splitrim = function(t){ return this.trim().split(new RegExp(’s*’+t+’s*’)) }

//test splitrim

test = ‘ testing   , splitrim ‘;

var arr = test.splitrim(’,');

document.write (’"’ + arr[0] + ‘"’);

document.write (’"’ + arr[1] + ‘"’);

This extension escapes HTML in the string:

String.prototype.escHtml = function(){ var i,e={’&’:'&’,'<’:'<’,'>’:'>’,'"’:'"’},t=this; for(i in e) t=t.replace(new RegExp(i,’g'),e[i]); return t }

//test escHtml

test = ‘testing escHtml’;

document.write (test.escHtml());

 

This extension unescapes HTML in the string:

String.prototype.unescHtml = function(){ var i,e={’<’:'<’,'>’:'>’,'&’:'&’,'"’:'"’},t=this; for(i in e) t=t.replace(new RegExp(i,’g'),e[i]); return t }

//test unescHtml

test = ‘testing unescHtml’;

document.write (test.unescHtml());

This extension URL encodes the string:

String.prototype.urlEncode = function(){ return encodeURIComponent(this); }

//test urlEncode

test = ‘http://www.gmail.com’;

document.write (test.urlEncode());

This extension checks if the string is a valid email address:

String.prototype.isEmail = function () { var rx = new RegExp("w+([-+.’]w+)*@w+([-.]w+)*.w+([-.]w+)*"); var matches = rx.exec(this); return (matches != null && this == matches[0]); }

//test isEmail

test = ‘test@gmail.com’;

document.write (test.isEmail());

This extension checks if the string is a valid URL address:

String.prototype.isURL = function () { var rx = new RegExp("http(s)?://([w-]+.)+[w-]+(/[w-+ ./?%:&=#[]]*)?"); var matches = rx.exec(this); return (matches != null && this == matches[0]); }

//test isURL

test = ‘http://www.gmail.com’;

document.write (test.isURL());

This extension checks if the string contains the passed as parameter value:

String.prototype.contains = function(t) { return this.indexOf(t) >= 0 ? true : false; }

//test contains

test = ‘Can you find me?’;

document.write (test.contains(’find me’));

This extension checks if the string begins with the passed as parameter value. The second parameter is for ignore case:

String.prototype.beginsWith = function(t, i) { if (i==false) { return (t == this.substring(0, t.length)); } else { return (t.toLowerCase() == this.substring(0, t.length).toLowerCase()); } }

//test beginsWith

test = ‘Can you find me?’;

document.write (test.beginsWith(’can you’, true));

This extension checks if the string ends with the passed as parameter value. The second parameter is for ignore case:

String.prototype.endsWith = function(t, i) { if (i==false) { return (t == this.substring(this.length - t.length)); } else { return (t.toLowerCase() == this.substring(this.length - t.length).toLowerCase()); } }

//test endsWith

test = ‘Can you find me?’;

document.write (test.endsWith(’Me?’, true));

JavaScript, String.prototype, Top 10



IvanUzunov.net