2012-05-31

Add a confirm box when user leaves the web page

You can use the following javascript to alert the user when s/he leaves the page.

<script type="text/javascript">
    window.onbeforeunload = prompt;
    function prompt() {
        return "Do you want to leave the page?";
    }
</script>

If the user press cancel, user can stay on the same page.

Protecting e-mail address from bots

Write the e-mail address in following format

emailid(at)domainname(dot)com

Bot is looking for @ sign and . sign to recognise e-mail address. If you didn't include those symbols in your e-mail address, bot has no way to know it's an e-mail address or not. But believe me, Nowaday bots are really smart!  So you cannot completely get rid of the problem. But this will take down number of spams you are getting dramatically.

How to open and close an application in the server from code

You can use the below code snippet. Kill() method to stop the process and Start method to start the application. But remember it will open the application in the server. Not in the client side.

using System.Diagnostics;

int _processID;

private void button1_Click(object sender, System.EventArgs e) {
Process p = Process.Start("program.exe");
_processID = p.Id;
}

private void button2_Click(object sender, System.EventArgs e) {
foreach (Process proc in Process.GetProcesses()) {
if (proc.Id == _processID) {
proc.Kill();
}
}
}

Round double values to the nearest value in C#

If you want to round to the nearest upper perfect number, use the following code.

double a = Math.Ceiling(551425.451078772);

If you want to round to the nearest lower perfect number, use the following code.

double a = Math.Floor(551425.451078772);

Math.Ceiling method will always return the smallest integer which is greater than the provided double value. Math.Floor method will always return the largest integer which is lower than the provided double value. But both function will return the integer value as 'double' type. So you have to assign it to a double type variable.

Set a webpage as Home page using javascripts

You can use the below code to set a particular page as the home page in a web browser.

<INPUT TYPE="button" VALUE="Set as homepage" onClick="this.style.behavior='url(#default#homepage)'; this.setHomePage('Page URL beginning with http:// here');">

The problem with the above code is, it will not work in Firefox if you have set the signed.applets.codebase_principal_support to false. In that case, use the following code.

function setHome()
  {
    if (document.all)
    {
     document.body.style.behavior=’url(#default#homepage)’;
     document.body.setHomePage(’
http://url_of_page.com’);

    }
    else if (window.sidebar)
     {
         if(window.netscape)
         {
          try
          {
          netscape.security.PrivilegeManager.enablePrivilege(”UniversalXPConnect”);
          }
       catch(e)
      {
    alert(”this action was aviod by your browser,if you want to enable,please enter  about:config in your address line,and change the value of     signed.applets.codebase_principal_support to true”);
}
}
var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components. interfaces.nsIPrefBranch);
prefs.setCharPref(’browser.startup.homepage’,’
http://url_of_page.com’);
}
}

Call the setHome() function on click of the button or link

2012-05-29

How to read the value from a disabled textbox

There is actually no way to read the value from a disabled or hidden textbox from server side. But sometimes we need to prevent users from entering values to a textbox after some condition but access the already provided textbox value from the server side. For that, we can set the readonly property of the textbox to true. Setting it to true will not prevent server side from accessing it. It will just prevent end users from entering value to the textbox.

As for example, you can set it to readonly mode with following javascript code snippet.

document.getElementById(textboxID).readOnly = true;

Now you can access that textbox from server side even though it prevent end users from entering values.

Permanently remove underline of hyperlinks

It’s never been a good idea to remove hyperlink underline because of user experience issues. But if you really need it, you can do it easily by using the following CSS styles.

a
{
text-decoration: none;
}

a:hover
{
text-decoration: none;
}

Fire a button event when press the Enter key

Use asp:Panel to enclose all the controls and define a DefaultButton (The button ID you want to fire when the user press 'Enter' key.)

<asp:Panel runat="server" DefaultButton="btn2">
    <asp:TextBox ID="1" runat="server"></asp:TextBox>
    <asp:Button ID="btn1" runat="server"  OnClick="btn1_Click" />
    <asp:Button ID="btn2" runat="server"  OnClick="btn2_Click" />
    <asp:Button ID="btn3" runat="server"  OnClick="btn3_Click" />
</asp:Panel>

In the above example, btn2_Click event would fire when the user press Enter key.

Access all elements in a page and set an attribute/style for all of them

Here is how you can get all the elements in a page and apply an attribute/style for all of them using javascripts. Here, as for the example, I’ll change the background color of all elements. Following is the complete code for that. I will explain one by one after that.

<script>
window.onload=function test()
{
var all = document.getElementsByTagName('*');

for(var i=0;i<all.length;i++)
{
all[i].style.backgroundColor = "Red";
}
}
</script>

I’m calling the above function on window.onload event, so it will get called automatically when the page loads.

document.getElementsByTagName('*');

Above line returns a collection of HTML elements. For the tag name, I’ve passed * (Which is the wildcard character for ‘all’) so it will return all the HTML elements within the page.

for(var i=0;i<all.length;i++)
{
all[i].style.backgroundColor = "Red";
}
}

Then I’m going through that collection accessing each element and applying the style for each of them. Here I’m changing the background color of each element. Not only the style, you can change/get/set any property you would like.

Force browser to download the file instead of opening it in the browser

Sometimes files such as images, videos, textfiles, XML files etc. are getting open in the browser window, when we give the download link directly to the file. To avoid that behavior and to force browser to download the file to the user’s computer when user clicks on the download link/button, we can use the below code on the button click event.

FileInfo fileInfo = new FileInfo("file_path_here");
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.Flush();
Response.WriteFile(fileInfo.FullName);
Response.End();

Select only unique records from SQL DB table

You can use the below SQL query to get only unique records from a table.

SELECT DISTINCT * FROM table_name

Changing the color of HTML un ordered list.

It’s a hot topic among web developers that is it possible to change the color of HTML bulletin list? Well, as many says, it’s impossible, there is a very simple way to deal with it. Following is the full code to change the size and change the color.

<ul style="font-size:20px">
<li style="color:Red" ><span style="color:Black; font-size:12px">1</span></li>
</ul>

Let’s see one by one what exactly the code do.

<ul style="font-size:20px">

By setting the font-size for the whole list you can change the size of the bullet. It applies for both text and the bullet. So later, we have to include the text within a span tag and define the style for the text itself.

<li style="color:Red" >

By setting the color, you can specify what color the bullet should take.

<span style="color:Black; font-size:12px">

Since the color and font-size applies for the text also, you need to include the text within span tags to separate it from the bullets so you can specify a separate style for the text.

I tested it with latest FF, IE and Chrome web browsers and it works like a charm!

Custom error page loading inside an iframe

Hello all,

When we use Custom error pages in our website, and when we load our pages inside iframes, if an error occurs the custom error page loads inside that iframe. Sometimes it breakups the site uniformity and there are times we need to display the custom error page as it is (Not load it inside the iframe). There is an easy way to do this. By having the following javascript/jQuery code within the custom error page head section, it will check whether it’s loading inside an iframe. If it’s loading inside an iframe, then the custom error page will set as the top page.

<script>

        $(function () {

            if (window != window.top) { //Checks whether the custom error page is loading inside an iframe

                window.top.location = window.location; //Set the top location to custom error page location

            }

        });

</script>