2012-06-19

How to access session variables from App_Code folder

You can use the below code to access session values within a class inside a App Code folder

System.Web.SessionState.HttpSessionState session = HttpContext.Current.Session;
session["key"] = "test";

Note: From Visual Studio 2010, App_Code folder will not be available for a web application project by default. But you can still create a new folder named App_Code and it will just work fine.

2012-06-18

Dynamically add a reference to a css file

Have a <link> tag in your aspx page

<link id="CSSFile" type="text/css" rel="Stylesheet" runat="server" />

And add the href attribute for the link tag from code behind, like below

protected void Page_Init(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
         CSSFile.Attributes.Add("href", "Dynamic.css");
    }
}

The reason I do this on Page_Init method is Page_Init would be the better place to place this kind of code since Page_Init() method fires before Page_Load event. Page_Init() is usually what we use to do the initialization steps. Page_Init() method fires only the first time the page is loaded. It will NOT fire everytime when there is a postback.

2012-06-16

Reset Visual Studio user settings

If you need to restore default settings for your Visual Studio IDE, you can do the following

Open Visual Studio Command Prompt and enter the following command.

>devenv /ResetSettings

If you need to load the settings from a specific .vssettings file, you can use the below command

>devenv /ResetSettings SettingsFileName.vssettings

So now it will set the settings specified in the .vssettings file.

2012-06-15

How to play a background music continuously while browsing through the website

When you set the background music for a webpage, it will get restart once the page post backs. If you need the background music to be play continuously even though the page post backs, you have two options.

1. Play the background music in a different window. You can achieve this by having a popup playing the background music once the user enter to the website. This is not a good option because it will require two windows for a one website. And this will not work if the user has disabled the popups in their browser.

2. Other option is by using iframes. Load the background music into a one iframe and make it consistent across pages. Have a seperate iframe to load the site pages. So the iframe which contains the background music won't get reloaded when there is a postback.

Having said that, background music is not very handy when it comes to user experience. It’s a really annoying thing. Background music sucks big time specially when there is no way to stop it! Just think, what if your users open the website while they are at a hospital etc.?

How to set/retrieve/remove cookies from C#

To set Cookies, use the following code.

HttpCookie cookie = new HttpCookie("CookieName");
cookie["CookieName"] = Your_value_here;
cookie.Expires = DateTime.Now.AddDays(90d); //It will set the cookie for about 3 months.
Response.Cookies.Add(cookie);

To get the Cookies,

string cookieValue;
if (HttpContext.Current.Request.Cookies["CookieName"] != null)
cookieValue = HttpContext.Current.Request.Cookies["CookieName"];

To clear the Cookies,

HttpContext.Current.Response.Cookies["CookieName"].Expires = DateTime.Now.AddDays(-1d);

2012-06-11

How to avoid a web page from being cached in ASP.net

You can add the below code to the Page_Load() method of the page

Response.ExpiresAbsolute=DateTime.Now.AddDays(-1d);
Response.Expires =-1500;
Response.CacheControl = "no-cache";

Now let’s take a look at each of the line and what exactly they do

1. Response.ExpiresAbsolute=DateTime.Now.AddDays(-1d);

Response.ExpiresAbsolute specify when the page cache is going to be expired. By adding -1d, we are ensuring that it's always expired since we are referring to a date in the past.

2. Response.Expires

Response.Expires specifies the duration of time before a page that is cached on a browser expires. So by assigning a large negative number, it will always ensure that it expires immediatly after. Actually there is no need to specify both Response.ExpiresAbsolute and Response.Expires since which ever you define last will override the other.

3. Response.CacheControl = "no-cache";

The above line will tell browser to not to cache the page.

As far as I know, the above no caching mechanism works for many browsers.

How to check whether popups are disabled on client browser

Sometimes we use popups in our application. But what if popups are disabled on the client browser? Then it’s possible that your entire application would fail. By using the below code snippet, you can check whether client browser has disabled popups so you can implement an alternative way if popups are disabled.

var myWindow=window.open('http://ruchirac.blogpost.com');
if (myWindow== null || typeof(myWindow)=='undefined') {
  alert('Popups are disabled');
}

2012-06-08

Remove dotted border from HTML elements

The dotted border is a browser things. However, you can set outline and border properties to none as below so there will be no dotted border around the selected/focused element.

.test{ 
outline:none; 
border:none; 
}

<asp:ImageButton ID="ImageButton1" runat="server" OnClick="ImageButton1_Click" ImageUrl="~/Images/Image1.png" CssClass="test" />

2012-06-07

Difference between string equality and object equality

I’ll try to explain this with an example. Let’s say we have the following code

string a = "MyName";
string b = "MyName";

object aa = "MyName";
object bb = "MyName";

Response.Write(a == b);
Response.Write(aa == bb);

If you see the result, you can see that the first response displays true and second response displays false.

To understand this correctly, you need to have to have a knowledge about how string variables save in the heap. When you create string literals, there are creating several strings in the string pool. So from this code, you are creating four different string literals.

In the following line,

Response.Write(a == b);

It’s comparing the actual value. Since the value containing in variables a and b are same, it will return true.

In the following line,

Response.Write(aa == bb);

It’s comparing two objects, which is looking whether both aa and bb refers to the same object. As I said, aa and bb now refers to two different string literals in string pool. So it will return false.

If you want to compare the content of the object, you have to override the Object class’s Equal method.

2012-06-05

How to change the default arrow image in asp:Menu

You can change the arrow image and use a custom image as below.

<asp:Menu ID="menuID" Runat="server" StaticPopOutImageUrl="~/images/downArrow.png" DynamicPopOutImageUrl="~/images/downArrow.png">

window.close() does not work in Firefox

In your firefox window, enter about:config (It will warn you, click I'll be carefull I promise button and proceed.) and see whether following line is set to false.

allow_scripts_to_close_windows

Entering the above value in the Filter box and will show it. If it's set to false, there is nothing you can do with the javascript. Set it to true will fix it on your browser but it won't affect for client browser. It's a browser setting. However, just double click on the value and you will see it's getting change to the true and it will bold out.

Now try again the window.close() method. Now it will work on Firefox.

Check whether browser is IE or not

Use the following javasript for that. Here is an example code

<html>
<head>

<script>

function DetectBrowser()
{
  var val = navigator.userAgent.toLowerCase();
  if(val.indexOf("msie") > -1)
  {
   alert("Good! You are using IE!");
  }
  else
  {
   alert("Please use IE");
  }
}

</script>

</head>
<body onload="DetectBrowser()">
</body>
</html>

Publish and deploy an asp.net application in IIS

You can simply publish your web application to the File System and copy paste all the files to your server. Then from IIS, you can add a new website. If you are not sure what files you should include, it's better to choose 'All files in the project' from the Package/Publish Web. Otherwise choose 'Only files needed to run this application'. You can set this by right clicking on the web application in the solution explorer and choosing 'Package/Publish Settings'.

IC452454

Right click on your project in the solution explorer and choose 'Publish'. From the dialog box, as the publish method, choose 'File System'. And choose some directory as the Target Location.

PublishToFileSystem_cd6550ea-8b67-4ef2-a4a8-21b05066da5b

You can add the website by right clicking on the 'Sites' in IIS.

CreateNewSite

Then give a name to your site and select the Physical path from where you copied the site folder

IIS7-Add-Web-Site

2012-06-01

Resize an iframe according to the content height

Here is how you can resize the iframe height dynamically according to the web page height which is loaded inside the iframe.

Place the following method within the web page which contains the iframe

function resizeiFrame(newHeight)
{
    var Tab1_ = document.getElementById('frame');
    Tab1_.height = newHeight;
}

And on the page, which you wish to load inside the iframe, add the below method so it will call the above method

<body onload="parent.resizeiFrame(document.body.scrollHeight)">

How to rollback a SQL transaction if it fails at some point

Sometimes we write SQL stored procedures with more than one SQL statements within it. For example, let’s say we have a stored procedure which do both an insert and update operation. In order to perceive the consistent of data, we need both statements to be successful. Otherwise, we don’t need to perform both if at least one of them fails. So we need to rollback the whole transaction if any of the statement fails. Following is what you can do.

Place the Stored Procedure inside a Try block. And at catch block, roll back the transaction.

BEGIN TRY
        Your stored procedure implementation here
END TRY

BEGIN CATCH
        If @@Trancount > 0 Rollback Transaction
END CATCH

Tips for creating a user friendly Search box in websites

There are no exact set of rules for creating a search box for a website. But it’s always better if you adhere to the web conventions, when you design the search box so it will increase the user experience of your website. Following is a set of tips to create a good search box.

1. First of all, it needs to be a box.

2. Do not use multiline textbox.

3. Fire the search event when user is focusing the search box and press enter.

4. At the right hand corner, add an image of a magnificant glass and allow users to search when click on that ImageButton.

5. Add a watermark text inside the textbox saying what you can search. Make it dissapear onFocus and make it reappear onBlur