2012-12-07

Redirect the user to login page when session timeouts

If the webpage’s session expirers due to the idle state, you may need to redirect the user to login page/default page to prevent unexpected errors/results. Easiest way to handle this is on the Session_Start event of the global.asax file. Whenever a new session starts, the Session_Start event get fired. Whenever the current session timeouts, a new session will get started. In other words, Session_Start even in the global.asax file will get fires whenever the session expires. So add the below code in global.asax file

void Session_Start(object sender, EventArgs e)
{
     // Code that runs when a new session is started
     Response.Redirect("~/Login.aspx");
}

The above code will redirect the user to Login page whenever a session timeouts. So you don’t have to worry about checking whether a session is null or not before proceed.

2012-11-29

Visual Studio 2012 Update 1 is available now!

Microsoft released the first update for Visual Studio 2012 yesterday (26th of November, 2012). It’s an early. Visual Studio 2012 released in September and it’s about after two month that they have release the Update. Nevertheless the Update seems really great and fixed many of the bugs in Visual Studio 2012. Specially, they have improved the Unit testing in Visual Studio 2012. I’ve seen most of the users are unhappy with the new UI of the Visual Studio. Most of them had submitted their ideas saying add more colors to the UI etc. through Connect and UserVoice websites. However, the UI remain unchanged in the Update 1. Hopefully, their second update will address it Smile

You can see what’s new in Visual Studio 2012 Update 1 from their official page,

http://www.microsoft.com/visualstudio/eng/visual-studio-update#story-update-1

You can download it from the below link

http://www.microsoft.com/visualstudio/eng/downloads#d-visual-studio-2012-update

For offline installation, you can follow the below steps

  1. Download the installer from the above link.
  2. Open command prompt by typing ‘cmd’ in Run (CTRL+R).
  3. Go the directory where you downloaded the installer.
  4. Type ‘vsupdate_KB2707250.exe /layout’ and press Enter key.
  5. Now this will launch the installer with a option where you can specify the download directory (Otherwise it will download the update to a temporary directory).
  6. Specify the download location and click ‘Download’
  7. Now the installer will download the relevant files to the download location (To a folder called ‘packages’) and install it from there.
  8. Later, you can go to the download folder and get the offline version of the Visual Studio 2012 Update 1 from there.

If you need to install it, just copy and paste the ‘packages’ folder along with the installation file to the offline machine. Make sure you have the installation file in the same directory as ‘packages’. Just double click on the installation file and now it will install the Update from the downloaded ‘packages’ folder instead of downloading it over the internet.

Finally, after you install it, you can see whether Update 1 has been correctly installed or not by going to the Visual Studio and click Help –> About. In the dialog box, you can see on the top left hand side, the version is listed as Version 11.0.51106.01 Update1 if the Update 1 has been successfully installed.

The Update will work for every edition of Visual Studio 2012 (Express, Premium, Ultimate, Professional)

Great job VS team and thank you!

2012-11-26

Sri Lanka .NET forum monthly user group meeting – November 2012

I’m glad to say that I’ve successfully delivered a session at Microsoft Sri Lanka for the November .NET forum user group meeting. Session duration was 45 minutes. Thank you all the people who have helped me for that and who have encouraged me by words! Special thanks for the organizers and thank you all for coming. :)

Topic – Common Sense Web Designing

Date – 01st November 2012

You can get the presentation slides from the below link,

https://skydrive.live.com/redir?resid=56E5E527D356065A!112

Following are some of the photos taken at the Session.

IMG_0133 IMG_0134

IMG_0135 IMG_0139

2012-10-26

Configure log4net with asp.net (Logging with asp.net)

Logging is a very important thing for a web site specially if the website is on live! It will help you to debug your live web application without needing to enable remote debug on the server, so it comes very handy when you need to log the errors which can occur at the live site, when users are using it.
So here I’m going to explain how to configure log4net with a website built on asp.net.

1. Download the log4net dll file from here.
2. Add the log4net.dll file to your project
3. Add reference to the log4net.dll file in your project.
4. Add the below section at the top of your web.config file (right after you open the <configuration> section).
<configSections>     
      <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/> 
</configSections>
5. Add the below section to your web.config file within the <configuration> section.
<log4net>
   <root>
     <level value="Debug"/>
     <appender-ref ref="LogFileAppender"/>
   </root>
   <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
     <param name="File" value="C:\CentralCMS_Logs\Logs.txt"/>
     <param name="AppendToFile" value="true"/>
     <rollingStyle value="Size"/>
     <maxSizeRollBackups value="10"/>
     <maximumFileSize value="3MB"/>
     <staticLogFileName value="true"/>
     <layout type="log4net.Layout.PatternLayout">
       <param name="ConversionPattern" value="%date [%thread] %-5level %logger - %message%newline"/>
     </layout>
   </appender>
   <logger name="CentralCMS">
     <level value="DEBUG"/>
   </logger>
 </log4net>
  • I’ve defined the level as ‘Debug’ since I just need to debug my application. If you need to stop the application or need something like that when an error occurs, you should go for a level like ‘Fatal’.
  • I’ve used appender type as log4net.Appender.RollingFileAppender. So it will roll the log files based on rollingStyle. In this example, ‘Size’.
  • Here, you can set the path where you need log files to be saved by specifying the parameter name ‘File’. In this example, I’m storing them on the directory CentralCMS_Logs in C drive. If there is no directory like that, your program will automatically create a folder.
  • Set ‘AppendToFile’ parameter to ‘true’ if you need the new logs to be appended to the existing log file. If you need to override the old logs with new log, set it to ‘false’.
  • Here I’ve set rollingStyle to the ‘Size’, which means it will roll the file once the maximum File Size reaches. The default value for the rollingStyle is ‘Composite’, which means it will roll the file both depending on the file size and the date. If it reached the maximum file size before the day ends, it will go for a new file. If not, it will open a new file on next day.
  • Here I’ve defined maxSizeRollBackups as 10, which means it will create 10 backup files before the oldest one is erased. Once it reach for 10 files, it will delete the oldest log file and create a new file.
  • As the name suggests, maximumFileSize is the maximum file size for a log file. It will go for a new file when the maximum file size reaches. If the rollingStyle is set to ‘Date’, then it will not log further logs if the maximum file size reaches before the end of the day.
  • I’ve set staticLogFileName to ‘true’ since I want to log on the same file. If you need separate file for each log, set it to false.
  • I’ve set layout type to PatternLayout because I need my own pattern for the log texts. Through the ConversionPattern parameter, I’ve specified my own format for the log texts. I.e.
    • %date - Date and time followed by,
    • [%thread] - thread number which generated the log event followed by,
    • %-5level - level of the logging event (Right pad with spaces if the level of the logging event is less than 5 characters long) followed by,
    • %logger – the logger of the logging event (Global file, Default file etc. with the namespace) followed by,
    • %message – log message followed by,
    • %newline – a new line.
6. In your Global.asax file, import the log4net class like this
using log4net;
7. Configure log4net at the Application_Start() method like this
void Application_Start(object sender, EventArgs e) {
      // Code that runs on application startup
      log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));
 }
8. To use the logging, initiate a global variable like below in your class where you need to log the information. Note that I’ve passed the logger name I’ve given in the web.config file to the GetLogger() method. It will return a ILog object which you can use to do the logging.
private static readonly ILog log = LogManager.GetLogger("CentralCMS");
In my example, I’m showing how to log all the unhandled exceptions you are getting for your web application. So I’m going to declare this variable in the Global.asax file.
9. Now you can successfully use the log4net for logging. By doing the logging on the Application_Error() method, we can get all the unhandled exceptions like below
void Application_Error(object sender, EventArgs e) {
      Exception ex = Server.GetLastError();
      log.Debug("++++++++++++++++++++++++++++");
      log.Error("Exception - \n" + ex);
      log.Debug("++++++++++++++++++++++++++++");
 }

2012-10-19

How to un bind an event from a HTML element

Sometimes we need to stop an event being fired. We can remove/unbind that particular event with the use of removeEventListener method in JavaScript.

For an example, let’s say we need to unbind the function named ‘test’ from the event ‘onkeypress’ event. Then we can use the removeEventListener method as follows,

HTML code

<input type=”text” onkeypress=”test();” id=”textboxID” />

JavaScript code

function test()
{
  // Some code here
}

function removeEvent()
{
  var elementObject = document.getElementById(“textboxID”);
  elementObject.removeEventListener("onkeypress", test);
}

Here the elementObject is the object which has the event.

How to make word-wrap work for asp:Label

word-wrap CSS3 property won't work for inline elements. asp:Label is getting rendered as span in the browser. Spans are inline elements. So we have to specifically set the span to an inline-block behavior to get the word-wrap property to work with asp:Labels.

.test{
width:20px;
word-wrap:break-word;
display:inline-block
}

The above CSS class demonstrate of an example of how to properly set word-wrap for an asp:Label.

Unrecognized tag prefix or device filter 'asp' error

Sometimes we are getting the Unrecognized tag prefix or device filter 'asp'. warning message and intellisense will also not work for asp.net controls. There could be two reasons for this kind of behavior.

  1. Because of a wrong Page directive. If that’s the case, you can check the Page directive at the top of the page and correct it.
  2. Failure of generating correct Reflected Schemas. If that’s the case, first thing you can try is restart the PC and open the Visual Studio so it will regenerate the schemas. Or delete the schemas manually by going to the below path.

C:\Documents and Settings\[Username]\Application Data\Microsoft\VisualStudio\10.0\ReflectedSchemas

How to make HTML5 work in old browsers

First of all, I need to tell that only the latest versions of browsers support HTML5. If the browser doesn't support HTML5 then you don't really have any choice. It's an internal thing of the browser. You cannot force it to load HTML5.

Being said that, there are some ‘tricks’ we can do to replace HTML5 features with alternatives. Modernizr is such a library which can detect the HTML5 and CSS3 capability of the browser. It does not make browser works for HTML5 or CSS3. You have to detect the features browser supports and write alternatives for the features it does not support. Modernizr is just a library  which tells you whether a particular feature is available in the browser or not.

With the use of html5shiv we can add basic support for HTML5 in IE. html5shiv is only working in IE and it only allow styling of HTML5. It will not recognize tags such as <audio>, <video>.

2012-09-21

Automatically logged in on one site when logged in from another site

Have you ever encountered with a situation where you develop two separate websites in asp.net, using Forms authentication and once you logged in from a one website, your second website (Which runs completely separate from the first website) automatically logged in???

Well, that usually happens if you use the same name for the forms tag in web.config file

<authentication mode="Forms">
   <forms name="test" />
</authentication>

The name “test” is the cookie name used for the authentication. If it’s same for both websites, it’s likely sharing the same authentication cookie hence your second website automatically logged in the user when (s)he use the same browser.

What you have to do to get rid of this is, simply specify different names for the forms tag for each website.

Run a process as the admin of the server

Some programs require to run as administrator in order to work properly. We can use the Process class in asp.net to run a process in server. The below example code shows, how to pass credentials to start the process when we use the Process class to start a process.

string returnvalue = string.Empty;

ProcessStartInfo info = new ProcessStartInfo(fileName);
info.UseShellExecute = false;

info.Arguments = args;
info.RedirectStandardOutput = true;
info.CreateNoWindow = true;

string passwordStr = "PasswordHere";

SecureString password = new SecureString();

foreach (char c in passwordStr)
   password.AppendChar(c);

info.Password = password;
info.UserName = "Administrator";

using (Process process = Process.Start(info))
{
     StreamReader sr = process.StandardOutput;
     returnvalue = sr.ReadToEnd();
}

We have to pass the Password as a SecureString. So, first we have to convert the string value to a SecureString by passing each character through a loop and append each to the SecureString. ProcessStartInfo class has the properties “UserName” and “Password” which we are setting to start the process with the given credentials.

2012-09-20

Highlight a date range in asp:Calender

Sometimes we need to highlight a selected date range in asp:Calender control. Here is how it’s done.

ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">

</head>
<body>
    <form id="form1" runat="server">
    <asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>
    </form>
</body>
</html>

We get the difference as a TimeSpan and highlight the dates one by one by going through a loop. In this example I’m highlighting the dates from 2012/08/11 to today’s date.

Code behind (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DateTime startDate = Convert.ToDateTime("2012/08/11");
            DateTime endDate = DateTime.Now;
            TimeSpan difference = endDate.Date - startDate.Date;

            Calendar1.SelectedDates.Clear(); //Clear previously selected dates, if any
            for (int i = 0; i <= difference.Days; i++)
                Calendar1.SelectedDates.Add(startDate.AddDays(i)); //Highlight the dates
        }
    }
}

Use AJAX ModalPopup to block the UI while a postback

It’s a nice user experience if we can display a “Please wait” or a “Loading..” message while our website is processing the user request or a file upload etc. It’s even nicer if we can prevent the user from using website until the postback finishes. We can make use of ModalPopupExtender in the AJAX toolkit for achieve this kind of thing. Following is a short example for this. To make it simpler, I will include only the relevant parts of the code.

ASPX code snippet.

<asp:Button runat="server" Text="Send" CssClass="input-button"
OnClick="btn_Click" Width="167px" OnClientClick="showProgress();" />

<ajaxToolkit:ModalPopupExtender ID="mdlPopup" runat="server" TargetControlID="pnlPopup"
PopupControlID="pnlPopup" BackgroundCssClass="modalBackground" />
    <asp:Panel ID="pnlPopup" runat="server" CssClass="updateProgress">
        <div id="imageDiv">
            <div style="float: left; margin: 9px">
                <img src="Resources/Images/ajax-loader.gif" width="32px" height="32px" /></div>
            <div style="padding-top: 17.5px; font-family: Arial,Helvetica,sans-serif; font-size: 12px;">
                Sending file. Please wait...
            </div>
        </div>
    </asp:Panel>

And the jQuery would be like this

<script type="text/javascript">
    function showProgress() {
        $find('mdlPopup').show();
    }
</script>

On the button click, I’m calling the showProgress() method which shows the ModalPopupExtender. Since I’m calling it OnClientClick event, it fires the modalpopup just before a postback occurs.

We can define the CSS class for the Background from the BackgroundCssClass property of the ajaxToolkit:ModalPopupExtender. Usually we use a grayed out background and make it transparent to show that UI is blocked. We can use the below CSS class for that.

.modalBackground
{
    background-color: Gray;
    filter: alpha(opacity=60);
    opacity: 0.60;
}

The asp:Panel is the part where we show the loading message and the activity indicator. I used a simple gif image here and a text saying “Sending file. Please wait…”. To make that part prominent from the popup background, I’ve applied a different background color for the panel. Following is the CSS class for that

.updateProgress
{
    border-width: 5px;
    border-style: solid;
    background-color: #FFFFFF;
    position: absolute;
    height: 50px;
    width: 290px;
}

Once the postback finished, the page is reloading so the ModalPopup will again reset to it’s initial state (hidden).

Get name of the user account which the website runs under in the server

When you host your website in IIS, it runs under a different user account. It’s not the same account as you host it. To get the user account name which the website runs under, we can use the below code.

Response.Write(WindowsIdentity.GetCurrent().Name);

We have to import the below namespace in order to use the above code

using System.Security.Principal;

C# and PHP database connection code comparison

Here, I’m trying to provide the equivalent DB connectivity code in C# and PHP. Let’s say the PHP code is as below,

<?php

mysql_connect('server.url.goes.here.com', 'username_goes_here', 'password_goes_here');
mysql_select_db('db_name_goes_here');

$q = 'SELECT * FROM myTable';
$r = mysql_query($q);

while (mysql_fetch_object($r)) {
        // do stuff
}

?>

The equivalent C# code would be like below

SqlConnection connection;
SqlDataReader r;

try
{
string connectionString = @ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
connection = new SqlConnection(connectionString);
connection.Open();
string q = "SELECT * FROM myTable";

SqlCommand sqlComm = new SqlCommand(q, connection);
r = sqlComm.ExecuteReader();

while (r.Read()) {
    //do stuff
}
}
catch(Exception)
{}
finally
{
  r.Close();
  connection.Close();
}

To make it easier to understand, I will take chunk by chunk from the code of both languages and try to explain.

 

PHP code:

mysql_connect('server.url.goes.here.com', 'username_goes_here', 'password_goes_here');
mysql_select_db('db_name_goes_here');

C# code:

SqlConnection connection;

string connectionString = @ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
connection = new SqlConnection(connectionString);
connection.Open();

In asp.net, Username and Password for the Database server, IP address/URL for the database sever and DB name are storing in the web.config file under connectionStrings section.

 

PHP code:

$q = 'SELECT * FROM myTable';

C# code:

string q = "SELECT * FROM myTable";

That’s how actually we declare variables in those languages. There is no relevant for DB. Above shows just how we store the strings in both languages.

 

PHP code:

$r = mysql_query($q);

C# code:

SqlCommand sqlComm = new SqlCommand(q, connection);
SqlDataReader r = sqlComm.ExecuteReader();

That’s how we execute the SQL query and store the result in a reader object. In C#, we use SqlDataReader object. In PHP we can directly execute the string representation of the SQL query. In C#, we have to build a SqlCommand object from the string representation of the SQL query.

 

PHP code:

while (mysql_fetch_object($r)) {
        // do stuff
}

C# code:

while (r.Read()) {
    //do stuff
}

That’s how we read the data from the reader objects.

Set SkinID for a Custom Controller

SkinID property should set in or before the Page_PreInit event for static controls. Since Custom Controller is written within a class, not a page, there are no page events available to set the SkinID. So, to set the SkinID property for a Custom Controller, you have to override it in the implementation of the custom controller class as below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.ComponentModel;
using System.Web.UI.Adapters;

namespace WebApplication2
{
    [ToolboxData("<{0}:Class1 runat=\"server\"  SkinID=\"Skin1\"> </{0}:Class1>")]
    public class Class1 : Label
    {
       public override string SkinID
       {
           get
           {
               return "Skin2";
           }
           set
           {
               base.SkinID = value;
           }
       }

        protected override void Render(HtmlTextWriter writer)
        {
            Text = this.HeaderText;
            base.Render(writer);
        }

        [Bindable(true)]
        public String HeaderText
        {
            get
            {
                return (string)this.ViewState["HeaderText"] ?? String.Empty;
            }
            set
            {
                this.ViewState["HeaderText"] = value;
            }
        }
    }
}

I’m inheriting this custom controller from asp:Label class.

Skin file should be like below. Note that SkinID for the custom controller in this skin file is same as what I’ve returned in the class, when override the SkinID property. Since the skin file does not recognize the Custom Controller, we have to register it first using Register directive.

<%@ Register Assembly="WebApplication2" Namespace="WebApplication2" TagPrefix="cc2" %>
<cc2:Class1 runat="server" BackColor="Red"  ForeColor="White"  Font-Name="Arial"  Font-Size="9px" SkinID="Skin2" />

Now you can test it with the below ASPX code

<%@ Page Title="About Us" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="About.aspx.cs" Inherits="WebApplication1.About" %>

<%@ Register Assembly="WebApplication2" Namespace="WebApplication2" TagPrefix="cc2" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <cc2:Class1 ID="Class1" runat="server" HeaderText="Ruchira Gamage"> </cc2:Class1>
</asp:Content>

2012-08-27

How to get date and time in a different Time Zone

To get the Date and time for a different time zone, first we need to create a TimeZoneInfo object from the required time zone, as below

TimeZoneInfo timezone = TimeZoneInfo.FindSystemTimeZoneById("Central Time zone");

Here I’m passing the Central Time Zone as the Time zone. To get the equivalent date time representation of a particular date time, we have to use the ConvertTime method and pass the TimeZoneInfo object as shown below

DateTime dateTime = TimeZoneInfo.ConvertTime(DateTime.Now, timezone);

So altogether, to get the current date and time for the Central Time zone, the final code looks like below

TimeZoneInfo timezone = TimeZoneInfo.FindSystemTimeZoneById("Central Time zone");

DateTime dateTime = TimeZoneInfo.ConvertTime(DateTime.Now, timezone);

2012-08-24

Programmatically load a video to embedded Windows Media player

To load video from code behind to the embedded windows media player in a web page, you can refer to the sample code below.

ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
</head>
<body>
    <form id="form1" runat="server">
    <object id="MediaPlayer" width="192" height="190" classid="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95"
        standby="Loading Windows Media Player components..." type="application/x-oleobject">
        <param name="FileName" id="file" runat="server" />
        <param name="ShowControls" value="true" />
        <param name="ShowStatusBar" value="false" />
        <param name="ShowDisplay" value="false" />
        <param name="autostart" value="false" />
    </object>
    </form>
</body>
</html>

Code behind (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            file.Attributes.Add("value", @"E:\MyHardDisk\Videos\English\where.have.you.been.avi");
        }
    }
}

How to grant folder permissions to the IUSR

To perform certain tasks we need to grant read/write access to the IUSR for some folders in our website. I will describe how to grant write permission for the IUSR for particular folder.

1. Right click on the folder and choose ‘Properties’

1

2. Select ‘Security’ tab  and click ‘Edit…’ button

2

3. Then Click ‘Add…’ button. On the dialog box, type IUSR and click OK

3

4. Now you can see the IUSR in the ‘Groups or user names:’ list. Select that user and tick the ‘Write’ permission checkbox. And then click OK for both and you are done.

4

2012-08-14

Change the background color of Visual Studio

Sometimes, to save the energy and all, we need to change the default background color of the Visual Studio Editor (When the screen is dark, the light emitting from the monitor isn’t powerful so it preserve the energy). So to do that, you can follow the below instructions

Go to Tools->Options->Fonts and Colors

From the Show Settings for: dropdown list, select Text Editor. From the list, select Plain Text. Now you can change the Item background from the drop down list or by pressing the Custom... button.

2012-08-13

How to programmatically add users and assign them to roles in asp.net membership provider

First of all we have to import the Security namespace as below

using System.Web.Security;

By using the below line, we can create users programmatically. Below I’m creating a user named “Ruchira” with password “Password”.

MembershipUser newUser = Membership.CreateUser("Ruchira", "Password");

By using the below line, we can programmatically assign the user to a particular role. Here I’m assigning the user named “Ruchira” (Which I created above) to the role named “RoleName”

Roles.AddUserToRole("Ruchira", "RoleName");

So altogether, the code would be looks like below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

namespace WebApplication2
{
    public partial class WebForm1 : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            MembershipUser newUser = Membership.CreateUser("Ruchira", "Password");
            Roles.AddUserToRole("Ruchira", "Role");
        }

    }
}

How to set Default Document from web.config file

Apart from setting the default document in IIS, we can directly set the default document for a particular website from the web.config file.

<system.webServer>
  <defaultDocument>
    <files>
      <clear />
      <add value="Test.aspx" />
    </files>
  </defaultDocument>
</system.webServer>

Here, I clear all the other pages in the default document list and add the Test.aspx file to the list.

2012-08-10

How to rotate an asp:Lable

There is actually no one perfect code which works in every browser. We have to make use of few codes together in order to get it work in all the major browsers. Following demonstrates how to rotate a label text by 90 degrees.

<style>
  .test
  {
    -moz-transform: rotate(90deg); /* FF3.5+ */
    -o-transform: rotate(90deg); /* Opera 10.5 */
    -webkit-transform: rotate(90deg); /* Saf3.1+, Chrome */
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=90); /* IE6,IE7 */
    -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=90)"; /* IE8 */
    -sand-transform: rotate(90deg);
  }
</style>

<asp:Label ID="lblCaseIDVert" runat="server" style="z-index: 100; left: 33px; position: relative; top: 98px" Height="1px" Width="192px" CssClass="test"></asp:Label>

Add a new option for an asp:DropDownList from javascripts

With using pure javascripts, we can add a new option dynamically to a dropdown list. Below is an example I’ve created. I’m adding the option ‘Hi’ to the dropdown list on click of the Button.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function addItem() {
            var option = document.createElement("option");
            option.text = "Hi";
            try {
                // for IE earlier than version 8
                document.getElementById("<%=DropDownList1.ClientID%>").add(option, x.options[null]);
            }
            catch (e) {
                document.getElementById("<%=DropDownList1.ClientID%>").add(option, null);
            }
        }
    </script>
</head>
<body>
    <form id="Form1" runat="server">
    <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="addItem(); return false;" />
    <p>
        Options-
        <asp:DropDownList ID="DropDownList1" runat="server">
        </asp:DropDownList>
    </p>
    </form>
</body>
</html>

How to get the User ID of currently logged in user

When using asp.net membership provider, sometimes we need to get the user ID of the logged in user. We can get it like below.

Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;

Convert image to a byte array in ASP.Net

Following example shows how to take the byte representation of an image.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace WebApplication2
{
    public partial class _Default : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            string strPhoto = (@"C:\\Webcam.jpg");
            FileStream fs = new FileStream(strPhoto, FileMode.Open, FileAccess.Read);

            Byte[] imgByte = new byte[fs.Length];

            fs.Read(imgByte, 0, System.Convert.ToInt32(fs.Length));
        }

    }
}

2012-08-06

How to access a controller inside an asp:CreateUserWizard

In C#

Label lbl = (Label)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("DisplayWelcomeMessageLabel"));

Here the RegisterUser is the ID of the asp:CreateUserWizard control.

<asp:CreateUserWizard ID="RegisterUser" runat="server" EnableViewState="false" OnCreatedUser="RegisterUser_CreatedUser">

……….

</asp:CreateUserWizard>

Get source code of a webpage using jQuery

With the help of below jQuery snippet, we can get the source code of a particular webpage.

<script type="text/javascript">
    var url = "test.html";

    $.get(url, function (data) {
        alert("Page Source: " + data);
    });
</script>

2012-08-01

How to make asp:TextBox to enter only numbers and round up to two decimal points

With the use of two javascript functions, we can achieve this. First, we should prohibit the user from entering non numeric characters. For that, we can use the below javascript function

function isNumberKey(sender, evt) {
    var txt = sender.value;
    var dotcontainer = txt.split('.');
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (!(dotcontainer.length == 1 && charCode == 46) && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

This function will not allow user to enter anything other than numbers. So the ASPX markup of the textbox should looks like below

<asp:TextBox ID="txtTaxRate" runat="server" OnKeyPress="return isNumberKey(this, event);"></asp:TextBox>

Now, since we allow only numbers in that textbox, we can perform the round up operation for the value.

For that, we can use the below javascript function

function mathRoundForTaxes(source) {
    var txtBox = document.getElementById(source);
    var txt = txtBox.value;
    if (!isNaN(txt) && isFinite(txt) && txt.length != 0) {
       var rounded = Math.round(txt * 100) / 100;
       txtBox.value = rounded.toFixed(2);
    }
}

This function will round up the entered numeric value. So altogether, final markup for the textbox should looks like below

<asp:TextBox ID="txtTaxRate" runat="server" OnKeyPress="return isNumberKey(this, event);" onchange="mathRoundForTaxes(this.id);"></asp:TextBox>

2012-07-31

How to change label text of a particular row in GridView on click of a button next to it

Following example code demonstrates how to access another control in the same row as the clicked button, and change it’s behavior.

ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" OnRowCommand="List_RowCommand">
        <Columns>
            <asp:TemplateField HeaderText="Status">
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Action">
                <ItemTemplate>
                    <asp:LinkButton CommandName="Activate" ID="lnkActivate"
                        runat="server" Text="testlink"></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    </form>
</body>
</html>

Here, I’m going to change the text of Label1 when the testlink button Clicked. Following is the code behind (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
using System.Data;

namespace WebApplication1
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn("column1");

            DataRow dr = dt.NewRow();
            dt.Rows.Add(dr);

            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

        protected void List_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            GridViewRow clickedRow = ((LinkButton)e.CommandSource).NamingContainer as GridViewRow;
            Label lblID = (Label)clickedRow.FindControl("Label1");
            lblID.Text = "Some text here";
        }
    }
}

Now when the user press the link button, text of the Label which is associated in the same row will change to “Some text here”. In this example, I’m having only a one row.

2012-07-30

How to retain values of dynamically created controls in asp.net

Dynamically generated controls are getting lost whenever a post back happens. There is actually no way to keep them persistent across post backs. What we can do is, store the dynamically created controls in session and restore them back from the session when a post back happens. Following example demonstrate how to store the dynamically generated controls in session and restore them back when a post back happens.

ASPX code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
</head>
<body>
    <form id="form1" runat="server">
    <asp:TextBox ID="HowManyToGenerateTextBox" runat="server" Text="0"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Generate" OnClick="GenerateButton_Click" />
    <asp:Button ID="Button2" runat="server" Text="Calculate" OnClick="CalculateButton_Click" />
    <asp:Label ID="ResultLabel" runat="server" Text="Result"></asp:Label>
    <asp:Panel ID="Panel1" runat="server">
    </asp:Panel>
    </form>
</body>
</html>

In this example, you can enter value in the textbox so it will dynamically generate that number of textboxes when the Generate button clicks. And when the Calculate button clicks, it will sum up all the values entered in the dynamically created textboxes and display the result in Result Label. Following is the C# code behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Page_Init(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Generate initial textboxes
                GenerateButton_Click(sender, e);
            }
        }

        protected void GenerateButton_Click(object sender, EventArgs e)
        {
            //Generate textboxes
            int z = int.Parse(HowManyToGenerateTextBox.Text);

            Panel1.Controls.Clear();

            for (int i = 0; i < z; i++)
            {
                TextBox s = new TextBox();
                s.Text = i.ToString();
                s.ID = "tb" + i.ToString();
                Session[s.ID] = s;
                Panel1.Controls.Add(s);
            }
        }

        protected void CalculateButton_Click(object sender, EventArgs e)
        {
            //Calculate sum
            int sum = 0;

            for (int i = 0; i < Session.Count; i++)
            {
                string textboxID = "tb"+i.ToString();
                TextBox checkIfTextBox = (TextBox)Session[textboxID];

                if (checkIfTextBox != null)
                    sum += int.Parse(checkIfTextBox.Text);
            }

            ResultLabel.Text = sum.ToString();
        }

    }
}

At the page load method, I’m calling to the Generate button click event to initialize the textboxes. In this case, since I’ve hardcoded value 0 to the HowManyToGenerateTextBox, it will not create any textboxes dynamically when the page loads. After that, you can enter any value to the textbox and click Generate button so it will create that number of textboxes. Now you can enter numbers to the dynamically created textboxes and click on the Calculate button. Now a post back happens. But I have stored the dynamically created textboxes in session so I can get them back from the session. I’m getting them back from session, sum it up and display the result in the Result label.

2012-07-27

Set a placeholder image when the image is not available

When you are using img tags, sometimes you need to set a default image for the img tag if the source image is not found or corrupted. There is an event for the img tag called onerror. By using that event, we can easily set a default placeholder image for the img tag, if the image failed to load. Following is an example for the onerror method.

<script>
    function test(e)
    {
       e.src="images/placeholder.jpg";
    }
<script>

<img onerror="test(this);" src="......." />

Now the test() method will get called whenever there is a problem loading the image to the src and will set the placeholder.jpg as the image src.

How to create a simple countdown using javascripts

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ClientDisplayForserver.aspx.cs" Inherits="ClientDisplayForserver" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script>
       function GetCount(amount) {
           document.getElementById('test').innerHTML = amount;
           if (amount == 0)
               clearTimeout();
           else
               setTimeout(function () { GetCount(amount - 1) }, 1000);
       }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <span id="test">Test<br />
        <br />
    </span>&nbsp;<asp:Button ID="Button1" runat="server" OnClientClick="GetCount(30); return false" Text="Button" /></div>
    </form>
</body>
</html>

The above sample code is for a countdown when the user press the button. Here it will go from 30. You can change the parameter pass to the GetCount() method,

2012-07-26

Auto-scroll to the bottom of a multiline textbox when page loads

Using the below javascript code snippet, you can auto scroll to the bottom of an asp:TextBox, which’s TextMode property is set to Multiline.

Let’s say the textbox is like below

<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine"></asp:TextBox>

Then the javascript code should look like below

window.onload=function myScroll() {
   var x = document.getElementById("<%=textboxid.ClientID%>");
   var h = x.clientHeight;
   x.scrollTop = h;
}

Now, when the page loads, the scroll of the Multiline textbox would go to the bottom.

2012-07-25

How to get the current position when paused, in the embedded windows media player

The below sample code will alert the user, time elapsed, when the user press the pause button. Since it’s Windows Media player, it will only work in IE. To get it work in other browsers, you may need to install plugins/add-ons.

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1">
    <title></title>
</head>
<body>
    <form id="Form1">
    <object id="Player" height="0" width="0" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">
    </object>
    <input type="button" name="BtnPlay" value="Play" onclick="StartMeUp()" />
    <input type="button" name="BtnStop" value="Stop" onclick="ShutMeDown()" />
    <input type="button" name="BtnPause" value="Pause" onclick="Pause()" />
    <script type="text/javascript">
<!--

        function StartMeUp() {
            document.getElementById('Player').URL = "Danza kuduro.mp3";
        }

        function ShutMeDown() {
            document.getElementById('Player').Controls.stop();
        }

        function Pause() {
            document.getElementById('Player').Controls.Pause();
            alert(document.getElementById('Player').Controls.currentPosition);
        }

-->
    </script>
    </form>
</body>
</html>

Process an image pixel by pixel to check color on each pixel in C#

By using the below kind of code, we can read an image pixel by pixel and get the color on each.

Bitmap img = new Bitmap("image name here"); 
Color c;

for (int i = 0; i < img.Width; i++)
{
for (int j = 0; j < img.Height; j++)
{
c = img.GetPixel(i, j);
if (c == Color.Black)
{
//Code here
}
else
{
//Code here
}
}
}


On that sample code, I’m checking the pixel color against Black color.

2012-07-23

Specify the Maximum length for JSON response

By adding the following part to the web.config file, you can specify the maximum length for a JSON response

<configuration>
    <system.web.extensions>
        <scripting>
            <webServices>
               <jsonSerialization maxJsonLength="1000" />
            </webServices>
        </scripting>
    </system.web.extensions>
</configuration>

Addition of two short type numbers causing a negative result

I will try to explain this using a simple example. Following code adds two short type numbers and assign the result to another short type variable.

short num1 = 30000, num2 = 30000;
short answer = (short)num1+num2;

But if you see the result, you will get a negative number.

The value range of short data type is -32,768 to 32,767. So the first line is correct because we are storing 30000 (which is less than 32,767) in the variables.

But in the second line, we are adding those two variables which results in 60000 which is bigger than the maximum value which can be stored for a short variable.

Binary representation of the 60000 is 1110101001100000

Binary representation of the 32,767 is 0111111111111111

The first bit is the sign bit. 0 represent positive number and 1 represent negative number. That's why the Binary representation value of the 32,767 is 0111111111111111 (Notice the leading 0). short data type can store only 15 bits (Except the sign bit). As I said, the first bit is used to indicate the sign (negative or positive) of the number. But the binary value of 60000 (1110101001100000) requires 16 bits. So when we store the 60000 in a short variable the leading 1 will assigned to the sign bit and as a result of it, we are getting a negative number. The leading sign bit has the value of 2^15. When it's positive, it's 0 (Because the value of the bit is 0). But when it's negative, it has the value of -2^15 (-32768).

So let's go back to the result 60000. When we assign the value to a short variable, the binary representation of it 1110101001100000 will assign the leading 1 to the sign bit. So now it has value of -32768. Except the sign bit, the left over is 110101001100000 (Notice that I've left out the leading 1) which's value is 27232. So altogether, when we take that value with the sign bit, the final value is  -32768+27232 =-5536.

How to display a popup window in full screen mode

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript">
        function openPopup() {
            window.open("yourpagename.html", null, "fullscreen=yes, channelmode=no, scrollbars=yes, resizable=no, status=no, toolbar=no, directories=no")
        }
    </script>
</head>
<body>
    <form>
    <input type="button" name="btnFullscreen" value="Open in fullscreen" onclick="openPopup();" />
    </form>
</body>
</html>

When you press the button, the popup will open in full screen. Note that this can be vary depend on the browser settings and this is not a good user experience too.

2012-07-09

How to vertically center align a text within a dynamically created asp:Label

The following code example shows how to center a text within a asp:Label using a bit of mathematics and help of CSS styles. For the horizontal align, we can simply set the CSS style, text-align to center. For vertically center align the text, we have to use some calculations and position the text accordingly.

Label lblproof = new Label();

lblproof.ID = "label2";

int width = 60;

int height = 30;

int fontSize = 12;

lblproof.Width = width;

lblproof.Height = height-(((height - fontSize) / 2)/2);

lblproof.Text = "Pueba2";

lblproof.Style["position"] = "absolute";

lblproof.Style["font-size"] = "12px";

lblproof.Style["border-bottom"] = "2px";

lblproof.Style["border-left"] = "2px";

lblproof.Style["border-top"] = "2px";

lblproof.Style["border-right"] = "2px";

lblproof.Style["border-style"] = "solid";

lblproof.Style["text-align"]= "center";

lblproof.Style["padding-top"] = (((height - fontSize) / 2) / 2).ToString()+"px";

lblproof.Style["margin-left"] = "auto";

lblproof.Style["margin-right"] = "auto";

this.Controls.Add(lblproof);

You can change the variable values for height, width and fontSize. The mathematical calculation will take the respective values and center the text inside the label both vertically and horizontally.

2012-07-05

The difference between float and display:inline-block

When you use float, the elements will follow you (i.e. if you float:left an element, the elements after it will follow you to the right. If you float:right an element, the elements after it will follow you to the left.). As the name suggests, the element will float in your web page as much as it can (either to left or to right, as you define). If you use float property, it can overlap with other elements on your webpage. But when you set the display:inline-block, it would not make an element overlap with others.

Since the floating elements float either to left or right, it's bit hard to deal with aligning a floated element to the center.

2012-07-04

Simple example for parseJSON function

Following is a simple sample app which parse a JSON string to a jQuery object and access a value in the JSON string.

<html>
<head>
    <title></title>
    <script src="
http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        var str = "[{\"CityName\":\"Colombo\",\"CityID\":1,\"ZipCodeID\":1,\"ZipCode\":1098},
                       {\"CityName\":\"Kandy\",\"CityID\":2,\"ZipCodeID\":2,\"ZipCode\":1675}]";
        var test = jQuery.parseJSON(str);
        for (var i = 0; i < test.length; i++)
            alert(test[i].CityName); //Here, this will alert the City name in the JSON string
    </script>
</head>
<body>
</body>
</html>

2012-07-02

SQL injections

I'll try to explain it with a simple example.

Let's take a table named 'Users' which has two columns, 'Username' and 'Password'. In the 'Username' field, they store the username and in the 'Password' field they store passwords. For the simplicity, let's assume they are storing the password in plain text (Facebook surely don't store their password in plain text). Now let's look what it looks like the SQL query for a legal user. They will provide the username along with the correct password. So their query will looks like below.

SELECT * FROM Users WHERE Username = 'Ruchira' AND Password = '123'

Here I'm login to that site using my username 'Ruchira' and my password '123' which is the correct one. So now, the select query will return a one row. Now the system know I'm a legal user because it returns a record which matches both my password and username.

Now, let's see how SQL query for a hacker looks like. Hacker knows my Username but don't know my password. So he is TRYING to make a query like below.

SELECT * FROM Users WHERE Username = 'Ruchira' AND Password = 'none' OR 'x'='x'

Now the question is how can a hacker makes such a query.

He can pass the username as I do but problems occurs when he provide the password because he don't know it. Now what he is doing is he provides something which makes the second condition (i.e. Password='none'…. part) always evaluates to true no matter what he provides for the password. In the backend, the website have something likes this

SELECT * FROM Users WHERE Username = '+txtUserName.Text+' AND Password = '+txtPassword.Text+'

Where they are getting the username from txtUserName TextBox and password from txtPassword TextBox. So now, the hacker provides the following value for the txtPassword field

none' OR 'x'='x

So the final query he is sending looks like below

SELECT * FROM Users WHERE Username = '+txtUserName.Text+' AND Password = 'none' OR 'x'='x'

So what basically SQL injection preventions do is, they prevent/ignore users from inserting words such as OR in to the password fields or prevent users inserting special characters such as " ' or distinguish data from the SQL query so the data will not be used to build the query.

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');
}