Simple plugin for watermark effect – TinyWatermark

You should try this out, a very short and simple code for a watermark plugin. You need 2 files, first the jQuery library, secondly jquery.tinywatermark-3.1.0.js, when you add references you should follow the same order. You can get the plugin files from the below link, it also consists of some demo controls as well.

Code sample,

$("#mytextbox").watermark('watermark', 'Please type something')

It works in all browsers, but unfortunately I came across a situation in chrome few days ago. Following is the error message I got when I focus on the input control.

“Uncaught Error: NOT_FOUND_ERR: DOM Exception 8”

Error came from the replaceWith() method, it seems the DOM representation for the internal variable cannot be found, so replacing of elements cannot happen. But the same code is working fine in Firefox. It confused me a lot. But after some struggle, came up with a fix. You have to change the code in the plugin a bit. Replace the code inside the focus event with the following.

try {
} catch (r) {
   $("#" + $c.attr('id')).replaceWith(i);
setTimeout(function () { i.focus(); }, 1);

NOTE: This plugin is usually working fine, I guess this is a special scenario. So avoid updating your js file if you don’t get any errors.

Have fun!!!


Clear values in your FORM using jQuery

Simply copy and paste the below code where you want,

$("input", $("#form1")).not("input[type=button]").not("input[type=submit]").each(function (i, e) { $(e).val(''); });

Note: Use of “.not()” method is up to you to decide, which controls you want to avoid getting cleared.

Happy coding.

JQuery – Dialog plugin

Recently I came across some crazy behavior on my jquery dialog popup. What happen was all my css “:hover” effects started going crazy. The behavior was when I hover over the button or text (which has :hover class), it started changing back and forth, hover <-> normal mode continuously as the mouse pointer moves over the control. But the same controls works fine when get displayed on the page directly. This issue is only occurring when displayed on the popup. And it affected to all browsers (FF, Chrome, Safari, IE9), some in different ways (IE: it was hiding the popup content when hover).

I went through the internet over this problem, but the solutions suggested didn’t work for me. Some of them are listed here in case for someone to be useful.

1. Add the “position” attribute as “relative”

2. Add the “background” attribute as a transparent repeated image or rgba(0,0,0,0)

None of the above worked for me. Although…

The Solution that worked for me

The body content for the popup was wrapped by a div element. Which have the “display” style attribute as “inline”. I changed it to “inline-block”, and yee…haaaaa… it started working.

Also note I have used “:hover” class in different elements(div, label, input) other than a “link/anchor”. Sometimes it may be related, but I don’t have any idea what went wrong with the use of “display” property to behave in such a crazy way. But I am relieved now.

Hope this will help someone.

Read more

Download the reCaptcha library from this link and add the reference to your web project. Sometimes its not getting copied to your bin folder, if so just to make sure do it manually.

Signup in the reCaptcha official web site and register the web address you will be running your site. Then it will give you 2 keys as public and private.
Store them in your main web.config file appsetting section.

Changes in View

Now the background is setup. Let’s open the view file. Place the following code where you want to appear the captcha.


Note: if you just use @Html.GenerateCaptcha() it will only render the script as it is. I had a nasty time struggling to tackle. 🙂 But it motivated me to write this down.

Changes in Controller

Now go to your controller add the following attributes to your action method,
Also add an additional Boolean parameter called captchaValid, which will be populated from the injected recaptcha module.


public ActionResult Register(RegisterModel model, bool captchaValid)
   if (captchaValid)
      if (ModelState.IsValid) {
         //Submit Data
         return RedirectToAction("Index", "Home");
      ModelState.AddModelError("", "You did not type the verification word correctly please try again.");

That is all. Now you are secured against automatic login request attempts.

Anti patterns

I believe if there is something good then opposite also exist. Patterns is a good technique to apply for reoccurring problems, or when you set standards in the company sometimes you suggest all the team members that you all should code in this structure, or pattern. That is to have a enterprise wide common understanding and standard on the code. It will enable to maintain the code easily.

Well… The bad part of it is if you make a wrong call by mistake on a certain approach, you are doom. This is not a anti pattern, it’s just wrong, and you will have to fix it.

I found a nice book on javascript patterns, called Learning JavaScript Design Patterns, by Addy Osmani. This has a section covering anti patterns, read it if you have this book. Personally I think this is an amazing book that you should have in your library.

So what is an anti pattern? And why should we care?

I will be taking some part from this book,

The term anti-patterns was coined in 1995 by Andrew Koenig in the November C++ Report that year, inspired by the GoF’s book Design Patterns. In Koenig’s report, there are two notions of anti-patterns that are presented. Anti-Patterns:

  1. Describe abad solution to a particular problem which resulted in a bad situation occurring
  2. Describe how to get out of said situation and how to go from there to a good solution

To summarize, an anti-pattern is a bad design that is worthy of documenting.

Examples of anti-patterns in JavaScript are the following,

  1. Polluting the global namespace by defining a large number of variables in the global context
  2. Passing strings rather than functions to either setTimeout or setInterval as this triggers the use of eval() internally.
  3. Modifying the Object class prototype (this is a particularly bad anti-pattern)
  4. Using JavaScript in an inline form as this is inflexible
  5. The use of document.write where native DOM alternatives such as document.createElement are more appropriate

If you know what above means, you must have started rewriting your javascript code now.
What if you asked yourself how you can solve the above problems, there’s no answer than rewriting your code. But how would you like to write your code. Without proper guidance you might write the same code again. So when I deal with my subordinates, I have a little principle that is to be a leader not a preacher. That is set an example yourself, rather preaching. That may be working because I am a code lover. Somehow my point is that you should always try to show/be an example,

Lets get back to business right…

Point 1
If I tell you the answer in a nut shell, then its “use Module Pattern”
Actually there are a bunch of patterns you can use, but this pattern gives you a very neat code in the end. Hope you are aware about that in javascript the functions and classes are same. According to this pattern you can move all of your public variables to a class and access them from another class. And you don’t have to worry about the scope anymore. See the below example.

var myclass = (function(){
   var index = 0;
   var func1 = function(param1){
      param1 = index + param1;

   return {
      myfunc1: function(param1){
         return func1(param1);

“myclass” variable is actually representing the above mention class. And that class have a public function/method called “myfunc1” which accept a parameter “param1”. Function “func1” is not been exposed to the outside, its a private method. Sometimes you might have seen the use of “this” keyword to expose public functions. But this pattern is very neat. In the class level “return” keyword is the place that defines the public functions. Inside each call it decide what private functions should be called. You can have your own library set rather writing page level javascript codes.
How you access these method is given below.

myclass.myfunc1(1); --> alert(1);
myclass.myfunc1(2); --> alert(3);
myclass.myfunc1(3); --> alert(5);

I think this clears up any confusions in how you should write your code to avoid having too many global variables.

Point 2
This is pretty forward, as the above statement itself clears how you should do it. But for those who still struggle how to write this, I will explain using some code.


Above code might work, but its not the best. This has many limitations, that you can’t pass parameters, and when it executes first it do a eval over the string etc…
Look at the below code, which is correct in this case.

} ,1000);

How about using a setInterval. For new coders, the differences between the setTimeout and setInterval, is setTimeout gets called only once after the specified time, but the setInterval will call the function specified, by the given time interval. Such as if we consider the above sample, if its been used by setInterval, then myfunc() method will get called in every second. And you will use clearInterval(x) to stop it.

var index = 0;
var x = setInterval(function(){
   if (index == 11) {
}, 1000);

Good practice:

  • Every-time when you write a setInterval code make sure to get the reference. See above sample code, I have assigned the reference to the “x” variable.
  • Without clearing the previous reference, do not use the same variable to assign for another setInterval. This will create memory leaks in the client browser, as you are releasing the reference of a living code while it still executes. See below example.

var index = 0;
function process(){
   if (index == 10) {
      index = 21;
      x = setInterval(function(){ index--;process(); },1000); //using the same variable
var x = setInterval(function(){
}, 1000);

Point 3
Personally I have not tend to change the object class prototype. So I prefer to avoid this section. Well of course you can use jQuery extenders instead of this. If somebody knows better in this subject please enlighten me.

Point 4
Using javascript inline always screw up your code without your knowledge. Because remember that even the little script tag that you initialize is added to the scripts at global level of the page. So you even can access global variables defined in some other script file, within your script tag section. Watch out for script errors and overriding global variables unintentionally.

Point 5
document.write() can be used to testing purposes or in tutorials. But in real world applications its always wise to use document.createElement(), because this is faster and reliable. Plus document.write can lead to clearing the whole html in your page, and you don’t have much control over what you write.
FYI: after using document.createElement(), you can use some element.appendChild() to get the new element rendered to the page.

I guess that’s all for this post. Hope this will be useful to someone.

Destiny is a globally defined variable, God has forgotten to use Module pattern when writing the worldcreation() class. Otherwise createHumen(isMen) function would have its own Destiny. But if you want you can own it, don’t wait till some one else does it for you. Said By… m3

My life

Welcome to my blog. I am Chinthana Jayawardena. A Technical Consultant in a software firm.

Blogging is something really cool, that allows us to share our thoughts, day to day problems and solutions etc… I do think internet has been the leader to bring innovations to the world. That is in the aspect of allowing a place to share ideas. Therefore more people get to know lot of experience that they never had by reading other people blogs. Actually blogs have saved my day because of some bloggers. I must say that everybody should start sharing to build a better world tomorrow.

In the end all these thoughts running in someones mind suddenly blast into a new innovative idea.

Now what I would like to cover in my blog is the problems that I counter day to day, or my team members, that is worth sharing.

Technology wise I am open to all. But my majors are,

  1. Microsoft technologies .NET, ASP.NET/ C#/ MVC, entity framework/Azure
  2. SpringFramework for .net
  3. nHibernate
  4. Javascript/jQuery
  5. HTML5/CSS3
  6. Deployment packages experience with Windows 2008 server, Azure servers

New applications trend has gone to UI Rich applications. Therefore we have a great challenge, and demanding requirement which everybody ask that is a cohesive model that give best performance with UI Rich experience.

My blogs will mostly focused in these matters. But of course I may give crash courses/tutorials kind a samples as time allows.

May god bless me and you and our families to do our duties to the world.

High five for the bloggers!

Solution for a common error "An error was encountered. Please return to the previous page and try again"

After some time I am back in web site coding. I think out of sight is out of mind is correct. Because I got into a very familiar error message, but forgot what I did back then. Anyway after some struggle I got over with it.

Above error message is a common error that throws when you try to access the Web Site Administration Tool. The reason behind is in the physical folder structure for your web application or web site is containing spaces in at least one of the folder names.

This error message is a very high level error message, so there may be other scenarios that it throws the same error message. I have no clue more than this.

My advice is to always keep your solutions path without spaces, you may use “_” or Camel-Case for folder naming.

I wish this information will be useful to someone.

How To Setup SSL in Azure Web Role

(Imported from my old blog

This is a problem I struggled for some days and I feel it’s worthwhile to share that knowledge among others. 

Can’t untie all knots at once, Lets go step by step.

First I would like to provide steps how you can setup SSL for a web site manually. There is no major difference in how you should setup SSL in Azure or in a normal web server. Except for the Azure deployment package needs to have instructions on how the SSL should be setup automatically (like a installation script). Because sometimes Azure servers get restarted due to maintenance requirements (such as OS upgrades), if you don’t have the correct instructions, then it will reset the manually configured settings in the server.

What is the first requirement to make a SSL web site?

You need to have a certificate issued by an authorized SSL provider to your domain name.
If you plan to have sub domain names then you should obtain a wild card SSL certificate.

How can you obtain a SSL certificate? 

Create Certificate Request

  1. Open IIS and select the Web Server node
  2. On the right side panel under IIS category you will find an icon with the name “Server Certificates”. Go to that feature.
  3. You will see if you have certificates in that section.
  4. Under the “Actions” panel, click on “Create Certificate Request” 
  5. Complete the fields, make sure your domain name is correctly filled in “Common Name” field.
  6. On “Next”, you need to provide Cryptographic Service Provider Properties.
  7. Now the minimum requirement of the bit length has increased by most of SSL providers to 2048.
  8. No need to change the provider, but pick 2048 bit-length.
  9. On “Next”, you can provide the file path, where the certificate request will be saved.
  10. Then press “Finish”
  11. The generated file must be send to the SSL provider.

Complete the Certificate Request

  1. The SSL provider will send you the certificate file once your organization is verified. Sometimes they send only the certificate string so you may have to copy and paste it into notepad and save it as a .cer file.
  2. You will have to go to IIS again. 
  3. Go to Server Certificates Feature -> Complete Certificate Request
  4. In that popup, browse and pick the file you just saved as .cer file.
  5. Give a friendly name to the certificate that will distinguish this certificate from other certificates installed in the server.
  6. Press Ok.

(You can find these steps in most of SSL providers’ web sites.)

Now you have the SSL certificate for your domain name and its been installed in the server. What’s left is to configure a HTTPS binding to your web site.That you can do in following steps,

  1. Select your web site node in the IIS
  2. Click on “Bindings” link under “Actions” panel
  3. Press “Add” button in the popup
  4. Pick the type as HTTPS
  5. Assign an IP Address
  6. Leave the port as 443
  7. Pick the certificate you just installed. It should be with your friendly name.
  8. Press “OK”
  9. If you want your site to work only under HTTPS, check “Require SSL” in the “SSL Settings” Feature under the web site node.

Ok!!! Then are we done with manual instructions for setting up SSL? That’s a big NO. The whole process of making your site to run under SSL is to give safeness for the users. If we try to validate the SSL for your domain name it will indicate that you are missing some intermediate certificates. So, what are we missing? These are the certificates which verifies your SSL provider. Sometimes you may find these SSL providers’ certificates are installed by default in your server. But I am referring to the scenario which does not have :-/.

You will have to go to the SSL providers web site to get these certificates. And installation instructions will be in their web site. Mostly those certificates are installed under the Local Computer ->Intermediate Certification Authorities
You can check certificate installation using certmgr tool. Or just typing “mmc” in Run command tool and adding the Certificates snap-in.
Remember there is another thing that you need to be aware of. That is these certificates can be revoked by the owner. If the SSL provider had certain certificates earlier that were been revoked lately, and now they have reissued those certificates. You will have to disable/remove all those old certificates from your certificate store.
Now I believe that you have successfully completed with setting up SSL manually.

Setup SSL in Azure package

Let’s see what you have to do in Azure, to have those instructions to be automatically configured.
You can find some information on “How to configure an SSL certificate on an HTTPs endpoint” in here “”
Usually the certificate issued for your domain name is installed in the Local Machine-> Personal folder in the Certificate Store.

To setup the Domain certificate for the Web Role.

  1. Open the WebRole settings page.
  2. Go to the Certificates tab.
  3. Press “Add Certificate” button
  4. In the new line just got added look for the Thumbprint column.
  5. By pressing the “…” button you will get a popup listing certificates installed in the Certificate Store for Local Machine in the Personal Folder.
  6. If the domain certificate does not exist in the list you will have to install or import it to that location. If not you will have to get the thumbprint from the certificate details tab and paste it here. (to get the thumbprint you can double click the cer file and go to the Details tab, it will list the thumbprint field)
  7. You will have to install your SSL providers’ certificates in your development environment under the Local Machine->Personal folder in the Certificate Store.
  8. Once all your certificates are installed in the Personal folder, you can get them in the popup.
  9. First certificate would be the domain certificate, select it from the popup.
  10. The thumbprint automatically gets populated
  11. “Store Location” shall be “Local Machine”
  12. “Store Name” shall be “My”
  13. Give a proper name as you like

To Setup the SSL Providers’ Certificates

  1. Repeat from step 3 to 5 of the above steps
  2. Select the certificate
  3. “Store Location” shall be “Local Machine”
  4. “Store Name” shall be “CA”
  5. Give a name for the certificate
  6. You may repeat the above steps if the provider have more certificates.

Now your web role is ready to install all certificates. But your certificate provider may have certificates that needs to be disabled/removed. 

CertUtil tool

How to use that? Use certutil command as follows in a Startup command file.  

certutil -v -delstore authroot

authroot – means the non-microsoft Root CAs.
Refer to this link given below for better understanding on certificate store folder names. You can check with the SSL Provider to figure out the folder name.

Now your package is ready for deployment. But if you try to deploy you will get an error stating that the certificates in the package are not available in azure. You will have to upload all the certificates into the Azure hosted service. In order to do that, you need to have the .PFX file of the certificate, and not the .CER file.You can always create the PFX file of the domain certificate using IIS where your domain certificate is created. Follow the steps given below,

  1. Go to IIS -> Server Certificates
  2. Select the domain certificate and click “Export”
  3. You will have to give a location for the file to be saved and a password for the file. Then press “OK”

How to create PFX files for the SSL Provider’s certificates.

There is a way to do that. But by using PowerShell ISE, the tool may reside in C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe (Similar to command prompt tool.)
This information is taken from here. You can refer to semicolonsandcurlybraces link for more information. Special thanks to them, it motivated me to do this blog.

Execute the following code to generate the PFX file, you may change the password as you wish.

$c = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2(“C:\SSL_CA.cer”)
$bytes = $c.Export(“Pfx”,”Password”)
[System.IO.File]::WriteAllBytes(“C:\SSL_CA.pfx”, $bytes)

Now you have PFX files for your certificates. Upload them to the Hosted Service you plan to deploy the package.

Few more points for your information,
If you are familiar with Azure, you may be aware of how the URL are being generated. All of them are sub domain of You will have to have a CName record pointing to the Azure production URL (Or else with IP address – an A record) with your domain name provider. So it may take a while to propagate IP address changes. If you are trying to verify the SSL Certificate installation is correct, there are tools available from Verisigndigicert and there may be more if you can search for it. 

Thanks for reading. I believe this will help someone.